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: strip provenance from bundled collection pushes and make the stamp correctable (#3311)
[._.]/ Adam Eivy560c5d90dd64
diff --git a/scripts/migrations/220-backfill-media-collection-source.js b/scripts/migrations/220-backfill-media-collection-source.jsindex 3a1028496f..ba6044da8f 100644--- a/scripts/migrations/220-backfill-media-collection-source.js+++ b/scripts/migrations/220-backfill-media-collection-source.js@@ -58,15 +58,21 @@ import { join } from 'path';// The client heuristic has a FOURTH marker this migration deliberately does not// use: the `Creative Director: ` / `Writers Room: ` / `Universe: ` / `Series: `// NAME prefix. Nothing reserves those prefixes — the create route takes a free-// name — so a user-made collection called `Universe: Notes` matches it, and-// stamping is permanent (a stamped record is skipped on every later pass, and-// there is no API to correct it). Leaving name-only matches unstamped keeps-// them on the client fallback, which classifies them exactly as it does today-// and still re-evaluates if the user renames them. Nothing is lost: every real-// auto-creator also carries one of the markers below — Creative Director and-// Writers Room stamp an `Auto-…` description (the create form takes a name-// only, so a user cannot produce one), and universe/series buckets carry the-// deterministic id and/or the owner link.+// name — so a user-made collection called `Universe: Notes` matches it, and a+// stamped record is skipped on every later pass rather than re-evaluated.+// Leaving name-only matches unstamped keeps them on the client fallback, which+// classifies them exactly as it does today and still re-evaluates if the user+// renames them. Nothing is lost: every real auto-creator also carries one of+// the markers below — Creative Director and Writers Room stamp an `Auto-…`+// description, and universe/series buckets carry the deterministic id and/or+// the owner link.+//+// The description prefixes are far weaker evidence than the id/link markers+// (the POST/PATCH routes do accept a free description), but they are the ONLY+// markers a legacy Creative Director / Writers Room bucket carries — those get+// a random uuid and no owner link. `PATCH /api/media/collections/:id` accepts+// `source`, so the rare user collection described as `Auto-created for project+// …` can be corrected rather than being stuck.const AUTO_DESCRIPTION_PREFIXES = ['Auto-created for project ', 'Auto-generated images for '];const AUTO_ID_PREFIXES = ['uc-', 'sc-'];diff --git a/server/routes/mediaCollections.js b/server/routes/mediaCollections.jsindex 9f9360d484..4c8670f2de 100644--- a/server/routes/mediaCollections.js+++ b/server/routes/mediaCollections.js@@ -2,7 +2,7 @@* GET /api/media/collections → Collection[]* POST /api/media/collections → Collection (body: { name, description? })* GET /api/media/collections/:id → Collection- * PATCH /api/media/collections/:id → Collection (body: { name?, description?, coverKey? })+ * PATCH /api/media/collections/:id → Collection (body: { name?, description?, coverKey?, source? })* DELETE /api/media/collections/:id → { id }* POST /api/media/collections/:id/items → Collection (body: { kind, ref })* POST /api/media/collections/:id/items/bulk → { collection, added, removed }@@ -43,6 +43,12 @@ const patchSchema = z.object({description: descriptionSchema.optional(),// coverKey: null clears it (auto = newest); a string pins a specific item.coverKey: z.union([z.string().trim().min(1).max(svc.REF_MAX_LENGTH + 8), z.null()]).optional(),+ // Provenance override (#3311) — lets the user correct a collection the+ // migration's marker classification stamped wrong. Deliberately absent from+ // `createSchema`: a POST is a person creating a collection, which the service+ // stamps 'user' on its own, so accepting the field there would only let a+ // client mislabel its own new collection.+ source: z.enum(svc.COLLECTION_SOURCES).optional(),}).refine((p) => Object.keys(p).length > 0, { message: 'patch must include at least one field' });const itemSchema = z.object({diff --git a/server/routes/mediaCollections.test.js b/server/routes/mediaCollections.test.jsindex e2ea78a33e..1fd4a589fb 100644--- a/server/routes/mediaCollections.test.js+++ b/server/routes/mediaCollections.test.js@@ -7,6 +7,8 @@ import { errorMiddleware } from '../lib/errorHandler.js';// → response wiring without standing up the real file-backed store.const stubs = {bulkUpdateCollectionItems: vi.fn(),+ updateCollection: vi.fn(async (id, patch) => ({ id, ...patch })),+ createCollection: vi.fn(async (input) => ({ id: 'new', ...input })),};vi.mock('../services/mediaCollections.js', async () => {@@ -14,6 +16,8 @@ vi.mock('../services/mediaCollections.js', async () => {return {...actual,bulkUpdateCollectionItems: (...args) => stubs.bulkUpdateCollectionItems(...args),+ updateCollection: (...args) => stubs.updateCollection(...args),+ createCollection: (...args) => stubs.createCollection(...args),};});@@ -99,3 +103,24 @@ describe('mediaCollections routes — POST /:id/items/bulk', () => {expect(r.status).toBe(409);});});++describe('mediaCollections routes — provenance (#3311)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('passes a valid source through PATCH and rejects an unknown one', async () => {+ const ok = await request(makeApp()).patch('/api/media/collections/c1').send({ source: 'user' });+ expect(ok.status).toBe(200);+ expect(stubs.updateCollection).toHaveBeenCalledWith('c1', { source: 'user' });++ const bad = await request(makeApp()).patch('/api/media/collections/c1').send({ source: 'robot' });+ expect(bad.status).toBe(400);+ });++ it('strips source from a create body so a client cannot claim provenance', async () => {+ await request(makeApp()).post('/api/media/collections').send({ name: 'Concept Art', source: 'auto' });+ // Zod drops the unknown key → the service applies its own 'user' default.+ expect(stubs.createCollection).toHaveBeenCalledWith({ name: 'Concept Art', description: '' });+ });+});diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex 43ace34cd9..f556707875 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -130,7 +130,7 @@ const SERIES_ID_MAX = 80;// heuristic for those rather than mislabeling them user-made. So the sanitizer// OMITS the key entirely rather than defaulting it (same posture as// `sanitizeItem`'s optional `origin`).-const COLLECTION_SOURCES = Object.freeze(['auto', 'user']);+export const COLLECTION_SOURCES = Object.freeze(['auto', 'user']);const sanitizeSource = (raw) => (COLLECTION_SOURCES.includes(raw) ? raw : null);const sanitizeCollection = (raw) => {@@ -688,6 +688,11 @@ export const unlinkCollectionsForUniverse = (universeId) =>export const renameCollectionForUniverse = (universeId, newUniverseName) =>renameOwnerLinked('universeId', universeId, UNIVERSE_ID_MAX, universeCollectionNameFor, newUniverseName);+// The `updateCollection` patch keys that peers can actually observe. Anything+// outside this list is local-only and must not advance `updatedAt` (the LWW+// clock every peer compares against) — see the `source` note below.+const WIRE_VISIBLE_PATCH_FIELDS = ['name', 'description', 'coverKey'];+export async function updateCollection(id, patch) {assertCollectionId(id);const merged = await store().queueRecordWrite(id, async () => {@@ -724,7 +729,19 @@ export async function updateCollection(id, patch) {...('name' in patch ? { name: patch.name } : {}),...('description' in patch ? { description: patch.description } : {}),...('coverKey' in patch ? { coverKey: patch.coverKey } : {}),- updatedAt: new Date().toISOString(),+ // Provenance is correctable (#3311). The migration classifies legacy+ // records from markers a user could in principle have typed themselves+ // (a description starting `Auto-created for project …`), so "the stamp is+ // wrong and I can't fix it" must not be a dead end. Local-only like the+ // rest of the field — this edit never leaves the install.+ ...('source' in patch ? { source: patch.source } : {}),+ // A source-only edit changes nothing a peer can see (the field is+ // stripped from the wire), so it must NOT advance the shared LWW clock —+ // same reasoning as migration 220 leaving `updatedAt` alone. Otherwise+ // correcting a badge locally would out-race a peer's real edit.+ updatedAt: WIRE_VISIBLE_PATCH_FIELDS.some((k) => k in patch)+ ? new Date().toISOString()+ : cur.updatedAt,};await store().saveOneNow(id, merged);return merged;diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.jsindex 7bddaee81e..f745f6ad67 100644--- a/server/services/mediaCollections.test.js+++ b/server/services/mediaCollections.test.js@@ -1812,6 +1812,22 @@ describe('source provenance', () => {expect('source' in (await svc.getCollection('c-bogus'))).toBe(false);});+ it('is correctable via updateCollection WITHOUT advancing the LWW clock', async () => {+ // The migration classifies from markers a user could in principle have+ // typed (an `Auto-…` description), so a wrong stamp must be fixable. And+ // because the field never reaches a peer, fixing it must not bump+ // `updatedAt` — that would out-race a peer's real edit for a change no peer+ // can even see.+ const c = await svc.createCollection({ name: 'Renders', source: 'auto' });+ const fixed = await svc.updateCollection(c.id, { source: 'user' });+ expect(fixed.source).toBe('user');+ expect(fixed.updatedAt).toBe(c.updatedAt);+ // A patch that DOES touch wire-visible state still bumps it.+ const renamed = await svc.updateCollection(c.id, { name: 'Renders 2', source: 'auto' });+ expect(renamed.source).toBe('auto');+ expect(renamed.updatedAt).not.toBe(c.updatedAt);+ });+it('survives an edit and rides through the tombstone', async () => {const c = await svc.createCollection({ name: 'Writers Room: Example Work', source: 'auto' });expect((await svc.updateCollection(c.id, { description: 'edited' })).source).toBe('auto');diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex f05dae9782..8e96b465ff 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -2065,6 +2065,37 @@ describe('peerSync', () => {expect(captured.linkedCollection.items).toHaveLength(1);});+ it('strips the local-only provenance stamp from a bundled linkedCollection', async () => {+ // #3311: `source` is per-install and must not cross the wire in ANY+ // transport. The standalone mediaCollection push goes through+ // sanitizeRecordForWire; the bundled copy has to as well, or the two+ // forms of the same record disagree and an upgraded peer's collection+ // checksum drifts from a not-yet-upgraded one's.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Universe' });+ vi.mocked(findCollectionByUniverseId).mockResolvedValueOnce({+ id: 'col-1',+ name: 'Universe: U',+ description: '',+ coverKey: null,+ universeId: 'u1',+ seriesId: null,+ source: 'auto',+ items: [],+ createdAt: '2026-05-22T00:00:00Z',+ updatedAt: '2026-05-22T01:00:00Z',+ });+ let captured = null;+ vi.mocked(peerFetch).mockImplementation(async (_url, opts) => {+ captured = JSON.parse(opts.body);+ return { ok: true, json: async () => ({}) };+ });+ await pushRecordToPeer({+ id: 's', peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',+ });+ expect(captured.linkedCollection.id).toBe('col-1');+ expect(captured.linkedCollection.source).toBeUndefined();+ });+it('re-pushes when only the linked collection items change (universe record byte-identical)', async () => {vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Universe' });vi.mocked(findCollectionByUniverseId)diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.jsindex 2010c157a7..4e9d15c80b 100644--- a/server/services/sharing/peerSyncPush.js+++ b/server/services/sharing/peerSyncPush.js@@ -630,13 +630,19 @@ export async function buildPushPayload(sub, sourceInstanceId) {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,- ...(linkedCollection ? { linkedCollection } : {}),+ ...(bundledCollection ? { linkedCollection: bundledCollection } : {}),...(catalogBundle ? { catalogBundle } : {}),};}@@ -706,6 +712,8 @@ export async function buildPushPayload(sub, sourceInstanceId) {: 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,@@ -713,7 +721,7 @@ export async function buildPushPayload(sub, sourceInstanceId) {assetManifest,sourceInstanceId,portosMeta,- ...(linkedCollection ? { linkedCollection } : {}),+ ...(bundledCollection ? { linkedCollection: bundledCollection } : {}),...(manuscriptReview && manuscriptReview.comments?.length ? { manuscriptReview } : {}),...(reverseOutline && reverseOutline.status === 'complete' ? { reverseOutline } : {}),};