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

fix: keep collection provenance off the sync wire and out of forgeable names (#3311)

[._.]/ Adam Eivy7f327b8475fc
diff --git a/client/src/lib/mediaCollectionList.js b/client/src/lib/mediaCollectionList.js
index d61a0e43e1..88acc2adc7 100644
--- a/client/src/lib/mediaCollectionList.js
+++ b/client/src/lib/mediaCollectionList.js
@@ -71,10 +71,13 @@ export function splitCollectionName(name) {
* 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 ABSENT `source` is a third state, NOT a synonym for `'user'`. The stamp is
+ * local to each install (it is stripped from the sync wire — see
+ * `sanitizeRecordForWire`), so an unstamped record is one this install received
+ * from a peer after its own migration ran, or restored from a pre-migration
+ * backup. Those fall back to the marker heuristic below, which is what
+ * classified every collection before #3311 — so the fallback is never worse
+ * than the old behavior. 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
diff --git a/scripts/migrations/220-backfill-media-collection-source.js b/scripts/migrations/220-backfill-media-collection-source.js
index c89cb163dc..3a1028496f 100644
--- a/scripts/migrations/220-backfill-media-collection-source.js
+++ b/scripts/migrations/220-backfill-media-collection-source.js
@@ -16,8 +16,10 @@
* 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
+ * `source: 'auto'` on each live record matching a non-forgeable marker and
+ * carrying no `source` yet (see the marker note below — a bare name prefix is
+ * deliberately NOT enough, since the create route lets a user pick one).
+ * 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
@@ -32,11 +34,11 @@
* 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.
+ * Cross-install: `source` is LOCAL-ONLY — `sanitizeRecordForWire` strips it, so
+ * no `schemaVersions` bump is needed and no peer's checksum moves. Each peer
+ * upgrades and runs this independently over ITS OWN copy of the shared
+ * collections; because the markers are deterministic, they classify the same
+ * record identically.
*
* The legacy monolithic `data/media-collections.json` is not read — migration
* 059 split it into `data/media-collections/<id>/index.json` and runs first.
@@ -52,31 +54,34 @@ import { join } from 'path';
// 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: '];
+//
+// 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.
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.
+ * True when a record carries a marker of machine creation that a user could not
+ * have produced through the create form. A subset of `isAutoCollection` in
+ * `client/src/lib/mediaCollectionList.js` — see the note above on why the name
+ * prefix is excluded. 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.description === 'string' && AUTO_DESCRIPTION_PREFIXES.some((p) => record.description.startsWith(p))) return true;
if (typeof record.id === 'string' && AUTO_ID_PREFIXES.some((p) => record.id.startsWith(p))) return true;
return Boolean(record.universeId || record.seriesId);
}
diff --git a/scripts/migrations/220-backfill-media-collection-source.test.js b/scripts/migrations/220-backfill-media-collection-source.test.js
index 20107728ed..63f06becc3 100644
--- a/scripts/migrations/220-backfill-media-collection-source.test.js
+++ b/scripts/migrations/220-backfill-media-collection-source.test.js
@@ -49,9 +49,9 @@ afterEach(() => {
});
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' });
+ it('stamps every non-forgeable marker and leaves user-made, stamped, and tombstoned records alone', async () => {
+ await writeRecord('cd-1', { name: 'Creative Director: Example Project', description: 'Auto-created for project cd-1' });
+ await writeRecord('wr-1', { name: 'Writers Room: Example Work', description: 'Auto-generated images for "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' });
@@ -59,9 +59,13 @@ describe('migration 220 — backfill media collection source', () => {
await writeRecord('linked-legacy', { name: 'Renamed Bucket', universeId: 'universe-2' });
// Left alone:
await writeRecord('user-1', {});
+ // A user is free to NAME a collection with an auto-creator's prefix — the
+ // create route reserves nothing — so a bare name match must never freeze a
+ // permanent 'auto' stamp. It keeps flowing through the client fallback.
+ await writeRecord('name-only-1', { name: 'Universe: Notes I Made Myself' });
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 });
+ await writeRecord('tombstone-1', { name: 'Universe: Deleted One', universeId: 'universe-3', 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');
@@ -78,6 +82,7 @@ describe('migration 220 — backfill media collection source', () => {
expect(rec.updatedAt, id).toBe(STAMP);
}
expect((await readRecord('user-1')).source).toBeUndefined();
+ expect((await readRecord('name-only-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();
@@ -96,10 +101,12 @@ describe('migration 220 — backfill media collection source', () => {
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);
+ it('ignores the user-forgeable name prefix and tolerates non-record input', () => {
+ // The create route takes a free name, so a prefix alone proves nothing.
+ expect(isAutoCreated({ id: 'x', name: 'Universe: Example' })).toBe(false);
+ // The same record with a marker the create form cannot produce does qualify.
+ expect(isAutoCreated({ id: 'x', name: 'Universe: Example', universeId: 'u1' })).toBe(true);
+ expect(isAutoCreated({ id: 'x', description: 'Auto-created for project x' })).toBe(true);
expect(isAutoCreated(null)).toBe(false);
expect(stampAutoSource('nope')).toBe(null);
});
diff --git a/server/lib/syncWire.js b/server/lib/syncWire.js
index 5d1bff84b0..16e7f2f704 100644
--- a/server/lib/syncWire.js
+++ b/server/lib/syncWire.js
@@ -184,7 +184,23 @@ export function sanitizeRecordForWire(kind, record) {
// Collections have no `ephemeral` field — unlike universe/series,
// they are always wire-syncable when non-ephemeral (there is no
// collection-level ephemeral flag), so no ephemeral minimization path.
- const { deleted: _d, deletedAt: _da, ...rest } = record;
+ //
+ // `source` (#3311 provenance: 'auto' vs 'user') is LOCAL-ONLY, stripped
+ // here for the same reason as `ephemeral`/`importDraft` above. It drives
+ // the grid's card ordering + badge, not record content, and every install
+ // derives its own: the creators stamp at mint time and migration 220
+ // classifies whatever was already on disk. Emitting it would give an
+ // upgraded peer a permanently different `mediaCollections` checksum from a
+ // not-yet-upgraded one (whose sanitizer drops the unknown field), which
+ // the UI reads as "behind" forever and the 60s snapshot loop re-exchanges
+ // every cycle for a merge that can never converge. The alternative —
+ // bumping `schemaVersions.mediaCollections` — would pause ALL collection
+ // sync between version-mismatched peers over a card-ordering flag. A peer
+ // that receives an unstamped record falls back to the marker heuristic in
+ // `client/src/lib/mediaCollectionList.js`, exactly as it did before #3311.
+ // If provenance ever needs to federate, it needs a schemaVersions bump —
+ // do NOT simply stop stripping it here.
+ const { deleted: _d, deletedAt: _da, source: _source, ...rest } = record;
return { ...rest, ...sanitizeSoftDeleteFields(record) };
}
case 'author':
diff --git a/server/lib/syncWire.test.js b/server/lib/syncWire.test.js
index 9e708dc91e..50cfa70e8e 100644
--- a/server/lib/syncWire.test.js
+++ b/server/lib/syncWire.test.js
@@ -255,6 +255,27 @@ describe('syncWire', () => {
expect(sanitizeRecordForWire('author', { name: 'no id' })).toBeNull();
});
});
+
+ describe('mediaCollection kind', () => {
+ it('strips the local-only provenance stamp so an upgraded peer stays checksum-stable', () => {
+ // #3311: `source` drives the grid's ordering/badge on THIS install only.
+ // A peer that predates the field would sanitize it away, leaving the two
+ // installs permanently checksum-mismatched on the mediaCollections
+ // category — so it must not cross the wire at all.
+ const stamped = { id: 'c1', name: 'Universe: Example', source: 'auto', items: [] };
+ const unstamped = { id: 'c1', name: 'Universe: Example', items: [] };
+ expect(sanitizeRecordForWire('mediaCollection', stamped).source).toBeUndefined();
+ expect(JSON.stringify(sanitizeRecordForWire('mediaCollection', stamped)))
+ .toBe(JSON.stringify(sanitizeRecordForWire('mediaCollection', unstamped)));
+ });
+
+ it('strips the stamp from the snapshot-category projection too', () => {
+ const { data } = sanitizeStateForWire('mediaCollections', {
+ collections: [{ id: 'c1', name: 'Concept Art', source: 'user', items: [] }],
+ });
+ expect(data.collections[0].source).toBeUndefined();
+ });
+ });
});
describe('sanitizeStateForWire', () => {
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index 8d10b98ded..7ba59d65f6 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -554,7 +554,15 @@ async function getMediaCollectionsSnapshot({ exclude } = {}) {
// forever. Sort collections by id (stable, unique) and each collection's
// items by `<kind>:<ref>` (the same key used for set membership in
// `mergeCollectionItems`).
- const canonical = filtered
+ // Project through the SHARED wire sanitizer before canonicalizing, so this
+ // snapshot and the per-record push agree on which fields cross the wire
+ // instead of each deciding for itself (see `sanitizeRecordForWire` — it
+ // normalizes the soft-delete pair to tail position, which service-sanitized
+ // records already satisfy, and drops the local-only `source` provenance stamp
+ // added in #3311 so an upgraded peer's checksum stays byte-stable against a
+ // not-yet-upgraded one).
+ const { data: wire } = sanitizeStateForWire('mediaCollections', { collections: filtered });
+ const canonical = wire.collections
.map((c) => ({
...c,
items: [...(c.items || [])].sort((a, b) => itemKey(a).localeCompare(itemKey(b))),
diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.js
index 76c103bb0d..43ace34cd9 100644
--- a/server/services/mediaCollections.js
+++ b/server/services/mediaCollections.js
@@ -116,16 +116,20 @@ const SERIES_ID_MAX = 80;
// `'user'` = the person created it through the API. The grid uses it to sort
// auto-generated empties last and to badge the card.
//
+// **LOCAL-ONLY.** `sanitizeRecordForWire` strips it, so provenance never
+// crosses to a peer — see the rationale there (an emitted field would leave an
+// upgraded peer permanently checksum-mismatched against an older one, and
+// gating it behind a `schemaVersions` bump would pause all collection sync).
+// Every install derives its own: the creators below stamp at mint time and
+// `scripts/migrations/220-backfill-media-collection-source.js` classifies
+// whatever was already on disk when the install upgraded.
+//
// **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
+// before this field shipped, or received from a peer after this install's
+// migration ran, 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.
+// `sanitizeItem`'s optional `origin`).
const COLLECTION_SOURCES = Object.freeze(['auto', 'user']);
const sanitizeSource = (raw) => (COLLECTION_SOURCES.includes(raw) ? raw : null);
@@ -1058,23 +1062,18 @@ 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);
+ // NOTE — `source` (#3311) is deliberately absent from the scalar list
+ // below. It is a LOCAL-ONLY provenance stamp that `sanitizeRecordForWire`
+ // strips before sending, so a remote record never carries one and a
+ // remote-wins overwrite must not be able to clear ours. The `...local`
+ // spread preserves it; a brand-new record inserted above keeps whatever
+ // the sanitizer accepted (an offline export/import bundle can legitimately
+ // carry it). Do NOT add it to the LWW scalars without also un-stripping it
+ // on the wire — and that needs a schemaVersions bump.
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 3fbd55d53b..7bddaee81e 100644
--- a/server/services/mediaCollections.test.js
+++ b/server/services/mediaCollections.test.js
@@ -1819,9 +1819,10 @@ describe('source provenance', () => {
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.
+ it('merge keeps the local stamp when a peer sends the record without one', async () => {
+ // The cross-install case: `source` never crosses the wire (sanitizeRecordForWire
+ // strips it), so every remote record arrives unstamped. Its (newer) scalars
+ // win LWW, but they must not erase local 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,
@@ -1834,26 +1835,9 @@ describe('source provenance', () => {
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 () => {
+ it('merge inserts a stamp that an offline export/import bundle legitimately carries', async () => {
+ // Peer sync always strips `source`, but the merge also backs the import
+ // path — a record that does arrive stamped is inserted verbatim.
await svc.mergeMediaCollectionsFromSync([{
id: 'c-remote', name: 'Concept Art', description: '', coverKey: null,
universeId: null, seriesId: null, items: [], source: 'user',