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
feat([data-versioning-split-pipeline-issues]): split pipeline storage
Adam Eivy092aef52131f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9138c825b3..54beec748c 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -12,6 +12,7 @@- **Bumped the bundled `lib/slashdo` submodule v2.18.0 → v3.1.0.** v3.1.0's `/do:pr` / `/do:release` accept an ordered, comma-separated `--review-with` list plus `--review-stop-on-*` and `--reviewer-applies` flags — the slashdo capability this release wires into the task forms. Added `.claude/commands/do/` symlinks for the new `depfree` / `pr-better` / `scan` commands so the in-repo project slash-command set matches the vendored submodule.- `data.sample/` renamed to `data.reference/` to reflect its actual role: the canonical reference / seed source consumed by `scripts/setup-data.js` (and by migrations that look up the post-migration shipped version of a file). The old name implied "optional samples"; the new name conveys "this is what `./data/` is bootstrapped from and compared against." All code, tests, and active docs (CLAUDE.md, README, docs/) updated; historical `.changelog/v*.md` entries kept as-is since they describe past releases. The `DATA_SAMPLE_DIR` constant in `server/index.js` is now `DATA_REFERENCE_DIR`; `sampleDir` in `setup-data.js` is now `referenceDir`.- `server/services/universeBuilder.js` rewritten to consume `collectionStore` instead of `readJSONFile` + `atomicWrite` against a monolithic file. The per-entity `CURRENT_SCHEMA_VERSION = 4` (stamped INSIDE each universe record) is preserved unchanged — it describes record shape and is orthogonal to the new type-level `schemaVersion: 5` (storage layout). Cross-record state (`runs[]` history) moves to `data/universes/index.json` under `config.runs`. Per-record edits no longer serialize against unrelated universe edits — concurrent PATCHes on different universes now run in parallel.+- **[data-versioning-split-pipeline-issues] Split pipeline issues and series into collection stores.** `data/pipeline-issues.json` now migrates to `data/pipeline-issues/{id}/index.json` via migration 035, and `data/pipeline-series.json` migrates to `data/pipeline-series/{id}/index.json` via migration 036 so the pipeline area lands on one storage convention. The issue and series services now use `collectionStore` with boot-time schema verification, per-record saves for ordinary issue/series edits, series-scoped queues only where issue renumbering touches siblings, and sync snapshots read through the service APIs instead of monolithic files.- `server/services/dataSync.js` universe-sync category points at the new `data/universes/` directory. `readFingerprintMap` walks two levels deep so per-record edits invalidate the cache; the dir layout's `index.json` mtime catches add/remove/edit at every nesting level. `getUniverseSnapshot()` reads via `listUniverses({ includeDeleted: true })` so peer sync sees the same set tombstones included.- `/work <task>` Claude Code slash command (`.claude/commands/work.md`) — slugifies the task, spins up a fresh git worktree under `.claude/worktrees/<slug>/` branched off local `main` (NOT current HEAD), `cd`s into it, carries out the work without disturbing the originating checkout's uncommitted edits / branch / HEAD, and on completion always chains `/simplify` → `/do:review --with codex,gemini` → `/do:pr --review-with copilot` so codex + gemini findings are addressed locally *before* the PR opens (otherwise Copilot kicks in immediately on unreviewed code and burns review cycles). Branch / dir collision auto-suffixes with `-2`, `-3`, etc. `.claude/worktrees/` is already gitignored.- **Fork-aware update flow.** The PortOS update tab now detects whether the local clone's `origin` remote points at upstream `atomantic/PortOS` or at a personal fork (`server/lib/gitRemote.js` parses SCP-style + HTTPS + ssh:// remote URLs, case-insensitive owner/repo match). When running from a fork the Update tab swaps the "Update Now" button for three explicit choices: **Sync Fork & Update** (runs `gh repo sync <owner>/<fork> --source atomantic/PortOS --branch main` then proceeds with the local update — fast-forward only, so it refuses to clobber divergent fork commits), **Sync Fork Only** (sync without applying), and **Update from Fork As-Is** (skip sync, pull from your fork's origin — useful if you already merged upstream into your fork via your own workflow). The server `/api/update/execute` endpoint now gates fork runs behind either a fresh `lastForkSync` record (≤10 min, same fullName) or an explicit `acknowledgeFork: true` to avoid the silent "I clicked Update and nothing happened" failure mode when a fork's main is behind upstream. The release-check still polls `atomantic/PortOS` so fork users continue to see upstream version notifications. `POST /api/update/sync-fork` exposes the gh-sync action; a 409 with `FORK_DIVERGED` is returned when the fork's main has commits not on upstream, with guidance pointing the user at PRs / feature branches / the explicit `--force` escape hatch they can run from a terminal. `update.sh` / `update.ps1` now log the active origin URL so users can confirm in the update log which repo they actually pulled from.diff --git a/PLAN.md b/PLAN.mdindex 639abff4d3..9dda9f381a 100644--- a/PLAN.md+++ b/PLAN.md@@ -4,8 +4,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel## Next Up-- [ ] [data-versioning-split-pipeline-issues] **Split `data/pipeline-issues.json` → `data/pipeline-issues/{id}/index.json` via `collectionStore`.** Highest-value follow-up from the data-versioning POC (PR #458). File is ~1MB / 173 records and every panel/page edit rewrites the whole thing through `server/services/pipeline/issues.js`'s `issueWriteTail` single-file queue. Per-record split gives the comic pipeline real concurrent-write headroom — multiple `PATCH /api/pipeline/issues/:id` calls against different issues stop blocking each other. Migration `035-split-pipeline-issues-to-per-id.js` mirrors `034-split-universe-builder-to-per-uuid.js`: pre-flight scan, atomic per-record writes, monolithic file renamed to `pipeline-issues.json.bak-035`. Bump `PORTOS_SCHEMA_VERSIONS.pipelineIssues` (new key) in `server/lib/schemaVersions.js` and register the store in `server/index.js`'s `verifyCollectionVersions` boot call. Per-record `schemaVersion` (record shape) stays where it is. Audit consumers of `loadIssues()` / `saveIssues()`: every caller must move to `store.loadOne` / `store.saveOne` / `store.listIds` + parallel load. Cross-record state in `pipeline-issues.json` (if any beyond the array — check before migrating) moves into `data/pipeline-issues/index.json`'s `config` slot.-- [ ] [data-versioning-split-pipeline-series] **Split `data/pipeline-series.json` → `data/pipeline-series/{id}/index.json`.** Lower record count than issues (21 records) but same structural fix; do it in the same PR as `[data-versioning-split-pipeline-issues]` so the pipeline area lands at one consistent layout. Same migration shape (`036-split-pipeline-series-to-per-id.js`) — mostly a copy-paste of the issues migration with type swapped.- [ ] [data-versioning-history-jsonl] **`data/history.json` → `data/history.jsonl` — proactive structural fix.** Data shape is append-only by definition; rewriting the whole array on every append is the wrong shape regardless of current size. Convert to line-delimited JSON so appends are O(1) instead of O(N) and `tail`-based reads / log rotation become trivial. Migration `037-history-json-to-jsonl.js`: read `data/history.json`, emit one line per entry, rename old file to `history.json.bak-037`. Add `appendJsonLine(path, obj)` + `readJsonLines(path, { from, limit })` helpers to `server/lib/fileUtils.js` (barrel + README) so `data/brain/digests.jsonl` and `data/brain/inbox_log.jsonl` (already JSONL but hand-rolled) can adopt the same primitives. Pair with a quick audit of other append-only-shaped monolithic files (`client-errors.json`?, `media-jobs.json`?) — convert any that match the shape in the same PR or a follow-up.- [ ] [test-autosubscribe-fanout-getpeers-guard-remaining] **Apply the `getPeers → []` test stub to the remaining record-creating test files (and consider a shared guard).** Root-caused 2026-05-23: `createUniverse` (universeBuilder.js:939) and `createSeries` (pipeline/series.js:223) fire a non-awaited `import('./sharing/peerSync.js').then(autoSubscribeRecordToAllPeers)`. `autoSubscribeRecordToAllPeers` reads the live peer registry via `getPeers()` (instances.js, `dataPath` closure to the REAL PATHS), so any test that creates a non-ephemeral universe/series and does NOT mock `getPeers` fans the fixture out to real peers (void/null/NaN), which persist it into real `data/`. Fixed in `universeBuilder.test.js`, `universeBuilderPromote.test.js`, `universeCanon.test.js` (this is how the "Moebius SciFi"/uuid-0000 leak happened). **Still unguarded** (create subscribable records, no `getPeers` mock — verified via `grep -L getPeers` against the createUniverse/createSeries/createIssue caller set): `pipeline/arcPlanner.test.js`, `pipeline/autoRunner.test.js`, `pipeline/coverUniverseFiler.test.js`, `pipeline/episodeVideo.test.js`, `pipeline/issues.test.js`, `pipeline/migrateSeriesCanon.test.js`, `pipeline/seasons.test.js`, `pipeline/series.test.js`, `pipeline/textStages.test.js`, `pipeline/volumeBeatsRunner.test.js`, `sharing/subscriptions.test.js`, `sharing/integration.test.js`, `universeBuilderAutoSort.test.js` (the last is safe-by-accident: its synthetic in-memory fileUtils mock lacks `dataPath`, which breaks the peerSync import chain — but that's fragile). These create *series*, so they'd pollute `data/pipeline-series/` not `data/universes/` (no residue found yet, but same race). The `sharing/*` ones likely set up real peers intentionally — handle carefully (don't blanket-stub). **Better fix to evaluate:** a shared `mockNoPeers()` helper in `server/lib/mockPathsDataRoot.js` (or a vitest `setupFiles` default stub that individual sharing tests can override) so every new record-creating test is protected by default instead of relying on each author remembering. Add the `getPeers→[]` convention to CLAUDE.md's test section.- [ ] [prune-orphan-subscriptions-for-deleted-records] **Sweep orphaned peer subscriptions left by tombstone prune.** `pruneTombstonedUniverses` / `pruneTombstonedSeries` rm the record dir but leave its rows in `data/peer_subscriptions.json`. After the 2026-05-23 leaked-fixture cleanup (22 universes force-pruned), the matching subs are now orphaned — on `peer:online`, `retryPendingPushesForPeer` walks them, `loadOne` returns null, and the push no-ops (harmless but inflates the "retrying N pending pushes" count — saw 141). Add an orphan-subscription sweep (drop subs whose `recordKind/recordId` no longer resolves to an on-disk record) to the tombstone GC path, or call it from the prune helpers. Low urgency; cosmetic + minor wasted work per sync cycle. Surfaced by /simplify efficiency review during the ai-fallback PR (2026-05-22). When a stuck provider has N simultaneous in-flight calls, each failure independently runs `pickFallbackProvider` → `getAllProviders()` → `loadProviders()` (which reads `providers.json` from disk every time — no in-memory cache) → `markUnavailable` (writing `provider-status.json`). Two fixes that compound: (a) add a tiny TTL cache (~1s) to `aiToolkit/providers.js#loadProviders` so the read cost is amortized; (b) coalesce per-provider failure handling in `promptRunner.js` with a `Map<providerId, Promise>` so subsequent failures for the same provider await the first's mark-and-pick result and skip the duplicate work. Together they cut N-way failure storms to one disk-write + one mark. Acceptance: under a simulated 10-concurrent-failure load, providers.json is read at most twice and provider-status.json is written once.diff --git a/scripts/migrations/035-036-split-pipeline-collections.test.js b/scripts/migrations/035-036-split-pipeline-collections.test.jsnew file mode 100644index 0000000000..90ea4c355d--- /dev/null+++ b/scripts/migrations/035-036-split-pipeline-collections.test.js@@ -0,0 +1,116 @@+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 issuesMigration from './035-split-pipeline-issues-to-per-id.js';+import seriesMigration from './036-split-pipeline-series-to-per-id.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++const cases = [+ {+ name: 'issues',+ migration: issuesMigration,+ legacyFile: 'pipeline-issues.json',+ backupSuffix: '.bak-035',+ typeDir: 'pipeline-issues',+ type: 'pipelineIssues',+ key: 'issues',+ validId: 'iss-alpha',+ otherId: 'iss-beta',+ invalidId: 'bad',+ },+ {+ name: 'series',+ migration: seriesMigration,+ legacyFile: 'pipeline-series.json',+ backupSuffix: '.bak-036',+ typeDir: 'pipeline-series',+ type: 'pipelineSeries',+ key: 'series',+ validId: 'ser-alpha',+ otherId: 'ser-beta',+ invalidId: 'bad',+ },+];++describe.each(cases)('migration split pipeline $name', (cfg) => {+ let rootDir;+ let dataDir;+ let legacyPath;+ let typeDir;+ let typeIndexPath;+ let backupPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), `migration-${cfg.name}-`));+ dataDir = join(rootDir, 'data');+ mkdirSync(dataDir, { recursive: true });+ legacyPath = join(dataDir, cfg.legacyFile);+ typeDir = join(dataDir, cfg.typeDir);+ typeIndexPath = join(typeDir, 'index.json');+ backupPath = legacyPath + cfg.backupSuffix;+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('fresh install stamps an empty type index', async () => {+ const result = await cfg.migration.up({ rootDir });+ expect(result).toEqual({ ok: true, reason: 'fresh-install' });+ const idx = readJson(typeIndexPath);+ expect(idx).toMatchObject({ schemaVersion: 1, type: cfg.type, config: {} });+ expect(existsSync(legacyPath)).toBe(false);+ expect(existsSync(backupPath)).toBe(false);+ });++ it('splits each valid record and backs up the legacy file', async () => {+ writeJson(legacyPath, {+ [cfg.key]: [+ { id: cfg.validId, name: 'Alpha', title: 'Alpha' },+ { id: cfg.otherId, name: 'Beta', title: 'Beta' },+ ],+ });++ const result = await cfg.migration.up({ rootDir });+ expect(result).toEqual({ ok: true, reason: 'split', written: 2, skipped: 0, invalid: 0 });+ expect(readJson(typeIndexPath).schemaVersion).toBe(1);+ expect(readJson(join(typeDir, cfg.validId, 'index.json')).id).toBe(cfg.validId);+ expect(readJson(join(typeDir, cfg.otherId, 'index.json')).id).toBe(cfg.otherId);+ expect(existsSync(legacyPath)).toBe(false);+ expect(existsSync(backupPath)).toBe(true);+ });++ it('recovers partial splits without clobbering already-split records', async () => {+ writeJson(legacyPath, {+ [cfg.key]: [+ { id: cfg.validId, name: 'Legacy', title: 'Legacy' },+ { id: cfg.otherId, name: 'Other', title: 'Other' },+ ],+ });+ mkdirSync(join(typeDir, cfg.validId), { recursive: true });+ writeJson(join(typeDir, cfg.validId, 'index.json'), { id: cfg.validId, name: 'Newer', title: 'Newer' });++ const result = await cfg.migration.up({ rootDir });+ expect(result).toEqual({ ok: true, reason: 'split', written: 1, skipped: 1, invalid: 0 });+ const preserved = readJson(join(typeDir, cfg.validId, 'index.json'));+ expect(preserved.name || preserved.title).toBe('Newer');+ expect(existsSync(join(typeDir, cfg.otherId, 'index.json'))).toBe(true);+ });++ it('skips invalid ids and reports unreadable legacy files', async () => {+ writeJson(legacyPath, { [cfg.key]: [{ id: cfg.validId }, { id: cfg.invalidId }, null] });+ const split = await cfg.migration.up({ rootDir });+ expect(split.written).toBe(1);+ expect(split.invalid).toBe(2);++ rmSync(rootDir, { recursive: true, force: true });+ mkdirSync(dataDir, { recursive: true });+ writeFileSync(legacyPath, 'not json');+ const unreadable = await cfg.migration.up({ rootDir });+ expect(unreadable).toEqual({ ok: false, reason: 'unreadable' });+ });+});diff --git a/scripts/migrations/035-split-pipeline-issues-to-per-id.js b/scripts/migrations/035-split-pipeline-issues-to-per-id.jsnew file mode 100644index 0000000000..a0b1b0adb6--- /dev/null+++ b/scripts/migrations/035-split-pipeline-issues-to-per-id.js@@ -0,0 +1,129 @@+/**+ * Split `data/pipeline-issues.json` into per-record files under+ * `data/pipeline-issues/{id}/index.json`.+ *+ * The legacy single-file shape serialized every issue edit behind one write+ * queue. The collection layout keeps record writes scoped to the issue id, so+ * unrelated issue PATCHes can proceed independently.+ */++import { readFile, writeFile, rename, mkdir, stat, readdir } from 'fs/promises';+import { join } from 'path';++const TYPE_DIR_NAME = 'pipeline-issues';+const LEGACY_FILENAME = 'pipeline-issues.json';+const BACKUP_SUFFIX = '.bak-035';+const TYPE_SCHEMA_VERSION = 1;+const TYPE_LABEL = 'pipelineIssues';+const VALID_ID = /^iss-[A-Za-z0-9-]+$/;++const fileExists = (path) => stat(path).then(() => true, (err) => {+ if (err.code === 'ENOENT') return false;+ throw err;+});++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');++async function existingRecordIds(typeDir) {+ const ids = new Set();+ if (!await fileExists(typeDir)) return ids;+ const entries = await readdir(typeDir, { withFileTypes: true }).catch(() => []);+ for (const entry of entries) {+ if (entry.name === 'index.json' || entry.name.startsWith('.') || !entry.isDirectory()) continue;+ if (await fileExists(join(typeDir, entry.name, 'index.json'))) ids.add(entry.name);+ }+ return ids;+}++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;++ const typeIndex = await readJsonStrict(typeIndexPath);+ if (typeIndex && typeIndex.schemaVersion >= TYPE_SCHEMA_VERSION) {+ console.log(`📦 migration 035: pipeline issues already at schemaVersion=${typeIndex.schemaVersion} — no-op`);+ return { ok: true, reason: 'already-applied' };+ }++ const legacyExists = await fileExists(legacyPath);+ const backupExists = await fileExists(backupPath);+ 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 035: fresh install — stamped data/${TYPE_DIR_NAME}/index.json @ v${TYPE_SCHEMA_VERSION}`);+ return { ok: true, reason: 'fresh-install' };+ }++ const sourcePath = legacyExists ? legacyPath : backupPath;+ const doc = await readJsonTolerant(sourcePath);+ if (!doc || typeof doc !== 'object' || doc.__unreadable) {+ console.warn(`⚠️ migration 035: ${sourcePath} unreadable — skipping. Resolve manually before next boot.`);+ return { ok: false, reason: 'unreadable' };+ }++ const issues = Array.isArray(doc.issues) ? doc.issues : [];+ const existingIds = await existingRecordIds(typeDir);+ await mkdir(typeDir, { recursive: true });++ let written = 0;+ let skipped = 0;+ let invalid = 0;+ for (const record of issues) {+ if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !VALID_ID.test(record.id)) {+ invalid += 1;+ console.warn(`⚠️ migration 035: skipping issue with invalid id "${record?.id ?? null}"`);+ continue;+ }+ if (existingIds.has(record.id)) {+ skipped += 1;+ continue;+ }+ await mkdir(join(typeDir, record.id), { recursive: true });+ await writeJson(join(typeDir, record.id, 'index.json'), record);+ written += 1;+ }++ await writeJson(typeIndexPath, {+ schemaVersion: TYPE_SCHEMA_VERSION,+ type: TYPE_LABEL,+ updatedAt: new Date().toISOString(),+ config: {},+ });++ if (legacyExists) await rename(legacyPath, backupPath);++ console.log(+ `📦 migration 035: split ${written} issue(s) into data/${TYPE_DIR_NAME}/<id>/index.json ` ++ `(${skipped} already split, ${invalid} invalid); legacy file backed up as ${LEGACY_FILENAME}${BACKUP_SUFFIX}`,+ );+ return { ok: true, reason: 'split', written, skipped, invalid };+ },+};diff --git a/scripts/migrations/036-split-pipeline-series-to-per-id.js b/scripts/migrations/036-split-pipeline-series-to-per-id.jsnew file mode 100644index 0000000000..c65a4e35b4--- /dev/null+++ b/scripts/migrations/036-split-pipeline-series-to-per-id.js@@ -0,0 +1,125 @@+/**+ * Split `data/pipeline-series.json` into per-record files under+ * `data/pipeline-series/{id}/index.json`.+ */++import { readFile, writeFile, rename, mkdir, stat, readdir } from 'fs/promises';+import { join } from 'path';++const TYPE_DIR_NAME = 'pipeline-series';+const LEGACY_FILENAME = 'pipeline-series.json';+const BACKUP_SUFFIX = '.bak-036';+const TYPE_SCHEMA_VERSION = 1;+const TYPE_LABEL = 'pipelineSeries';+const VALID_ID = /^ser-[A-Za-z0-9-]+$/;++const fileExists = (path) => stat(path).then(() => true, (err) => {+ if (err.code === 'ENOENT') return false;+ throw err;+});++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');++async function existingRecordIds(typeDir) {+ const ids = new Set();+ if (!await fileExists(typeDir)) return ids;+ const entries = await readdir(typeDir, { withFileTypes: true }).catch(() => []);+ for (const entry of entries) {+ if (entry.name === 'index.json' || entry.name.startsWith('.') || !entry.isDirectory()) continue;+ if (await fileExists(join(typeDir, entry.name, 'index.json'))) ids.add(entry.name);+ }+ return ids;+}++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;++ const typeIndex = await readJsonStrict(typeIndexPath);+ if (typeIndex && typeIndex.schemaVersion >= TYPE_SCHEMA_VERSION) {+ console.log(`📦 migration 036: pipeline series already at schemaVersion=${typeIndex.schemaVersion} — no-op`);+ return { ok: true, reason: 'already-applied' };+ }++ const legacyExists = await fileExists(legacyPath);+ const backupExists = await fileExists(backupPath);+ 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 036: fresh install — stamped data/${TYPE_DIR_NAME}/index.json @ v${TYPE_SCHEMA_VERSION}`);+ return { ok: true, reason: 'fresh-install' };+ }++ const sourcePath = legacyExists ? legacyPath : backupPath;+ const doc = await readJsonTolerant(sourcePath);+ if (!doc || typeof doc !== 'object' || doc.__unreadable) {+ console.warn(`⚠️ migration 036: ${sourcePath} unreadable — skipping. Resolve manually before next boot.`);+ return { ok: false, reason: 'unreadable' };+ }++ const series = Array.isArray(doc.series) ? doc.series : [];+ const existingIds = await existingRecordIds(typeDir);+ await mkdir(typeDir, { recursive: true });++ let written = 0;+ let skipped = 0;+ let invalid = 0;+ for (const record of series) {+ if (!record || typeof record !== 'object' || typeof record.id !== 'string' || !VALID_ID.test(record.id)) {+ invalid += 1;+ console.warn(`⚠️ migration 036: skipping series with invalid id "${record?.id ?? null}"`);+ continue;+ }+ if (existingIds.has(record.id)) {+ skipped += 1;+ continue;+ }+ await mkdir(join(typeDir, record.id), { recursive: true });+ await writeJson(join(typeDir, record.id, 'index.json'), record);+ written += 1;+ }++ await writeJson(typeIndexPath, {+ schemaVersion: TYPE_SCHEMA_VERSION,+ type: TYPE_LABEL,+ updatedAt: new Date().toISOString(),+ config: {},+ });++ if (legacyExists) await rename(legacyPath, backupPath);++ console.log(+ `📦 migration 036: split ${written} series record(s) into data/${TYPE_DIR_NAME}/<id>/index.json ` ++ `(${skipped} already split, ${invalid} invalid); legacy file backed up as ${LEGACY_FILENAME}${BACKUP_SUFFIX}`,+ );+ return { ok: true, reason: 'split', written, skipped, invalid };+ },+};diff --git a/server/index.js b/server/index.jsindex 09ac599a82..d243129c07 100644--- a/server/index.js+++ b/server/index.js@@ -141,6 +141,8 @@ import { createAIToolkit } from './lib/aiToolkit/index.js';import { runMigrations } from '../scripts/run-migrations.js';import { verifyCollectionVersions } from './lib/collectionStore.js';import { universeStore } from './services/universeBuilder.js';+import { seriesStore } from './services/pipeline/series.js';+import { issueStore } from './services/pipeline/issues.js';import { createPortOSProviderRoutes } from './routes/providers.js';import { createPortOSRunsRoutes } from './routes/runs.js';import { createPortOSPromptsRoutes } from './routes/prompts.js';@@ -196,7 +198,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()]).catch(err => {+await verifyCollectionVersions([universeStore(), seriesStore(), issueStore()]).catch(err => {console.error(`❌ Collection version check failed at startup: ${err?.stack ?? err}`);});diff --git a/server/lib/README.md b/server/lib/README.mdindex 91f7defeed..0a1745b8e7 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -80,7 +80,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|-| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records don't serialize. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. |+| `collectionStore.js` | Per-type, per-record JSON storage with explicit type-level `schemaVersion` stamping. Use for collections that have outgrown a monolithic JSON file. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `saveOneNow` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records don't serialize; `saveOneNow` is for callers already inside a collection write queue. Boot-time `verifyCollectionVersions([store, ...])` logs schema-version mismatches. || `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply on the comparator result so an upgraded sender can't corrupt a downstream peer. || `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `safeJSONParse`, dir scans, hashes, JSON helpers. Most paths/file work goes through here. || `fileWriteQueue.js` | Single-tail promise chain for serializing writes to a file. |diff --git a/server/lib/collectionStore.js b/server/lib/collectionStore.jsindex 7d75856530..7a314f07f7 100644--- a/server/lib/collectionStore.js+++ b/server/lib/collectionStore.js@@ -39,7 +39,8 @@* - `saveOne(id, record)` already wraps its write in `queueRecordWrite`, so* plain mutations don't need explicit queueing. Wrap a custom RMW cycle* in `queueRecordWrite(id, async () => { ... })` when an external read- * spans the load/save boundary.+ * spans the load/save boundary, then call `saveOneNow` inside that queue+ * so the queued function does not wait on itself.*/import { join } from 'path';@@ -92,6 +93,10 @@ export function createCollectionStore({const typeIndexPath = () => join(dir, 'index.json');const recordDir = (id) => join(dir, id);const recordPath = (id) => join(dir, id, 'index.json');+ // Process-local fallback for tests that mock fileUtils' read/write helpers+ // without backing them with a real directory tree. Production listIds still+ // uses readdir as the source of truth whenever the collection dir exists.+ const knownIds = new Set();const isValidId = (id) => typeof id === 'string' && idPattern.test(id);@@ -183,9 +188,10 @@ export function createCollectionStore({*/async function listIds() {const entries = await readdir(dir).catch((err) => {- if (err?.code === 'ENOENT') return [];+ if (err?.code === 'ENOENT') return null;throw err;});+ if (entries === null) return [...knownIds].filter(isValidId);const candidates = entries.filter((name) =>name !== 'index.json'&& !name.startsWith('.')@@ -251,6 +257,19 @@ export function createCollectionStore({* are expected to pre-sanitize before calling — same convention as the* monolithic-state services).*/+ async function saveOneNow(id, record) {+ if (!isValidId(id)) {+ throw new Error(`collectionStore[${type}]: invalid record id "${id}" — must match ${idPattern}`);+ }+ if (!isPlainObject(record)) {+ throw new Error(`collectionStore[${type}]: record must be a plain object`);+ }+ await ensureDir(recordDir(id));+ await atomicWrite(recordPath(id), record);+ knownIds.add(id);+ return record;+ }+function saveOne(id, record) {if (!isValidId(id)) {throw new Error(`collectionStore[${type}]: invalid record id "${id}" — must match ${idPattern}`);@@ -259,9 +278,7 @@ export function createCollectionStore({throw new Error(`collectionStore[${type}]: record must be a plain object`);}return queueRecordWrite(id, async () => {- await ensureDir(recordDir(id));- await atomicWrite(recordPath(id), record);- return record;+ return saveOneNow(id, record);});}@@ -277,6 +294,7 @@ export function createCollectionStore({}return queueRecordWrite(id, async () => {await rm(recordDir(id), { recursive: true, force: true });+ knownIds.delete(id);});}@@ -341,6 +359,7 @@ export function createCollectionStore({loadOne,loadOneRaw,loadAll,+ saveOneNow,saveOne,deleteOne,// Concurrency primitivesdiff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 156e072d04..59781e50fb 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -31,7 +31,11 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// v5 = post-split. Migration 034 introduced it. The per-record-shape version// stays at 4 (stamped inside each record by `sanitizeTemplate`).universes: 5,- // future: series: N, issues: N, mediaCollections: N, ...+ // v1 = post-split. Migrations 035/036 introduced the pipeline collection+ // layout for issues and series.+ pipelineIssues: 1,+ pipelineSeries: 1,+ // future: mediaCollections: N, ...});/**diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsindex 33f980b8fd..eb16d8b635 100644--- a/server/lib/schemaVersions.test.js+++ b/server/lib/schemaVersions.test.js@@ -18,6 +18,11 @@ describe('PORTOS_SCHEMA_VERSIONS', () => {// deliberate two-file edit.expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(5);});++ it('declares pipeline collection layout versions', () => {+ expect(PORTOS_SCHEMA_VERSIONS.pipelineIssues).toBe(1);+ expect(PORTOS_SCHEMA_VERSIONS.pipelineSeries).toBe(1);+ });});describe('buildPortosMeta', () => {@@ -25,6 +30,8 @@ describe('buildPortosMeta', () => {const meta = await buildPortosMeta();expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);expect(meta.schemaVersions.universes).toBe(5);+ expect(meta.schemaVersions.pipelineIssues).toBe(1);+ expect(meta.schemaVersions.pipelineSeries).toBe(1);});it('overrides merge into schemaVersions', async () => {@@ -105,7 +112,7 @@ describe('compareSchemaVersions', () => {expect(compareSchemaVersions(null, { universes: 5 }).behind).toHaveLength(1);expect(compareSchemaVersions(undefined, { universes: 5 }).behind).toHaveLength(1);// Default receiver is PORTOS_SCHEMA_VERSIONS (live).- expect(compareSchemaVersions(null).behind).toHaveLength(1);+ expect(compareSchemaVersions(null).behind).toHaveLength(Object.keys(PORTOS_SCHEMA_VERSIONS).length);});});diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex f319cf3052..184a3b0123 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -19,7 +19,7 @@ import {} from '../lib/schemaVersions.js';import { mergeUniversesFromSync, listUniverses } from './universeBuilder.js';import { mergeSeriesFromSync, listSeries } from './pipeline/series.js';-import { mergeIssuesFromSync } from './pipeline/issues.js';+import { mergeIssuesFromSync, listIssues } from './pipeline/issues.js';import { mergeMediaCollectionsFromSync, listCollections, itemKey } from './mediaCollections.js';import { sanitizeStateForWire } from '../lib/syncWire.js';@@ -32,8 +32,8 @@ const CHRONOTYPE_FILE = join(PATHS.digitalTwin, 'chronotype.json');const LONGEVITY_FILE = join(PATHS.digitalTwin, 'longevity.json');const FEEDBACK_FILE = join(PATHS.digitalTwin, 'feedback.json');const MEATSPACE_DIR = PATHS.meatspace;-const PIPELINE_SERIES_FILE = join(PATHS.data, 'pipeline-series.json');-const PIPELINE_ISSUES_FILE = join(PATHS.data, 'pipeline-issues.json');+const PIPELINE_SERIES_DIR = join(PATHS.data, 'pipeline-series');+const PIPELINE_ISSUES_DIR = join(PATHS.data, 'pipeline-issues');// Universes used to live in a single `universe-builder.json`; migration 034// splits them into `data/universes/<id>/index.json` with a type-level// `data/universes/index.json`. Sync uses the directory for both reading@@ -386,26 +386,22 @@ async function applyUniverseRemote(remoteData) {// --- Category: Pipeline ---async function getPipelineSnapshot() {- const [seriesFile, issuesFile] = await Promise.all([- readJSONFile(PIPELINE_SERIES_FILE, { series: [] }),- readJSONFile(PIPELINE_ISSUES_FILE, { issues: [] }),+ const [series, issues] = await Promise.all([+ listSeries({ includeDeleted: true }),+ listIssues({ includeDeleted: true }),]);// Wire-projection lives in `server/lib/syncWire.js` — see getUniverseSnapshot.const { data } = sanitizeStateForWire('pipeline', {- series: seriesFile.series,- issues: issuesFile.issues,+ series,+ issues,});return { data, checksum: computeChecksum(data) };}async function applyPipelineRemote(remoteData) {if (!remoteData) return { applied: false, count: 0 };- // Routes through the per-file merge entry points so each side's- // read-modify-write runs INSIDE its own file-level write queue- // (`queueSeriesWrite` / `queueIssueWrite`) — serialized against every other- // local writer (bible edits, season metadata PATCH, season-cover render- // PATCH, updateStage, etc.). Each incoming record passes through its- // service's sanitizer for shape enforcement on the way in.+ // Routes through the service merge entry points so each incoming record+ // passes through the same sanitizer and LWW contract as local writes.const [seriesResult, issuesResult] = await Promise.all([mergeSeriesFromSync(remoteData.series || []),mergeIssuesFromSync(remoteData.issues || []),@@ -541,13 +537,13 @@ const CHECKSUM_PATHS = {digitalTwin: Object.values(DIGITAL_TWIN_FILES).map((f) => f.path),meatspace: Object.keys(MEATSPACE_FILES).map((f) => join(MEATSPACE_DIR, f)),universe: [UNIVERSE_BUILDER_DIR],- pipeline: [PIPELINE_SERIES_FILE, PIPELINE_ISSUES_FILE],+ pipeline: [PIPELINE_SERIES_DIR, PIPELINE_ISSUES_DIR],// mediaCollections invalidates on its own file AND on the parent record// files — `getMediaCollectionsSnapshot` filters collections whose linked// 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_FILE],+ mediaCollections: [MEDIA_COLLECTIONS_FILE, UNIVERSE_BUILDER_DIR, PIPELINE_SERIES_DIR],};const CATEGORIES = {diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 8bf57c6abe..cf1632ff74 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -23,8 +23,8 @@ afterAll(cleanup);const dataSync = await import('./dataSync.js');-const SERIES_PATH = join(tempRoot, 'pipeline-series.json');-const ISSUES_PATH = join(tempRoot, 'pipeline-issues.json');+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');@@ -37,6 +37,32 @@ function readJSON(path) {return JSON.parse(readFileSync(path, 'utf-8'));}+function writeCollectionState(dir, type, records) {+ mkdirSync(dir, { recursive: true });+ writeJSON(join(dir, 'index.json'), {+ schemaVersion: 1,+ type,+ updatedAt: '2026-05-17T09:00:00Z',+ config: {},+ });+ for (const record of records) {+ mkdirSync(join(dir, record.id), { recursive: true });+ writeJSON(join(dir, record.id, 'index.json'), record);+ }+}++function readCollectionState(dir) {+ if (!existsSync(dir)) return [];+ return readdirSync(dir, { withFileTypes: true })+ .filter((entry) => entry.isDirectory())+ .map((entry) => readJSON(join(dir, entry.name, 'index.json')));+}++const writeSeriesState = (series) => writeCollectionState(SERIES_DIR, 'pipelineSeries', series);+const writeIssueState = (issues) => writeCollectionState(ISSUES_DIR, 'pipelineIssues', issues);+const readSeriesState = () => readCollectionState(SERIES_DIR);+const readIssueState = () => readCollectionState(ISSUES_DIR);+// Write the universes split layout (migration 034's output): one// `universes/<id>/index.json` per record + a type-level `universes/index.json`// whose `config.runs` carries the cross-record runs[] log.@@ -202,12 +228,8 @@ describe('dataSync — universe category', () => {describe('dataSync — pipeline category', () => {it('snapshot bundles series + issues from their respective files', async () => {- writeJSON(SERIES_PATH, {- series: [{ id: 'ser-1', name: 'A', updatedAt: '2026-05-17T10:00:00Z' }]- });- writeJSON(ISSUES_PATH, {- issues: [{ id: 'iss-1', seriesId: 'ser-1', title: 'One', updatedAt: '2026-05-17T10:00:00Z' }]- });+ writeSeriesState([{ id: 'ser-1', name: 'A', updatedAt: '2026-05-17T10:00:00Z' }]);+ writeIssueState([{ id: 'iss-1', seriesId: 'ser-1', title: 'One', updatedAt: '2026-05-17T10:00:00Z' }]);const snap = await dataSync.getSnapshot('pipeline');expect(snap.data.series).toHaveLength(1);expect(snap.data.issues).toHaveLength(1);@@ -221,8 +243,8 @@ describe('dataSync — pipeline category', () => {});it('applyRemote merges series + issues; count reports records actually changed', async () => {- writeJSON(SERIES_PATH, { series: [{ id: 'ser-1', name: 'Old', updatedAt: '2026-05-17T10:00:00Z' }] });- writeJSON(ISSUES_PATH, { issues: [] });+ writeSeriesState([{ id: 'ser-1', name: 'Old', updatedAt: '2026-05-17T10:00:00Z' }]);+ writeIssueState([]);const result = await dataSync.applyRemote('pipeline', {series: [@@ -242,21 +264,21 @@ describe('dataSync — pipeline category', () => {expect(result.seriesChanged).toBe(2);expect(result.issuesChanged).toBe(1);- const persistedSeries = readJSON(SERIES_PATH).series;+ const persistedSeries = readSeriesState();expect(persistedSeries).toHaveLength(2);expect(persistedSeries.find(s => s.id === 'ser-1').name).toBe('New'); // LWWexpect(persistedSeries.find(s => s.id === 'ser-2').name).toBe('Foundry');- const persistedIssues = readJSON(ISSUES_PATH).issues;+ const persistedIssues = readIssueState();expect(persistedIssues).toHaveLength(1);expect(persistedIssues[0].seriesId).toBe('ser-2');});it('applyRemote count reports only the changed side when only series differs', async () => {- writeJSON(SERIES_PATH, { series: [{ id: 'ser-1', name: 'Old', updatedAt: '2026-05-17T10:00:00Z' }] });+ writeSeriesState([{ id: 'ser-1', name: 'Old', updatedAt: '2026-05-17T10:00:00Z' }]);// Local issues exist but won't change — sync must not inflate count to// include them (the pre-fix bug counted total post-merge issues).- writeJSON(ISSUES_PATH, { issues: [{ id: 'iss-1', seriesId: 'ser-1', title: 'Local', updatedAt: '2026-05-17T10:00:00Z' }] });+ writeIssueState([{ id: 'iss-1', seriesId: 'ser-1', title: 'Local', updatedAt: '2026-05-17T10:00:00Z' }]);const result = await dataSync.applyRemote('pipeline', {series: [{ id: 'ser-1', name: 'New', updatedAt: '2026-05-17T11:00:00Z' }],@@ -269,22 +291,22 @@ describe('dataSync — pipeline category', () => {});it('applyRemote is a no-op when nothing is newer', async () => {- writeJSON(SERIES_PATH, { series: [{ id: 'ser-1', updatedAt: '2026-05-17T10:00:00Z' }] });- writeJSON(ISSUES_PATH, { issues: [{ id: 'iss-1', updatedAt: '2026-05-17T10:00:00Z' }] });+ writeSeriesState([{ id: 'ser-1', name: 'Old', updatedAt: '2026-05-17T10:00:00Z' }]);+ writeIssueState([{ id: 'iss-1', seriesId: 'ser-1', title: 'Local', updatedAt: '2026-05-17T10:00:00Z' }]);- const before = readJSON(SERIES_PATH);+ const before = readSeriesState();const result = await dataSync.applyRemote('pipeline', {series: [{ id: 'ser-1', updatedAt: '2026-05-17T10:00:00Z' }], // same tsissues: [{ id: 'iss-1', updatedAt: '2026-05-17T09:00:00Z' }] // older});expect(result.applied).toBe(false);expect(result.count).toBe(0);- expect(readJSON(SERIES_PATH)).toEqual(before);+ expect(readSeriesState()).toEqual(before);});it('applyRemote skips writes for unchanged sides (writes only what differs)', async () => {- writeJSON(SERIES_PATH, { series: [{ id: 'ser-1', updatedAt: '2026-05-17T10:00:00Z' }] });- writeJSON(ISSUES_PATH, { issues: [] });+ writeSeriesState([{ id: 'ser-1', name: 'Old', updatedAt: '2026-05-17T10:00:00Z' }]);+ writeIssueState([]);// Only issues change. Use a valid issue payload (id + seriesId + title)// since the merge now routes through sanitizeIssue.@@ -295,8 +317,8 @@ describe('dataSync — pipeline category', () => {// Series file untouched (no incidental rewrite that could clobber a// concurrent write outside the sync orchestrator).- expect(readJSON(SERIES_PATH).series[0].updatedAt).toBe('2026-05-17T10:00:00Z');- expect(readJSON(ISSUES_PATH).issues).toHaveLength(1);+ expect(readSeriesState()[0].updatedAt).toBe('2026-05-17T10:00:00Z');+ expect(readIssueState()).toHaveLength(1);});});@@ -326,13 +348,13 @@ describe('dataSync — getChecksum cache', () => {});it('reflects an out-of-band file mutation (pipeline series changes outside this service)', async () => {- writeJSON(SERIES_PATH, { series: [{ id: 'ser-1', updatedAt: '2026-05-17T10:00:00Z' }] });- writeJSON(ISSUES_PATH, { issues: [] });+ writeSeriesState([{ id: 'ser-1', name: 'Old', updatedAt: '2026-05-17T10:00:00Z' }]);+ writeIssueState([]);const before = await dataSync.getChecksum('pipeline');// Force a different mtime — vitest can run faster than the FS's ms tick,// so wait long enough that the mtime is guaranteed to advance.await new Promise((r) => setTimeout(r, 5));- writeJSON(SERIES_PATH, { series: [{ id: 'ser-1', updatedAt: '2026-05-17T11:00:00Z' }] });+ writeSeriesState([{ id: 'ser-1', name: 'New', updatedAt: '2026-05-17T11:00:00Z' }]);const after = await dataSync.getChecksum('pipeline');expect(after.checksum).not.toBe(before.checksum);});diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex 6d30547900..8cd38a2957 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -15,13 +15,13 @@* Each stage record carries a status, the user-editable input, the AI output,* and a `lastRunId` pointer into data/runs/<runId>/ for the LLM transcript.*- * Persisted to data/pipeline-issues.json.+ * Persisted to data/pipeline-issues/{id}/index.json.*/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 { isPlainObject } from '../../lib/objects.js';import { IMAGE_GEN_MODE } from '../imageGen/modes.js';import {@@ -38,15 +38,42 @@ import { emitRecordUpdated } from '../sharing/recordEvents.js';import { applyVolumeOrderedNumbers, UNSCOPED_ANCHOR } from '../../lib/pipelineIssueOrder.js';import * as seriesSvc from './series.js';-// Lazy resolution — see series.js for context.-const statePath = () => join(PATHS.data, 'pipeline-issues.json');+// TYPE-level (storage layout) schema version stamped on+// `data/pipeline-issues/index.json`.+// v1 — issues split out of monolithic `data/pipeline-issues.json` into+// per-record `data/pipeline-issues/{id}/index.json`. See migration 035.+const TYPE_SCHEMA_VERSION = 1;-// File-level write lock: serializes concurrent updateIssue / updateStage calls-// against the shared pipeline-issues.json state file so a blur-save PATCH can-// never clobber an in-flight cover-render PATCH (and vice-versa, across any-// pair of issues — not just two writes to the same issue id). CLAUDE.md:-// "simple re-entrancy guards… are fine and expected."-const queueIssueWrite = createFileWriteQueue();+let _store = null;+const store = () => {+ if (_store && _store.dir === join(PATHS.data, 'pipeline-issues')) return _store;+ _store = createCollectionStore({+ dir: join(PATHS.data, 'pipeline-issues'),+ type: 'pipelineIssues',+ schemaVersion: TYPE_SCHEMA_VERSION,+ sanitizeRecord: sanitizeIssue,+ idPattern: /^iss-[A-Za-z0-9-]+$/,+ });+ return _store;+};++export const issueStore = () => store();++// Series-scoped queue for mutations that can renumber siblings. Ordinary+// per-issue PATCH/stage writes use collectionStore's per-id queue so edits to+// different issues no longer serialize behind one monolithic JSON tail.+const seriesIssueTails = new Map();+function queueSeriesIssuesWrite(seriesId, fn) {+ const key = typeof seriesId === 'string' && seriesId ? seriesId : '__unknown__';+ const prev = seriesIssueTails.get(key) || Promise.resolve();+ const next = prev.then(fn, fn);+ const silenced = next.catch(() => {});+ seriesIssueTails.set(key, silenced);+ silenced.finally(() => {+ if (seriesIssueTails.get(key) === silenced) seriesIssueTails.delete(key);+ });+ return next;+}export const ERR_NOT_FOUND = 'PIPELINE_ISSUE_NOT_FOUND';export const ERR_VALIDATION = 'PIPELINE_ISSUE_VALIDATION';@@ -422,14 +449,16 @@ const sanitizeIssue = (raw) => {};async function readState() {- await ensureDir(PATHS.data);- const raw = await readJSONFile(statePath(), { issues: [] }, { logError: false });- const issues = Array.isArray(raw.issues) ? raw.issues.map(sanitizeIssue).filter(Boolean) : [];- return { issues };+ return { issues: await store().loadAll() };+}++async function saveIssueNow(issue) {+ await store().saveOneNow(issue.id, issue);+ return issue;}-async function writeState(state) {- await atomicWrite(statePath(), state);+async function saveIssuesNow(issues) {+ await Promise.all(issues.map((issue) => saveIssueNow(issue)));}export async function listIssues({@@ -486,8 +515,7 @@ export async function listRecentIssues({ limit = 10, withHistory = true, include}export async function getIssue(id, { includeDeleted = false } = {}) {- const { issues } = await readState();- const found = issues.find((i) => i.id === id);+ const found = await store().loadOne(id);if (!found) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);if (found.deleted && !includeDeleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);return found;@@ -498,7 +526,7 @@ export function createIssue(input = {}) {if (!seriesId) return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));const title = trimTo(input.title, TITLE_MAX);if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));- return queueIssueWrite(async () => {+ return queueSeriesIssuesWrite(seriesId, async () => {const state = await readState();const next = sanitizeIssue({id: `iss-${randomUUID()}`,@@ -523,11 +551,11 @@ export function createIssue(input = {}) {if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);state.issues.push(next);await renumberInline(state, seriesId, next.seasonId || UNSCOPED_ANCHOR);- await writeState(state);+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));// New issue = series-level change for any active share subscription.emitRecordUpdated('series', next.seriesId);return next;- }); // end queueIssueWrite+ });}async function renumberInline(state, seriesId, fromSeasonId = null) {@@ -545,11 +573,11 @@ async function renumberInline(state, seriesId, fromSeasonId = null) {}export function recomputeIssueNumbersForSeries(seriesId, fromSeasonId = null) {- return queueIssueWrite(async () => {+ return queueSeriesIssuesWrite(seriesId, async () => {const state = await readState();const changed = await renumberInline(state, seriesId, fromSeasonId);if (!changed) return { changed: false };- await writeState(state);+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));emitRecordUpdated('series', seriesId);return { changed: true };});@@ -557,12 +585,12 @@ export function recomputeIssueNumbersForSeries(seriesId, fromSeasonId = null) {/*** Reassign every issue under `(seriesId, fromSeasonId)` to `toSeasonId` in a- * single readState → in-memory mutate → writeState → one renumber pass.+ * single collection load → in-memory mutate → per-record save pass.* Used by `deleteSeason` (and any future bulk season-move flow) to collapse- * N per-issue queueIssueWrite cycles into one — the legacy N+1 pattern was+ * N per-issue write cycles into one — the legacy N+1 pattern was* `for (iss of children) await updateIssue(iss.id, { seasonId: toSeasonId }, { skipRenumber: true })`- * which paid N readState + N writeState round-trips and N debounced re-exports- * even with `withReexportSuppressed`.+ * which paid N read/write round-trips and N debounced re-exports even with+ * `withReexportSuppressed`.** Returns `{ reassigned, fromSeasonId, toSeasonId }`. `toSeasonId` may be* `null` (un-grouped). A re-export of the parent series is emitted once, after@@ -570,7 +598,7 @@ export function recomputeIssueNumbersForSeries(seriesId, fromSeasonId = null) {* `series:updated` event regardless of the issue count.*/export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null, { _preloadedSeries = null } = {}) {- return queueIssueWrite(async () => {+ return queueSeriesIssuesWrite(seriesId, async () => {// Honor per-season locks — refuse to move issues OUT of or INTO a locked// volume. Series lives in a different write queue, so this is best-effort// single-user gating, not strict serialization (fine per CLAUDE.md).@@ -615,7 +643,7 @@ export function bulkReassignSeason(seriesId, fromSeasonId, toSeasonId = null, {// One renumber pass after the bulk move — the source AND destination// volume both reshuffled, so use the series-wide form (fromSeasonId=null).await renumberInline(state, seriesId, null);- await writeState(state);+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));emitRecordUpdated('series', seriesId);return { reassigned, fromSeasonId, toSeasonId };});@@ -634,7 +662,7 @@ export function insertIssueWithId(input = {}) {if (!seriesId) return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));const title = trimTo(input.title, TITLE_MAX);if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));- return queueIssueWrite(async () => {+ return queueSeriesIssuesWrite(seriesId, async () => {const state = await readState();// Tombstone-overwrite: same contract as universeBuilder.insertUniverseWithId.const existingIdx = state.issues.findIndex((i) => i.id === input.id);@@ -652,110 +680,113 @@ export function insertIssueWithId(input = {}) {// Imported `number` is a starting hint — local canonical numbering still// comes from (volume order, arcPosition) of the local state.await renumberInline(state, seriesId, next.seasonId || UNSCOPED_ANCHOR);- await writeState(state);+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));return next;});}-export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {- return queueIssueWrite(async () => {- const state = await readState();- const idx = state.issues.findIndex((i) => i.id === id);- if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- const cur = state.issues[idx];- if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);-- // Per-stage merge: a stage patch carries only the fields the caller is- // changing (e.g. `{ genConfig }` or `{ cover }`). Without this, the top-level- // spread would replace the entire stage object and silently drop sibling- // fields like `scenes` / `pages` / `genConfig`. Sanitization then defaults- // those back to empty arrays/null, erasing work the user (or LLM) just did.- // Callers that need stage-level changes without touching issue-level fields- // should use `updateStage`, which does a shallow merge of the patch over the- // existing stage (`{ ...cur.stages[stageId], ...patch }`) before sanitizing.- // Note: `updateStage` still merges — omitted sibling stage fields are- // preserved. To clear a field explicitly, pass it as `null` or `""` in the- // patch.- //- // `cover` and `genConfig` are treated as deep-merge sub-objects: a partial- // `{ cover: { script } }` patch from a textarea-blur save must not wipe the- // sibling `imageJobId` / `prompt` that a parallel "Render cover" mutation- // just persisted. Passing `null` explicitly still clears the sub-object- // (intentional-clear semantics).- const NESTED_DEEP_MERGE_KEYS = ['cover', 'genConfig'];- let mergedStages = cur.stages;- if ('stages' in patch && patch.stages && typeof patch.stages === 'object') {- mergedStages = { ...cur.stages };- for (const [stageId, stagePatch] of Object.entries(patch.stages)) {- const prev = cur.stages?.[stageId];- if (prev && stagePatch && typeof prev === 'object' && typeof stagePatch === 'object') {- const merged = { ...prev, ...stagePatch };- // Mirror the snapshot trigger from updateStageWithLatest so a- // route-level PATCH that swaps lastRunId (e.g. the restore endpoint)- // also produces a runHistory entry. No-op when the patch is a plain- // save-edit without lastRunId.- merged.runHistory = snapshotRunHistory(prev, stagePatch, stageId);- for (const key of NESTED_DEEP_MERGE_KEYS) {- if (key in stagePatch- && stagePatch[key] && typeof stagePatch[key] === 'object'- && prev[key] && typeof prev[key] === 'object') {- merged[key] = { ...prev[key], ...stagePatch[key] };- }- }- // Clear transient error fields when a content/status change implies- // the previous failure is no longer the active state. Mirrors the- // pre-per-stage-merge behavior, where a `{ status, input, output }`- // patch replaced the whole stage and implicitly wiped errorMessage.- if ('status' in stagePatch && stagePatch.status !== 'error'- && stagePatch.status !== 'generating'- && !('errorMessage' in stagePatch)) {- merged.errorMessage = '';+function mergeIssuePatch(cur, patch = {}) {+ // Per-stage merge: a stage patch carries only the fields the caller is+ // changing (e.g. `{ genConfig }` or `{ cover }`). Without this, the top-level+ // spread would replace the entire stage object and silently drop sibling+ // fields like `scenes` / `pages` / `genConfig`. Sanitization then defaults+ // those back to empty arrays/null, erasing work the user (or LLM) just did.+ // Callers that need stage-level changes without touching issue-level fields+ // should use `updateStage`, which does a shallow merge of the patch over the+ // existing stage (`{ ...cur.stages[stageId], ...patch }`) before sanitizing.+ //+ // `cover` and `genConfig` are treated as deep-merge sub-objects: a partial+ // `{ cover: { script } }` patch from a textarea-blur save must not wipe the+ // sibling `imageJobId` / `prompt` that a parallel "Render cover" mutation+ // just persisted. Passing `null` explicitly still clears the sub-object.+ const NESTED_DEEP_MERGE_KEYS = ['cover', 'genConfig'];+ let mergedStages = cur.stages;+ if ('stages' in patch && patch.stages && typeof patch.stages === 'object') {+ mergedStages = { ...cur.stages };+ for (const [stageId, stagePatch] of Object.entries(patch.stages)) {+ const prev = cur.stages?.[stageId];+ if (prev && stagePatch && typeof prev === 'object' && typeof stagePatch === 'object') {+ const merged = { ...prev, ...stagePatch };+ merged.runHistory = snapshotRunHistory(prev, stagePatch, stageId);+ for (const key of NESTED_DEEP_MERGE_KEYS) {+ if (key in stagePatch+ && stagePatch[key] && typeof stagePatch[key] === 'object'+ && prev[key] && typeof prev[key] === 'object') {+ merged[key] = { ...prev[key], ...stagePatch[key] };}- mergedStages[stageId] = merged;- } else {- mergedStages[stageId] = stagePatch;}+ if ('status' in stagePatch && stagePatch.status !== 'error'+ && stagePatch.status !== 'generating'+ && !('errorMessage' in stagePatch)) {+ merged.errorMessage = '';+ }+ mergedStages[stageId] = merged;+ } else {+ mergedStages[stageId] = stagePatch;}}+ }- const merged = sanitizeIssue({- ...cur,- ...('title' in patch ? { title: patch.title } : {}),- ...('number' in patch ? { number: patch.number } : {}),- ...('status' in patch ? { status: patch.status } : {}),- ...('seasonId' in patch ? { seasonId: patch.seasonId } : {}),- ...('arcPosition' in patch ? { arcPosition: patch.arcPosition } : {}),- ...('arcRole' in patch ? { arcRole: patch.arcRole } : {}),- ...('lengthProfile' in patch ? { lengthProfile: patch.lengthProfile } : {}),- ...('pageTarget' in patch ? { pageTarget: patch.pageTarget } : {}),- ...('minutesTarget' in patch ? { minutesTarget: patch.minutesTarget } : {}),- ...('origin' in patch ? { origin: patch.origin } : {}),- // Local-only "don't sync" marker. Issues piggyback on their parent- // series' subscription, so an ephemeral issue is dropped from the- // series push payload via sanitizeRecordForWire returning null.- ...('ephemeral' in patch ? { ephemeral: patch.ephemeral } : {}),- stages: mergedStages,- updatedAt: new Date().toISOString(),+ const merged = sanitizeIssue({+ ...cur,+ ...('title' in patch ? { title: patch.title } : {}),+ ...('number' in patch ? { number: patch.number } : {}),+ ...('status' in patch ? { status: patch.status } : {}),+ ...('seasonId' in patch ? { seasonId: patch.seasonId } : {}),+ ...('arcPosition' in patch ? { arcPosition: patch.arcPosition } : {}),+ ...('arcRole' in patch ? { arcRole: patch.arcRole } : {}),+ ...('lengthProfile' in patch ? { lengthProfile: patch.lengthProfile } : {}),+ ...('pageTarget' in patch ? { pageTarget: patch.pageTarget } : {}),+ ...('minutesTarget' in patch ? { minutesTarget: patch.minutesTarget } : {}),+ ...('origin' in patch ? { origin: patch.origin } : {}),+ // Local-only "don't sync" marker. Issues piggyback on their parent+ // series' subscription, so an ephemeral issue is dropped from the+ // series push payload via sanitizeRecordForWire returning null.+ ...('ephemeral' in patch ? { ephemeral: patch.ephemeral } : {}),+ stages: mergedStages,+ updatedAt: new Date().toISOString(),+ });+ if (!merged) throw makeErr('Invalid issue payload', ERR_VALIDATION);+ return merged;+}++export function updateIssue(id, patch = {}, { skipRenumber = false } = {}) {+ const needsRenumber = !skipRenumber && ('seasonId' in patch || 'arcPosition' in patch);+ if (!needsRenumber) {+ return store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ const merged = mergeIssuePatch(cur, patch);+ await saveIssueNow(merged);+ emitRecordUpdated('series', merged.seriesId);+ return merged;});- if (!merged) throw makeErr('Invalid issue payload', ERR_VALIDATION);- state.issues[idx] = merged;- // A seasonId move affects both source and destination volumes, so full- // renumber. An arcPosition change only reorders within the current volume.- // `skipRenumber` lets bulk callers (e.g. deleteSeason) collapse N per-update- // renumbers into one final pass.- if (!skipRenumber) {+ }++ return getIssue(id, { includeDeleted: true }).then((existing) =>+ queueSeriesIssuesWrite(existing.seriesId, async () => {+ const state = await readState();+ const idx = state.issues.findIndex((i) => i.id === id);+ if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ const cur = state.issues[idx];+ if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ const merged = mergeIssuePatch(cur, patch);+ state.issues[idx] = merged;+ // A seasonId move affects both source and destination volumes, so full+ // renumber. An arcPosition change only reorders within the current volume.if ('seasonId' in patch && cur.seasonId !== merged.seasonId) {await renumberInline(state, merged.seriesId, null);} else if ('arcPosition' in patch && cur.arcPosition !== merged.arcPosition) {await renumberInline(state, merged.seriesId, merged.seasonId || UNSCOPED_ANCHOR);}- }- await writeState(state);- // Issues are exported as part of their parent series — re-export the- // series so any active subscription picks up the issue change.- emitRecordUpdated('series', merged.seriesId);- return merged;- }); // end queueIssueWrite+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === merged.seriesId));+ // Issues are exported as part of their parent series — re-export the+ // series so any active subscription picks up the issue change.+ emitRecordUpdated('series', merged.seriesId);+ return merged;+ })+ );}/**@@ -808,22 +839,24 @@ export function deleteIssue(id) {// record stays on disk with `deleted: true` so the next sync propagates the// delete to peers; the orchestrator's GC sweep prunes it once all peers ack.// `renumberInline` filters tombstones, so surviving issues stay contiguous.- return queueIssueWrite(async () => {- const state = await readState();- const idx = state.issues.findIndex((i) => i.id === id);- if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- const cur = state.issues[idx];- if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);- const seriesId = cur.seriesId;- const now = new Date().toISOString();- state.issues[idx] = { ...cur, deleted: true, deletedAt: now, updatedAt: now };- await renumberInline(state, seriesId, cur.seasonId || UNSCOPED_ANCHOR);- await writeState(state);- // Series export bundles every issue, so a deletion is an update on the- // parent series for any active share-bucket subscription.- emitRecordUpdated('series', seriesId);- return { id };- }); // end queueIssueWrite+ return getIssue(id, { includeDeleted: true }).then((existing) =>+ queueSeriesIssuesWrite(existing.seriesId, async () => {+ const state = await readState();+ const idx = state.issues.findIndex((i) => i.id === id);+ if (idx < 0) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ const cur = state.issues[idx];+ if (cur.deleted) throw makeErr(`Issue not found: ${id}`, ERR_NOT_FOUND);+ const seriesId = cur.seriesId;+ const now = new Date().toISOString();+ state.issues[idx] = { ...cur, deleted: true, deletedAt: now, updatedAt: now };+ await renumberInline(state, seriesId, cur.seasonId || UNSCOPED_ANCHOR);+ await saveIssuesNow(state.issues.filter((i) => i.seriesId === seriesId));+ // Series export bundles every issue, so a deletion is an update on the+ // parent series for any active share-bucket subscription.+ emitRecordUpdated('series', seriesId);+ return { id };+ })+ );}/**@@ -843,11 +876,9 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {// rather than waiting in line for an error it already knows about.return Promise.reject(makeErr(`Unknown stage: ${stageId}`, ERR_VALIDATION));}- return queueIssueWrite(async () => {- const state = await readState();- const idx = state.issues.findIndex((i) => i.id === issueId);- if (idx < 0) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);- const cur = state.issues[idx];+ return store().queueRecordWrite(issueId, async () => {+ const cur = await store().loadOne(issueId);+ if (!cur) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);if (cur.deleted) throw makeErr(`Issue not found: ${issueId}`, ERR_NOT_FOUND);const isVisual = VISUAL_STAGE_IDS.includes(stageId);const isAudio = AUDIO_STAGE_IDS.includes(stageId);@@ -879,22 +910,19 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {stages: { ...cur.stages, [stageId]: next },updatedAt: new Date().toISOString(),});- state.issues[idx] = mergedIssue;- await writeState(state);+ await saveIssueNow(mergedIssue);emitRecordUpdated('series', mergedIssue.seriesId);return { issue: mergedIssue, stage: mergedIssue.stages[stageId] };- }); // end queueIssueWrite+ });}/*** Sync-orchestrator entry point. Merges a remote peer's issues array into- * local state INSIDE `queueIssueWrite`, so the read-modify-write window can't- * clobber (or be clobbered by) a concurrent updateIssue / updateStage /- * cover-render PATCH running through the same queue. Each incoming record- * passes through `sanitizeIssue` for shape enforcement (stage statuses,- * trimmed fields, valid id format). LWW by `updatedAt`; returns- * `{ applied, count }` where `count` is the number of issues actually- * changed/added.+ * local state through the collection store's type-index queue for one+ * consistent merge snapshot. Each incoming record passes through+ * `sanitizeIssue` for shape enforcement (stage statuses, trimmed fields,+ * valid id format). LWW by `updatedAt`; returns `{ applied, count }` where+ * `count` is the number of issues actually changed/added.*/export async function mergeIssuesFromSync(remoteIssues) {if (!Array.isArray(remoteIssues)) return { applied: false, count: 0 };@@ -919,7 +947,7 @@ export async function mergeIssuesFromSync(remoteIssues) {.filter((s) => s?.ephemeral === true).map((s) => s.id),);- return queueIssueWrite(async () => {+ return store().queueTypeIndexWrite(async () => {const state = await readState();const localById = new Map(state.issues.map((i) => [i.id, i]));let changed = 0;@@ -982,7 +1010,7 @@ export async function mergeIssuesFromSync(remoteIssues) {for (const seriesId of seriesNeedingRenumber) {await renumberInline(state, seriesId, null);}- await writeState(state);+ await saveIssuesNow(state.issues);// Re-emit a series-updated for each touched series so any active share// subscription re-exports the post-merge issue set.for (const seriesId of seriesNeedingRenumber) {@@ -1003,17 +1031,15 @@ export async function mergeIssuesFromSync(remoteIssues) {*/export async function pruneTombstonedIssues(beforeMs) {if (!Number.isFinite(beforeMs)) return { pruned: 0 };- return queueIssueWrite(async () => {- const state = await readState();- const original = state.issues.length;- state.issues = state.issues.filter((i) => {- if (!i?.deleted) return true;+ return store().queueTypeIndexWrite(async () => {+ const { issues } = await readState();+ const prunable = issues.filter((i) => {+ if (!i?.deleted) return false;const t = Date.parse(i.deletedAt || '');- if (!Number.isFinite(t)) return true;- return t >= beforeMs;+ if (!Number.isFinite(t)) return false;+ return t < beforeMs;});- const pruned = original - state.issues.length;- if (pruned > 0) await writeState(state);- return { pruned };+ await Promise.all(prunable.map((i) => store().deleteOne(i.id)));+ return { pruned: prunable.length };});}diff --git a/server/services/pipeline/migrateSeriesCanon.js b/server/services/pipeline/migrateSeriesCanon.jsindex 7d14c7a043..101d4ff816 100644--- a/server/services/pipeline/migrateSeriesCanon.js+++ b/server/services/pipeline/migrateSeriesCanon.js@@ -13,6 +13,7 @@// next series-side write will rewrite the JSON without the legacy fields.import { join } from 'path';+import { readdir, readFile } from 'fs/promises';import { createHash } from 'node:crypto';import { updateSeries } from './series.js';import { PATHS, readJSONFile } from '../../lib/fileUtils.js';@@ -27,10 +28,39 @@ import { mergeExtractedBible, BIBLE_FIELD, BIBLE_SOURCE } from '../../lib/storyBexport const deriveOrphanUniverseId = (seriesId) =>`uni-from-series-${createHash('sha1').update(String(seriesId)).digest('hex').slice(0, 32)}`;-// Raw read of pipeline-series.json (bypasses sanitizeSeries, which post-B.4-// strips the legacy canon fields the migration needs to see).-const readRawSeriesState = () =>- readJSONFile(join(PATHS.data, 'pipeline-series.json'), { series: [] }, { logError: false });+// Raw read of pipeline series records (bypasses sanitizeSeries, which post-B.4+// strips the legacy canon fields the migration needs to see). Prefer the+// split collection layout, but keep the legacy/backup files readable for+// older installs and recovery runs.+const readRawSplitSeriesState = async () => {+ const dir = join(PATHS.data, 'pipeline-series');+ const entries = await readdir(dir, { withFileTypes: true }).catch((err) => {+ if (err?.code === 'ENOENT') return [];+ throw err;+ });+ const series = [];+ for (const entry of entries) {+ if (!entry.isDirectory()) continue;+ const raw = await readFile(join(dir, entry.name, 'index.json'), 'utf-8').catch(() => null);+ if (!raw) continue;+ try {+ const parsed = JSON.parse(raw);+ if (parsed && typeof parsed === 'object') series.push(parsed);+ } catch {+ // A single corrupt record should not make the whole best-effort legacy+ // canon migration unreadable.+ }+ }+ return { series };+};++const readRawSeriesState = async () => {+ const split = await readRawSplitSeriesState();+ if (split.series.length > 0) return split;+ const legacy = await readJSONFile(join(PATHS.data, 'pipeline-series.json'), null, { logError: false });+ if (legacy && Array.isArray(legacy.series)) return legacy;+ return readJSONFile(join(PATHS.data, 'pipeline-series.json.bak-036'), { series: [] }, { logError: false });+};// Reverse of BIBLE_FIELD — maps the persisted field name (`characters`) back// to its BIBLE_KIND value (`character`) so the migration can calldiff --git a/server/services/pipeline/seasons.js b/server/services/pipeline/seasons.jsindex 9ddf3c911f..3ac7e2738c 100644--- a/server/services/pipeline/seasons.js+++ b/server/services/pipeline/seasons.js@@ -141,9 +141,9 @@ export async function deleteSeason(seriesId, seasonId, { reassignTo = null } = {}}// Re-point child issues first so a mid-write crash doesn't leave them- // dangling against a deleted season id. `bulkReassignSeason` collapses what- // used to be N per-issue queueIssueWrite cycles into a single readState →- // in-memory mutate → writeState → one renumber pass.+ // dangling against a deleted season id. `bulkReassignSeason` collapses the+ // old N per-issue write cycle into one collection load, in-memory mutate,+ // renumber pass, and per-record save batch.//// Each updateSeries + bulkReassignSeason still emits `emitRecordUpdated('series', …)`. Without// suppression those two events would schedule two debounced re-exports of the samediff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 996aab4ca5..99b2d2204b 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -7,14 +7,14 @@* those flow into every Issue's stage prompts so issues stay visually and* tonally consistent.*- * Persisted to data/pipeline-series.json. Issues live in their own file- * (server/services/pipeline/issues.js) and reference a series by id.+ * Persisted to data/pipeline-series/{id}/index.json. Issues live in their own+ * collection (server/services/pipeline/issues.js) and reference a series by id.*/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 { isStr, trimTo } from '../../lib/storyBible.js';import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';import { sanitizeOrigin } from '../../lib/sharingOrigin.js';@@ -22,18 +22,28 @@ import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';import { emitRecordUpdated, emitRecordDeleted } from '../sharing/recordEvents.js';import { renameCollectionForSeries, unlinkCollectionsForSeries } from '../mediaCollections.js';-// Lazy resolution — PATHS.data may not be available at module-load time-// (e.g. tests that swap it through a Proxy mock).-const statePath = () => join(PATHS.data, 'pipeline-series.json');+// TYPE-level (storage layout) schema version stamped on+// `data/pipeline-series/index.json`.+// v1 — series split out of monolithic `data/pipeline-series.json` into+// per-record `data/pipeline-series/{id}/index.json`. See migration 036.+const TYPE_SCHEMA_VERSION = 1;-// File-level write lock. Required because multiple write paths can race on the single shared-// pipeline-series.json file: PATCH /series/:id (bible edits), PATCH-// /seasons/:seasonId (season metadata), the new volume cover-render route,-// the season-cover filename hook landing, and the bible-extract merge.-// All of those read-then-write the same JSON; without serialization a-// later writer's `readState` can land on a pre-image snapshot and clobber-// the earlier write. CLAUDE.md: "single tail per shared file."-const queueSeriesWrite = createFileWriteQueue();+// Lazy store factory so tests that swap PATHS.data per-test still see the+// right temp root — the store captures PATHS.data once at first call.+let _store = null;+const store = () => {+ if (_store && _store.dir === join(PATHS.data, 'pipeline-series')) return _store;+ _store = createCollectionStore({+ dir: join(PATHS.data, 'pipeline-series'),+ type: 'pipelineSeries',+ schemaVersion: TYPE_SCHEMA_VERSION,+ sanitizeRecord: sanitizeSeries,+ idPattern: /^ser-[A-Za-z0-9-]+$/,+ });+ return _store;+};++export const seriesStore = () => store();export const ERR_NOT_FOUND = 'PIPELINE_SERIES_NOT_FOUND';export const ERR_VALIDATION = 'PIPELINE_SERIES_VALIDATION';@@ -92,8 +102,6 @@ const sanitizeSeriesLocked = (raw = {}) => {return out;};-const DEFAULT_STATE = { series: [] };-const sanitizeSeries = (raw) => {if (!raw || typeof raw !== 'object') return null;if (!isStr(raw.id) || !raw.id) return null;@@ -155,26 +163,14 @@ const sanitizeSeries = (raw) => {};};-async function readState() {- await ensureDir(PATHS.data);- const raw = await readJSONFile(statePath(), DEFAULT_STATE, { logError: false });- const series = Array.isArray(raw.series) ? raw.series.map(sanitizeSeries).filter(Boolean) : [];- return { series };-}--async function writeState(state) {- await atomicWrite(statePath(), state);-}-export async function listSeries({ includeDeleted = false } = {}) {- const { series } = await readState();+ const series = await store().loadAll();const filtered = includeDeleted ? series : series.filter((s) => !s.deleted);return [...filtered].sort((a, b) => (b.updatedAt || '').localeCompare(a.updatedAt || ''));}export async function getSeries(id, { includeDeleted = false } = {}) {- const { series } = await readState();- const found = series.find((s) => s.id === id);+ const found = await store().loadOne(id);if (!found) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);if (found.deleted && !includeDeleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);return found;@@ -183,35 +179,30 @@ export async function getSeries(id, { includeDeleted = false } = {}) {export async function createSeries(input = {}) {const name = trimTo(input.name, NAME_MAX);if (!name) throw makeErr(`Series name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);- const created = await queueSeriesWrite(async () => {- const state = await readState();- const now = new Date().toISOString();- const next = sanitizeSeries({- id: `ser-${randomUUID()}`,- name,- logline: input.logline || '',- premise: input.premise || '',- universeId: input.universeId || null,- writersRoomWorkId: input.writersRoomWorkId || null,- arc: input.arc || null,- seasons: input.seasons || [],- locked: input.locked || {},- styleNotes: input.styleNotes || '',- titleLogo: input.titleLogo || '',- author: input.author || '',- stylePromptOverride: input.stylePromptOverride || '',- stylePromptOverrideMode: input.stylePromptOverrideMode,- targetFormat: input.targetFormat || 'comic+tv',- issueCountTarget: input.issueCountTarget || 0,- llm: input.llm || null,- createdAt: now,- updatedAt: now,- ephemeral: input.ephemeral === true,- });- state.series.push(next);- await writeState(state);- return next;+ const now = new Date().toISOString();+ const created = sanitizeSeries({+ id: `ser-${randomUUID()}`,+ name,+ logline: input.logline || '',+ premise: input.premise || '',+ universeId: input.universeId || null,+ writersRoomWorkId: input.writersRoomWorkId || null,+ arc: input.arc || null,+ seasons: input.seasons || [],+ locked: input.locked || {},+ styleNotes: input.styleNotes || '',+ titleLogo: input.titleLogo || '',+ author: input.author || '',+ stylePromptOverride: input.stylePromptOverride || '',+ stylePromptOverrideMode: input.stylePromptOverrideMode,+ targetFormat: input.targetFormat || 'comic+tv',+ issueCountTarget: input.issueCountTarget || 0,+ llm: input.llm || null,+ createdAt: now,+ updatedAt: now,+ ephemeral: input.ephemeral === true,});+ await store().saveOne(created.id, created);// Skip auto-subscribe for ephemeral series — wire-side push would short-// circuit via sanitizeRecordForWire anyway, but not creating the sub up// front keeps the subscription store clean.@@ -241,24 +232,20 @@ export async function insertSeriesWithId(input = {}) {}const name = trimTo(input.name, NAME_MAX);if (!name) throw makeErr(`Series name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);- return queueSeriesWrite(async () => {- const state = await readState();+ return store().queueRecordWrite(input.id, async () => {// Tombstone-overwrite: same contract as universeBuilder.insertUniverseWithId —// re-import undeletes; peer-sync resurrection is prevented at the merge// path via LWW, not here.- const existingIdx = state.series.findIndex((s) => s.id === input.id);- if (existingIdx >= 0 && !state.series[existingIdx].deleted) {+ const existing = await store().loadOne(input.id);+ if (existing && !existing.deleted) {throw makeErr(`Series id already exists: ${input.id}`, ERR_DUPLICATE);}const next = sanitizeSeries({ ...input, name });if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);- if (existingIdx >= 0) {+ if (existing) {console.warn(`♻️ insertSeriesWithId: overwriting tombstone for ${input.id}`);- state.series[existingIdx] = next;- } else {- state.series.push(next);}- await writeState(state);+ await store().saveOneNow(next.id, next);return next;});}@@ -272,11 +259,9 @@ export async function updateSeries(id, patch = {}) {if (legacyFields.length > 0) {console.warn(`⚠️ series PATCH ${id.slice(0, 8)} stripped legacy canon fields: ${legacyFields.join(', ')}`);}- const { merged, nameChanged, prevEphemeral, nextEphemeral } = await queueSeriesWrite(async () => {- const state = await readState();- const idx = state.series.findIndex((s) => s.id === id);- if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);- const cur = state.series[idx];+ const { merged, nameChanged, prevEphemeral, nextEphemeral } = await store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);// Per-field merge so `{ provider: 'codex' }` doesn't clobber an existing `model`.const mergedLlm = 'llm' in patch@@ -308,8 +293,7 @@ export async function updateSeries(id, patch = {}) {updatedAt: new Date().toISOString(),});if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);- state.series[idx] = next;- await writeState(state);+ await store().saveOneNow(next.id, next);return {merged: next,nameChanged: next.name !== cur.name,@@ -359,11 +343,9 @@ export async function setArcFieldLock(id, field, locked) {if (!ARC_LOCKABLE_FIELDS.includes(field)) {throw makeErr(`Unknown arc lock field: ${field}`, ERR_VALIDATION);}- return queueSeriesWrite(async () => {- const state = await readState();- const idx = state.series.findIndex((s) => s.id === id);- if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);- const cur = state.series[idx];+ return store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);const arcFields = { ...(cur.locked?.arcFields || {}) };if (locked === true) arcFields[field] = true;@@ -377,8 +359,7 @@ export async function setArcFieldLock(id, field, locked) {updatedAt: new Date().toISOString(),});if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);- state.series[idx] = next;- await writeState(state);+ await store().saveOneNow(next.id, next);emitRecordUpdated('series', next.id);return next;});@@ -386,9 +367,9 @@ export async function setArcFieldLock(id, field, locked) {/*** Apply a structured patch to one season inside a series. Routes through the- * shared series write tail so a season-cover render PATCH, the season-cover- * filename hook landing, and a user-driven season metadata edit all serialize- * against the single pipeline-series.json file. Returns the updated series.+ * per-series collection-store queue so a season-cover render PATCH, the+ * season-cover filename hook landing, and a user-driven season metadata edit+ * all serialize against the same series record. Returns the updated series.** Throws `PIPELINE_SEASON_NOT_FOUND` (the seasons-service ERR_NOT_FOUND* value, inlined here to avoid a circular import seasons → series → seasons)@@ -396,11 +377,9 @@ export async function setArcFieldLock(id, field, locked) {* with "Season not found" rather than "Series not found".*/export async function updateSeasonOnSeries(seriesId, seasonId, patchFn) {- return queueSeriesWrite(async () => {- const state = await readState();- const idx = state.series.findIndex((s) => s.id === seriesId);- if (idx < 0) throw makeErr(`Series not found: ${seriesId}`, ERR_NOT_FOUND);- const cur = state.series[idx];+ return store().queueRecordWrite(seriesId, async () => {+ const cur = await store().loadOne(seriesId);+ if (!cur) throw makeErr(`Series not found: ${seriesId}`, ERR_NOT_FOUND);if (cur.deleted) throw makeErr(`Series not found: ${seriesId}`, ERR_NOT_FOUND);const seasons = Array.isArray(cur.seasons) ? cur.seasons : [];const seasonIdx = seasons.findIndex((s) => s.id === seasonId);@@ -428,8 +407,7 @@ export async function updateSeasonOnSeries(seriesId, seasonId, patchFn) {updatedAt: new Date().toISOString(),});if (!merged) throw makeErr('Invalid series payload after season patch', ERR_VALIDATION);- state.series[idx] = merged;- await writeState(state);+ await store().saveOneNow(merged.id, merged);emitRecordUpdated('series', merged.id);return merged;});@@ -440,15 +418,12 @@ export async function deleteSeries(id) {// tombstone propagates via the existing LWW merge. Side effects (media-// collection unlink + recordDeleted emit) still run locally and also fire// on the receiving peer via mergeSeriesFromSync's transition detection.- const result = await queueSeriesWrite(async () => {- const state = await readState();- const idx = state.series.findIndex((s) => s.id === id);- if (idx < 0) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);- const cur = state.series[idx];+ const result = await store().queueRecordWrite(id, async () => {+ const cur = await store().loadOne(id);+ if (!cur) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);if (cur.deleted) throw makeErr(`Series not found: ${id}`, ERR_NOT_FOUND);const now = new Date().toISOString();- state.series[idx] = { ...cur, deleted: true, deletedAt: now, updatedAt: now };- await writeState(state);+ await store().saveOneNow(id, { ...cur, deleted: true, deletedAt: now, updatedAt: now });// Any live share-bucket subscription for this series tears itself down via// the recordEvents listener instead of orphaning.emitRecordDeleted('series', id);@@ -477,12 +452,10 @@ async function cascadeDeleteSideEffects(id) {/*** Sync-orchestrator entry point. Merges a remote peer's series array into- * local state INSIDE `queueSeriesWrite`, so the read-modify-write window- * can't clobber (or be clobbered by) a concurrent bible edit, season-metadata- * PATCH, season-cover render PATCH, or season-cover filename hook also running- * through the same queue. Each incoming record passes through `sanitizeSeries`- * for shape enforcement. LWW by `updatedAt`; returns `{ applied, count }`- * where `count` is the number of series actually changed/added.+ * local state through per-record collection-store queues. Each incoming record+ * passes through `sanitizeSeries` for shape enforcement. LWW by `updatedAt`;+ * returns `{ applied, count }` where `count` is the number of series actually+ * changed/added.*/export async function mergeSeriesFromSync(remoteSeries) {if (!Array.isArray(remoteSeries)) return { applied: false, count: 0 };@@ -493,41 +466,37 @@ export async function mergeSeriesFromSync(remoteSeries) {// see `mergeUniversesFromSync` for the rationale (the Stage 2 per-record// peer-sync push owns sync-time edit emits).const transitionedToDeleted = [];- const result = await queueSeriesWrite(async () => {- const state = await readState();- const localById = new Map(state.series.map((s) => [s.id, s]));- let changed = 0;- for (const remote of remoteSeries) {- if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;+ let changed = 0;+ for (const remote of remoteSeries) {+ if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;+ if (!SERIES_ID_RE.test(remote.id)) continue;+ await store().queueRecordWrite(remote.id, async () => {const sanitized = sanitizeSeries(remote);- if (!sanitized) continue;+ if (!sanitized) return;// Strip inbound `ephemeral` — see mergeUniversesFromSync.if ('ephemeral' in sanitized) delete sanitized.ephemeral;- const local = localById.get(sanitized.id);+ const local = await store().loadOne(sanitized.id);if (!local) {// See universeBuilder.mergeUniversesFromSync — no local means no// cascade work, regardless of inbound tombstone state.- localById.set(sanitized.id, sanitized);+ await store().saveOneNow(sanitized.id, sanitized);changed++;} else if (local.ephemeral === true) {// Local-ephemeral series are immune to inbound merges. See// mergeUniversesFromSync for the contract.- continue;+ return;} else {const localTs = local.updatedAt || '';const remoteTs = sanitized.updatedAt || '';if (remoteTs > localTs) {- localById.set(sanitized.id, sanitized);+ await store().saveOneNow(sanitized.id, sanitized);if (sanitized.deleted && !local.deleted) transitionedToDeleted.push(sanitized.id);changed++;}}- }- if (changed === 0) return { applied: false, count: 0 };- state.series = Array.from(localById.values());- await writeState(state);- return { applied: true, count: changed };- });+ });+ }+ const result = changed === 0 ? { applied: false, count: 0 } : { applied: true, count: changed };for (const id of transitionedToDeleted) {await cascadeDeleteSideEffects(id);}@@ -542,17 +511,13 @@ export async function mergeSeriesFromSync(remoteSeries) {*/export async function pruneTombstonedSeries(beforeMs) {if (!Number.isFinite(beforeMs)) return { pruned: 0 };- return queueSeriesWrite(async () => {- const state = await readState();- const original = state.series.length;- state.series = state.series.filter((s) => {- if (!s?.deleted) return true;+ const series = await store().loadAll();+ const prunable = series.filter((s) => {+ if (!s?.deleted) return false;const t = Date.parse(s.deletedAt || '');- if (!Number.isFinite(t)) return true;- return t >= beforeMs;- });- const pruned = original - state.series.length;- if (pruned > 0) await writeState(state);- return { pruned };+ if (!Number.isFinite(t)) return false;+ return t < beforeMs;});+ await Promise.all(prunable.map((s) => store().deleteOne(s.id)));+ return { pruned: prunable.length };}diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 2af1e1773b..61337eeaba 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -184,9 +184,9 @@ describe('sharing round-trip', () => {await series.updateSeries(s.id, { name: 'Test Series (renamed)' });// Force the local updatedAt to be older than the manifest so LWW triggers override.// (Easiest: mutate the on-disk JSON directly to set an old updatedAt.)- const statePath = join(tempData, 'pipeline-series.json');+ const statePath = join(tempData, 'pipeline-series', s.id, 'index.json');const state = JSON.parse(readFileSync(statePath, 'utf-8'));- state.series[0].updatedAt = '2020-01-01T00:00:00.000Z';+ state.updatedAt = '2020-01-01T00:00:00.000Z';writeFileSync(statePath, JSON.stringify(state, null, 2));// Process the new manifest — should LWW-override.