Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: bind bundled companion records in a peer push to the pushed record (#12427)
[._.]/ Adam Eivy9dffd1fe9709
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 3dc0cc2f62..718d3d17ee 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -3268,7 +3268,7 @@ describe('peerSync', () => {it('routes a bundled linkedCollection through mergeMediaCollectionsFromSync', async () => {const linkedCollection = {- id: 'col-1', name: 'Universe: U', items: [+ id: 'col-1', name: 'Universe: U', universeId: 'u1', items: [{ kind: 'image', ref: 'a.png', addedAt: '2026-05-22T01:00:00Z' },],};@@ -3518,6 +3518,124 @@ describe('peerSync', () => {}});+ describe('bundled companion records are bound to the pushed record (#12427)', () => {+ const live = { deleted: false, deletedAt: null };+ const SOURCE = { source: { via: 'peer-push', peerId: 'peer-a' } };++ it.each([+ ['universe', 'universeId', 'u1'],+ ['series', 'seriesId', 'ser-1'],+ ])('merges a %s linkedCollection only when its %s is the pushed record', async (kind, field, id) => {+ const bound = { id: 'col-bound', name: 'Bound', [field]: id, items: [] };+ await applyIncomingPush({ kind, record: { id, ...live }, linkedCollection: bound, assetManifest: [], sourceInstanceId: 'peer-a' });+ expect(mergeMediaCollectionsFromSync).toHaveBeenCalledWith([bound], SOURCE);++ vi.mocked(mergeMediaCollectionsFromSync).mockClear();+ const foreign = { id: 'col-foreign', name: 'Other', [field]: 'someone-else', items: [] };+ const unlinked = { id: 'col-unlinked', name: 'Loose', items: [] };+ for (const linkedCollection of [foreign, unlinked]) {+ await applyIncomingPush({ kind, record: { id, ...live }, linkedCollection, assetManifest: [], sourceInstanceId: 'peer-a' });+ }+ expect(mergeMediaCollectionsFromSync).not.toHaveBeenCalled();+ });++ it('refuses a linkedCollection that would re-parent a local collection linked elsewhere', async () => {+ vi.mocked(getCollection).mockResolvedValue({ id: 'col-victim', universeId: 'u-other', items: [] });+ await applyIncomingPush({+ kind: 'universe', record: { id: 'u1', ...live },+ linkedCollection: { id: 'col-victim', universeId: 'u1', items: [] },+ assetManifest: [], sourceInstanceId: 'peer-a',+ });+ expect(mergeMediaCollectionsFromSync).not.toHaveBeenCalled();++ vi.mocked(getCollection).mockResolvedValue({ id: 'col-mine', universeId: 'u1', items: [] });+ await applyIncomingPush({+ kind: 'universe', record: { id: 'u1', ...live },+ linkedCollection: { id: 'col-mine', universeId: 'u1', items: [] },+ assetManifest: [], sourceInstanceId: 'peer-a',+ });+ expect(mergeMediaCollectionsFromSync).toHaveBeenCalledTimes(1);+ });++ it('refuses a linkedCollection on a kind that has no collection parent', async () => {+ await applyIncomingPush({+ kind: 'musicVideoProject', record: { id: 'mv-1', ...live },+ linkedCollection: { id: 'col-1', universeId: 'mv-1', items: [] },+ assetManifest: [], sourceInstanceId: 'peer-a',+ });+ expect(mergeMediaCollectionsFromSync).not.toHaveBeenCalled();+ });++ it('upserts only catalog refs for the pushed record and the ingredients those refs name', async () => {+ vi.mocked(getBackendName).mockReturnValue('postgres');+ const ref = (ingredientId, refId, refKind = 'universe') => ({ ingredientId, refKind, refId, role: 'canon-character', createdAt: '2026-01-02T00:00:00Z' });+ const ing = (id) => ({ id, type: 'character', name: id, updatedAt: '2026-01-02T00:00:00Z' });+ await applyIncomingPush({+ kind: 'universe', record: { id: 'u1', ...live }, assetManifest: [],+ catalogBundle: {+ ingredients: [ing('cat-mine'), ing('cat-other'), ing('cat-unreferenced')],+ refs: [ref('cat-mine', 'u1'), ref('cat-other', 'u-other'), ref('cat-mine', 'u1', 'series')],+ },+ sourceInstanceId: 'peer-a', portosMeta: { schemaVersions: { ...PORTOS_SCHEMA_VERSIONS } },+ });+ expect(applyCatalogRemoteChanges).toHaveBeenCalledTimes(1);+ const arg = vi.mocked(applyCatalogRemoteChanges).mock.calls[0][0];+ expect(arg.refs).toEqual([ref('cat-mine', 'u1')]);+ expect(arg.ingredients).toEqual([ing('cat-mine')]);+ });++ it('applies nothing when no catalog ref belongs to the pushed record', async () => {+ vi.mocked(getBackendName).mockReturnValue('postgres');+ await applyIncomingPush({+ kind: 'universe', record: { id: 'u1', ...live }, assetManifest: [],+ catalogBundle: {+ ingredients: [{ id: 'cat-other', type: 'character', name: 'Other', updatedAt: '2026-01-02T00:00:00Z' }],+ refs: [{ ingredientId: 'cat-other', refKind: 'universe', refId: 'u-other', role: 'canon-character', createdAt: '2026-01-02T00:00:00Z' }],+ },+ sourceInstanceId: 'peer-a', portosMeta: { schemaVersions: { ...PORTOS_SCHEMA_VERSIONS } },+ });+ expect(applyCatalogRemoteChanges).not.toHaveBeenCalled();+ });++ it('does not let a music-video push overwrite a local track the local project does not link', async () => {+ const linkedTrack = { id: 'track-victim', title: 'Hijacked', ...live };+ const push = (record) => applyIncomingPush({+ kind: 'musicVideoProject', record: { ...record, ...live }, linkedTrack, assetManifest: [], sourceInstanceId: 'peer-a',+ });+ vi.mocked(getTrack).mockResolvedValue({ id: 'track-victim', title: 'Mine' });++ // No local copy of the project, or one linking a different track: refused.+ await push({ id: 'mv-new', trackId: 'track-victim' });+ vi.mocked(getMusicVideoProject).mockResolvedValue({ id: 'mv-old', trackId: 'track-mine' });+ await push({ id: 'mv-old', trackId: 'track-victim' });+ expect(mergeTracksFromSync).not.toHaveBeenCalled();++ // The local copy already links this track: the update merges.+ vi.mocked(getMusicVideoProject).mockResolvedValue({ id: 'mv-linked', trackId: 'track-victim' });+ await push({ id: 'mv-linked', trackId: 'track-victim' });+ expect(mergeTracksFromSync).toHaveBeenCalledWith([linkedTrack], SOURCE);+ });++ it('merges a linkedTrack that does not exist locally yet', async () => {+ const linkedTrack = { id: 'track-new', title: 'Fresh', ...live };+ await applyIncomingPush({+ kind: 'musicVideoProject', record: { id: 'mv-fresh', trackId: 'track-new', ...live },+ linkedTrack, assetManifest: [], sourceInstanceId: 'peer-a',+ });+ expect(mergeTracksFromSync).toHaveBeenCalledWith([linkedTrack], SOURCE);+ });++ it('withholds the sender hash when the local track lookup fails, without failing the push', async () => {+ vi.mocked(getTrack).mockRejectedValue(new Error('db unavailable'));+ const result = await applyIncomingPush({+ kind: 'musicVideoProject', record: { id: 'mv-err', trackId: 'track-new', ...live },+ linkedTrack: { id: 'track-new', title: 'Fresh', ...live }, assetManifest: [], sourceInstanceId: 'peer-a',+ });+ expect(mergeTracksFromSync).not.toHaveBeenCalled();+ expect(result.trackSyncPending).toBe(true);+ });+ });+it('dispatches series pushes through mergeSeriesFromSync AND mergeIssuesFromSync for bundled issues', async () => {await applyIncomingPush({kind: 'series',@@ -3586,7 +3704,7 @@ describe('peerSync', () => {{ id: 'issue-2', seriesId: 'ser-1', ephemeral: true, imageRefs: ['private.png'] },{ id: 'issue-3', seriesId: 'ser-1', deleted: true, imageRefs: ['deleted.png'] },],- linkedCollection: { id: 'collection-1', items: [{ kind: 'video', ref: 'collection-clip' }] },+ linkedCollection: { id: 'collection-1', seriesId: 'ser-1', items: [{ kind: 'video', ref: 'collection-clip' }] },assetManifest: manifest, sourceInstanceId: 'peer-a',});expect(result.missingAssets).toEqual(manifest.slice(0, 3));@@ -4076,7 +4194,11 @@ describe('peerSync', () => {kind: 'universe',record: { id: 'u1', name: 'Foo', deleted: false, deletedAt: null },assetManifest: [],- catalogBundle: { ingredients: [], refs: [], relations: [{ fromIngredientId: 'cat-chr-1', toIngredientId: 'cat-chr-2', kind: 'ally-of', updatedAt: '2026-01-02T00:00:00Z' }] },+ catalogBundle: {+ ingredients: [],+ refs: [{ ingredientId: 'cat-chr-1', refKind: 'universe', refId: 'u1', role: 'canon-character', createdAt: '2026-01-02T00:00:00Z' }],+ relations: [{ fromIngredientId: 'cat-chr-1', toIngredientId: 'cat-chr-2', kind: 'ally-of', updatedAt: '2026-01-02T00:00:00Z' }],+ },sourceInstanceId: 'peer-a',portosMeta: { schemaVersions: { ...PORTOS_SCHEMA_VERSIONS } },});@@ -4094,6 +4216,7 @@ describe('peerSync', () => {assetManifest: [],catalogBundle: {ingredients: [{ id: 'cat-chr-1', deleted: true, deletedAt: '2026-03-01T00:00:00Z', updatedAt: '2026-03-01T00:00:00Z' }],+ refs: [{ ingredientId: 'cat-chr-1', refKind: 'universe', refId: 'u1', role: 'canon-character', deleted: true, deletedAt: '2026-03-01T00:00:00Z', updatedAt: '2026-03-01T00:00:00Z' }],relations: [{ id: 'cat-rel-1', deleted: true, deletedAt: '2026-03-01T00:00:00Z', updatedAt: '2026-03-01T00:00:00Z' }],},sourceInstanceId: 'peer-a',diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.jsindex 6e63508b5a..28f052b8a2 100644--- a/server/services/sharing/peerSyncReceive.js+++ b/server/services/sharing/peerSyncReceive.js@@ -69,6 +69,75 @@ async function applyCatalogBundle(catalogBundle, portosMeta) {});}+/**+ * Bundled companion records (`linkedCollection`, `catalogBundle`,+ * `linkedTrack`) ride a push admitted for ONE record's category. Without a+ * binding to that record, a peer admitted for `universe` could overwrite+ * media collections, catalog rows or tracks outside the categories the user+ * enabled for it (#12427). Each bundle is kept only when it provably belongs+ * to `record`; an unbound bundle is skipped with one warning and never fails+ * the push (the bundle contract is non-fatal, so older peers that send+ * well-formed bundles are unaffected).+ */+const COLLECTION_PARENT_FIELD = { universe: 'universeId', series: 'seriesId' };++async function bindLinkedCollection({ kind, record, linkedCollection, sourceInstanceId }) {+ if (!isPlainObject(linkedCollection)) return null;+ const parentField = COLLECTION_PARENT_FIELD[kind];+ if (!parentField || linkedCollection[parentField] !== record.id) {+ console.warn(`⚠️ peerSync: skipped unbound linkedCollection from ${sourceInstanceId} — not linked to ${kind} ${record.id}`);+ return null;+ }+ // The merge overwrites the collection's own parent link by id, so a peer that+ // names another collection's id while claiming this record as parent would+ // re-parent it. Refuse when the local collection is linked elsewhere.+ const local = isNonBlankStr(linkedCollection.id)+ ? await RECORD_KINDS.mediaCollection.load(linkedCollection.id).catch(() => null)+ : null;+ const localParentId = local?.universeId || local?.seriesId || null;+ if (localParentId && localParentId !== record.id) {+ console.warn(`⚠️ peerSync: skipped linkedCollection from ${sourceInstanceId} — local collection belongs to another parent`);+ return null;+ }+ return linkedCollection;+}++function bindCatalogBundle({ kind, record, catalogBundle, sourceInstanceId }) {+ if (!isPlainObject(catalogBundle)) return null;+ const rawRefs = Array.isArray(catalogBundle.refs) ? catalogBundle.refs : [];+ const rawIngredients = Array.isArray(catalogBundle.ingredients) ? catalogBundle.ingredients : [];+ const refs = rawRefs.filter((ref) => isPlainObject(ref) && ref.refKind === kind && ref.refId === record.id);+ const named = new Set(refs.map((ref) => ref.ingredientId));+ const ingredients = rawIngredients.filter((ing) => isPlainObject(ing) && named.has(ing.id));+ const dropped = (rawRefs.length - refs.length) + (rawIngredients.length - ingredients.length);+ if (dropped > 0) {+ console.warn(`⚠️ peerSync: dropped ${dropped} catalog bundle rows from ${sourceInstanceId} not bound to ${kind} ${record.id}`);+ }+ return refs.length === 0 && ingredients.length === 0 ? null : { ingredients, refs };+}++// A project may bundle only the track it links, and may not replace a local+// track the local copy of this project does not already link.+async function bindLinkedTrack({ record, linkedTrack, sourceInstanceId, onLookupError }) {+ if (!isPlainObject(linkedTrack) || linkedTrack.id !== record.trackId) return null;+ let localTrack;+ let localProject;+ try {+ [localTrack, localProject] = await Promise.all([+ RECORD_KINDS.track.load(linkedTrack.id),+ RECORD_KINDS.musicVideoProject.load(record.id).catch(() => null),+ ]);+ } catch (err) {+ onLookupError(err);+ return null;+ }+ if (localTrack && localProject?.trackId !== linkedTrack.id) {+ console.warn(`⚠️ peerSync: skipped linkedTrack from ${sourceInstanceId} — local track is not linked by local project ${record.id}`);+ return null;+ }+ return linkedTrack;+}+/*** SCHEMA-VERSION GATE — runs BEFORE any merge so a sender on a newer storage* layout can't corrupt local state. Outside catalog, legacy senders without@@ -193,7 +262,7 @@ export async function applyIncomingPush(payload, authorization) {if (!isPlainObject(payload)) {throw makeErr('payload must be an object', ERR_VALIDATION);}- const { kind, record, issues, linkedCollection, linkedTrack, catalogBundle, manuscriptReview, reverseOutline, assetManifest, draftBodyManifest, bibleManifest, sourceInstanceId, portosMeta } = payload;+ const { kind, record, issues, linkedCollection: pushedCollection, linkedTrack: pushedTrack, catalogBundle: pushedCatalog, manuscriptReview, reverseOutline, assetManifest, draftBodyManifest, bibleManifest, sourceInstanceId, portosMeta } = payload;if (!PEER_SUBSCRIBABLE_KINDS.includes(kind)) {throw makeErr(`unknown kind: ${kind}`, ERR_VALIDATION);}@@ -212,8 +281,10 @@ export async function applyIncomingPush(payload, authorization) {await authorizeIncomingPush(payload, authorization);+ // The gate sees the bundles as pushed: a schema-ahead sender is rejected even+ // when its bundle is later found unbound and skipped.const { senderSchemaVersions } = await assertSchemaVersionGate({- kind, record, issues, linkedCollection, catalogBundle, linkedTrack, portosMeta, sourceInstanceId,+ kind, record, issues, linkedCollection: pushedCollection, catalogBundle: pushedCatalog, linkedTrack: pushedTrack, portosMeta, sourceInstanceId,});// Look up the LOCAL record state BEFORE merging so we can detect the@@ -247,6 +318,20 @@ export async function applyIncomingPush(payload, authorization) {console.log(`⚠️ peerSync: ${key} merge failed: ${err.message}`);pending.add(ENVELOPE_PENDING_KEYS[key]);};+ // Bundles that are not bound to `record` are dropped here (#12427), so every+ // later use (merge, asset diff, host-mode ownership) sees only bound ones.+ // Tombstone and local-ephemeral pushes merge no bundles, so they bind none.+ const bundlesMergeable = !localEphemeral && record.deleted !== true;+ const linkedCollection = bundlesMergeable+ ? await bindLinkedCollection({ kind, record, linkedCollection: pushedCollection, sourceInstanceId })+ : null;+ const catalogBundle = bundlesMergeable+ ? bindCatalogBundle({ kind, record, catalogBundle: pushedCatalog, sourceInstanceId })+ : null;+ // Only a music-video push has a linked track to bundle.+ const linkedTrack = bundlesMergeable && kind === 'musicVideoProject'+ ? await bindLinkedTrack({ record, linkedTrack: pushedTrack, sourceInstanceId, onLookupError: markPending('linkedTrack') })+ : null;// #1922: true only once the bundled linkedTrack merge actually RAN and// succeeded — gates whether `linkedTrack` may contribute to// `ackedDeletesUpTo` below. Stays false on every skip path (mismatched id,