Skip to content

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

feat: stamp media-collection provenance server-side with a source field (#3311)

[._.]/ Adam Eivy5c44c7035dad
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 2b868feb37..2b2016298b 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -122,3 +122,7 @@
## Creative Director
- **[issue-3287] The developer smoke test no longer leads the Creative Director action bar.** `Run smoke test` sat in the leading position of a four-button header where the eye lands first, named a mechanism rather than an outcome, and consumed one of the seven interactive elements that fit above the fold on a phone — despite spending real render time on every click. It now lives behind a "…" menu beside `Model defaults`, reads `Render a 6s test clip` so the cost is legible before you commit, and asks for an inline confirmation naming what it will spend. The header bar reads `New directive` · `Model defaults` · `New project`.
+
+## Media Collections
+
+- **[issue-3311] A collection now records who created it instead of the grid guessing from its name.** The "auto-generated" ordering and badge shipped in #3283 reverse-engineered provenance on the client from four independent clues — a name prefix, an `Auto-…` description, a `uc-`/`sc-` id, or a universe/series link — so every new machine-created bucket quietly sorted as if you had made it yourself until someone remembered to extend that list. Collections are now stamped `auto` or `user` when they are created, existing ones were classified once by a migration, and the old clue-matching only runs for a record a peer on an older version has not stamped yet.
diff --git a/client/src/lib/mediaCollectionList.js b/client/src/lib/mediaCollectionList.js
index fb298a087a..d61a0e43e1 100644
--- a/client/src/lib/mediaCollectionList.js
+++ b/client/src/lib/mediaCollectionList.js
@@ -15,7 +15,12 @@ import { tokenizeQuery, matchHaystack } from './mediaSearch.js';
// make, paired with the badge label the card renders above the title instead
// of inside it — otherwise every auto-generated card shows the same clipped
// prefix and the trailing project name/date that tells them apart is what gets
-// cut. Keep in sync with the server-side creators: `universeCollectionNameFor`
+// cut. This list drives PRESENTATION (the badge) plus the provenance fallback
+// for records an older peer sent without a `source` stamp — the classification
+// itself comes from `collection.source` now (#3311), so a new auto-creator only
+// has to stamp `source: 'auto'` server-side, not extend this list (it should
+// still add its prefix here if it wants the badge). Keep in sync with the
+// server-side creators: `universeCollectionNameFor`
// / `seriesCollectionNameFor` in `server/services/mediaCollections.js`,
// `server/services/creativeDirector/projects{DB,File}.js`, and
// `server/services/writersRoom/local.js`.
@@ -59,14 +64,26 @@ export function splitCollectionName(name) {
/**
* True when a collection was created by an automated flow rather than by the
- * user. Any one of the four independent markers is sufficient — an install can
- * hold records from before a given marker existed, so this must not require
- * all of them to agree.
+ * user.
+ *
+ * The server stamps provenance at mint time (`source: 'auto' | 'user'`, #3311)
+ * and migration 220 backfilled existing records, so the stamp is authoritative
+ * whenever it is present — a new auto-creator no longer has to remember to
+ * extend a client-side list.
+ *
+ * An ABSENT `source` is a third state, NOT a synonym for `'user'`: the record
+ * came from a federated peer still running a PortOS that predates the field (or
+ * was restored from a pre-migration backup). Those fall back to the marker
+ * heuristic below, where any ONE of the four independent markers is sufficient
+ * — an install can hold records from before a given marker existed, so this
+ * must not require all of them to agree.
* @param {object} collection
* @returns {boolean}
*/
export function isAutoCollection(collection) {
if (!collection || collection.synthetic) return false;
+ if (collection.source === 'auto') return true;
+ if (collection.source === 'user') return false;
if (splitCollectionName(collection.name).badge) return true;
const description = typeof collection.description === 'string' ? collection.description : '';
if (AUTO_DESCRIPTION_PREFIXES.some((p) => description.startsWith(p))) return true;
diff --git a/client/src/lib/mediaCollectionList.test.js b/client/src/lib/mediaCollectionList.test.js
index c3ed2c88bb..9ab8ba39f8 100644
--- a/client/src/lib/mediaCollectionList.test.js
+++ b/client/src/lib/mediaCollectionList.test.js
@@ -64,6 +64,25 @@ describe('isAutoCollection', () => {
expect(isAutoCollection(unsorted)).toBe(false);
expect(isAutoCollection(null)).toBe(false);
});
+
+ it('prefers the server-stamped source over the markers in both directions', () => {
+ // source:'auto' classifies a record no marker would have caught — the whole
+ // point of stamping provenance server-side (#3311).
+ expect(isAutoCollection({ id: 'x', name: 'Nightly Renders', source: 'auto' })).toBe(true);
+ // source:'user' wins over a name that merely looks auto-generated.
+ expect(isAutoCollection({ id: 'x', name: 'Universe: My Own Bucket', source: 'user' })).toBe(false);
+ expect(isAutoCollection({ id: 'x', name: 'Foo', universeId: 'u1', source: 'user' })).toBe(false);
+ // Synthetic still short-circuits ahead of any stamp.
+ expect(isAutoCollection({ ...unsorted, source: 'auto' })).toBe(false);
+ });
+
+ it('falls back to the markers when a peer sends no source at all', () => {
+ // An older peer strips the field; absent must NOT read as 'user'.
+ expect(isAutoCollection({ id: 'uc-universe-1', name: 'Universe: Example' })).toBe(true);
+ expect(isAutoCollection({ id: 'x', name: 'Concept Art', source: undefined })).toBe(false);
+ // A garbage value is not a stamp either — fall through to the markers.
+ expect(isAutoCollection({ id: 'x', name: 'Writers Room: The Deep', source: 'nonsense' })).toBe(true);
+ });
});
describe('collectionItemCount', () => {
diff --git a/scripts/migrations/220-backfill-media-collection-source.js b/scripts/migrations/220-backfill-media-collection-source.js
new file mode 100644
index 0000000000..c89cb163dc
--- /dev/null
+++ b/scripts/migrations/220-backfill-media-collection-source.js
@@ -0,0 +1,138 @@
+/**
+ * Migration 220 — backfill `source: 'auto'` on media collections that a machine
+ * flow created before the field existed (#3311).
+ *
+ * Background:
+ * Every Creative Director project, Writers Room work, and universe/series
+ * render bucket auto-files itself as a media collection. Until #3311 nothing
+ * recorded that fact, so the grid reverse-engineered it on the CLIENT from
+ * four independent markers — a name prefix, an `Auto-…` description, a
+ * `uc-`/`sc-` id, or a universe/series link. Every new auto-creator silently
+ * regressed the ordering until someone remembered to extend that list.
+ *
+ * `server/services/mediaCollections.js` now stamps `source` at mint time.
+ * This migration performs the one-time classification of records already on
+ * disk, using the SAME four markers, so the client heuristic stops being
+ * load-bearing for anything this install already had.
+ *
+ * What it writes:
+ * `source: 'auto'` on each live record matching a marker and carrying no
+ * `source` yet. Nothing else — in particular `updatedAt` is deliberately NOT
+ * bumped: this is a derived classification, not a user edit, and advancing
+ * the LWW clock would make every collection look freshly edited to peers and
+ * out-race real remote edits. `source` is not part of the conflict journal's
+ * scalar projection either, so no base hashes churn.
+ *
+ * Deliberately NOT written:
+ * - `source: 'user'` on non-matching records. The client treats an ABSENT
+ * stamp as "fall back to the marker heuristic", which returns false for
+ * exactly these records — identical behavior with no extra writes, and no
+ * risk of freezing a misclassification.
+ * - Tombstones (`deleted: true`). `deleteCollection` clears the owner links
+ * and items; nothing renders a tombstone, and rewriting one only adds sync
+ * noise.
+ *
+ * Cross-install: `source` is additive and rides the wire's `.passthrough()`
+ * record schema, so no `schemaVersions` bump is needed. Peers upgrade and run
+ * this independently; because the markers are deterministic, two peers classify
+ * the same record identically, and `mergeMediaCollectionsFromSync` keeps a stamp
+ * sticky rather than letting an older peer's unstamped copy erase it.
+ *
+ * The legacy monolithic `data/media-collections.json` is not read — migration
+ * 059 split it into `data/media-collections/<id>/index.json` and runs first.
+ *
+ * Idempotent: a record that already carries a `source` is skipped, so a second
+ * pass writes nothing.
+ */
+
+import { readdir, readFile, writeFile, rename } from 'fs/promises';
+import { join } from 'path';
+
+// Frozen snapshot of the markers as of #3311. Kept INLINE rather than imported
+// from `client/src/lib/mediaCollectionList.js` / `services/mediaCollections.js`
+// on purpose: a migration is a point-in-time transform and must not shift if
+// those lists later evolve.
+const AUTO_NAME_PREFIXES = ['Creative Director: ', 'Writers Room: ', 'Universe: ', 'Series: '];
+const AUTO_DESCRIPTION_PREFIXES = ['Auto-created for project ', 'Auto-generated images for '];
+const AUTO_ID_PREFIXES = ['uc-', 'sc-'];
+
+// The name check requires a non-empty remainder (`splitCollectionName` only
+// yields a badge when the title survives the prefix), while the description
+// check is a bare prefix match — mirroring the two client predicates exactly so
+// this migration and the fallback heuristic can never disagree on a record.
+const hasAutoName = (value) =>
+ typeof value === 'string' && AUTO_NAME_PREFIXES.some((p) => value.startsWith(p) && value.length > p.length);
+const hasAutoDescription = (value) =>
+ typeof value === 'string' && AUTO_DESCRIPTION_PREFIXES.some((p) => value.startsWith(p));
+
+/**
+ * True when a record carries any marker of machine creation. Mirrors
+ * `isAutoCollection` in `client/src/lib/mediaCollectionList.js` — ANY one
+ * marker suffices, because an install can hold records from before a given
+ * marker existed.
+ * @param {object} record
+ * @returns {boolean}
+ */
+export function isAutoCreated(record) {
+ if (!record || typeof record !== 'object') return false;
+ if (hasAutoName(record.name)) return true;
+ if (hasAutoDescription(record.description)) return true;
+ if (typeof record.id === 'string' && AUTO_ID_PREFIXES.some((p) => record.id.startsWith(p))) return true;
+ return Boolean(record.universeId || record.seriesId);
+}
+
+/**
+ * Decide the new record for one on-disk collection. Returns `null` when the
+ * record should be left exactly as it is (already stamped, tombstoned, or no
+ * marker matched).
+ * @param {object} record
+ * @returns {object|null}
+ */
+export function stampAutoSource(record) {
+ if (!record || typeof record !== 'object') return null;
+ if (record.source === 'auto' || record.source === 'user') return null;
+ if (record.deleted === true) return null;
+ if (!isAutoCreated(record)) return null;
+ return { ...record, source: 'auto' };
+}
+
+const readJson = async (abs) => {
+ const raw = await readFile(abs, 'utf-8').catch((err) => { if (err.code === 'ENOENT') return null; throw err; });
+ if (raw == null) return null;
+ try { return JSON.parse(raw); } catch { return null; }
+};
+
+const writeJsonAtomic = async (abs, value) => {
+ const tmp = `${abs}.tmp-220`;
+ await writeFile(tmp, JSON.stringify(value, null, 2) + '\n');
+ await rename(tmp, abs);
+};
+
+export default {
+ async up({ rootDir }) {
+ const typeDir = join(rootDir, 'data', 'media-collections');
+ const entries = await readdir(typeDir, { withFileTypes: true })
+ .catch((err) => { if (err.code === 'ENOENT') return null; throw err; });
+ if (entries === null) {
+ console.log('📦 migration 220: no data/media-collections dir — fresh install, no-op');
+ return { ok: true, reason: 'no-collections' };
+ }
+
+ let stamped = 0;
+ let scanned = 0;
+ for (const entry of entries) {
+ if (!entry.isDirectory()) continue; // skips the type-level index.json
+ const recordPath = join(typeDir, entry.name, 'index.json');
+ const record = await readJson(recordPath);
+ if (!record) continue; // missing or unparseable — leave it for the store to drop
+ scanned += 1;
+ const next = stampAutoSource(record);
+ if (!next) continue;
+ await writeJsonAtomic(recordPath, next);
+ stamped += 1;
+ }
+
+ console.log(`📦 migration 220: stamped source:auto on ${stamped} of ${scanned} media collection(s)`);
+ return { ok: true, reason: stamped ? 'migrated' : 'nothing-to-stamp', stamped, scanned };
+ },
+};
diff --git a/scripts/migrations/220-backfill-media-collection-source.test.js b/scripts/migrations/220-backfill-media-collection-source.test.js
new file mode 100644
index 0000000000..20107728ed
--- /dev/null
+++ b/scripts/migrations/220-backfill-media-collection-source.test.js
@@ -0,0 +1,106 @@
+/**
+ * Migration 220 — backfill `source: 'auto'` on machine-created media
+ * collections (#3311). Lays down one record per marker the classifier honors
+ * plus the four records it must leave alone (user-made, already stamped,
+ * tombstoned, unparseable) and asserts exactly the auto ones gain the stamp —
+ * with `updatedAt` untouched, since a derived classification must not advance
+ * the LWW clock.
+ */
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync } from 'fs';
+import { mkdir, writeFile, readFile } from 'fs/promises';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import migration, { isAutoCreated, stampAutoSource } from './220-backfill-media-collection-source.js';
+
+let ROOT;
+const typeDir = () => join(ROOT, 'data', 'media-collections');
+
+const STAMP = '2026-01-01T00:00:00.000Z';
+
+async function writeRecord(id, patch) {
+ await mkdir(join(typeDir(), id), { recursive: true });
+ await writeFile(join(typeDir(), id, 'index.json'), JSON.stringify({
+ id,
+ name: 'Concept Art',
+ description: '',
+ coverKey: null,
+ universeId: null,
+ seriesId: null,
+ items: [],
+ createdAt: STAMP,
+ updatedAt: STAMP,
+ deleted: false,
+ deletedAt: null,
+ ...patch,
+ }, null, 2));
+}
+
+const readRecord = async (id) => JSON.parse(await readFile(join(typeDir(), id, 'index.json'), 'utf-8'));
+
+beforeEach(async () => {
+ ROOT = mkdtempSync(join(tmpdir(), 'migration-220-'));
+ await mkdir(typeDir(), { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(ROOT, { recursive: true, force: true });
+});
+
+describe('migration 220 — backfill media collection source', () => {
+ it('stamps every auto marker and leaves user-made, stamped, and tombstoned records alone', async () => {
+ await writeRecord('cd-1', { name: 'Creative Director: Example Project' });
+ await writeRecord('wr-1', { name: 'Writers Room: Example Work' });
+ await writeRecord('desc-1', { description: 'Auto-created for project abc' });
+ await writeRecord('desc-2', { description: 'Auto-generated images for "Example Work"' });
+ await writeRecord('uc-universe-1', { name: 'Universe: Example Universe', universeId: 'universe-1' });
+ await writeRecord('sc-series-1', { name: 'Series: Example Series', seriesId: 'series-1' });
+ await writeRecord('linked-legacy', { name: 'Renamed Bucket', universeId: 'universe-2' });
+ // Left alone:
+ await writeRecord('user-1', {});
+ await writeRecord('user-2', { source: 'user', name: 'Universe: Named Like An Auto One' });
+ await writeRecord('already-auto', { source: 'auto', name: 'Creative Director: Example Project' });
+ await writeRecord('tombstone-1', { name: 'Universe: Deleted One', deleted: true, deletedAt: STAMP });
+ // Unparseable record — skipped without failing the run.
+ await mkdir(join(typeDir(), 'broken-1'), { recursive: true });
+ await writeFile(join(typeDir(), 'broken-1', 'index.json'), '{ not json');
+ // The type-level index is a FILE, not a record dir — must not be touched.
+ await writeFile(join(typeDir(), 'index.json'), JSON.stringify({ schemaVersion: 1, type: 'mediaCollections' }));
+
+ const result = await migration.up({ rootDir: ROOT });
+ expect(result).toMatchObject({ ok: true, reason: 'migrated', stamped: 7 });
+
+ for (const id of ['cd-1', 'wr-1', 'desc-1', 'desc-2', 'uc-universe-1', 'sc-series-1', 'linked-legacy']) {
+ const rec = await readRecord(id);
+ expect(rec.source, id).toBe('auto');
+ // A derived classification must not look like a user edit to a peer.
+ expect(rec.updatedAt, id).toBe(STAMP);
+ }
+ expect((await readRecord('user-1')).source).toBeUndefined();
+ expect((await readRecord('user-2')).source).toBe('user');
+ expect((await readRecord('already-auto')).source).toBe('auto');
+ expect((await readRecord('tombstone-1')).source).toBeUndefined();
+ expect(JSON.parse(await readFile(join(typeDir(), 'index.json'), 'utf-8')).schemaVersion).toBe(1);
+ });
+
+ it('is idempotent — a second pass stamps nothing', async () => {
+ await writeRecord('uc-universe-1', { name: 'Universe: Example Universe', universeId: 'universe-1' });
+ expect((await migration.up({ rootDir: ROOT })).stamped).toBe(1);
+ const second = await migration.up({ rootDir: ROOT });
+ expect(second).toMatchObject({ reason: 'nothing-to-stamp', stamped: 0, scanned: 1 });
+ });
+
+ it('no-ops on a fresh install with no media-collections dir', async () => {
+ rmSync(typeDir(), { recursive: true, force: true });
+ expect(await migration.up({ rootDir: ROOT })).toMatchObject({ ok: true, reason: 'no-collections' });
+ });
+
+ it('mirrors the client heuristic on prefix-only names and non-record input', () => {
+ // A bare prefix with no title yields no badge client-side, so it is not a marker.
+ expect(isAutoCreated({ id: 'x', name: 'Universe: ' })).toBe(false);
+ expect(isAutoCreated({ id: 'x', name: 'Universe: Example' })).toBe(true);
+ expect(isAutoCreated(null)).toBe(false);
+ expect(stampAutoSource('nope')).toBe(null);
+ });
+});
diff --git a/server/services/creativeDirector/projectsDB.js b/server/services/creativeDirector/projectsDB.js
index 918de4d4e7..21ce611d25 100644
--- a/server/services/creativeDirector/projectsDB.js
+++ b/server/services/creativeDirector/projectsDB.js
@@ -124,7 +124,7 @@ export async function listProjectIds({ includeDeleted = false } = {}) {
export async function createProject(input) {
const id = `cd-${randomUUID()}`;
const now = new Date().toISOString();
- const collection = await createCollection({ name: `Creative Director: ${input.name}`, description: `Auto-created for project ${id}` });
+ const collection = await createCollection({ name: `Creative Director: ${input.name}`, description: `Auto-created for project ${id}`, source: 'auto' });
const project = buildProjectRecord(input, { id, now, collectionId: collection.id });
await persist(query, project);
console.log(`🎬 Created Creative Director project: ${id} (${input.name})`);
diff --git a/server/services/creativeDirector/projectsFile.js b/server/services/creativeDirector/projectsFile.js
index fb9324519f..a5f22498cc 100644
--- a/server/services/creativeDirector/projectsFile.js
+++ b/server/services/creativeDirector/projectsFile.js
@@ -74,7 +74,7 @@ export async function createProject(input) {
const now = new Date().toISOString();
// Auto-create a media collection scoped to this project. All segment renders
// + the final stitched output land in here.
- const collection = await createCollection({ name: `Creative Director: ${input.name}`, description: `Auto-created for project ${id}` });
+ const collection = await createCollection({ name: `Creative Director: ${input.name}`, description: `Auto-created for project ${id}`, source: 'auto' });
const project = buildProjectRecord(input, { id, now, collectionId: collection.id });
const all = await loadAll();
all.push(project);
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index 3af406a7ca..76c103bb0d 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -111,6 +111,24 @@ const sanitizeItem = (raw) => {
const UNIVERSE_ID_MAX = 80;
const SERIES_ID_MAX = 80;
+// Provenance stamp (#3311). `'auto'` = minted by a machine flow (Creative
+// Director project, Writers Room work, universe/series render bucket);
+// `'user'` = the person created it through the API. The grid uses it to sort
+// auto-generated empties last and to badge the card.
+//
+// **Absent is a THIRD state, not a synonym for `'user'`.** A record written
+// before this field shipped, or received from a peer still running an older
+// PortOS, carries no stamp at all — the client falls back to its marker
+// 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`), which also keeps unstamped records
+// byte-identical on the wire for peers that never learn about the field.
+// `scripts/migrations/220-backfill-media-collection-source.js` backfills
+// `'auto'` on existing local records so the heuristic stops being load-bearing
+// for anything this install already had.
+const COLLECTION_SOURCES = Object.freeze(['auto', 'user']);
+const sanitizeSource = (raw) => (COLLECTION_SOURCES.includes(raw) ? raw : null);
+
const sanitizeCollection = (raw) => {
if (!raw || typeof raw !== 'object') return null;
// Reject ids the store can't persist (path-segment allowlist) so a peer-
@@ -162,7 +180,21 @@ const sanitizeCollection = (raw) => {
// happened at or after the last edit, so createdAt would make the tombstone
// look far older than it is and skew LWW merges + the GC cutoff window.
const deletedAt = deleted && typeof raw.deletedAt === 'string' ? raw.deletedAt : (deleted ? updatedAt : null);
- return { id: raw.id, name, description, coverKey, universeId, seriesId, items, createdAt, updatedAt, deleted, deletedAt };
+ const source = sanitizeSource(raw.source);
+ return {
+ id: raw.id,
+ name,
+ description,
+ coverKey,
+ universeId,
+ seriesId,
+ ...(source ? { source } : {}),
+ items,
+ createdAt,
+ updatedAt,
+ deleted,
+ deletedAt,
+ };
};
// Storage-layout (type-level) schema version stamped on
@@ -223,7 +255,11 @@ const announceNewCollection = (id) => {
autoSubscribeRecordToAllPeers('mediaCollection', id).catch(() => {});
};
-export async function createCollection({ name, description = '' }) {
+// `source` defaults to 'user' because the HTTP POST route is the only caller
+// that doesn't pass it — a person clicking "New collection". Machine flows
+// (Creative Director, Writers Room) pass `source: 'auto'` explicitly. The route
+// schema doesn't accept `source`, so a client can't claim either stamp.
+export async function createCollection({ name, description = '', source = 'user' }) {
// Service-layer guards mirror sanitizeCollection so a direct caller
// (tests, future internal usage) can't persist a record that the next
// listCollections() read would silently drop.
@@ -231,6 +267,9 @@ export async function createCollection({ name, description = '' }) {
if (!trimmedName || trimmedName.length > NAME_MAX_LENGTH) {
throw makeErr('Collection name is required (1..' + NAME_MAX_LENGTH + ' chars)', ERR_VALIDATION);
}
+ if (!COLLECTION_SOURCES.includes(source)) {
+ throw makeErr(`source must be one of ${COLLECTION_SOURCES.join('|')}`, ERR_VALIDATION);
+ }
const trimmedDescription = typeof description === 'string'
? description.trim().slice(0, DESCRIPTION_MAX_LENGTH)
: '';
@@ -242,6 +281,7 @@ export async function createCollection({ name, description = '' }) {
name: trimmedName,
description: trimmedDescription,
coverKey: null,
+ source,
items: [],
createdAt: now,
updatedAt: now,
@@ -265,6 +305,11 @@ export async function createCollection({ name, description = '' }) {
// The legacy `universeId` parameter remains for callers that need the
// best-effort backfill of an unlinked legacy bucket, but new code should
// prefer the universeId-first helper.
+//
+// Records this mints are stamped `source: 'auto'` (#3311) like the other
+// provisioners: reaching this helper means a script or hook asked for a bucket,
+// which is not the same as a person creating one in the UI (that path is
+// `createCollection`, which defaults to `'user'`).
export async function findOrCreateCollectionByName({ name, description = '', universeId = null }) {
const trimmed = typeof name === 'string' ? name.trim() : '';
if (!trimmed || trimmed.length > NAME_MAX_LENGTH) {
@@ -332,6 +377,8 @@ export async function findOrCreateCollectionByName({ name, description = '', uni
description: trimmedDescription,
coverKey: null,
universeId: normalizedUniverseId,
+ // Programmatic provisioner — see the docstring above (#3311).
+ source: 'auto',
items: [],
createdAt: now,
updatedAt: now,
@@ -475,6 +522,8 @@ export async function findOrCreateUniverseCollection({ universeId, universeName,
description: trimmedDescription,
coverKey: null,
universeId: normalizedUniverseId,
+ // Machine-provisioned render bucket — never a user-made collection (#3311).
+ source: 'auto',
items: [],
createdAt: now,
updatedAt: now,
@@ -531,6 +580,8 @@ export async function findOrCreateSeriesCollection({ seriesId, seriesName, descr
description: trimmedDescription,
coverKey: null,
seriesId: normalizedSeriesId,
+ // Machine-provisioned render bucket — never a user-made collection (#3311).
+ source: 'auto',
items: [],
createdAt: now,
updatedAt: now,
@@ -1007,10 +1058,23 @@ export async function mergeMediaCollectionsFromSync(remoteCollections, { source
const coverKey = !scalarDeleted && scalarSource.coverKey && presentKeys.has(scalarSource.coverKey)
? scalarSource.coverKey
: null;
+ // Provenance is STICKY, not LWW (#3311). A peer running a PortOS that
+ // predates the field strips `source` from the wire entirely, so a
+ // remote-wins scalar overwrite must not erase a stamp we already hold —
+ // that would silently demote a machine-made bucket back to the client's
+ // marker heuristic (or worse, to "user-made") on every sync from an older
+ // machine. Prefer the LWW winner's stamp, then whichever side has one,
+ // then leave it unstamped. `source` is excluded from the conflict
+ // journal's scalar projection (MEDIA_COLLECTION_SCALAR_FIELDS), so
+ // adopting it here can't churn base hashes.
+ const nextSource = sanitizeSource(scalarSource.source)
+ || sanitizeSource(local.source)
+ || sanitizeSource(sanitized.source);
const next = {
...local,
name: scalarSource.name,
description: scalarSource.description,
+ ...(nextSource ? { source: nextSource } : {}),
coverKey: scalarDeleted ? null : coverKey,
universeId: scalarDeleted ? null : scalarSource.universeId,
seriesId: scalarDeleted ? null : scalarSource.seriesId,
diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.js
index 2db29344a0..3fbd55d53b 100644
--- a/server/services/mediaCollections.test.js
+++ b/server/services/mediaCollections.test.js
@@ -1758,3 +1758,107 @@ describe('pruneTombstonedCollections', () => {
expect(await svc.pruneTombstonedCollections(Infinity)).toEqual({ pruned: 0 });
});
});
+
+// Provenance stamp (#3311) — the server records whether a collection was minted
+// by a machine flow or by the user, so the grid stops reverse-engineering it
+// from name/description/id markers.
+describe('source provenance', () => {
+ it('createCollection defaults to user and accepts an explicit auto stamp', async () => {
+ const byUser = await svc.createCollection({ name: 'Concept Art' });
+ expect(byUser.source).toBe('user');
+ expect((await readStored(byUser.id)).source).toBe('user');
+
+ const byMachine = await svc.createCollection({ name: 'Writers Room: Example Work', source: 'auto' });
+ expect(byMachine.source).toBe('auto');
+ expect((await svc.getCollection(byMachine.id)).source).toBe('auto');
+ });
+
+ it('createCollection rejects an unknown source rather than persisting it', async () => {
+ await expect(svc.createCollection({ name: 'A', source: 'robot' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ expect(await svc.listCollections()).toEqual([]);
+ });
+
+ it('stamps auto on the universe- and series-linked render buckets', async () => {
+ const uc = await svc.findOrCreateUniverseCollection({ universeId: 'universe-1', universeName: 'Example Universe' });
+ const sc = await svc.findOrCreateSeriesCollection({ seriesId: 'series-1', seriesName: 'Example Series' });
+ expect(uc.source).toBe('auto');
+ expect(sc.source).toBe('auto');
+ });
+
+ it('leaves a legacy record UNSTAMPED rather than defaulting it to user', async () => {
+ // Absent is a third state: the client falls back to its marker heuristic for
+ // these. Defaulting them to 'user' here would mislabel every pre-#3311
+ // auto-created bucket as user-made on a peer that never ran migration 220.
+ await seedState({
+ collections: [{
+ id: 'c-legacy', name: 'Universe: Example Universe', description: '', coverKey: null,
+ universeId: null, seriesId: null, items: [],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z',
+ }],
+ });
+ const [legacy] = await svc.listCollections();
+ expect('source' in legacy).toBe(false);
+ });
+
+ it('drops a garbage stamp instead of persisting it', async () => {
+ await seedState({
+ collections: [{
+ id: 'c-bogus', name: 'Bogus', description: '', coverKey: null, source: 'robot',
+ universeId: null, seriesId: null, items: [],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z',
+ }],
+ });
+ expect('source' in (await svc.getCollection('c-bogus'))).toBe(false);
+ });
+
+ 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');
+ await svc.deleteCollection(c.id);
+ expect((await svc.getCollection(c.id, { includeDeleted: true })).source).toBe('auto');
+ });
+
+ it('merge keeps a local stamp when an older peer sends the record without one', async () => {
+ // The cross-install case: a peer predating #3311 strips `source` from the
+ // wire. Its (newer) scalars win LWW, but they must not erase provenance.
+ const c = await svc.createCollection({ name: 'Writers Room: Example Work', source: 'auto' });
+ const result = await svc.mergeMediaCollectionsFromSync([{
+ id: c.id, name: 'Writers Room: Renamed', description: '', coverKey: null,
+ universeId: null, seriesId: null, items: [],
+ createdAt: c.createdAt, updatedAt: '2099-01-01T00:00:00Z',
+ }]);
+ expect(result.applied).toBe(true);
+ const merged = await svc.getCollection(c.id);
+ expect(merged.name).toBe('Writers Room: Renamed');
+ expect(merged.source).toBe('auto');
+ });
+
+ it('merge adopts a remote stamp onto an unstamped local record even when local wins LWW', async () => {
+ await seedState({
+ collections: [{
+ id: 'c-legacy', name: 'Universe: Example Universe', description: '', coverKey: null,
+ universeId: null, seriesId: null, items: [],
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2099-01-01T00:00:00Z',
+ }],
+ });
+ const result = await svc.mergeMediaCollectionsFromSync([{
+ id: 'c-legacy', name: 'Universe: Stale Name', description: '', coverKey: null,
+ universeId: null, seriesId: null, items: [], source: 'auto',
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z',
+ }]);
+ expect(result.applied).toBe(true);
+ const merged = await svc.getCollection('c-legacy');
+ expect(merged.name).toBe('Universe: Example Universe'); // local still wins LWW
+ expect(merged.source).toBe('auto');
+ });
+
+ it('merge inserts a new remote record carrying its stamp', async () => {
+ await svc.mergeMediaCollectionsFromSync([{
+ id: 'c-remote', name: 'Concept Art', description: '', coverKey: null,
+ universeId: null, seriesId: null, items: [], source: 'user',
+ createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z',
+ }]);
+ expect((await svc.getCollection('c-remote')).source).toBe('user');
+ });
+});
diff --git a/server/services/writersRoom/local.js b/server/services/writersRoom/local.js
index 80f3b3bae4..958d58cc62 100644
--- a/server/services/writersRoom/local.js
+++ b/server/services/writersRoom/local.js
@@ -210,6 +210,9 @@ export async function ensureWorkMediaCollection(workId) {
const collection = await createCollection({
name: `Writers Room: ${manifest.title}`.slice(0, 80),
description: `Auto-generated images for "${manifest.title}"`,
+ // Machine-provisioned bucket — this work's renders land here without the
+ // user ever asking for a collection (#3311).
+ source: 'auto',
});
await saveManifest(workId, { ...manifest, mediaCollectionId: collection.id, updatedAt: nowIso() });
return collection;