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
Migrate media collections to per-record collectionStore layout
[._.]/ Adam Eivy12c5769cd9af
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 60962d0f45..b7f0f1c675 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,7 @@## Changed+- **[media-collections-per-record-store] Media collections now persist per-record instead of in one monolithic file.** `data/media-collections.json` is split into `data/media-collections/<id>/index.json` (plus a type-level `index.json` stamping the storage `schemaVersion`) via the shared `createCollectionStore` layout — the same per-record shape universes / series / issues already use. Every collection write (`addItem`, `bulkUpdateCollectionItems`, merges, tombstone GC) now serializes on its own record queue, so high-frequency render-filing no longer rewrites the whole ~200 KB document per image or blocks unrelated collections' writes. Migration `059-split-media-collections.js` performs the one-time split (idempotent, backs the legacy file up as `.bak-059`), the boot-time verifier checks the on-disk version, and the dataSync snapshot watcher tracks the directory so per-record edits still invalidate the checksum cache. The wire sync payload is unchanged, so collections still sync across peers of mixed versions.- **[chrome-canary-followups] Custom Chrome setup writes browser config through the shared atomic writer.** The Canary setup script now uses `server/lib/fileUtils.js#atomicWrite` for browser-config updates, so it gets the same temp-file/rename behavior and Windows fallback as the rest of PortOS config persistence.- **[media-job-store-progress-on-job-record] Render queue rows now hydrate live progress from the job record.** The media job queue now stores `progress` and `statusMsg` on the running job whenever image/video runners emit progress or status events, exposes those fields through `GET /api/media-jobs/:id` and list responses, and preserves them in persisted queue snapshots. The Image / Video render queue uses that snapshot to show a compact progress bar during polling, so non-SSE consumers no longer reset in-flight jobs to 0% until the next live event arrives.- **[shared-bounded-concurrency-mapper] Bounded-concurrency worker pool extracted to a shared helper.** The cursor-based worker-pool idiom that was hand-rolled in `embeddings.js`, `catalogExtraction.js`, and `routes/imageVideoModels.js` is now a single tested `server/lib/mapWithConcurrency.js` (order-preserving, concurrency-bounded), with all three call sites migrated and behavior unchanged.diff --git a/PLAN.md b/PLAN.mdindex fc103bf57c..86d1567708 100644--- a/PLAN.md+++ b/PLAN.md@@ -129,8 +129,13 @@ Surfaced while building the sync-hygiene feature. Consciously scoped out of v1.### Storage scalability — deferred follow-ups (2026-05-26)-- [ ] [media-collections-per-record-store] **Migrate `media-collections.json` to the per-record `createCollectionStore` layout (like universes / issues / series).** Today all collections live in one monolithic `data/media-collections.json`; every `addItem` / `bulkUpdateCollectionItems` rewrites the *entire* file through a single `serializeFileWrite` tail — so high-frequency render-filing serializes unrelated writes and rewrites a ~200 KB doc per image. Convert to `createCollectionStore({ dir: join(PATHS.data,'media-collections'), type: 'mediaCollections', … })`, mirroring migration 034 (`universeBuilder.js`). Cross-install work: needs a `scripts/migrations/0NN-split-media-collections.js`, a storage `schemaVersion` + boot-time `verifySchemaVersion` hook, seed handling, and a careful rewrite of every reader/writer — especially the sync layer (`mergeMediaCollectionsFromSync`, `listCollections({ includeDeleted })`, the push/subscription pipeline in `sharing/peerSync.js`, `pruneTombstonedCollections`).- > ❓ **Question:** Greenlight this now, or defer? It's a large, federation-touching refactor that wants a brainstorm/plan pass before any code. It's independent of any bug (the LWW cascade dup bug was already fixed). My read: defer unless you're hitting real write-amplification pain (lots of auto-collection render-filing) — say the word and I'll start a design doc.+- [x] [media-collections-per-record-store] **Migrated `media-collections.json` to the per-record `createCollectionStore` layout** (migration `059-split-media-collections.js`, boot verifier wired, dataSync watch path → dir, full reader/writer + sync rewrite). Design record: `docs/plans/2026-05-31-media-collections-per-record-store.md`. Follow-ups surfaced in `/simplify` and deferred below.++#### media-collections store — deferred follow-ups (2026-05-31)++- [ ] [makesplitmigration-shared-factory] **Extract a shared `makeSplitMigration` factory into `scripts/migrations/_lib.js`.** The monolithic→per-record split scaffolding (`fileExists` / `readJsonStrict` / `readJsonTolerant` / `writeJson` + the `withFileTypes` already-split scan + the gate1/gate2/recovery/split/stamp/backup body) is now copied verbatim across **four** migrations: `034-split-universe-builder`, `035-split-pipeline-issues`, `036-split-pipeline-series`, `059-split-media-collections`. They differ only in `{ typeDirName, legacyFilename, backupSuffix, typeSchemaVersion, typeLabel, recordsKey, idPattern, buildConfig }` (e.g. `config: { runs }` for universes vs `config: {}` for collections). `_lib.js` already houses cross-migration families (`makePromptReplaceMigration`, layout helpers) — add a split family there and collapse the four to ~15-line config blocks. Pre-existing duplication; 059 was the 4th copy. Own change + test surface, so deferred out of the migration PR.+- [ ] [mediacollections-deterministic-loadone-fastpath] **`findCollectionByUniverseId` / `findCollectionBySeriesId` (and the `findOrCreate*` provisioners) `loadAll()` where a deterministic `loadOne(uc-/sc-<id>)` fast-path would usually hit.** `server/services/mediaCollections.js` — these scan every record by stamp to also catch legacy unconverged collections at random ids. peerSync calls the lookups per outbound push (`peerSync.js:608/1108/1175`), so a `loadOne(linkedCollectionId({...}))`-first / `loadAll`-fallback would cut the warm path to O(1). Modest under single-user load; kept as a faithful scan for now.+- [ ] [mediacollections-parallel-merge-prune] **Parallelize the multi-record loops in `mergeMediaCollectionsFromSync` and `pruneTombstonedCollections`.** Both iterate distinct record ids in a sequential `for await` over `queueRecordWrite` — different ids use different per-record queues, so a bounded `Promise.all` (use the shared bounded-concurrency mapper) would fan out the snapshot-apply batch (`dataSync.js` passes a full collections list) and the GC sweep. Most peer pushes carry a single record so the realized win is the snapshot/GC paths only; low priority.### Browser / Chrome-variant + commands hardening (review candidates, 2026-05-25)diff --git a/docs/plans/2026-05-31-media-collections-per-record-store.md b/docs/plans/2026-05-31-media-collections-per-record-store.mdnew file mode 100644index 0000000000..f5952d59af--- /dev/null+++ b/docs/plans/2026-05-31-media-collections-per-record-store.md@@ -0,0 +1,186 @@+# Migrate media collections to a per-record `createCollectionStore`++PLAN.md item: `[media-collections-per-record-store]`++## Context++Today every media collection lives in one monolithic `data/media-collections.json`+(`{ collections: [...] }`). Every mutator — `addItem`, `bulkUpdateCollectionItems`,+`removeItem`, `mergeMediaCollectionsFromSync`, `pruneTombstonedCollections` — does a+`listCollections (read whole file) → modify → atomicWrite (whole file)` round, all+serialized through a **single** file-level write tail (`serializeFileWrite` in+`server/services/mediaCollections.js:164`).++The pain: high-frequency render-filing (pipeline `coverUniverseFiler`, Universe Builder+completion hook, image-gen auto-file) calls `addItem` constantly, and each call+serializes against every *unrelated* collection's write **and** rewrites the entire+~200 KB document per image. The fix is the same per-record split we already shipped for+universes (migration 034), series, and issues: `createCollectionStore`+(`server/lib/collectionStore.js`), where writes to different record ids run in parallel+and each write touches only one record's file.++This is a federation-touching refactor: the sync layer reads the whole collection list+in several places, so the migration must preserve every reader/writer's behavior while+swapping the storage substrate. The public API of `mediaCollections.js` stays identical —+all 20+ callers (routes, pipeline, importer/exporter, peerSync, dataSync, tombstoneGc)+are untouched.++## Design overview++The change is contained to **five** areas. The service's public surface does not change,+so no caller is modified.++### Target on-disk layout+```+data/media-collections/+├── index.json // { schemaVersion: 1, type: 'mediaCollections', updatedAt, config: {} }+├── <id-1>/index.json // one collection record+└── <id-2>/index.json+```+Collection ids are `randomUUID()`, `uc-<universeId>`, or `sc-<seriesId>` — all match the+store's default `idPattern` (`/^[A-Za-z0-9_-]{1,128}$/`), so no custom pattern is needed.++### Versioning decisions (deliberate)+- **Type-level storage `schemaVersion: 1`** stamped on `data/media-collections/index.json`+ (this is the new collectionStore layout version — distinct from the wire version).+- **Do NOT bump the wire `mediaCollections: 1`** in `server/lib/schemaVersions.js`. The+ wire payload shape (`{ collections: [...] }` snapshot; per-record push of the same+ record shape) is **unchanged** by an on-disk split. Bumping it would needlessly gate+ sync between an upgraded peer and a not-yet-upgraded one. Storage-layout change ≠+ wire-contract change.+- **No record-level `schemaVersion`** field on collections — there is no field-shape+ migration here, only a storage-layout move. `sanitizeCollection` already tolerates the+ existing record shape.++## Step 1 — Rewrite `server/services/mediaCollections.js` persistence layer++Keep `sanitizeItem` / `sanitizeCollection` / all validation / all exported function+signatures **exactly as-is**. Replace only the persistence plumbing.++**Remove:** `statePath`, `DEFAULT_STATE`, the `serializeFileWrite = createFileWriteQueue()`+tail, and `writeAll` (lines ~33, 46, 160-168). Drop the `createFileWriteQueue`,+`readJSONFile`, `atomicWrite` imports that become unused.++**Add** a lazy store getter mirroring `universeBuilder.js:76-98`:+```js+import { createCollectionStore } from '../lib/collectionStore.js';+const TYPE_SCHEMA_VERSION = 1;+let _store = null;+const store = () => {+ const dir = join(PATHS.data, 'media-collections');+ if (_store && _store.dir === dir) return _store;+ _store = createCollectionStore({+ dir, type: 'mediaCollections', schemaVersion: TYPE_SCHEMA_VERSION,+ sanitizeRecord: sanitizeCollection,+ });+ return _store;+};+export const mediaCollectionStore = () => store();+```+(Lazy capture of `PATHS.data` is required — tests swap it via Proxy mock.)++**Rewrite each function to delegate to the store:**++| Function | New implementation |+|---|---|+| `listCollections({includeDeleted})` | `await store().loadAll()` → existing dedupe-by-id + `deleted` filter loop. (`loadAll` already runs `sanitizeRecord`; tombstones come back with `deleted:true`.) |+| `getCollection(id, {includeDeleted})` | `store().loadOne(id)`; throw `NOT_FOUND` if null or (`deleted && !includeDeleted`) — direct per-record load, no full scan |+| `findCollectionByUniverseId` / `findCollectionBySeriesId` | `store().loadOne(linkedCollectionId({...}))` — deterministic id means a direct load replaces the full-list scan |+| `addItem`, `removeItem`, `bulkUpdateCollectionItems`, `updateCollection`, `deleteCollection` (soft) | `store().queueRecordWrite(id, async () => { const cur = await store().loadOne(id); ...modify...; await store().saveOneNow(id, next); return result; })` — soft-delete is a `saveOneNow` of the tombstoned record (`deleted:true`, cleared items), NOT `deleteOne` |+| `createCollection`, `findOrCreate*` | compute id, then `queueRecordWrite(id, …)` → `saveOneNow`. The find-by-name adoption scan uses `loadAll()` first. |+| `renameCollectionForUniverse/Series`, `unlinkCollectionsForUniverse/Series` | `loadAll()` to find matching records, then `queueRecordWrite(id, …)` per matched id |+| `pruneTombstonedCollections(olderThanMs)` (hard delete) | `loadAll({includeDeleted:true})`, for each tombstone older than cutoff `await store().deleteOne(id)`; return `{ pruned }` |+| `mergeMediaCollectionsFromSync(remote)` | for each remote collection, `queueRecordWrite(id, async () => { const local = await store().loadOne(id); ...union-merge items + LWW scalars (existing logic)...; if changed await saveOneNow })`. Preserve the `collectionsEqual` skip-if-unchanged guard per record. |++**Concurrency note (call out in the PR):** the global single-tail queue is replaced by+per-record queues. Same-target writes still serialize — the hot render-filing paths+(`coverUniverseFiler`, importer, Universe Builder hook) all use deterministic+`uc-`/`sc-` ids, so concurrent `addItem`s to the same collection share one queue.+Writes to *different* collections now run in parallel (the win). The only relaxation is+`createCollection` / `findOrCreateCollectionByName`'s check-then-create on a *random*+UUID, which is user-initiated (single human, single-user trust model) — acceptable per+CLAUDE.md's trust model.++**Barrel/README:** `mediaCollections.js` is a service, not in `server/lib`, so no barrel+row is needed. (Confirm it isn't re-exported anywhere that needs updating.)++## Step 2 — Migration `scripts/migrations/059-split-media-collections.js`++Next free number is **059** (highest applied is `058-claude-default-opus-4-8.js`). Mirror+`034-split-universe-builder-to-per-uuid.js` exactly, with the simpler shape (no+cross-record `runs[]` — collections have no type-level config, so `config: {}`):++- `export default { async up({ rootDir }) {...} }`+- **Gate 1:** if `data/media-collections/index.json` already at `schemaVersion >= 1` → no-op.+- **Gate 2:** no legacy `data/media-collections.json` and no `.bak-059` → fresh install;+ stamp `data/media-collections/index.json` `{ schemaVersion:1, type:'mediaCollections',+ updatedAt, config:{} }` and return.+- **Split:** read legacy `{ collections: [...] }`; for each record with a valid id, write+ `data/media-collections/<id>/index.json` (skip ids already split — partial-recovery+ scan like 034:131-146). Validate id against `/^[A-Za-z0-9_-]{1,128}$/`.+- **Stamp type index AFTER all records land** (so a mid-split crash leaves the index+ missing and the next boot re-runs the loop).+- **Back up** legacy file to `media-collections.json.bak-059` via `rename` (don't delete).+- Return `{ ok:true, reason:'split', written, skipped, invalid }`.++Add `scripts/migrations/059-split-media-collections.test.js` mirroring `034`'s test:+assert fresh-install stamp, full split, idempotent re-run, partial-recovery skip, and+backup creation.++## Step 3 — Boot-time schema verifier (`server/index.js`)++- Import `mediaCollectionStore` alongside the other store imports (near line 154).+- Add `mediaCollectionStore()` to the `verifyCollectionVersions([...])` array at+ `server/index.js:213`. Migrations already run (line ~207) before this check.++## Step 4 — dataSync watch invalidation (`server/services/dataSync.js`)++- Line 45: rename `MEDIA_COLLECTIONS_FILE = join(PATHS.data, 'media-collections.json')`+ → `MEDIA_COLLECTIONS_DIR = join(PATHS.data, 'media-collections')`.+- Line 707: update the `mediaCollections:` watch-path array to reference the dir. The+ fingerprint walker already "descends into the dir so per-record edits invalidate"+ (comment at dataSync.js:43-44), so a directory path is the correct shape and makes+ per-record writes invalidate the snapshot checksum cache.++## Step 5 — Seed + test fixtures++- **`data.reference/`:** if a seed `data.reference/media-collections.json` exists, replace+ it with `data.reference/media-collections/index.json` (`{ schemaVersion:1, type:+ 'mediaCollections', config:{} }`) plus any seed record dirs. `scripts/setup-data.js`+ copies missing files recursively, so the new dir layout seeds correctly on fresh+ installs. (Verify whether a seed file currently exists; if none, nothing to do.)+- **Tests that pre-seed the monolithic file:** grep for any test writing+ `media-collections.json` directly and switch it to seed via the service or the+ per-record layout. `mediaCollections.test.js`, `peerSync.test.js`,+ `sharing/integration.test.js`, and `routes/mediaCollections.test.js` should otherwise+ pass unchanged because the public API is preserved.++## Out of scope (leave as separate PLAN items)++- `[conflict-journal-media-collections]` (line 119) — scalar-overwrite journaling stays+ deferred; this PR only changes storage.+- `[data-versioning-typeindex-config-convention]` (line 104) — collections use `config:{}`+ for now; no shared config slot needed.++## Verification++1. **Unit/integration tests** — `cd server && npm test`. Targeted runs:+ `npx vitest run services/mediaCollections.test.js routes/mediaCollections.test.js+ services/sharing/peerSync.test.js services/sharing/integration.test.js+ ../scripts/migrations/059-split-media-collections.test.js`. All must pass — the merge,+ union-by-`kind:ref`, LWW-scalar, tombstone, and per-record-subscription assertions+ are the regression net for the sync rewrite.+2. **Migration on real data** — with a populated `data/media-collections.json`, boot the+ server (or run the migration runner). Confirm: `data/media-collections/<id>/index.json`+ files exist, `data/media-collections/index.json` has `schemaVersion:1`,+ `media-collections.json.bak-059` exists, and `migrations.applied.json` lists `059`.+ Re-run → no-op (Gate 1).+3. **Boot log** — `verifyCollectionVersions` prints a green/OK line for `mediaCollections`.+4. **App smoke** (`npm run dev`) — Collections page lists, create/rename/delete a+ collection, add/remove items, pin a cover. Run the pipeline cover-filer / Universe+ Builder path that auto-files renders and confirm items land in the right `uc-`/`sc-`+ collection.+5. **Federation smoke** (covered by integration.test.js, optionally manual) — two+ instances still converge: item union across peers, deleted-collection GC, bundled+ `linkedCollection` on universe/series push.+6. Run `/simplify` on the diff, then commit + open a PR.diff --git a/scripts/migrations/059-split-media-collections.js b/scripts/migrations/059-split-media-collections.jsnew file mode 100644index 0000000000..46a1b53ba8--- /dev/null+++ b/scripts/migrations/059-split-media-collections.js@@ -0,0 +1,200 @@+/**+ * Split the monolithic `data/media-collections.json` into per-record files+ * under `data/media-collections/{id}/index.json`, with a type-level+ * `data/media-collections/index.json` stamping `schemaVersion: 1`.+ *+ * Why:+ * The legacy single-file shape (`{ collections: [...] }`) serialized every+ * write across every collection through one file-level queue and rewrote the+ * whole ~200 KB document per item. High-frequency render-filing (pipeline+ * cover filer, Universe Builder completion hook, image-gen auto-file) calls+ * `addItem` constantly, so unrelated writes blocked each other. The new+ * per-record layout reads/writes one collection at a time and per-id writes+ * don't serialize against each other. See `server/lib/collectionStore.js`.+ *+ * What changes on disk:+ *+ * before: after:+ * data/ data/+ * └── media-collections.json ├── media-collections/+ * │ ├── index.json (schemaVersion: 1)+ * │ ├── <id-1>/+ * │ │ └── index.json (the collection record)+ * │ └── <id-2>/+ * │ └── index.json+ * └── media-collections.json.bak-059+ *+ * The legacy file is RENAMED, not deleted — recovery path stays open. A later+ * migration (or manual cleanup) can remove `.bak-059` once validated.+ *+ * Idempotency: a re-run after partial completion safely finishes the split; a+ * re-run after full completion is a no-op.+ *+ * Unlike universes, collections carry no cross-record type-level state (there is+ * no `runs[]` analog), so the type index `config` is an empty object. Collection+ * records carry no record-shape `schemaVersion` — only the type-level layout+ * version (1, this migration's stamp) applies.+ */++import { readFile, writeFile, rename, mkdir, stat, readdir } from 'fs/promises';+import { join } from 'path';++const TYPE_DIR_NAME = 'media-collections';+const LEGACY_FILENAME = 'media-collections.json';+const BACKUP_SUFFIX = '.bak-059';+const TYPE_SCHEMA_VERSION = 1;+const TYPE_LABEL = 'mediaCollections';++const fileExists = (path) => stat(path).then(() => true, (err) => {+ if (err.code === 'ENOENT') return false;+ throw err;+});++// Two read variants so we distinguish "missing file" from "present but+// unparseable" — the latter is a recovery-required state we report through+// the migration's return value rather than crashing the boot.+const readJsonStrict = async (path) => {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ return JSON.parse(raw);+};++const readJsonTolerant = async (path) => {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ try { return JSON.parse(raw); } catch { return { __unreadable: true }; }+};++const writeJson = (path, value) =>+ writeFile(path, JSON.stringify(value, null, 2) + '\n');++// Match the collectionStore default `idPattern` so a record whose id the store+// would accept gets split, and one it would reject (and silently drop from+// listIds) is left in the backup for manual recovery rather than written to a+// directory the store can never load. Collection ids are random UUIDs or the+// deterministic `uc-<universeId>` / `sc-<seriesId>` forms — all match.+const VALID_COLLECTION_ID = /^[A-Za-z0-9_-]{1,128}$/;++export default {+ async up({ rootDir }) {+ const dataDir = join(rootDir, 'data');+ const typeDir = join(dataDir, TYPE_DIR_NAME);+ const typeIndexPath = join(typeDir, 'index.json');+ const legacyPath = join(dataDir, LEGACY_FILENAME);+ const backupPath = legacyPath + BACKUP_SUFFIX;++ // Idempotency gate 1: type index already at v1 → nothing to do. A re-run+ // after full success lands here. Read strictly — a corrupted index.json+ // is unexpected and we want the loud throw at this layer.+ const typeIndex = await readJsonStrict(typeIndexPath);+ if (typeIndex && typeIndex.schemaVersion >= TYPE_SCHEMA_VERSION) {+ console.log(`📦 migration 059: media-collections already at schemaVersion=${typeIndex.schemaVersion} — no-op`);+ return { ok: true, reason: 'already-applied' };+ }++ const legacyExists = await fileExists(legacyPath);+ const backupExists = await fileExists(backupPath);++ // Idempotency gate 2: fresh install — no legacy file, no backup, just+ // stamp the type index so verifyCollectionVersions doesn't flag missing.+ if (!legacyExists && !backupExists) {+ await mkdir(typeDir, { recursive: true });+ await writeJson(typeIndexPath, {+ schemaVersion: TYPE_SCHEMA_VERSION,+ type: TYPE_LABEL,+ updatedAt: new Date().toISOString(),+ config: {},+ });+ console.log(`📦 migration 059: fresh install — stamped data/media-collections/index.json @ v${TYPE_SCHEMA_VERSION}`);+ return { ok: true, reason: 'fresh-install' };+ }++ // Recovery gate: the previous run split records but didn't finish renaming+ // the legacy file. Use whichever file is present as the source of truth —+ // prefer the live file if both somehow exist (split must not have happened).+ const sourcePath = legacyExists ? legacyPath : backupPath;+ const doc = await readJsonTolerant(sourcePath);+ if (!doc || typeof doc !== 'object' || doc.__unreadable) {+ console.warn(`⚠️ migration 059: ${sourcePath} unreadable — skipping. Resolve manually before next boot.`);+ return { ok: false, reason: 'unreadable' };+ }++ const collections = Array.isArray(doc.collections) ? doc.collections : [];++ // Pre-flight: find any already-split records so we don't double-write the+ // ones we've already moved. Helps partial-completion recovery. Use+ // `withFileTypes: true` so we skip stray non-directory entries without+ // statting INTO them (an ENOTDIR would crash the whole migration).+ const existingIds = new Set();+ if (await fileExists(typeDir)) {+ const entries = await readdir(typeDir, { withFileTypes: true }).catch(() => []);+ for (const entry of entries) {+ const name = entry.name;+ if (name === 'index.json' || name.startsWith('.')) continue;+ if (!entry.isDirectory()) continue;+ const candidatePath = join(typeDir, name, 'index.json');+ if (await fileExists(candidatePath)) existingIds.add(name);+ }+ }++ await mkdir(typeDir, { recursive: true });++ let written = 0;+ let skipped = 0;+ let invalid = 0;+ for (const record of collections) {+ if (!record || typeof record !== 'object') {+ invalid += 1;+ continue;+ }+ const id = typeof record.id === 'string' ? record.id : null;+ if (!id || !VALID_COLLECTION_ID.test(id)) {+ invalid += 1;+ console.warn(`⚠️ migration 059: skipping record with invalid id "${id}" (left in backup for manual recovery)`);+ continue;+ }+ if (existingIds.has(id)) {+ // Already split in a prior partial run — leave it alone. The+ // monolithic record may have stale state (in-flight writes after the+ // crash), so trusting the already-split per-record file is safer.+ skipped += 1;+ continue;+ }+ const recordDir = join(typeDir, id);+ await mkdir(recordDir, { recursive: true });+ await writeJson(join(recordDir, 'index.json'), record);+ written += 1;+ }++ // Stamp the type-level index AFTER all records land so a crash mid-split+ // leaves the type index missing — the next boot's gate 1 won't trip, and+ // gate 2/recovery re-runs the loop.+ await writeJson(typeIndexPath, {+ schemaVersion: TYPE_SCHEMA_VERSION,+ type: TYPE_LABEL,+ updatedAt: new Date().toISOString(),+ config: {},+ });++ // Backup the legacy file. Skip if it's already been backed up (recovery+ // path was driven from the backup). Renaming preserves data; manual+ // restore is `mv media-collections.json.bak-059 media-collections.json`.+ if (legacyExists) {+ await rename(legacyPath, backupPath);+ }++ console.log(+ `📦 migration 059: split ${written} collection(s) into data/media-collections/<id>/index.json ` ++ `(${skipped} already split, ${invalid} invalid); stamped index.json @ v${TYPE_SCHEMA_VERSION}; ` ++ `legacy file backed up as ${LEGACY_FILENAME}${BACKUP_SUFFIX}`,+ );++ return { ok: true, reason: 'split', written, skipped, invalid };+ },+};diff --git a/scripts/migrations/059-split-media-collections.test.js b/scripts/migrations/059-split-media-collections.test.jsnew file mode 100644index 0000000000..e5032e8c84--- /dev/null+++ b/scripts/migrations/059-split-media-collections.test.js@@ -0,0 +1,160 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './059-split-media-collections.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++const collection = (id, overrides = {}) => ({+ id,+ name: `Collection ${id}`,+ description: '',+ coverKey: null,+ universeId: null,+ seriesId: null,+ items: [],+ createdAt: '2026-05-31T00:00:00.000Z',+ updatedAt: '2026-05-31T00:00:00.000Z',+ deleted: false,+ deletedAt: null,+ ...overrides,+});++describe('migration 059 — split media-collections.json to per-record files', () => {+ let rootDir;+ let dataDir;+ let legacyPath;+ let typeDir;+ let typeIndexPath;+ let backupPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-059-'));+ dataDir = join(rootDir, 'data');+ mkdirSync(dataDir, { recursive: true });+ legacyPath = join(dataDir, 'media-collections.json');+ typeDir = join(dataDir, 'media-collections');+ typeIndexPath = join(typeDir, 'index.json');+ backupPath = legacyPath + '.bak-059';+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('fresh install: no legacy file → stamps an empty type index', async () => {+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ ok: true, reason: 'fresh-install' });+ expect(existsSync(typeIndexPath)).toBe(true);+ const idx = readJson(typeIndexPath);+ expect(idx.schemaVersion).toBe(1);+ expect(idx.type).toBe('mediaCollections');+ expect(idx.config).toEqual({});+ expect(existsSync(legacyPath)).toBe(false);+ expect(existsSync(backupPath)).toBe(false);+ });++ it('full split: writes one file per collection and a type index', async () => {+ writeJson(legacyPath, {+ collections: [+ collection('11111111-1111-1111-1111-111111111111', { name: 'Standalone' }),+ collection('uc-aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa', { name: 'Universe: Alpha', universeId: 'aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa' }),+ collection('sc-bbbbbbbb-2222-2222-2222-bbbbbbbbbbbb', { name: 'Series: Beta', seriesId: 'bbbbbbbb-2222-2222-2222-bbbbbbbbbbbb' }),+ ],+ });++ const result = await migration.up({ rootDir });+ expect(result).toEqual({ ok: true, reason: 'split', written: 3, skipped: 0, invalid: 0 });++ expect(existsSync(typeIndexPath)).toBe(true);+ const idx = readJson(typeIndexPath);+ expect(idx.schemaVersion).toBe(1);+ expect(idx.config).toEqual({});++ for (const id of [+ '11111111-1111-1111-1111-111111111111',+ 'uc-aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa',+ 'sc-bbbbbbbb-2222-2222-2222-bbbbbbbbbbbb',+ ]) {+ const recordPath = join(typeDir, id, 'index.json');+ expect(existsSync(recordPath)).toBe(true);+ expect(readJson(recordPath).id).toBe(id);+ }++ expect(existsSync(legacyPath)).toBe(false);+ expect(existsSync(backupPath)).toBe(true);+ expect(readJson(backupPath).collections).toHaveLength(3);+ });++ it('idempotent: second run is a no-op once type index is at v1', async () => {+ writeJson(legacyPath, {+ collections: [collection('11111111-1111-1111-1111-111111111111')],+ });+ await migration.up({ rootDir });+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ ok: true, reason: 'already-applied' });+ expect(existsSync(backupPath)).toBe(true);+ });++ it('partial recovery: some records already split, finishes the rest', async () => {+ const ids = [+ '11111111-1111-1111-1111-111111111111',+ '22222222-2222-2222-2222-222222222222',+ '33333333-3333-3333-3333-333333333333',+ ];+ writeJson(legacyPath, {+ collections: ids.map((id, i) => collection(id, { name: `Collection-${i}-original` })),+ });+ // Pre-split the FIRST record with a name DIFFERENT from the legacy snapshot+ // — the migration must NOT clobber it (the per-record file is freshest).+ mkdirSync(join(typeDir, ids[0]), { recursive: true });+ writeJson(join(typeDir, ids[0], 'index.json'), collection(ids[0], { name: 'Collection-0-NEWER' }));++ const result = await migration.up({ rootDir });+ expect(result).toEqual({ ok: true, reason: 'split', written: 2, skipped: 1, invalid: 0 });++ expect(readJson(join(typeDir, ids[0], 'index.json')).name).toBe('Collection-0-NEWER');+ for (const id of ids.slice(1)) {+ expect(existsSync(join(typeDir, id, 'index.json'))).toBe(true);+ }+ expect(existsSync(backupPath)).toBe(true);+ });++ it('skips records with invalid ids and counts them', async () => {+ writeJson(legacyPath, {+ collections: [+ collection('11111111-1111-1111-1111-111111111111'),+ { id: 'has spaces', name: 'invalid id' }, // space fails idPattern+ { id: '../escape', name: 'evil' }, // slash + dot fails idPattern+ null, // not an object+ ],+ });+ const result = await migration.up({ rootDir });+ expect(result.ok).toBe(true);+ expect(result.written).toBe(1);+ expect(result.invalid).toBe(3);+ expect(existsSync(join(typeDir, '11111111-1111-1111-1111-111111111111', 'index.json'))).toBe(true);+ });++ it('reports unreadable when the legacy file is corrupted', async () => {+ writeFileSync(legacyPath, 'not json');+ const result = await migration.up({ rootDir });+ expect(result.ok).toBe(false);+ });++ it('recovers from the .bak-059 file if the legacy was already renamed', async () => {+ // Crash AFTER rename but BEFORE the type index was written — gate 1 doesn't+ // trip; gate 2 sees backup but no legacy, falls into the recovery branch.+ writeJson(backupPath, {+ collections: [collection('11111111-1111-1111-1111-111111111111', { name: 'Recovered' })],+ });+ const result = await migration.up({ rootDir });+ expect(result.ok).toBe(true);+ expect(result.written).toBe(1);+ expect(readJson(join(typeDir, '11111111-1111-1111-1111-111111111111', 'index.json')).name).toBe('Recovered');+ expect(existsSync(backupPath)).toBe(true);+ });+});diff --git a/server/index.js b/server/index.jsindex 04e38707ad..6fa760f1d1 100644--- a/server/index.js+++ b/server/index.js@@ -155,6 +155,7 @@ import { universeStore } from './services/universeBuilder.js';import { seriesStore } from './services/pipeline/series.js';import { issueStore } from './services/pipeline/issues.js';import { storyBuilderStore } from './services/storyBuilder.js';+import { mediaCollectionStore } from './services/mediaCollections.js';import { createPortOSProviderRoutes } from './routes/providers.js';import { createPortOSRunsRoutes } from './routes/runs.js';import { createPortOSPromptsRoutes } from './routes/prompts.js';@@ -210,7 +211,7 @@ await runMigrations({ rootDir: join(__dirname, '..') }).catch(err => {// but DO NOT crash the server. PortOS is single-user (CLAUDE.md "Security// Model"); a hard exit on startup is worse than a noisy log the user can act// on. Returns per-store statuses for downstream telemetry; we discard them.-await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore()]).catch(err => {+await verifyCollectionVersions([universeStore(), seriesStore(), issueStore(), conflictJournalStore(), storyBuilderStore(), mediaCollectionStore()]).catch(err => {console.error(`❌ Collection version check failed at startup: ${err?.stack ?? err}`);});diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex a32851988b..d5901cd199 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -42,7 +42,10 @@ const PIPELINE_ISSUES_DIR = join(PATHS.data, 'pipeline-issues');// (listUniverses, below) and for fingerprint-based checksum caching — the// fingerprint walker descends into the dir so per-record edits invalidate.const UNIVERSE_BUILDER_DIR = join(PATHS.data, 'universes');-const MEDIA_COLLECTIONS_FILE = join(PATHS.data, 'media-collections.json');+// Migration 059 split the monolithic media-collections.json into per-record+// `data/media-collections/<id>/index.json`. The fingerprint walker descends+// into the dir so per-record edits invalidate the snapshot checksum cache.+const MEDIA_COLLECTIONS_DIR = join(PATHS.data, 'media-collections');// Outbound peer subscriptions drive the per-peer snapshot exclude-set (see// getSnapshot's `forPeerId` scoping). A subscribe/unsubscribe changes which// records ride the scoped snapshot, so it must invalidate the per-peer@@ -704,7 +707,7 @@ const CHECKSUM_PATHS = {// universe/series is ephemeral, so a "mark ephemeral" PATCH on a universe// must re-checksum the collections snapshot even though// media-collections.json itself didn't move. Same goes for un-ephemeral.- mediaCollections: [MEDIA_COLLECTIONS_FILE, UNIVERSE_BUILDER_DIR, PIPELINE_SERIES_DIR, PEER_SUBSCRIPTIONS_FILE],+ mediaCollections: [MEDIA_COLLECTIONS_DIR, UNIVERSE_BUILDER_DIR, PIPELINE_SERIES_DIR, PEER_SUBSCRIPTIONS_FILE],// videoHistory is a flat history file with no parent-record dependency —// its checksum invalidates only when video-history.json itself moves.videoHistory: [VIDEO_HISTORY_FILE],diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 010c9d6240..d78acbfeab 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -27,7 +27,7 @@ const { PORTOS_SCHEMA_VERSIONS } = await import('../lib/schemaVersions.js');const SERIES_DIR = join(tempRoot, 'pipeline-series');const ISSUES_DIR = join(tempRoot, 'pipeline-issues');const UNIVERSES_DIR = join(tempRoot, 'universes');-const MEDIA_COLLECTIONS_PATH = join(tempRoot, 'media-collections.json');+const MEDIA_COLLECTIONS_DIR = join(tempRoot, 'media-collections');const PEER_SUBS_PATH = join(tempRoot, 'sharing', 'peer_subscriptions.json');const VIDEO_HISTORY_PATH = join(tempRoot, 'video-history.json');@@ -77,6 +77,16 @@ function readCollectionState(dir) {.map((entry) => readJSON(join(dir, entry.name, 'index.json')));}+// media-collections moved to the per-record collectionStore layout (migration+// 059); these adapters keep the `{ collections: [...] }`-shaped call sites below+// working against the split dir.+function writeMediaCollections({ collections = [] } = {}) {+ writeCollectionState(MEDIA_COLLECTIONS_DIR, 'mediaCollections', collections);+}+function readMediaCollections() {+ return { collections: readCollectionState(MEDIA_COLLECTIONS_DIR) };+}+const writeSeriesState = (series) => writeCollectionState(SERIES_DIR, 'pipelineSeries', series);const writeIssueState = (issues) => writeCollectionState(ISSUES_DIR, 'pipelineIssues', issues);const readSeriesState = () => readCollectionState(SERIES_DIR);@@ -385,7 +395,7 @@ describe('dataSync — mediaCollections category', () => {});it('snapshot returns sanitized collections array', async () => {- writeJSON(MEDIA_COLLECTIONS_PATH, {+ writeMediaCollections({collections: [{id: 'c1',name: 'Universe: Echoes',@@ -405,7 +415,7 @@ describe('dataSync — mediaCollections category', () => {});it('snapshot checksum is stable across reads when state is unchanged', async () => {- writeJSON(MEDIA_COLLECTIONS_PATH, {+ writeMediaCollections({collections: [{id: 'c1', name: 'A', description: '', coverKey: null, universeId: null, seriesId: null,items: [], createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T00:00:00Z',@@ -423,7 +433,7 @@ describe('dataSync — mediaCollections category', () => {});it('applyRemote inserts a new collection', async () => {- writeJSON(MEDIA_COLLECTIONS_PATH, { collections: [] });+ writeMediaCollections({ collections: [] });const result = await dataSync.applyRemote('mediaCollections', {collections: [{id: 'c-new', name: 'Universe: New', description: '', coverKey: null,@@ -434,13 +444,13 @@ describe('dataSync — mediaCollections category', () => {});expect(result.applied).toBe(true);expect(result.count).toBe(1);- const persisted = readJSON(MEDIA_COLLECTIONS_PATH);+ const persisted = readMediaCollections();expect(persisted.collections).toHaveLength(1);expect(persisted.collections[0].id).toBe('c-new');});it('applyRemote unions items by kind:ref — never loses a render', async () => {- writeJSON(MEDIA_COLLECTIONS_PATH, {+ writeMediaCollections({collections: [{id: 'c1', name: 'A', description: '', coverKey: null, universeId: null, seriesId: null,items: [{ kind: 'image', ref: 'local.png', addedAt: '2026-05-22T01:00:00Z' }],@@ -454,13 +464,13 @@ describe('dataSync — mediaCollections category', () => {createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T02:00:00Z',}],});- const persisted = readJSON(MEDIA_COLLECTIONS_PATH);+ const persisted = readMediaCollections();const refs = persisted.collections[0].items.map(i => i.ref).sort();expect(refs).toEqual(['local.png', 'remote.png']);});it('checksum changes after applyRemote bumps file mtime', async () => {- writeJSON(MEDIA_COLLECTIONS_PATH, {+ writeMediaCollections({collections: [{id: 'c1', name: 'A', description: '', coverKey: null, universeId: null, seriesId: null,items: [], createdAt: '2026-05-22T00:00:00Z', updatedAt: '2026-05-22T01:00:00Z',@@ -484,7 +494,7 @@ describe('dataSync — mediaCollections category', () => {// canonicalization in getMediaCollectionsSnapshot, their checksums// diverge permanently and the UI reads "behind" forever even though// they're converged.- writeJSON(MEDIA_COLLECTIONS_PATH, {+ writeMediaCollections({collections: [{id: 'c-b', name: 'B', description: '', coverKey: null, universeId: null, seriesId: null,@@ -508,7 +518,7 @@ describe('dataSync — mediaCollections category', () => {// Same SET, reversed order at every level.await new Promise((r) => setTimeout(r, 5)); // ensure mtime changes- writeJSON(MEDIA_COLLECTIONS_PATH, {+ writeMediaCollections({collections: [{id: 'c-a', name: 'A', description: '', coverKey: null, universeId: null, seriesId: null,@@ -604,7 +614,7 @@ describe('dataSync — per-peer snapshot scoping (forPeerId exclude-set)', () =>});it('mediaCollections: excludes the requesting peer\'s subscribed collection ids', async () => {- writeJSON(MEDIA_COLLECTIONS_PATH, {+ writeMediaCollections({collections: [{ id: 'col-sub', name: 'Subbed', description: '', coverKey: null, universeId: null, seriesId: null, items: [], createdAt: '2026-05-25T00:00:00Z', updatedAt: '2026-05-25T01:00:00Z' },{ id: 'col-free', name: 'Free', description: '', coverKey: null, universeId: null, seriesId: null, items: [], createdAt: '2026-05-25T00:00:00Z', updatedAt: '2026-05-25T01:00:00Z' },@@ -856,7 +866,7 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {});it('does NOT block a mediaCollections snapshot when the sender is ahead on universes', async () => {- writeJSON(MEDIA_COLLECTIONS_PATH, { collections: [] });+ writeMediaCollections({ collections: [] });const result = await dataSync.applyRemote('mediaCollections', {collections: [{id: 'c-new', name: 'New', description: '', coverKey: null, universeId: null, seriesId: null,diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex 0053aeb91e..bb6847fa40 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -2,36 +2,34 @@* Media Collections** User-named buckets for image filenames + video ids. Many-to-many: the same- * media item can live in any number of collections at once. Persisted to- * data/media-collections.json as a single { collections: [...] } document.+ * media item can live in any number of collections at once. Persisted via the+ * per-record `createCollectionStore` layout under data/media-collections/ —+ * one `{id}/index.json` per collection plus a type-level `index.json` stamping+ * the storage `schemaVersion`. (Migrated from the legacy monolithic+ * data/media-collections.json by scripts/migrations/059-split-media-collections.js.)** An item is identified by `{ kind: 'image'|'video', ref: <filename|videoId> }`.* A collection's `coverKey` is `null` (auto: newest item) or `"<kind>:<ref>"`* to pin a specific item as the cover thumbnail.*- * **Concurrency.** Every public mutator routes through `serializeFileWrite`- * (a single-tail queue keyed on the shared media-collections.json file).- * Without it, parallel write paths — e.g. the pipeline cover filer's- * `addItem` running alongside Universe Builder's completion-hook `addItem`,- * or a `deleteUniverse` unlink racing with an in-flight cover completion —- * each do a `listCollections → modify → atomicWrite(entire array)` round- * and the second write silently clobbers the first. Built on- * `createFileWriteQueue()` in `server/lib/fileWriteQueue.js`.+ * **Concurrency.** Every public mutator routes its read-modify-write through+ * the store's per-record queue (`store().queueRecordWrite(id, fn)`), so two+ * writes against the SAME collection serialize while writes against DIFFERENT+ * collections run in parallel. This replaces the legacy single-tail file queue+ * that serialized every unrelated write and rewrote the whole ~200 KB document+ * per item. The hot render-filing paths (pipeline cover filer, Universe Builder+ * completion hook, image-gen auto-file) all target deterministic `uc-`/`sc-`+ * ids, so concurrent `addItem`s to the same bucket still serialize correctly.*/import { join } from 'path';import { randomUUID } from 'crypto';-import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';-import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { PATHS } from '../lib/fileUtils.js';+import { createCollectionStore } from '../lib/collectionStore.js';import { ITEM_KIND, REF_MAX_LENGTH, itemKey } from '../lib/mediaItemKey.js';import { sanitizeOrigin } from '../lib/sharingOrigin.js';import { emitRecordUpdated, emitRecordDeleted } from './sharing/recordEvents.js';-// Lazy resolution — PATHS.data may not be available at module-load time-// (e.g. tests that swap it through a Proxy mock so different cases get-// different temp roots). See universeBuilder.js for the same pattern.-const statePath = () => join(PATHS.data, 'media-collections.json');-export const ERR_NOT_FOUND = 'NOT_FOUND';export const ERR_DUPLICATE = 'DUPLICATE';export const ERR_VALIDATION = 'VALIDATION_ERROR';@@ -43,8 +41,6 @@ export const ITEMS_MAX = 5000;export { REF_MAX_LENGTH, itemKey };-const DEFAULT_STATE = { collections: [] };-const sanitizeItem = (raw) => {if (!raw || typeof raw !== 'object') return null;if (!ITEM_KIND.has(raw.kind)) return null;@@ -134,39 +130,47 @@ const sanitizeCollection = (raw) => {return { id: raw.id, name, description, coverKey, universeId, seriesId, items, createdAt, updatedAt, deleted, deletedAt };};+// Storage-layout (type-level) schema version stamped on+// data/media-collections/index.json. Distinct from the wire schemaVersion in+// server/lib/schemaVersions.js (the on-disk split doesn't change the wire+// payload shape, so that stays at 1). Bump only on a future layout change.+const TYPE_SCHEMA_VERSION = 1;++// Lazy store getter — PATHS.data may not be available at module-load time+// (tests swap it through a Proxy mock so different cases get different temp+// roots). Mirrors universeBuilder.js's `store()` pattern: re-create when the+// resolved dir changes so a remapped data root takes effect.+let _store = null;+const store = () => {+ const dir = join(PATHS.data, 'media-collections');+ if (_store && _store.dir === dir) return _store;+ _store = createCollectionStore({+ dir,+ type: 'mediaCollections',+ schemaVersion: TYPE_SCHEMA_VERSION,+ // Runs on every loadOne/loadAll. Tombstones (deleted:true) survive+ // sanitization so the mutators and merge path can see them.+ sanitizeRecord: sanitizeCollection,+ });+ return _store;+};++// Exposed for the boot-time verifier in server/index.js.+export const mediaCollectionStore = () => store();+export async function listCollections({ includeDeleted = false } = {}) {- await ensureDir(PATHS.data);- const raw = await readJSONFile(statePath(), DEFAULT_STATE, { logError: false });- if (!Array.isArray(raw.collections)) return [];- const seen = new Set();- const out = [];- for (const c of raw.collections) {- const s = sanitizeCollection(c);- if (!s || seen.has(s.id)) continue;- seen.add(s.id);- if (!includeDeleted && s.deleted === true) continue;- out.push(s);- }- return out;+ const all = await store().loadAll();+ if (includeDeleted) return all;+ return all.filter((c) => c.deleted !== true);}export async function getCollection(id, { includeDeleted = false } = {}) {- const all = await listCollections({ includeDeleted });- const c = all.find((x) => x.id === id);+ const c = await store().loadOne(id);if (!c) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);+ if (c.deleted === true && !includeDeleted) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);return c;}-// Every public mutator wraps its read-modify-write in `serializeFileWrite`-// so the read always sees the freshest persisted state and the write-// completes before the next task's read begins. `writeAll` is the only-// persistence call and must only be invoked from inside a serialized task.-const serializeFileWrite = createFileWriteQueue();-const writeAll = async (collections) => {- await atomicWrite(statePath(), { collections });- return collections;-};-// Announce a newly-created collection to the per-record peer-sync pipeline:// emit the 'updated' event so any existing subscription pushes it, AND// auto-subscribe every mediaCollections-enabled peer so brand-new collections@@ -193,11 +197,11 @@ export async function createCollection({ name, description = '' }) {const trimmedDescription = typeof description === 'string'? description.trim().slice(0, DESCRIPTION_MAX_LENGTH): '';- const created = await serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });+ const id = randomUUID();+ const created = await store().queueRecordWrite(id, async () => {const now = new Date().toISOString();const next = {- id: randomUUID(),+ id,name: trimmedName,description: trimmedDescription,coverKey: null,@@ -205,7 +209,7 @@ export async function createCollection({ name, description = '' }) {createdAt: now,updatedAt: now,};- await writeAll([...all, next]);+ await store().saveOneNow(id, next);return next;});announceNewCollection(created.id);@@ -240,9 +244,14 @@ export async function findOrCreateCollectionByName({ name, description = '', uniconst normalizedUniverseId = typeof universeId === 'string' && universeId.trim()? universeId.trim().slice(0, UNIVERSE_ID_MAX): null;+ // Deterministic id when universe-linked (cross-machine convergence); a fresh+ // random id otherwise. Queue on whichever id this call would create/adopt so+ // two concurrent calls for the same universe serialize on the same record.+ const canonId = linkedCollectionId({ universeId: normalizedUniverseId });+ const queueId = canonId || randomUUID();let createdId = null;- const result = await serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });+ const result = await store().queueRecordWrite(queueId, async () => {+ const all = await store().loadAll();const needle = trimmed.toLowerCase();// Do not match (or reuse) tombstoned records — a deleted collection// should not be resurrected by name.@@ -254,7 +263,7 @@ export async function findOrCreateCollectionByName({ name, description = '', uni// DETERMINISTIC id at the same time — keeping the old random id would// leave a universe-linked collection that can't converge across peers// (the very bug deterministic ids fix).- const canonId = linkedCollectionId({ universeId: normalizedUniverseId });+ //// If the universe ALREADY has its canonical collection, don't promote a// same-named orphan over it (that would clobber the canonical record's// items) — return the canonical one; the orphan is a duplicate the merge@@ -262,19 +271,21 @@ export async function findOrCreateCollectionByName({ name, description = '', uniconst liveCanonical = all.find((c) => c.id === canonId && !c.deleted);if (liveCanonical) return liveCanonical;// No live canonical — rename the orphan to the deterministic id,- // reclaiming a tombstone at that id if one exists.+ // reclaiming a tombstone at that id if one exists (saveOneNow overwrites+ // the canonId record), then drop the old random-id record.const linked = { ...existing, id: canonId, universeId: normalizedUniverseId, updatedAt: new Date().toISOString() };- await writeAll([...all.filter((c) => c.id !== existing.id && c.id !== canonId), linked]);- if (canonId !== existing.id) createdId = canonId; // announce the newly-linked record+ await store().saveOneNow(canonId, linked);+ if (canonId !== existing.id) {+ await store().deleteOneNow(existing.id);+ createdId = canonId; // announce the newly-linked record+ }return linked;}return existing;}const now = new Date().toISOString();const next = {- // Deterministic id when universe-linked (cross-machine convergence);- // standalone (no link) keeps a random id. See linkedCollectionId.- id: linkedCollectionId({ universeId: normalizedUniverseId }) || randomUUID(),+ id: queueId,name: trimmed,description: trimmedDescription,coverKey: null,@@ -284,11 +295,9 @@ export async function findOrCreateCollectionByName({ name, description = '', uniupdatedAt: now,};createdId = next.id;- // Reclaim the deterministic id if a tombstone already holds it (re-creating- // a previously-deleted universe/series collection). A plain append would- // leave two records at the same id and listCollections' dedup keeps the- // tombstone (it's first), silently dropping this fresh live record.- await writeAll([...all.filter((c) => c.id !== next.id), next]);+ // saveOneNow overwrites any tombstone already at this deterministic id+ // (re-creating a previously-deleted universe/series collection).+ await store().saveOneNow(next.id, next);return next;});if (createdId) announceNewCollection(createdId);@@ -376,9 +385,15 @@ export async function findOrCreateUniverseCollection({ universeId, universeName,const trimmedDescription = typeof description === 'string'? description.trim().slice(0, DESCRIPTION_MAX_LENGTH): '';+ // Deterministic id so this universe's collection has the SAME id on every+ // peer (per-record sync keys on id) — see linkedCollectionId. Queue on it so+ // two concurrent provisions for the same universe serialize.+ const id = linkedCollectionId({ universeId: normalizedUniverseId });let createdId = null;- const result = await serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });+ const result = await store().queueRecordWrite(id, async () => {+ // Scan by stamp (not a direct loadOne) so a legacy unconverged collection+ // carrying this universeId at a random id is still found, not duplicated.+ const all = await store().loadAll();// Do not adopt a tombstoned universe-linked collection — deleted means gone.const linked = all.find((c) => !c.deleted && c.universeId === normalizedUniverseId);if (linked) return linked;@@ -395,9 +410,7 @@ export async function findOrCreateUniverseCollection({ universeId, universeName,// migration belong to "ambiguous, leave it" rather than "auto-adopt."const now = new Date().toISOString();const next = {- // Deterministic id so this universe's collection has the SAME id on every- // peer (per-record sync keys on id) — see linkedCollectionId.- id: linkedCollectionId({ universeId: normalizedUniverseId }),+ id,name: desiredName,description: trimmedDescription,coverKey: null,@@ -407,11 +420,9 @@ export async function findOrCreateUniverseCollection({ universeId, universeName,updatedAt: now,};createdId = next.id;- // Reclaim the deterministic id if a tombstone already holds it (re-creating- // a previously-deleted universe/series collection). A plain append would- // leave two records at the same id and listCollections' dedup keeps the- // tombstone (it's first), silently dropping this fresh live record.- await writeAll([...all.filter((c) => c.id !== next.id), next]);+ // saveOneNow overwrites any tombstone already at this deterministic id+ // (re-creating a previously-deleted universe collection).+ await store().saveOneNow(next.id, next);return next;});// Announce only when a NEW record was persisted (not a find-existing hit), so@@ -448,16 +459,17 @@ export async function findOrCreateSeriesCollection({ seriesId, seriesName, descrconst trimmedDescription = typeof description === 'string'? description.trim().slice(0, DESCRIPTION_MAX_LENGTH): '';+ // Deterministic id — same series collection id on every peer (see linkedCollectionId).+ const id = linkedCollectionId({ seriesId: normalizedSeriesId });let createdId = null;- const result = await serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });+ const result = await store().queueRecordWrite(id, async () => {+ const all = await store().loadAll();// Do not adopt a tombstoned series-linked collection — deleted means gone.const linked = all.find((c) => !c.deleted && c.seriesId === normalizedSeriesId);if (linked) return linked;const now = new Date().toISOString();const next = {- // Deterministic id — same series collection id on every peer (see linkedCollectionId).- id: linkedCollectionId({ seriesId: normalizedSeriesId }),+ id,name: desiredName,description: trimmedDescription,coverKey: null,@@ -467,66 +479,77 @@ export async function findOrCreateSeriesCollection({ seriesId, seriesName, descrupdatedAt: now,};createdId = next.id;- // Reclaim the deterministic id if a tombstone already holds it (re-creating- // a previously-deleted universe/series collection). A plain append would- // leave two records at the same id and listCollections' dedup keeps the- // tombstone (it's first), silently dropping this fresh live record.- await writeAll([...all.filter((c) => c.id !== next.id), next]);+ // saveOneNow overwrites any tombstone already at this deterministic id+ // (re-creating a previously-deleted series collection).+ await store().saveOneNow(next.id, next);return next;});if (createdId) announceNewCollection(createdId);return result;}-// Series mirror of `unlinkCollectionsForUniverse` — same cascade semantics,-// same reason for preserving `updatedAt` (see that function's note). A series-// merge tombstones the loser series-collection and the loser series; the-// series-tombstone cascade must not bump the collection past its own tombstone.-export async function unlinkCollectionsForSeries(seriesId) {- if (typeof seriesId !== 'string' || !seriesId) return [];- const needle = seriesId.slice(0, SERIES_ID_MAX);- return serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });- const matches = all- .map((c, i) => (c.seriesId === needle ? i : -1))- .filter((i) => i >= 0);- if (!matches.length) return [];- const next = [...all];- const unlinkedIds = [];- for (const i of matches) {- next[i] = { ...all[i], seriesId: null };- unlinkedIds.push(all[i].id);- }- await writeAll(next);- return unlinkedIds;- });+// Both cascade families below — unlink (clear the owner link) and rename+// (cascade the owner's display name) — share the same shape: scan all records+// by their owner stamp, then per-match queue a load→re-check→save. The+// re-check inside the queue (`cur[field] !== needle`) is the concurrency-safety+// invariant now that there's no single file lock spanning the whole sweep —+// keep it in these two helpers so the universe/series variants can't drift.++// Clear an owner-link field (`universeId` / `seriesId`) on every collection+// stamped with `needle`. Returns the cleared ids. Deliberately does NOT bump+// `updatedAt` — see `unlinkCollectionsForUniverse`'s note.+async function clearOwnerLink(field, rawValue, maxLen) {+ if (typeof rawValue !== 'string' || !rawValue) return [];+ const needle = rawValue.slice(0, maxLen);+ const matches = (await store().loadAll()).filter((c) => c[field] === needle);+ const clearedIds = [];+ for (const c of matches) {+ await store().queueRecordWrite(c.id, async () => {+ const cur = await store().loadOne(c.id);+ if (!cur || cur[field] !== needle) return;+ await store().saveOneNow(c.id, { ...cur, [field]: null });+ });+ clearedIds.push(c.id);+ }+ return clearedIds;}-export async function renameCollectionForSeries(seriesId, newSeriesName) {- if (typeof seriesId !== 'string' || !seriesId) return null;- const needle = seriesId.slice(0, SERIES_ID_MAX);- return serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });- const matchIdxs = all- .map((c, i) => (c.seriesId === needle ? i : -1))- .filter((i) => i >= 0);- if (!matchIdxs.length) return null;- const desired = seriesCollectionNameFor(newSeriesName);- if (!desired) return all[matchIdxs[0]];- const now = new Date().toISOString();- const next = [...all];- let changed = false;- for (const i of matchIdxs) {- if (next[i].name === desired) continue;- next[i] = { ...next[i], name: desired, updatedAt: now };- changed = true;- }- if (!changed) return all[matchIdxs[0]];- await writeAll(next);- return next[matchIdxs[0]];- });+// Cascade an owner rename onto EVERY collection stamped with `needle` (not just+// the first match — hand-edited state or a pre-serialization race could leave+// duplicate linked rows that would otherwise stay rename-locked under the stale+// name). Returns the first updated collection (back-compat).+async function renameOwnerLinked(field, rawValue, maxLen, nameFor, newOwnerName) {+ if (typeof rawValue !== 'string' || !rawValue) return null;+ const needle = rawValue.slice(0, maxLen);+ const matches = (await store().loadAll()).filter((c) => c[field] === needle);+ if (!matches.length) return null;+ const desired = nameFor(newOwnerName);+ if (!desired) return matches[0];+ const now = new Date().toISOString();+ let first = null;+ for (const c of matches) {+ const updated = await store().queueRecordWrite(c.id, async () => {+ const cur = await store().loadOne(c.id);+ if (!cur || cur[field] !== needle || cur.name === desired) return cur;+ const nextRec = { ...cur, name: desired, updatedAt: now };+ await store().saveOneNow(c.id, nextRec);+ return nextRec;+ });+ if (first === null) first = updated;+ }+ return first;}+// Series mirror of `unlinkCollectionsForUniverse` — same cascade semantics,+// same reason for preserving `updatedAt`. A series merge tombstones the loser+// series-collection and the loser series; the series-tombstone cascade must not+// bump the collection past its own tombstone.+export const unlinkCollectionsForSeries = (seriesId) =>+ clearOwnerLink('seriesId', seriesId, SERIES_ID_MAX);++export const renameCollectionForSeries = (seriesId, newSeriesName) =>+ renameOwnerLinked('seriesId', seriesId, SERIES_ID_MAX, seriesCollectionNameFor, newSeriesName);+// Clear the `universeId` link on any collection bound to this universe.// Used by deleteUniverse to release the rename-lock so the orphaned bucket// becomes a normal user-owned collection (renamable, deletable, etc.). The@@ -543,66 +566,20 @@ export async function renameCollectionForSeries(seriesId, newSeriesName) {// collection tombstone under pure LWW and strand a live duplicate on the peer.// Items always union on merge (`mergeCollectionItems`), so preserving the// timestamp can't lose renders.-export async function unlinkCollectionsForUniverse(universeId) {- if (typeof universeId !== 'string' || !universeId) return [];- const needle = universeId.slice(0, UNIVERSE_ID_MAX);- return serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });- const matches = all- .map((c, i) => (c.universeId === needle ? i : -1))- .filter((i) => i >= 0);- if (!matches.length) return [];- const next = [...all];- const unlinkedIds = [];- for (const i of matches) {- next[i] = { ...all[i], universeId: null };- unlinkedIds.push(all[i].id);- }- await writeAll(next);- return unlinkedIds;- });-}+export const unlinkCollectionsForUniverse = (universeId) =>+ clearOwnerLink('universeId', universeId, UNIVERSE_ID_MAX);-// Cascade a universe rename to its linked collection(s). Skips the-// rename-lock guard in updateCollection by writing the name directly — the-// lock exists to block user-driven renames, not system-driven cascades from-// the universe rename itself. Renames EVERY collection linked to this-// universe, not just the first match: hand-edited state or a pre--// serialization race could have left duplicate linked rows behind, and the-// stragglers would otherwise stay rename-locked under the old name forever.-// Returns the first updated collection (back-compat) — callers that need the-// full list can re-read after.-export async function renameCollectionForUniverse(universeId, newUniverseName) {- if (typeof universeId !== 'string' || !universeId) return null;- const needle = universeId.slice(0, UNIVERSE_ID_MAX);- return serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });- const matchIdxs = all- .map((c, i) => (c.universeId === needle ? i : -1))- .filter((i) => i >= 0);- if (!matchIdxs.length) return null;- const desired = universeCollectionNameFor(newUniverseName);- if (!desired) return all[matchIdxs[0]];- const now = new Date().toISOString();- const next = [...all];- let changed = false;- for (const i of matchIdxs) {- if (next[i].name === desired) continue;- next[i] = { ...next[i], name: desired, updatedAt: now };- changed = true;- }- if (!changed) return all[matchIdxs[0]];- await writeAll(next);- return next[matchIdxs[0]];- });-}+// Cascade a universe rename to its linked collection(s). Skips the rename-lock+// guard in updateCollection by writing the name directly — the lock exists to+// block user-driven renames, not system-driven cascades from the universe+// rename itself.+export const renameCollectionForUniverse = (universeId, newUniverseName) =>+ renameOwnerLinked('universeId', universeId, UNIVERSE_ID_MAX, universeCollectionNameFor, newUniverseName);export async function updateCollection(id, patch) {- const merged = await serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });- const idx = all.findIndex((c) => c.id === id);- if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);- const cur = all[idx];+ const merged = await store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);if (cur.deleted === true) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);// Product/UI constraint: universe-linked collections own their visible// name. The name is the user-facing identity of a universe's bucket, so@@ -636,9 +613,7 @@ export async function updateCollection(id, patch) {...('coverKey' in patch ? { coverKey: patch.coverKey } : {}),updatedAt: new Date().toISOString(),};- const next = [...all];- next[idx] = merged;- await writeAll(next);+ await store().saveOneNow(id, merged);return merged;});// A standalone collection (no universe/series link) reaches peers ONLY via a@@ -653,22 +628,20 @@ export async function updateCollection(id, patch) {}export async function deleteCollection(id) {- const { universeId: deletedUniverseId, seriesId: deletedSeriesId, alreadyDeleted } = await serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });- const idx = all.findIndex((c) => c.id === id);- if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);- const target = all[idx];+ const { universeId: deletedUniverseId, seriesId: deletedSeriesId, alreadyDeleted } = await store().queueRecordWrite(id, async () => {+ const target = await store().loadOne(id);+ if (!target) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);// Idempotent on an already-tombstoned record: re-stamping deletedAt/// updatedAt would make an old tombstone look "newer" to a peer's LWW (and// re-emitting churns the sync pipeline). Return without rewriting or// re-emitting.if (target.deleted === true) return { universeId: null, seriesId: null, alreadyDeleted: true };const now = new Date().toISOString();- const next = [...all];- // Clear coverKey too — with items emptied it would otherwise dangle- // (point at a non-existent item) and leak into the tombstone's wire payload.- next[idx] = { ...target, deleted: true, deletedAt: now, updatedAt: now, items: [], coverKey: null, universeId: null, seriesId: null };- await writeAll(next);+ // Soft-delete: keep the record on disk as a tombstone (NOT deleteOne) so it+ // still syncs to peers as a deletion. Clear coverKey/items too — with items+ // emptied the cover would otherwise dangle and leak into the wire payload.+ const tombstone = { ...target, deleted: true, deletedAt: now, updatedAt: now, items: [], coverKey: null, universeId: null, seriesId: null };+ await store().saveOneNow(id, tombstone);return { universeId: target.universeId || null, seriesId: target.seriesId || null, alreadyDeleted: false };});if (alreadyDeleted) return { id };@@ -712,11 +685,9 @@ const validateItemInput = (item) => {export async function addItem(id, item) {const { kind, ref } = validateItemInput(item);- const merged = await serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });- const idx = all.findIndex((c) => c.id === id);- if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);- const cur = all[idx];+ const merged = await store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);// A soft-deleted collection behaves as not-found for mutations (matches// updateCollection) — never resurrect a tombstone or churn its timestamps.if (cur.deleted === true) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);@@ -732,9 +703,7 @@ export async function addItem(id, item) {items: [...cur.items, { kind, ref, addedAt: new Date().toISOString() }],updatedAt: new Date().toISOString(),};- const next = [...all];- next[idx] = updated;- await writeAll(next);+ await store().saveOneNow(id, updated);return updated;});// Emit outside the serialized critical section — subscribers may issue@@ -778,11 +747,9 @@ export async function bulkUpdateCollectionItems(id, { add = [], remove = [] } =}}- const result = await serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });- const idx = all.findIndex((c) => c.id === id);- if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);- const cur = all[idx];+ const result = await store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);// A soft-deleted collection behaves as not-found for mutations (matches// updateCollection) — never resurrect a tombstone or churn its timestamps.if (cur.deleted === true) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);@@ -820,9 +787,7 @@ export async function bulkUpdateCollectionItems(id, { add = [], remove = [] } =coverKey,updatedAt: now,};- const next = [...all];- next[idx] = merged;- await writeAll(next);+ await store().saveOneNow(id, merged);return { collection: merged, added: additions.length, removed };});if (result.added || result.removed) {@@ -834,11 +799,9 @@ export async function bulkUpdateCollectionItems(id, { add = [], remove = [] } =}export async function removeItem(id, key) {- const merged = await serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });- const idx = all.findIndex((c) => c.id === id);- if (idx < 0) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);- const cur = all[idx];+ const merged = await store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);// A soft-deleted collection behaves as not-found for mutations (matches// updateCollection) — never resurrect a tombstone or churn its timestamps.if (cur.deleted === true) throw makeErr(`Collection not found: ${id}`, ERR_NOT_FOUND);@@ -854,9 +817,7 @@ export async function removeItem(id, key) {coverKey: cur.coverKey === key ? null : cur.coverKey,updatedAt: new Date().toISOString(),};- const next = [...all];- next[idx] = updated;- await writeAll(next);+ await store().saveOneNow(id, updated);return updated;});emitRecordUpdated('mediaCollection', merged.id);@@ -869,17 +830,26 @@ export async function removeItem(id, key) {// Called by tombstoneGc once every subscribed peer has acked the deletion.export async function pruneTombstonedCollections(olderThanMs) {if (!Number.isFinite(olderThanMs)) return { pruned: 0 };- return serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });- const keep = all.filter((c) => {- if (c.deleted !== true) return true;- const ms = Date.parse(c.deletedAt || '');- return !(Number.isFinite(ms) && ms < olderThanMs);- });- if (keep.length === all.length) return { pruned: 0 };- await writeAll(keep);- return { pruned: all.length - keep.length };+ const all = await store().loadAll();+ const candidates = all.filter((c) => {+ if (c.deleted !== true) return false;+ const ms = Date.parse(c.deletedAt || '');+ return Number.isFinite(ms) && ms < olderThanMs;});+ let pruned = 0;+ for (const c of candidates) {+ await store().queueRecordWrite(c.id, async () => {+ // Re-check inside the queue (deleteOneNow spans the load→delete boundary)+ // so a concurrent re-create at the same id isn't blown away.+ const cur = await store().loadOne(c.id);+ if (!cur || cur.deleted !== true) return;+ const ms = Date.parse(cur.deletedAt || '');+ if (!(Number.isFinite(ms) && ms < olderThanMs)) return;+ await store().deleteOneNow(c.id);+ pruned += 1;+ });+ }+ return { pruned };}/**@@ -896,24 +866,22 @@ export async function pruneTombstonedCollections(olderThanMs) {* should retain both rather than discard whichever has the older* collection-level updatedAt.*- * Mutating writes go through the same `serializeFileWrite` tail as every- * other mediaCollections mutator so a concurrent local `addItem` and remote- * apply can't interleave on the JSON file.+ * Each remote collection's merge runs inside the store's per-record queue+ * (`queueRecordWrite(id)`), so a concurrent local `addItem` and a remote apply+ * against the SAME collection can't interleave, while merges of DIFFERENT+ * collections proceed in parallel.*/export async function mergeMediaCollectionsFromSync(remoteCollections) {if (!Array.isArray(remoteCollections)) return { applied: false, count: 0 };- return serializeFileWrite(async () => {- const all = await listCollections({ includeDeleted: true });- const localById = new Map(all.map((c) => [c.id, c]));- let changed = 0;- for (const remote of remoteCollections) {- const sanitized = sanitizeCollection(remote);- if (!sanitized) continue;- const local = localById.get(sanitized.id);+ let changed = 0;+ for (const remote of remoteCollections) {+ const sanitized = sanitizeCollection(remote);+ if (!sanitized) continue;+ const didChange = await store().queueRecordWrite(sanitized.id, async () => {+ const local = await store().loadOne(sanitized.id);if (!local) {- localById.set(sanitized.id, sanitized);- changed++;- continue;+ await store().saveOneNow(sanitized.id, sanitized);+ return true;}const mergedItems = mergeCollectionItems(local.items, sanitized.items);// LWW on collection-level scalars. Parse to epoch ms (not lexicographic@@ -949,14 +917,14 @@ export async function mergeMediaCollectionsFromSync(remoteCollections) {deleted: scalarDeleted,deletedAt: scalarDeleted ? (scalarSource.deletedAt || (remoteWins ? remoteTs : localTs)) : null,};- if (collectionsEqual(local, next)) continue;- localById.set(sanitized.id, next);- changed++;- }- if (changed === 0) return { applied: false, count: 0 };- await writeAll(Array.from(localById.values()));- return { applied: true, count: changed };- });+ if (collectionsEqual(local, next)) return false;+ await store().saveOneNow(sanitized.id, next);+ return true;+ });+ if (didChange) changed++;+ }+ if (changed === 0) return { applied: false, count: 0 };+ return { applied: true, count: changed };}function mergeCollectionItems(localItems, remoteItems) {diff --git a/server/services/mediaCollections.test.js b/server/services/mediaCollections.test.jsindex bd61636f6c..f180cc7c9e 100644--- a/server/services/mediaCollections.test.js+++ b/server/services/mediaCollections.test.js@@ -1,15 +1,22 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { mkdtempSync, rmSync, mkdirSync } from 'fs';+import { writeFile, mkdir, readFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';import { mockNoPeerSync } from '../lib/mockPathsDataRoot.js';-const fileStore = new Map();--vi.mock('../lib/fileUtils.js', () => ({-tryReadFile: vi.fn().mockResolvedValue(null),- PATHS: { data: '/mock/data' },- ensureDir: vi.fn().mockResolvedValue(undefined),- atomicWrite: vi.fn(async (path, data) => { fileStore.set(path, data); }),- readJSONFile: vi.fn(async (path, fallback) => fileStore.has(path) ? fileStore.get(path) : fallback),-}));+// Real per-suite tmpdir backing the per-record media-collections/ layout that+// migration 059 produces. The fileUtils mock below overrides PATHS.data so the+// service + collectionStore land here instead of the real ./data; everything+// else (atomicWrite/readJSONFile/ensureDir) uses the real impl so the store's+// readdir/lstat/rm operate against a real fs tree.+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), 'media-collections-test-'));+const COLLECTIONS_DIR = join(TEST_DATA_ROOT, 'media-collections');++vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return { ...actual, PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT } };+});// Suppress the fire-and-forget dynamic import so tests don't load the real// peerSync module graph (which reads the live peer registry and imports@@ -24,11 +31,43 @@ vi.mock('crypto', async () => {const svc = await import('./mediaCollections.js');+// Wipe + recreate the collections dir before every test so each starts clean.+// The empty dir means collectionStore's readdir is the source of truth and its+// process-local knownIds fallback never leaks ids across tests.+function resetStore() {+ rmSync(COLLECTIONS_DIR, { recursive: true, force: true });+ mkdirSync(COLLECTIONS_DIR, { recursive: true });+ uuidCounter = 0;+}++// Seed per-record files exactly as migration 059 would (one dir per record ++// a type-level index.json). Takes the same `{ collections: [...] }` shape the+// suite previously handed to the monolithic file store.+async function seedState({ collections = [] } = {}) {+ await mkdir(COLLECTIONS_DIR, { recursive: true });+ for (const c of collections) {+ const recDir = join(COLLECTIONS_DIR, c.id);+ await mkdir(recDir, { recursive: true });+ await writeFile(join(recDir, 'index.json'), JSON.stringify(c, null, 2));+ }+ await writeFile(join(COLLECTIONS_DIR, 'index.json'), JSON.stringify({+ schemaVersion: 1, type: 'mediaCollections', updatedAt: new Date().toISOString(), config: {},+ }, null, 2));+}++// Read the raw persisted record (pre-sanitize) for storage-level assertions.+async function readStored(id) {+ const raw = await readFile(join(COLLECTIONS_DIR, id, 'index.json'), 'utf-8').catch(() => null);+ return raw ? JSON.parse(raw) : null;+}++afterAll(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+});++beforeEach(() => resetStore());+describe('mediaCollections service', () => {- beforeEach(() => {- fileStore.clear();- uuidCounter = 0;- });it('listCollections returns [] for fresh state', async () => {expect(await svc.listCollections()).toEqual([]);@@ -115,7 +154,7 @@ describe('mediaCollections service', () => {await svc.deleteCollection(c.id);// Assert on the PERSISTED record — listCollections' sanitizer would null a// dangling coverKey on read regardless, so inspect storage directly.- const stored = fileStore.get('/mock/data/media-collections.json').collections.find((x) => x.id === c.id);+ const stored = await readStored(c.id);expect(stored.deleted).toBe(true);expect(stored.items).toEqual([]);expect(stored.coverKey).toBeNull();@@ -293,7 +332,7 @@ describe('mediaCollections service', () => {const fat = { ...all[0], items: Array.from({ length: svc.ITEMS_MAX }, (_, i) => ({kind: 'image', ref: `r${i}.png`, addedAt: new Date().toISOString(),})) };- fileStore.set('/mock/data/media-collections.json', { collections: [fat] });+ await seedState({ collections: [fat] });await expect(svc.bulkUpdateCollectionItems(c.id, {add: [{ kind: 'image', ref: 'overflow.png' }],})).rejects.toMatchObject({ code: svc.ERR_VALIDATION });@@ -381,7 +420,7 @@ describe('mediaCollections service', () => {const a = await svc.findOrCreateCollectionByName({name: 'Universe: OldName', universeId: 'u-1',});- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [a,{ ...a, id: 'dup-id', name: 'Universe: OldName' },@@ -419,7 +458,7 @@ describe('mediaCollections service', () => {it('unlinkCollectionsForUniverse preserves updatedAt (cascade side-effect, not a user edit)', async () => {// The bump would let the unlinked bucket out-race its own tombstone on a// peer during a universe merge — see unlinkCollectionsForUniverse's note.- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'uc-u1', name: 'Universe: Foo', description: '', coverKey: null,universeId: 'u-1', seriesId: null,@@ -584,7 +623,7 @@ describe('mediaCollections service', () => {});const current = await svc.listCollections();current[0] = { ...current[0], name: 'Universe: SomeOtherName' };- fileStore.set('/mock/data/media-collections.json', { collections: current });+ await seedState({ collections: current });const found = await svc.findOrCreateUniverseCollection({universeId: 'u-1', universeName: 'NewName',});@@ -747,7 +786,7 @@ describe('mediaCollections service', () => {});it('unlinkCollectionsForSeries preserves updatedAt (cascade side-effect, not a user edit)', async () => {- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'sc-ser1', name: 'Series: Foo', description: '', coverKey: null,universeId: null, seriesId: 'ser-1',@@ -797,7 +836,7 @@ describe('mediaCollections service', () => {});it('sanitizer drops seriesId when universeId is also set (universeId wins)', async () => {- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'c1', name: 'Mixed', items: [],universeId: 'u-1', seriesId: 'ser-1',@@ -811,7 +850,7 @@ describe('mediaCollections service', () => {});it('sanitizes hand-edited JSON with bogus items', async () => {- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{ id: 'c1', name: 'OK', items: [{ kind: 'image', ref: 'a.png' },@@ -828,11 +867,6 @@ describe('mediaCollections service', () => {});describe('mergeMediaCollectionsFromSync', () => {- beforeEach(() => {- fileStore.clear();- uuidCounter = 0;- });-it('returns {applied:false,count:0} for empty / non-array input', async () => {expect(await svc.mergeMediaCollectionsFromSync(null)).toEqual({ applied: false, count: 0 });expect(await svc.mergeMediaCollectionsFromSync('nope')).toEqual({ applied: false, count: 0 });@@ -861,7 +895,7 @@ describe('mergeMediaCollectionsFromSync', () => {});it('unions items by kind:ref so neither side ever loses a render', async () => {- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'c1',name: 'A',@@ -902,7 +936,7 @@ describe('mergeMediaCollectionsFromSync', () => {});it('LWW: newer remote wins on top-level scalars (name, description, coverKey)', async () => {- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'c1',name: 'Old Name',@@ -935,7 +969,7 @@ describe('mergeMediaCollectionsFromSync', () => {});it('LWW: older remote loses on scalars, but items still union', async () => {- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'c1',name: 'Local',@@ -978,7 +1012,7 @@ describe('mergeMediaCollectionsFromSync', () => {// own (older) tombstone would then lose LWW and a live duplicate would// survive. Because the cascade unlink preserves updatedAt, the tombstone// still wins and converges to deleted.- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'uc-loser',name: 'Universe: Clandestiny',@@ -1018,7 +1052,7 @@ describe('mergeMediaCollectionsFromSync', () => {});it('reports count:0 when nothing actually changes (no-op no-op)', async () => {- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'c1',name: 'A',@@ -1047,7 +1081,7 @@ describe('mergeMediaCollectionsFromSync', () => {});it('drops dangling coverKey that points at an item missing post-union', async () => {- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'c1',name: 'A',@@ -1124,7 +1158,7 @@ describe('mergeMediaCollectionsFromSync', () => {// wrong way. The slash-format timestamp here ('05/22/2026 18:00 UTC')// sorts BEFORE the ISO timestamp lexicographically ('0' < '2'), but// it's actually LATER in real time — so remote should win.- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'c1', name: 'Local', description: 'local', coverKey: null,universeId: null, seriesId: null,@@ -1150,7 +1184,7 @@ describe('mergeMediaCollectionsFromSync', () => {// Defense in depth — a hand-edit or corrupted record shipping a// garbage `updatedAt` shouldn't be able to claim "newer" than a valid// local record and overwrite its scalars.- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'c1', name: 'Local', description: 'local', coverKey: null,universeId: null, seriesId: null,@@ -1254,7 +1288,7 @@ describe('mergeMediaCollectionsFromSync', () => {// deletedAt. The effective deletion time should align with the most-recent// timestamp (updatedAt), not createdAt — otherwise LWW + GC see it as far// older than it really is.- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'c1', name: 'Gone', description: '', coverKey: null,universeId: null, seriesId: null, items: [],@@ -1275,7 +1309,7 @@ describe('mergeMediaCollectionsFromSync', () => {// digit '0' sorts before '2'), but as parsed timestamps the slash-format// is actually EARLIER here. Numeric compare keeps "earlier wins" honest// across formats.- fileStore.set('/mock/data/media-collections.json', {+ await seedState({collections: [{id: 'c1', name: 'A', description: '', coverKey: null,universeId: null, seriesId: null,@@ -1403,26 +1437,14 @@ describe('mutators — mediaCollection updated emission (standalone per-record s});describe('pruneTombstonedCollections', () => {- beforeEach(() => {- fileStore.clear();- uuidCounter = 0;- });-it('prunes tombstoned collections older than the cutoff and returns the count', async () => {// Create a live collection and soft-delete it with an old timestamp by// injecting the tombstone directly into the file store.const c = await svc.createCollection({ name: 'ToDelete' });const oldTs = new Date(Date.now() - 48 * 60 * 60 * 1000).toISOString();- // Overwrite the file store with a tombstone carrying an old deletedAt.- const { atomicWrite, readJSONFile } = await import('../lib/fileUtils.js');- const path = '/mock/data/media-collections.json';- const current = await readJSONFile(path, { collections: [] });- const withTombstone = current.collections.map((col) =>- col.id === c.id- ? { ...col, deleted: true, deletedAt: oldTs, updatedAt: oldTs, items: [] }- : col,- );- await atomicWrite(path, { collections: withTombstone });+ // Re-seed the record as a tombstone carrying an old deletedAt.+ const stored = await readStored(c.id);+ await seedState({ collections: [{ ...stored, deleted: true, deletedAt: oldTs, updatedAt: oldTs, items: [] }] });const result = await svc.pruneTombstonedCollections(Date.now());expect(result).toEqual({ pruned: 1 });@@ -1438,17 +1460,10 @@ describe('pruneTombstonedCollections', () => {it('does NOT prune a tombstone newer than the cutoff', async () => {const c = await svc.createCollection({ name: 'RecentDelete' });- // Soft-delete with a future timestamp (simulating a delete that just happened).- const { atomicWrite, readJSONFile } = await import('../lib/fileUtils.js');- const path = '/mock/data/media-collections.json';- const current = await readJSONFile(path, { collections: [] });+ // Re-seed as a tombstone with a future timestamp (simulating a delete that just happened).const futureTs = new Date(Date.now() + 60 * 1000).toISOString();- const withTombstone = current.collections.map((col) =>- col.id === c.id- ? { ...col, deleted: true, deletedAt: futureTs, updatedAt: futureTs, items: [] }- : col,- );- await atomicWrite(path, { collections: withTombstone });+ const stored = await readStored(c.id);+ await seedState({ collections: [{ ...stored, deleted: true, deletedAt: futureTs, updatedAt: futureTs, items: [] }] });// Cut-off is now; the tombstone's deletedAt is in the future → not pruned.const result = await svc.pruneTombstonedCollections(Date.now());