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
Federate music records across peers
[._.]/ Adam Eivyeca60828637d
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 924e9efd9e..9ea5c86bf8 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -7,7 +7,7 @@ import {Database, Brain, CheckCircle2, AlertCircle, Clock,RefreshCcw, Timer,Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight,- Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen, FilePen+ Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3} from 'lucide-react';import toast from '../components/ui/Toast';import Pill from '../components/ui/Pill';@@ -493,13 +493,16 @@ const SYNC_CATEGORY_META = [{ key: 'videoHistory', label: 'Video History', icon: Film, description: 'Generated-video metadata rows (so synced collection videos render)' },{ key: 'storyBuilder', label: 'Story Builder', icon: BookOpen, description: 'Resumable Story Builder sessions you marked for cross-machine sync' },{ key: 'authors', label: 'Authors', icon: FilePen, description: 'Author personas + headshots used as series bylines (PostgreSQL)' },+ { key: 'artists', label: 'Artists', icon: Music, description: 'Music artist personas + portraits (PostgreSQL)' },+ { key: 'albums', label: 'Albums', icon: Disc3, description: 'Music albums + cover art and ordered track lists (PostgreSQL)' },+ { key: 'tracks', label: 'Tracks', icon: Music2, description: 'Music tracks + attached audio files (PostgreSQL)' },{ key: 'catalog', label: 'Catalog', icon: Library, description: 'Creative ingredients catalog: orphan ingredients + ref links (PostgreSQL)' }];// Snapshot categories — exclude the per-record / delta-based categories that-// have no 60s snapshot checksum: brain + memory (delta), catalog + authors+// have no 60s snapshot checksum: brain + memory (delta), catalog + authors/music// (PostgreSQL, per-record peer-push only — no snapshot loop).-const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors']);+const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks']);const SNAPSHOT_CATEGORIES = SYNC_CATEGORY_META.filter(m => !NON_SNAPSHOT_KEYS.has(m.key));function SyncCategoriesPanel({ peer, onRefresh }) {diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.jsindex 3f5efce4b4..4dd207cc0c 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -304,6 +304,9 @@ export const RESTORABLE_FIELDS = Object.freeze({// LWW-overwritten whole (no field-union like mediaCollection's items), so it// is hashed in full by contentHashForRecord — no scalar-narrowing branch.author: ['name', 'writingStyle', 'bio', 'physicalDescription', 'headshotStyle', 'headshotImageUrl'],+ artist: ['name', 'genre', 'bio', 'musicalStyle', 'physicalDescription', 'portraitStyle', 'portraitImageUrl'],+ album: ['title', 'artistId', 'artist', 'description', 'genre', 'releaseYear', 'coverImageUrl', 'trackIds'],+ track: ['title', 'albumId', 'artistId', 'artist', 'lyrics', 'prompt', 'engine', 'modelId', 'durationSec', 'audioFilename'],// Issue: the user-authored content the merge can restore. `stages` carries// the bulk of the work (prose, comic pages, render metadata). Server-owned /// structural fields are excluded deliberately — `number` is renumber-managed,diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.jsindex 3511b0b7a2..db7868e026 100644--- a/server/lib/peerSyncValidation.js+++ b/server/lib/peerSyncValidation.js@@ -15,7 +15,7 @@ import { catalogSyncIngredientSchema, catalogSyncRefSchema } from './catalogVali// subscriptions target another PortOS instance over Tailnet.export const peerSubscribeSchema = z.object({peerId: z.string().trim().min(1).max(120),- recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author']),+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track']),recordId: z.string().trim().min(1).max(120),}).strict();@@ -38,7 +38,7 @@ const peerAssetManifestEntrySchema = z.discriminatedUnion('kind', [}).strict(),z.object({filename: z.string().trim().min(1).max(255),- kind: z.enum(['image-ref', 'video']),+ kind: z.enum(['image-ref', 'video', 'music']),sha256: hex64.optional(),}).strict(),]);@@ -169,18 +169,33 @@ const authorPushSchema = z.object({kind: z.literal('author'),...peerSyncPushBase,}).strict();+const artistPushSchema = z.object({+ kind: z.literal('artist'),+ ...peerSyncPushBase,+}).strict();+const albumPushSchema = z.object({+ kind: z.literal('album'),+ ...peerSyncPushBase,+}).strict();+const trackPushSchema = z.object({+ kind: z.literal('track'),+ ...peerSyncPushBase,+}).strict();export const peerSyncPushSchema = z.discriminatedUnion('kind', [universePushSchema,seriesPushSchema,mediaCollectionPushSchema,authorPushSchema,+ artistPushSchema,+ albumPushSchema,+ trackPushSchema,]);// Manual sync action schemas — used by POST /sync-record, /sync-now, /pull-metadata.export const peerSyncRecordSchema = z.object({peerId: z.string().trim().min(1).max(120),- recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author']),+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track']),recordId: z.string().trim().min(1).max(200),}).strict();@@ -196,4 +211,3 @@ export const peerPullMetadataSchema = z.object({// manifest-entry filename handling.filenames: z.array(z.string().trim().min(1).max(300)).max(5000),}).strict();-diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 48cbfc95a6..5db729a31f 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -153,6 +153,13 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// MUST bump this to 2 then (where a v1 peer would round-trip the new shape// through an unaware sanitizer).authors: 1,+ // v1 = music artists/albums/tracks (PostgreSQL `artists`, `albums`, and+ // `tracks` tables) federated via the per-record peer-sync push pipeline.+ // Each kind gets its own category gate so an older peer can reject only the+ // music record type it cannot parse while unrelated categories keep flowing.+ artists: 1,+ albums: 1,+ tracks: 1,// v1 = creative ingredients catalog (Postgres tables: catalog_scraps,// catalog_ingredients, catalog_ingredient_sources, catalog_ingredient_refs).// v2 = `catalog_ingredients.search_tsv` expanded to also index the@@ -282,6 +289,9 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({issue: Object.freeze(['pipelineIssues']),mediaCollection: Object.freeze(['mediaCollections']),author: Object.freeze(['authors']),+ artist: Object.freeze(['artists']),+ album: Object.freeze(['albums']),+ track: Object.freeze(['tracks']),'cat-ingredient': Object.freeze(['catalog']),'cat-scrap': Object.freeze(['catalog']),storyBuilder: Object.freeze(['storyBuilder']),diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex 8d2d6d03f8..8b737a69b2 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -158,8 +158,11 @@ export function sanitizeRecordForWire(kind, record) {const { deleted: _d, deletedAt: _da, ...rest } = record;return { ...rest, ...sanitizeSoftDeleteFields(record) };}- case 'author': {- // Author personas: like mediaCollection, no `ephemeral` flag — always+ case 'author':+ case 'artist':+ case 'album':+ case 'track': {+ // Persona/music records: like mediaCollection, no `ephemeral` flag — always// wire-syncable when present. Strip-then-tail-re-add the soft-delete pair// for byte-stable checksums. The full record is small (a handful of text// fields + the LWW/tombstone trio), so unlike mediaCollection there's nodiff --git a/server/routes/instances.js b/server/routes/instances.jsindex 10beec88d3..221dfe01e3 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -61,6 +61,9 @@ const syncCategoriesSchema = z.object({videoHistory: z.boolean().optional(),storyBuilder: z.boolean().optional(),authors: z.boolean().optional(),+ artists: z.boolean().optional(),+ albums: z.boolean().optional(),+ tracks: z.boolean().optional(),catalog: z.boolean().optional()}).optional();diff --git a/server/services/albums/db.js b/server/services/albums/db.jsindex 170f6bc5d3..6ad06b0b8f 100644--- a/server/services/albums/db.js+++ b/server/services/albums/db.js@@ -102,8 +102,7 @@ export async function deleteAlbum(id) {/*** Merge an incoming batch of album records from a peer (per-record push). LWW on* `updatedAt` (tombstone-aware) via the shared `mergeAlbumRecord` decision.- * Federation-ready, but the album kind is not yet registered in peerSync — see- * issue #1502. Returns `{ applied, count }`.+ * Peer-sync merge entry point. Returns `{ applied, count }`.*/export async function mergeAlbumsFromSync(remoteAlbums, { source = { via: 'sync', peerId: null } } = {}) {if (!Array.isArray(remoteAlbums)) return { applied: false, count: 0 };diff --git a/server/services/albums/file.test.js b/server/services/albums/file.test.jsindex b9ad760301..0cbd561006 100644--- a/server/services/albums/file.test.js+++ b/server/services/albums/file.test.js@@ -2,9 +2,8 @@* Album file-backend store — CRUD + LWW merge outcomes.** Covers the CRUD round-trip the normal (non-DB) suite exercises plus the- * `mergeAlbumsFromSync` LWW outcomes. The conflict-journal base-hash side- * effects are NOT asserted here — they depend on the album record kind being- * registered in syncWire/peerSync (deferred; local-only — see issue #1502).+ * `mergeAlbumsFromSync` LWW outcomes plus the sync side effects that make+ * federation safe: base-hash seeding and conflict journaling before overwrite.* Runs against a tmpdir so it never touches real `data/`.*/@@ -21,13 +20,17 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {});const file = await import('./file.js');+const cj = await import('../../lib/conflictJournal.js');function reset() {rmSync(join(TEST_DATA_ROOT, 'albums.json'), { force: true });rmSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true, force: true });rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });+ cj.__resetBaseHashCacheForTests();}+const journalEntries = () => cj.conflictJournalStore().loadAll();+const album = (id, extra = {}) => ({id, title: id, artistId: '', artist: '', description: '', genre: '',releaseYear: null, coverImageUrl: '', trackIds: [],@@ -75,4 +78,40 @@ describe('albums file backend — mergeAlbumsFromSync (LWW outcomes)', () => {expect(await file.pruneTombstonedAlbums(Date.parse('2030-01-01T00:00:00.000Z'))).toEqual({ pruned: 1 });expect(await file.getAlbum('album-dead', { includeDeleted: true })).toBeNull();});++ it('seeds the base hash on first insert of a remote album', async () => {+ const remote = album('album-2', { description: 'inserted' });+ expect(await cj.getSyncBaseHash('album', 'album-2')).toBeNull();+ await file.mergeAlbumsFromSync([remote]);+ expect(await cj.getSyncBaseHash('album', 'album-2'))+ .toBe(cj.contentHashForRecord('album', remote));+ });++ it('journals the losing local album on true 3-way divergence', async () => {+ const local = album('album-3', { genre: 'local jazz', updatedAt: '2026-02-01T00:00:00.000Z' });+ await file.mergeAlbumsFromSync([local]);+ const base = album('album-3', { genre: 'common folk', updatedAt: '2026-01-01T00:00:00.000Z' });+ await cj.setSyncBaseHash('album', 'album-3', cj.contentHashForRecord('album', base));++ const remoteWinner = album('album-3', { genre: 'remote pop', updatedAt: '2026-03-01T00:00:00.000Z' });+ await file.mergeAlbumsFromSync([remoteWinner], { source: { via: 'peer-push', peerId: 'peer-A' } });++ const entry = (await journalEntries()).find((e) => e.recordKind === 'album' && e.recordId === 'album-3');+ expect(entry).toBeTruthy();+ expect(entry.source.peerId).toBe('peer-A');+ expect(entry.localSnapshot.genre).toBe('local jazz');+ expect(entry.remoteSnapshot.genre).toBe('remote pop');+ expect((await file.getAlbum('album-3')).genre).toBe('remote pop');+ expect(await cj.getSyncBaseHash('album', 'album-3'))+ .toBe(cj.contentHashForRecord('album', remoteWinner));+ });++ it('pruneTombstonedAlbums evicts the base hash for a hard-pruned tombstone', async () => {+ await file.mergeAlbumsFromSync([+ album('album-dead-base', { deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' }),+ ]);+ expect(await cj.getSyncBaseHash('album', 'album-dead-base')).not.toBeNull();+ await file.pruneTombstonedAlbums(Date.parse('2030-01-01T00:00:00.000Z'));+ expect(await cj.getSyncBaseHash('album', 'album-dead-base')).toBeNull();+ });});diff --git a/server/services/albums/index.js b/server/services/albums/index.jsindex 3a4ae96964..3666faaadf 100644--- a/server/services/albums/index.js+++ b/server/services/albums/index.js@@ -6,9 +6,8 @@* - PostgreSQL (db.js) for normal installs.* - File (file.js) only via MEMORY_BACKEND=file or NODE_ENV=test.*- * The recordEvents emits are kept so the store is federation-ready, but the- * album record kind is NOT yet registered in peerSync, so they are no-ops —- * albums are local-only until cross-peer sync is wired (see issue #1502).+ * The recordEvents emits feed the per-record peer-sync pipeline, so albums+ * federate when peers enable the Albums sync category.*/import { checkHealth, ensureSchema } from '../../lib/db.js';diff --git a/server/services/albums/logic.js b/server/services/albums/logic.jsindex 1713064ce4..aef82d5fa1 100644--- a/server/services/albums/logic.js+++ b/server/services/albums/logic.js@@ -17,10 +17,10 @@* - coverImageUrl — optional pointer to a generated/uploaded cover image* - trackIds — ordered list of track ids (`track-…`) on the album*- * Albums are `db-primary` (PostgreSQL `albums` table). The storage layer is- * federation-ready (LWW merge + tombstone prune mirror authors/artists), but the- * cross-peer peer-sync REGISTRATION is not wired yet — see issue #1502. Until- * then albums are local-only.+ * Albums are `db-primary` (PostgreSQL `albums` table) and federate across peers+ * via the per-record peer-sync pipeline (`record kind: album`, sync category:+ * albums). Tracks still carry denormalized artist/album context so they render+ * before related records arrive.*/import { compareNewerWins } from '../../lib/lwwTimestamp.js';@@ -94,7 +94,7 @@ export function sanitizeAlbum(raw) {/*** Resolve an album's `coverImageUrl` to the bare gallery-image filename under- * `data/images/` for a future peer-sync asset transfer. Returns null when+ * `data/images/` for peer-sync asset transfer. Returns null when* there's nothing local to ship. Mirrors artists' portraitImageFilename.*/export function coverImageFilename(coverImageUrl) {diff --git a/server/services/artists/db.js b/server/services/artists/db.jsindex b7de3d525f..e7b038501b 100644--- a/server/services/artists/db.js+++ b/server/services/artists/db.js@@ -105,7 +105,7 @@ export async function deleteArtist(id) {* Merge an incoming batch of artist records from a peer (per-record push). LWW* on `updatedAt` (tombstone-aware) via the shared `mergeArtistRecord` decision.* Federation-ready: this is wired identically to authors, but the artist kind is- * not yet registered in peerSync — see issue #1502. Returns `{ applied, count }`.+ * registered in peerSync. Returns `{ applied, count }`.*/export async function mergeArtistsFromSync(remoteArtists, { source = { via: 'sync', peerId: null } } = {}) {if (!Array.isArray(remoteArtists)) return { applied: false, count: 0 };diff --git a/server/services/artists/file.test.js b/server/services/artists/file.test.jsindex 12e4371b6e..fdea1ed53c 100644--- a/server/services/artists/file.test.js+++ b/server/services/artists/file.test.js@@ -5,12 +5,9 @@* exercises) and the `mergeArtistsFromSync` LWW outcomes (insert / newer-wins /* older-loses / tombstone), asserted via getArtist/listArtists.*- * NOTE: the conflict-journal base-hash + journaling SIDE EFFECTS that authors'- * file.test.js asserts are intentionally NOT covered here — they depend on the- * artist record kind being registered in syncWire/peerSync (cross-peer sync),- * which is deferred (artists are local-only for now — see issue #1502). When that- * registration lands, this suite should grow the base-hash/journaling assertions- * to mirror authors. Runs against a tmpdir so it never touches real `data/`.+ * Also pins the sync side effects that make the cross-peer registration real:+ * base-hash seeding on insert and conflict journaling before a remote overwrite.+ * Runs against a tmpdir so it never touches real `data/`.*/import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';@@ -26,13 +23,17 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {});const file = await import('./file.js');+const cj = await import('../../lib/conflictJournal.js');function reset() {rmSync(join(TEST_DATA_ROOT, 'artists.json'), { force: true });rmSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true, force: true });rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });+ cj.__resetBaseHashCacheForTests();}+const journalEntries = () => cj.conflictJournalStore().loadAll();+const artist = (id, extra = {}) => ({id, name: id, genre: '', bio: '', musicalStyle: '', physicalDescription: '',portraitStyle: '', portraitImageUrl: '',@@ -102,4 +103,40 @@ describe('artists file backend — mergeArtistsFromSync (LWW outcomes)', () => {expect(res).toEqual({ pruned: 1 });expect(await file.getArtist('artist-dead', { includeDeleted: true })).toBeNull();});++ it('seeds the base hash on first insert of a remote artist', async () => {+ const remote = artist('artist-2', { bio: 'inserted' });+ expect(await cj.getSyncBaseHash('artist', 'artist-2')).toBeNull();+ await file.mergeArtistsFromSync([remote]);+ expect(await cj.getSyncBaseHash('artist', 'artist-2'))+ .toBe(cj.contentHashForRecord('artist', remote));+ });++ it('journals the losing local artist on true 3-way divergence', async () => {+ const local = artist('artist-3', { bio: 'local edit', updatedAt: '2026-02-01T00:00:00.000Z' });+ await file.mergeArtistsFromSync([local]);+ const base = artist('artist-3', { bio: 'common ancestor', updatedAt: '2026-01-01T00:00:00.000Z' });+ await cj.setSyncBaseHash('artist', 'artist-3', cj.contentHashForRecord('artist', base));++ const remoteWinner = artist('artist-3', { bio: 'remote edit', updatedAt: '2026-03-01T00:00:00.000Z' });+ await file.mergeArtistsFromSync([remoteWinner], { source: { via: 'peer-push', peerId: 'peer-A' } });++ const entry = (await journalEntries()).find((e) => e.recordKind === 'artist' && e.recordId === 'artist-3');+ expect(entry).toBeTruthy();+ expect(entry.source.peerId).toBe('peer-A');+ expect(entry.localSnapshot.bio).toBe('local edit');+ expect(entry.remoteSnapshot.bio).toBe('remote edit');+ expect((await file.getArtist('artist-3')).bio).toBe('remote edit');+ expect(await cj.getSyncBaseHash('artist', 'artist-3'))+ .toBe(cj.contentHashForRecord('artist', remoteWinner));+ });++ it('pruneTombstonedArtists evicts the base hash for a hard-pruned tombstone', async () => {+ await file.mergeArtistsFromSync([+ artist('artist-dead-base', { deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' }),+ ]);+ expect(await cj.getSyncBaseHash('artist', 'artist-dead-base')).not.toBeNull();+ await file.pruneTombstonedArtists(Date.parse('2030-01-01T00:00:00.000Z'));+ expect(await cj.getSyncBaseHash('artist', 'artist-dead-base')).toBeNull();+ });});diff --git a/server/services/artists/index.js b/server/services/artists/index.jsindex 264e449319..8b5e42b59a 100644--- a/server/services/artists/index.js+++ b/server/services/artists/index.js@@ -8,10 +8,8 @@* - PostgreSQL (db.js) for normal installs.* - File (file.js) only via MEMORY_BACKEND=file or NODE_ENV=test.*- * The recordEvents emits below are kept so the store is federation-ready, but- * the artist record kind is NOT yet registered in peerSync, so they are no-ops- * (autoSubscribeRecordToAllPeers ignores unregistered kinds) — artists are- * local-only until cross-peer sync is wired (see issue #1502).+ * The recordEvents emits below feed the per-record peer-sync pipeline, so+ * artists federate when peers enable the Artists sync category.*/import { checkHealth, ensureSchema } from '../../lib/db.js';diff --git a/server/services/artists/logic.js b/server/services/artists/logic.jsindex af65b407c9..77d74df850 100644--- a/server/services/artists/logic.js+++ b/server/services/artists/logic.js@@ -18,11 +18,10 @@* - portraitStyle — art/photography direction for the portrait render* - portraitImageUrl — optional pointer to a generated/chosen portrait*- * Artists are `db-primary` (PostgreSQL `artists` table). The storage layer is- * federation-ready (LWW merge + tombstone prune mirror authors), but the cross-- * peer peer-sync REGISTRATION (schemaVersions / peerSync / syncWire / tombstone- * GC) is not wired yet — see issue #1502. Until then artists are local-only, like- * the Rounds workbench.+ * Artists are `db-primary` (PostgreSQL `artists` table) and federate across+ * peers via the per-record peer-sync pipeline (`record kind: artist`, sync+ * category: artists). A federated album/track still keeps denormalized artist+ * text so peers render before the artist persona itself arrives.*/import { compareNewerWins } from '../../lib/lwwTimestamp.js';@@ -72,8 +71,8 @@ export function sanitizeArtist(raw) {/*** Resolve an artist's `portraitImageUrl` to the bare gallery-image filename that- * lives under `data/images/` — the unit a future peer-sync asset pipeline can- * hash + transfer. Returns null when there's nothing local to ship (empty,+ * lives under `data/images/` — the unit the peer-sync asset pipeline hashes ++ * transfers. Returns null when there's nothing local to ship (empty,* external URL, or a non-image path). Mirrors authors' headshotImageFilename.*/export function portraitImageFilename(portraitImageUrl) {diff --git a/server/services/instances.js b/server/services/instances.jsindex bcf620e81a..376ec70548 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -227,6 +227,9 @@ const DEFAULT_SYNC_CATEGORIES = {videoHistory: false,storyBuilder: false,authors: false,+ artists: false,+ albums: false,+ tracks: false,catalog: false};@@ -237,16 +240,18 @@ export { DEFAULT_SYNC_CATEGORIES };// backfills. A false→true toggle on any of these triggers an inline backfill of// existing local records so the user doesn't have to wait for the next// `peer:online` / manual sync-now. Mirror of peerSync's KIND_TO_CATEGORY-// (inverted). `pipeline → series` bundles child issues at push time; authors +-// mediaCollections are standalone per-record kinds with NO snapshot category, so-// the toggle-time backfill is the ONLY place existing records get subscribed-// short of a reconnect — omitting them here strands a user's existing authors /-// collections until the peer next comes online.+// (inverted). `pipeline → series` bundles child issues at push time; authors,+// music records, and mediaCollections are standalone per-record kinds with no+// snapshot category, so toggle-time backfill is the main path that subscribes+// existing records short of a reconnect.const PER_RECORD_CATEGORY_KINDS = Object.freeze([['universe', 'universe'],['pipeline', 'series'],['mediaCollections', 'mediaCollection'],['authors', 'author'],+ ['artists', 'artist'],+ ['albums', 'album'],+ ['tracks', 'track'],]);export async function addPeer({ address, port = DEFAULT_PEER_PORT, name, host, auth }) {diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 00f9ee8caa..7e9f2a118a 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -79,13 +79,31 @@ import {mergeAuthorsFromSync,headshotImageFilename,} from '../authors/index.js';+import {+ getArtist,+ listArtists,+ mergeArtistsFromSync,+ portraitImageFilename,+} from '../artists/index.js';+import {+ getAlbum,+ listAlbums,+ mergeAlbumsFromSync,+ coverImageFilename,+} from '../albums/index.js';+import {+ getTrack,+ listTracks,+ mergeTracksFromSync,+ trackAudioFilename,+} from '../tracks/index.js';import {initCursor,ackDeletesUpTo,removeCursor as removeTombstoneCursor,} from './peerTombstoneCursors.js';-export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author']);+export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track']);/*** Cross-cutting event bus for the peer-sync receiver. The asset-pull worker@@ -359,6 +377,9 @@ const KIND_TO_CATEGORY = Object.freeze({series: 'pipeline',mediaCollection: 'mediaCollections',author: 'authors',+ artist: 'artists',+ album: 'albums',+ track: 'tracks',});function peerAllowsOutbound(peer) {@@ -447,6 +468,12 @@ export async function autoSubscribePeerToAllRecords(peerId, recordKind) {records = await listCollections({ includeDeleted: false }).catch(() => []);} else if (recordKind === 'author') {records = await listAuthors({ includeDeleted: false }).catch(() => []);+ } else if (recordKind === 'artist') {+ records = await listArtists({ includeDeleted: false }).catch(() => []);+ } else if (recordKind === 'album') {+ records = await listAlbums({ includeDeleted: false }).catch(() => []);+ } else if (recordKind === 'track') {+ records = await listTracks({ includeDeleted: false }).catch(() => []);}// Drop ephemeral records before the set-difference / sub creation. The wire// sanitizer would short-circuit any push anyway, but creating a sub that@@ -685,6 +712,9 @@ function summarizeAssetManifest(manifest) {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 === 'series') {const childIssues = await listIssues({ seriesId: record?.id, includeDeleted: true }).catch(() => []);const manifestIssues = childIssues.filter(@@ -846,6 +876,7 @@ function directoryForAssetKind(kind) {if (kind === 'image') return PATHS.images;if (kind === 'image-ref') return PATHS.imageRefs;if (kind === 'video') return PATHS.videos;+ if (kind === 'music') return PATHS.music;return null;}@@ -890,6 +921,18 @@ async function isSubscriptionRecordTombstone(sub) {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;+ }return false;}@@ -1416,6 +1459,30 @@ async function buildPushPayload(sub, sourceInstanceId) {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 };+ }return null;}@@ -1433,6 +1500,27 @@ async function buildAuthorAssetManifest(author) {return entry ? [entry] : [];}+async function buildArtistAssetManifest(artist) {+ const filename = portraitImageFilename(artist?.portraitImageUrl);+ if (!filename) return [];+ const entry = await hashImageForManifest(filename);+ return entry ? [entry] : [];+}++async function buildAlbumAssetManifest(album) {+ const filename = coverImageFilename(album?.coverImageUrl);+ if (!filename) return [];+ const entry = await hashImageForManifest(filename);+ return entry ? [entry] : [];+}++async function buildTrackAssetManifest(track) {+ const filename = trackAudioFilename(track?.audioFilename);+ if (!filename) return [];+ const entry = await hashSimpleAsset(filename, 'music', PATHS.music);+ return entry ? [entry] : [];+}+/*** Build the catalog bundle (`{ ingredients, refs }`) that piggy-backs on a* universe record push. Catalog data lives in Postgres only — on a non-Postgres@@ -1774,6 +1862,12 @@ export async function applyIncomingPush(payload) {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 });}// Apply the bundled collection (if any) — same LWW + union-of-items@@ -1997,6 +2091,18 @@ async function classifyLocalRecord(recordKind, recordId) {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';+ }return 'missing';}@@ -2006,6 +2112,7 @@ const ASSET_KIND_TO_URL_PREFIX = Object.freeze({image: '/data/images','image-ref': '/data/image-refs',video: '/data/videos',+ music: '/data/music',});const ASSET_PULL_TIMEOUT_MS = 60000;@@ -2262,7 +2369,7 @@ export async function collectSubscriptionsForUpdate(recordKind, recordId) {// mediaCollections.js's emitRecordUpdated('mediaCollection', …) inert, so// collection edits would only reach peers via initial subscribe / manual// force-push, never on subsequent edits.- if (recordKind === 'universe' || recordKind === 'series' || recordKind === 'mediaCollection' || recordKind === 'author') {+ if (PEER_SUBSCRIBABLE_KINDS.includes(recordKind)) {return listPeerSubscriptions({ recordKind, recordId });}if (recordKind === 'issue') {diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 29ebd77f4d..ed1a385752 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -249,12 +249,12 @@ afterEach(async () => {describe('peerSync', () => {describe('PEER_SUBSCRIBABLE_KINDS', () => {- it('is exactly [universe, series, mediaCollection, author]', () => {+ it('is exactly [universe, series, mediaCollection, author, artist, album, track]', () => {// Exact equality (not toContain) so an accidental add/remove/reorder is// caught — this list is canonical and its order can affect iteration// elsewhere (e.g. syncNow's per-kind backfill). Issues piggyback on series// subscriptions; direct issue subs are intentionally rejected (Stage 2).- expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author']);+ expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track']);});});diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.jsindex 324af6198d..0a1f7d9743 100644--- a/server/services/sharing/tombstoneGc.js+++ b/server/services/sharing/tombstoneGc.js@@ -31,6 +31,9 @@ import { pruneTombstonedSeries, listSeries } from '../pipeline/series.js';import { pruneTombstonedIssues, listIssueIds } from '../pipeline/issues.js';import { pruneTombstonedCollections, listCollections } from '../mediaCollections.js';import { pruneTombstonedAuthors, listAuthorIds } from '../authors/index.js';+import { pruneTombstonedArtists, listArtistIds } from '../artists/index.js';+import { pruneTombstonedAlbums, listAlbumIds } from '../albums/index.js';+import { pruneTombstonedTracks, listTrackIds } from '../tracks/index.js';import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';@@ -48,6 +51,9 @@ const LIVE_ID_LISTERS = Object.freeze({issue: () => listIssueIds(),mediaCollection: async () => (await listCollections()).map((r) => r.id),author: () => listAuthorIds(),+ artist: () => listArtistIds(),+ album: () => listAlbumIds(),+ track: () => listTrackIds(),});// Each peer-subscribable kind's UNCAPPED id source INCLUDING tombstones —@@ -62,6 +68,9 @@ const ALL_ID_LISTERS = Object.freeze({series: async () => (await listSeries({ includeDeleted: true })).map((r) => r.id),mediaCollection: async () => (await listCollections({ includeDeleted: true })).map((r) => r.id),author: () => listAuthorIds({ includeDeleted: true }),+ artist: () => listArtistIds({ includeDeleted: true }),+ album: () => listAlbumIds({ includeDeleted: true }),+ track: () => listTrackIds({ includeDeleted: true }),});// Build a kind-aware id-membership resolver for ONE sweep: lazily list each@@ -216,8 +225,17 @@ async function loadState() {return { peers, subs };}-function refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff, authorCutoff) {+function refusedFromCutoffs(cutoffs) {const refused = [];+ const {+ universeCutoff,+ seriesCutoff,+ collectionCutoff,+ authorCutoff,+ artistCutoff,+ albumCutoff,+ trackCutoff,+ } = cutoffs;if (universeCutoff === null) refused.push('universe');// Issue tombstones ride series pushes — refused exactly when series is.if (seriesCutoff === null) {@@ -229,6 +247,9 @@ function refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff, auth// 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');return refused;}@@ -245,19 +266,33 @@ function refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff, auth*/export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } = {}) {const { peers, subs } = await loadState();- const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff] = await Promise.all([+ const [+ universeCutoff,+ seriesCutoff,+ collectionCutoff,+ authorCutoff,+ artistCutoff,+ albumCutoff,+ trackCutoff,+ ] = await Promise.all([cutoffForKind('universe', { peers, subs, now, graceMs }),cutoffForKind('series', { peers, subs, now, graceMs }),cutoffForKind('mediaCollection', { peers, subs, now, graceMs }),cutoffForKind('author', { peers, subs, now, graceMs }),+ cutoffForKind('artist', { peers, subs, now, graceMs }),+ cutoffForKind('album', { peers, subs, now, graceMs }),+ cutoffForKind('track', { peers, subs, now, graceMs }),]);const issueCutoff = seriesCutoff;- const [u, s, i, c, a] = await Promise.all([+ const [u, s, i, c, a, ar, al, t] = await Promise.all([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),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),]);// Backstop AFTER the tombstone prunes: the prune paths already evict a freshly// hard-deleted record's base hash, so this sweep mops up only keys that@@ -279,9 +314,12 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =issues: i.pruned,collections: c.pruned,authors: a.pruned,+ artists: ar.pruned,+ albums: al.pruned,+ tracks: t.pruned,orphanBaseHashes: orphan.pruned,orphanSubscriptions: orphanSubs.pruned,- refused: refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff, authorCutoff),+ refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff }),};}@@ -290,13 +328,16 @@ 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] = await Promise.all([+ const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff] = await Promise.all([cutoffForKind('universe', { peers, subs, now, graceMs: 0 }),cutoffForKind('series', { peers, subs, now, graceMs: 0 }),cutoffForKind('mediaCollection', { peers, subs, now, graceMs: 0 }),cutoffForKind('author', { peers, subs, now, graceMs: 0 }),+ cutoffForKind('artist', { peers, subs, now, graceMs: 0 }),+ cutoffForKind('album', { peers, subs, now, graceMs: 0 }),+ cutoffForKind('track', { peers, subs, now, graceMs: 0 }),]);- return { refused: refusedFromCutoffs(universeCutoff, seriesCutoff, collectionCutoff, authorCutoff) };+ return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff }) };}export const TOMBSTONE_GRACE_MS = GRACE_MS;diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.jsindex 40fb6ca78b..fa7fa97684 100644--- a/server/services/sharing/tombstoneGc.test.js+++ b/server/services/sharing/tombstoneGc.test.js@@ -1,6 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-// All four downstream surfaces are mocked so we can drive the math without+// All downstream surfaces are mocked so we can drive the math without// touching real state files. The point of these tests is the cutoff policy// (grace + min-ack), not the pure-mechanical prune helpers — those are// covered by their own service tests.@@ -24,6 +24,18 @@ vi.mock('../authors/index.js', () => ({pruneTombstonedAuthors: vi.fn().mockResolvedValue({ pruned: 0 }),listAuthorIds: vi.fn().mockResolvedValue([]),}));+vi.mock('../artists/index.js', () => ({+ pruneTombstonedArtists: vi.fn().mockResolvedValue({ pruned: 0 }),+ listArtistIds: vi.fn().mockResolvedValue([]),+}));+vi.mock('../albums/index.js', () => ({+ pruneTombstonedAlbums: vi.fn().mockResolvedValue({ pruned: 0 }),+ listAlbumIds: vi.fn().mockResolvedValue([]),+}));+vi.mock('../tracks/index.js', () => ({+ pruneTombstonedTracks: vi.fn().mockResolvedValue({ pruned: 0 }),+ listTrackIds: vi.fn().mockResolvedValue([]),+}));vi.mock('../../lib/conflictJournal.js', () => ({pruneOrphanedBaseHashes: vi.fn().mockResolvedValue({ pruned: 0 }),}));@@ -48,6 +60,9 @@ import { pruneTombstonedSeries, listSeries } from '../pipeline/series.js';import { pruneTombstonedIssues, listIssueIds } from '../pipeline/issues.js';import { pruneTombstonedCollections, listCollections } from '../mediaCollections.js';import { pruneTombstonedAuthors, listAuthorIds } from '../authors/index.js';+import { pruneTombstonedArtists, listArtistIds } from '../artists/index.js';+import { pruneTombstonedAlbums, listAlbumIds } from '../albums/index.js';+import { pruneTombstonedTracks, listTrackIds } from '../tracks/index.js';import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';import { getMinAckAcrossPeers } from './peerTombstoneCursors.js';@@ -94,13 +109,17 @@ describe('TOMBSTONE_GRACE_MS', () => {});describe('sweepTombstones — no peers subscribed', () => {- it('uses now-GRACE as the cutoff for all four kinds when nobody is subscribed', async () => {+ it('uses now-GRACE as the cutoff for all kinds when nobody is subscribed', async () => {await sweepTombstones({ now: NOW });const expectedCutoff = NOW - TOMBSTONE_GRACE_MS + 1;expect(pruneTombstonedUniverses).toHaveBeenCalledWith(expectedCutoff);expect(pruneTombstonedSeries).toHaveBeenCalledWith(expectedCutoff);expect(pruneTombstonedIssues).toHaveBeenCalledWith(expectedCutoff);expect(pruneTombstonedCollections).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedAuthors).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedArtists).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedAlbums).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedTracks).toHaveBeenCalledWith(expectedCutoff);});});@@ -134,6 +153,10 @@ describe('sweepTombstones — orphaned base-hash sweep', () => {listSeries.mockResolvedValue([{ id: 's-live' }]);listIssueIds.mockResolvedValue(['i-live']); // already ids, uncappedlistCollections.mockResolvedValue([{ id: 'c-live' }]);+ listAuthorIds.mockResolvedValue(['auth-live']);+ listArtistIds.mockResolvedValue(['artist-live']);+ listAlbumIds.mockResolvedValue(['album-live']);+ listTrackIds.mockResolvedValue(['track-live']);// Capture the resolver the sweep hands to pruneOrphanedBaseHashes and drive// it directly — this is the real makeBaseHashKeyResolver closure.let resolver;@@ -142,13 +165,32 @@ describe('sweepTombstones — orphaned base-hash sweep', () => {expect(await resolver('universe', 'u-live')).toBe(true);expect(await resolver('universe', 'u-gone')).toBe(false);+ expect(await resolver('series', 's-live')).toBe(true);+ expect(await resolver('series', 's-gone')).toBe(false);expect(await resolver('issue', 'i-live')).toBe(true);+ expect(await resolver('issue', 'i-gone')).toBe(false);+ expect(await resolver('mediaCollection', 'c-live')).toBe(true);expect(await resolver('mediaCollection', 'c-gone')).toBe(false);+ expect(await resolver('author', 'auth-live')).toBe(true);+ expect(await resolver('author', 'auth-gone')).toBe(false);+ expect(await resolver('artist', 'artist-live')).toBe(true);+ expect(await resolver('artist', 'artist-gone')).toBe(false);+ expect(await resolver('album', 'album-live')).toBe(true);+ expect(await resolver('album', 'album-gone')).toBe(false);+ expect(await resolver('track', 'track-live')).toBe(true);+ expect(await resolver('track', 'track-gone')).toBe(false);// Unknown kind is always kept and never triggers a listing.expect(await resolver('brain', 'whatever')).toBe(true);// A second probe of an already-listed kind reuses the cached id-set —// listUniverses is called exactly once across both universe probes.expect(listUniverses).toHaveBeenCalledTimes(1);+ expect(listSeries).toHaveBeenCalledTimes(1);+ expect(listIssueIds).toHaveBeenCalledTimes(1);+ expect(listCollections).toHaveBeenCalledTimes(1);+ expect(listAuthorIds).toHaveBeenCalledTimes(1);+ expect(listArtistIds).toHaveBeenCalledTimes(1);+ expect(listAlbumIds).toHaveBeenCalledTimes(1);+ expect(listTrackIds).toHaveBeenCalledTimes(1);});});@@ -192,6 +234,10 @@ describe('sweepTombstones — orphaned peer-subscription sweep', () => {listUniverses.mockResolvedValue([{ id: 'u-live' }, { id: 'u-tomb', deleted: true }]);listSeries.mockResolvedValue([{ id: 's-live' }]);listCollections.mockResolvedValue([{ id: 'c-live' }]);+ listAuthorIds.mockResolvedValue(['auth-live']);+ listArtistIds.mockResolvedValue(['artist-live']);+ listAlbumIds.mockResolvedValue(['album-live']);+ listTrackIds.mockResolvedValue(['track-live']);let resolver;pruneOrphanedPeerSubscriptions.mockImplementationOnce(async (fn) => { resolver = fn; return { pruned: 0, removed: [] }; });await sweepTombstones({ now: NOW });@@ -200,7 +246,17 @@ describe('sweepTombstones — orphaned peer-subscription sweep', () => {expect(await resolver('universe', 'u-tomb')).toBe(true); // tombstoned → keptexpect(await resolver('universe', 'u-gone')).toBe(false); // dir gone → orphanexpect(await resolver('series', 's-live')).toBe(true);+ expect(await resolver('series', 's-gone')).toBe(false);+ expect(await resolver('mediaCollection', 'c-live')).toBe(true);expect(await resolver('mediaCollection', 'c-gone')).toBe(false);+ expect(await resolver('author', 'auth-live')).toBe(true);+ expect(await resolver('author', 'auth-gone')).toBe(false);+ expect(await resolver('artist', 'artist-live')).toBe(true);+ expect(await resolver('artist', 'artist-gone')).toBe(false);+ expect(await resolver('album', 'album-live')).toBe(true);+ expect(await resolver('album', 'album-gone')).toBe(false);+ expect(await resolver('track', 'track-live')).toBe(true);+ expect(await resolver('track', 'track-gone')).toBe(false);// Unknown kind (issues are never directly subscribed) is always kept and// never triggers a listing.expect(await resolver('issue', 'i-whatever')).toBe(true);@@ -343,8 +399,23 @@ describe('sweepTombstones — return shape', () => {pruneTombstonedIssues.mockResolvedValueOnce({ pruned: 5 });pruneTombstonedCollections.mockResolvedValueOnce({ pruned: 3 });pruneTombstonedAuthors.mockResolvedValueOnce({ pruned: 1 });+ pruneTombstonedArtists.mockResolvedValueOnce({ pruned: 4 });+ pruneTombstonedAlbums.mockResolvedValueOnce({ pruned: 6 });+ pruneTombstonedTracks.mockResolvedValueOnce({ pruned: 7 });const result = await sweepTombstones({ now: NOW });- expect(result).toEqual({ universes: 2, series: 0, issues: 5, collections: 3, authors: 1, orphanBaseHashes: 0, orphanSubscriptions: 0, refused: [] });+ expect(result).toEqual({+ universes: 2,+ series: 0,+ issues: 5,+ collections: 3,+ authors: 1,+ artists: 4,+ albums: 6,+ tracks: 7,+ orphanBaseHashes: 0,+ orphanSubscriptions: 0,+ refused: [],+ });});it('lists kinds whose cutoff was null in `refused` so the manual-trigger UI can explain why nothing pruned', async () => {@@ -528,6 +599,10 @@ describe('getSweepStatus — dry-run for UI button gating', () => {expect(pruneTombstonedSeries).not.toHaveBeenCalled();expect(pruneTombstonedIssues).not.toHaveBeenCalled();expect(pruneTombstonedCollections).not.toHaveBeenCalled();+ expect(pruneTombstonedAuthors).not.toHaveBeenCalled();+ expect(pruneTombstonedArtists).not.toHaveBeenCalled();+ expect(pruneTombstonedAlbums).not.toHaveBeenCalled();+ expect(pruneTombstonedTracks).not.toHaveBeenCalled();});it('returns an empty refused list when every kind has an ack horizon', async () => {diff --git a/server/services/tracks/db.js b/server/services/tracks/db.jsindex a348cb93ce..3354d6f473 100644--- a/server/services/tracks/db.js+++ b/server/services/tracks/db.js@@ -102,8 +102,7 @@ export async function deleteTrack(id) {/*** Merge an incoming batch of track records from a peer (per-record push). LWW on* `updatedAt` (tombstone-aware) via the shared `mergeTrackRecord` decision.- * Federation-ready, but the track kind is not yet registered in peerSync — see- * issue #1502. Returns `{ applied, count }`.+ * Peer-sync merge entry point. Returns `{ applied, count }`.*/export async function mergeTracksFromSync(remoteTracks, { source = { via: 'sync', peerId: null } } = {}) {if (!Array.isArray(remoteTracks)) return { applied: false, count: 0 };diff --git a/server/services/tracks/file.test.js b/server/services/tracks/file.test.jsindex e88c3d4794..b940ba5de6 100644--- a/server/services/tracks/file.test.js+++ b/server/services/tracks/file.test.js@@ -1,9 +1,9 @@/*** Track file-backend store — CRUD + LWW merge outcomes.*- * Covers the CRUD round-trip + `mergeTracksFromSync` LWW outcomes. Conflict-- * journal side effects are NOT asserted (track kind not yet registered in- * syncWire/peerSync — deferred, local-only; see issue #1502). tmpdir-backed.+ * Covers the CRUD round-trip + `mergeTracksFromSync` LWW outcomes plus the sync+ * side effects that make federation safe: base-hash seeding and conflict+ * journaling before overwrite. tmpdir-backed.*/import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';@@ -19,13 +19,17 @@ vi.mock('../../lib/fileUtils.js', async (importOriginal) => {});const file = await import('./file.js');+const cj = await import('../../lib/conflictJournal.js');function reset() {rmSync(join(TEST_DATA_ROOT, 'tracks.json'), { force: true });rmSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true, force: true });rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });+ cj.__resetBaseHashCacheForTests();}+const journalEntries = () => cj.conflictJournalStore().loadAll();+const track = (id, extra = {}) => ({id, title: id, albumId: '', artistId: '', artist: '', lyrics: '', prompt: '',engine: '', modelId: '', durationSec: null, audioFilename: '',@@ -67,4 +71,40 @@ describe('tracks file backend — mergeTracksFromSync (LWW outcomes)', () => {expect(await file.pruneTombstonedTracks(Date.parse('2030-01-01T00:00:00.000Z'))).toEqual({ pruned: 1 });expect(await file.getTrack('track-dead', { includeDeleted: true })).toBeNull();});++ it('seeds the base hash on first insert of a remote track', async () => {+ const remote = track('track-2', { prompt: 'inserted' });+ expect(await cj.getSyncBaseHash('track', 'track-2')).toBeNull();+ await file.mergeTracksFromSync([remote]);+ expect(await cj.getSyncBaseHash('track', 'track-2'))+ .toBe(cj.contentHashForRecord('track', remote));+ });++ it('journals the losing local track on true 3-way divergence', async () => {+ const local = track('track-3', { prompt: 'local prompt', updatedAt: '2026-02-01T00:00:00.000Z' });+ await file.mergeTracksFromSync([local]);+ const base = track('track-3', { prompt: 'common prompt', updatedAt: '2026-01-01T00:00:00.000Z' });+ await cj.setSyncBaseHash('track', 'track-3', cj.contentHashForRecord('track', base));++ const remoteWinner = track('track-3', { prompt: 'remote prompt', updatedAt: '2026-03-01T00:00:00.000Z' });+ await file.mergeTracksFromSync([remoteWinner], { source: { via: 'peer-push', peerId: 'peer-A' } });++ const entry = (await journalEntries()).find((e) => e.recordKind === 'track' && e.recordId === 'track-3');+ expect(entry).toBeTruthy();+ expect(entry.source.peerId).toBe('peer-A');+ expect(entry.localSnapshot.prompt).toBe('local prompt');+ expect(entry.remoteSnapshot.prompt).toBe('remote prompt');+ expect((await file.getTrack('track-3')).prompt).toBe('remote prompt');+ expect(await cj.getSyncBaseHash('track', 'track-3'))+ .toBe(cj.contentHashForRecord('track', remoteWinner));+ });++ it('pruneTombstonedTracks evicts the base hash for a hard-pruned tombstone', async () => {+ await file.mergeTracksFromSync([+ track('track-dead-base', { deleted: true, deletedAt: '2020-01-01T00:00:00.000Z', updatedAt: '2020-01-01T00:00:00.000Z' }),+ ]);+ expect(await cj.getSyncBaseHash('track', 'track-dead-base')).not.toBeNull();+ await file.pruneTombstonedTracks(Date.parse('2030-01-01T00:00:00.000Z'));+ expect(await cj.getSyncBaseHash('track', 'track-dead-base')).toBeNull();+ });});diff --git a/server/services/tracks/index.js b/server/services/tracks/index.jsindex 08b69f612b..431ef7bdc5 100644--- a/server/services/tracks/index.js+++ b/server/services/tracks/index.js@@ -6,9 +6,8 @@* - PostgreSQL (db.js) for normal installs.* - File (file.js) only via MEMORY_BACKEND=file or NODE_ENV=test.*- * The recordEvents emits are kept so the store is federation-ready, but the- * track record kind is NOT yet registered in peerSync, so they are no-ops —- * tracks are local-only until cross-peer sync is wired (see issue #1502).+ * The recordEvents emits feed the per-record peer-sync pipeline, so tracks+ * federate when peers enable the Tracks sync category.*/import { checkHealth, ensureSchema } from '../../lib/db.js';diff --git a/server/services/tracks/logic.js b/server/services/tracks/logic.jsindex 7d4c9b7a55..5aea3b77ef 100644--- a/server/services/tracks/logic.js+++ b/server/services/tracks/logic.js@@ -24,7 +24,9 @@* Tracks are `db-primary` (PostgreSQL `tracks` table). The audio bytes live in* the shared music library (services/pipeline/musicLibrary.js, `data/music/`);* a track stores only the filename pointer. The storage layer is federation-- * ready, but cross-peer sync is not wired yet — see issue #1502 (local-only).+ * ready and federates across peers via the per-record peer-sync pipeline+ * (`record kind: track`, sync category: tracks). Audio bytes ride the asset+ * manifest as `music` assets.*/import { compareNewerWins } from '../../lib/lwwTimestamp.js';@@ -90,7 +92,7 @@ export function sanitizeTrack(raw) {/*** The bare music-library filename for a track's audio (already a basename), or* null when no audio is attached. Tracks store the filename directly (not a- * URL), so this is mostly an existence/trim guard for the future asset pipeline.+ * URL), so this is mostly an existence/trim guard for the asset pipeline.*/export function trackAudioFilename(audioFilename) {const name = trimTo(audioFilename, AUDIO_FILENAME_MAX);