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
data versioning + per-record universes layout + cross-instance schema-version gating
Adam Eivyf04e3955cacf
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdnew file mode 100644index 0000000000..8d4d7f2cb1--- /dev/null+++ b/.changelog/NEXT.md@@ -0,0 +1,11 @@+# Unreleased Changes++## Added+- `server/lib/collectionStore.js` — per-type, per-record JSON storage helper with explicit type-level `schemaVersion` stamping. `createCollectionStore({ dir, type, schemaVersion, sanitizeRecord })` returns `loadOne` / `saveOne` / `listIds` / `loadAll` / `deleteOne` / `loadTypeIndex` / `saveTypeIndex` / `verifySchemaVersion`. Per-id write queue means writes to different records run in parallel — the win over a single-file write queue. `verifyCollectionVersions([store, ...])` is called at server boot after `runMigrations()` so a missed migration produces a loud, single-line log per collection (does not crash — PortOS is single-user).+- New layout `data/universes/{id}/index.json` for the universe builder, plus a type-level `data/universes/index.json` carrying `{ schemaVersion: 5, type, updatedAt, config: { runs } }`. Migration 034 (`scripts/migrations/034-split-universe-builder-to-per-uuid.js`) splits the legacy monolithic `data/universe-builder.json` (1.4MB / ~30 universes that previously rewrote in full on every mutation) into per-record files at boot. The legacy file is renamed to `universe-builder.json.bak-034` (not deleted) as a recovery path. Idempotent — partial-completion re-runs finish the split; full-completion re-runs are no-ops.+- **Cross-instance sync now gates on schema version.** New `server/lib/schemaVersions.js` is the single source of truth for the per-category storage-layout contract (`PORTOS_SCHEMA_VERSIONS = { universes: 5 }`); future category bumps add entries. Every outbound sync payload (federated peer push, 60s snapshot sync, share-bucket manifest) carries a `portosMeta { portosVersion, schemaVersions }` envelope. Receivers run `compareSchemaVersions(sender, local)`; when the sender is **ahead** on any category the receiver REJECTS — federated peer push returns 409 + `{ code: PEER_SYNC_SCHEMA_VERSION_AHEAD, context: { details: { ahead, behind, senderPortosVersion, receiverSchemaVersions } } }`, snapshot sync surfaces `blockedBySchema` on the peer record, share-bucket import skips the manifest with reason `portos-schema-ahead` and emits a `sharing:portos-schema-ahead` socket event. Senders persist the gap (`sub.blockedBySchema` on peer subscriptions, `peer.schemaGaps[category]` on peer records via `updatePeer`) and pause retries (5-minute cooldown; `peer:online` reconnect bypasses to re-probe in case the peer upgraded). Legacy senders without `portosMeta` pass through unchanged. The Instances page renders a new `<SchemaGapBadge>` per peer card explaining the gap in both directions: "Peer X is on an older PortOS — they need to update before we can sync universes" / "Peer X is on a newer PortOS — update PortOS to receive their universe updates." A "sender behind" mismatch DOES NOT gate — the existing sanitizer chain backfills older inputs.++## Changed+- `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.+- `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.diff --git a/.gitignore b/.gitignoreindex 9a41b13cee..b3784f815b 100644--- a/.gitignore+++ b/.gitignore@@ -9,7 +9,7 @@ build/# directory-level `data/` rule from the global ~/.gitignore so git descends# into data/ and evaluates the negation below; then re-exclude everything# inside except the .gitkeep that pins the empty directory. Seed/template-# content lives in data.sample/ and is copied in by scripts/setup-data.js;+# content lives in data.reference/ and is copied in by scripts/setup-data.js;# migration scripts live in scripts/migrations/.!data/data/*@@ -29,7 +29,7 @@ npm-debug.log**.png!client/public/portos-logo.png!docs/media/portos-logo.png-!data.sample/templates/*.png+!data.reference/templates/*.png# OS files.DS_Storediff --git a/.planning/codebase/ARCHITECTURE.md b/.planning/codebase/ARCHITECTURE.mdindex 9873e45c3c..50b9a13496 100644--- a/.planning/codebase/ARCHITECTURE.md+++ b/.planning/codebase/ARCHITECTURE.md@@ -46,7 +46,7 @@**Data Persistence:**- Purpose: Store application state in JSON files-- Location: `data/` directory (runtime), `data.sample/` (template)+- Location: `data/` directory (runtime), `data.reference/` (template)- Contains: apps.json, providers.json, runs/, prompts/, cos/, agents/, brain/, digital-twin/, meatspace/- Accessed by: Services via fileUtils and custom loadersdiff --git a/.planning/codebase/STRUCTURE.md b/.planning/codebase/STRUCTURE.mdindex c8ace6332b..a5298f5187 100644--- a/.planning/codebase/STRUCTURE.md+++ b/.planning/codebase/STRUCTURE.md@@ -49,7 +49,7 @@ PortOS/│ ├── agents/ # Agent personalities and state│ ├── meatspace/ # Meatspace (IRL) tracking data│ └── screenshots/ # Captured screenshots-├── data.sample/ # Sample data templates (checked in)+├── data.reference/ # Sample data templates (checked in)│ ├── providers.json # Sample provider config│ ├── prompts/ # Default prompt templates│ ├── cos/ # Sample CoS structure@@ -176,7 +176,7 @@ PortOS/- Contains: JSON files for apps, providers, runs, prompts, agents, CoS memory, brain state, etc.- Generated by: Services via fileUtils, AI toolkit-**`data.sample/`:**+**`data.reference/`:**- Purpose: Template data checked into git for bootstrapping new instances- Contains: Sample provider configs, prompt templates, CoS mission examples- Key files: `providers.json` (template AI providers)@@ -249,7 +249,7 @@ PortOS/- Committed: No (gitignored)- Persistence: JSON files, watched by services for changes-**`data.sample/`:**+**`data.reference/`:**- Purpose: Bootstrap templates for new instances- Generated: No (checked in manually)- Committed: Yes (part of repo)diff --git a/CLAUDE.md b/CLAUDE.mdindex 5004a7f44b..8f4050cdb5 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -165,6 +165,7 @@ If a close match exists, **extend it or use it**. Only add a new module when no- `tryReadFile` in `server/lib/fileUtils.js` — collapses `readFile(path).catch(() => null)`.- `atomicWrite` in `server/lib/fileUtils.js` — `ensureDir + writeFile + JSON.stringify` in one call.+- `createCollectionStore` in `server/lib/collectionStore.js` — when a service has outgrown its monolithic single-JSON-file shape (large per-record payload, frequent mutations, want concurrent writes to different records), use this instead of rolling another `readJSONFile`+`atomicWrite`+`createFileWriteQueue`. Lays out `data/{type}/{id}/index.json` with a type-level `data/{type}/index.json` that stamps `schemaVersion` (the storage-layout version, distinct from any per-record-shape `schemaVersion` the sanitizer carries inside each record). Includes per-id write queue and a `verifySchemaVersion` hook used by the boot-time verifier in `server/index.js`. Worked example: `server/services/universeBuilder.js` (migration 034 splits the legacy `universe-builder.json` into this shape).- `optionalBooleanMap(keys)` in `server/lib/validation.js` — `z.object(Object.fromEntries(KEYS.map(k => [k, z.boolean().optional()])))` collapsed.- `flattenCanonDescriptorFragments` / `mapCanonDescriptorFragments` in `server/lib/canonPrompt.js` (mirrored to client) — render `[{ prefix?, value }]` fragments to a sentence string or array.- `copyToClipboard` / `writeClipboardSilently` / `readClipboard` in `client/src/lib/clipboard.js` — safe across insecure-origin contexts. Do not use `navigator.clipboard.writeText` inline.@@ -221,7 +222,7 @@ When CoS agents or AI tools work on managed apps outside PortOS, all research, p- **"Run Now" actions must gate on saved state, not the form input.** When a settings page has a companion "Run this now" button that triggers a server action reading server-side settings (not the local form values), the button must be gated on the *saved* value, not the in-memory input. Track a parallel `saved*` state for each setting the action depends on, update it on successful save, and use it for the action's enabled gate. Disable the action while the form is dirty *or* a save is in flight — a tooltip-only warning is missed on touch and produces surprising "I edited X and ran, but X didn't apply" bugs.- **In-flight saves must gate dependent actions, not just the form.** When a field's PATCH is async and a button triggers server-side work that reads that field (auto-run, regenerate, etc.), the button must disable while the PATCH is in flight — not just while the input is "dirty." Otherwise the user picks a new value, the input clears, and they click the action before the server has the new value persisted. Track a `<field>Saving` boolean alongside the action's other disable predicates, set it before the PATCH and clear it in `.finally()`. See `PipelineIssue.jsx` `lengthProfileSaving` for the canonical example.- **Async PATCH races on shared records — serialize writes server-side.** When two write paths can mutate the same record concurrently (e.g. a blur-save plus an explicit "Render" button against `stages.comicPages.cover`), client-side guards (refs, `onMouseDown`, status checks) are unreliable — keyboard activation, status==='unknown' stalls, and `loadState → modify → saveState` interleaving all defeat them. The correct fix is to serialize writes at the *file* level on the server (every PATCH awaits the previous one to settle before reading state, so it merges against the freshest persisted record). See `issueWriteTail` in `server/services/pipeline/issues.js`. A `Map<recordId, Promise>` is *not* enough — two writes to different record ids share the same JSON state file and can still clobber each other; collapse the queue to a single tail per shared file.-- **Stage-prompt template changes need a migration.** `scripts/setup-data.js` only copies *missing* prompt files to `data/prompts/stages/` — existing installs keep their old templates. When you add a `{{template.variable}}` reference to a `data.sample/prompts/stages/*.md` file, also add an entry to `scripts/migrations/NNN-…js` that updates the corresponding installed prompt when its hash still matches the pre-change shipped version. Normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing so the comparison is correct on Windows checkouts. The drift warning in `scripts/setup-data.js` distinguishes auto-updatable (matches old shipped hash) from customized (matches neither) — when adding to the migrated list, mirror both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` there too so the warning stays actionable. Migration scripts live in `scripts/migrations/`; the per-install applied-list is `data/migrations.applied.json` (gitignored runtime state). See `scripts/migrations/003-update-pipeline-stage-prompts.js`.+- **Stage-prompt template changes need a migration.** `scripts/setup-data.js` only copies *missing* prompt files to `data/prompts/stages/` — existing installs keep their old templates. When you add a `{{template.variable}}` reference to a `data.reference/prompts/stages/*.md` file, also add an entry to `scripts/migrations/NNN-…js` that updates the corresponding installed prompt when its hash still matches the pre-change shipped version. Normalize line endings (`\r\n` → `\n`, bare `\r` → `\n`) before hashing so the comparison is correct on Windows checkouts. The drift warning in `scripts/setup-data.js` distinguishes auto-updatable (matches old shipped hash) from customized (matches neither) — when adding to the migrated list, mirror both `OLD_SHIPPED_MD5` and `NEW_SHIPPED_MD5` there too so the warning stays actionable. Migration scripts live in `scripts/migrations/`; the per-install applied-list is `data/migrations.applied.json` (gitignored runtime state). See `scripts/migrations/003-update-pipeline-stage-prompts.js`.- **High-frequency state writes must batch.** Per-line state mutations that round-trip through `withStateLock → loadState → saveState` (e.g. `appendAgentOutput` in `cosAgents.js`) are fine for human-pace events but catastrophic when called from a hot loop — PTY output streams, AI tool-call streams, or any producer that can emit dozens of events per second. When wiring a new streaming producer, add a batched variant that takes an array (see `appendAgentOutputLines` for the pattern) and flush from the caller on a ~250ms debounce. Always drain the pending buffer in the producer's `finish`/`cleanup` path before the final state write so completion events don't beat the last output batch to disk.- **Socket event-driven state — don't pre-clear before the server confirms.** When swapping which entity a socket-driven UI is showing (shell session, agent run, etc.), wait for the server's success event to drive the swap atomically; the error event is the recovery point. Pre-clearing the local `*Ref` / visible state up front leaves the UI stranded on a dead URL when the success event never arrives (target died mid-request, server rejected the switch). Pair every `socket.on('X:error')` that follows a stateful request with a recovery branch that restores the previously-displayed state or falls back to a live alternative.- **Single-subscriber socket resources need notify + recipient-relative advertise + filter + claim.** Some server-side resources (PTY shell sessions, etc.) intentionally store one attached socket and fan output to it. The contract: (1) emit `<resource>:detached` on the previous socket when a new socket takes over so the displaced client can drop its local view; (2) include an `attached: boolean` field on each list-entry payload, computed *relative to the recipient socket* (true only when bound to a different socket) — a globally-truthy `attached` makes a client's own sessions look unavailable to itself; (3) broadcast list updates from both attach AND detach paths; (4) auto-pick paths send `claim: true` and the server refuses to displace a different socket. Manual paths (tab click, deep-link URL) default to `claim: false` so explicit intent still wins. See `server/services/shell.js` for the canonical implementation.diff --git a/README.md b/README.mdindex b1be848b1c..ef705b2830 100644--- a/README.md+++ b/README.md@@ -285,7 +285,7 @@ PortOS/├── client/ # React + Vite frontend (Vite dev on :5554)├── server/ # Express.js API (always serves on :5555)├── data/ # Runtime data (apps, providers, history, brain, pipeline, …)-├── data.sample/ # Sample configurations to copy on first install+├── data.reference/ # Sample configurations to copy on first install├── docs/ # Documentation and screenshots├── lib/slashdo/ # Slashdo submodule (provides /do:* slash commands)├── scripts/ # Setup, migration, and maintenance scriptsdiff --git a/client/src/components/instances/SchemaGapBadge.jsx b/client/src/components/instances/SchemaGapBadge.jsxnew file mode 100644index 0000000000..53c62899ab--- /dev/null+++ b/client/src/components/instances/SchemaGapBadge.jsx@@ -0,0 +1,99 @@+import { AlertTriangle, ArrowUpCircle, ArrowDownCircle } from 'lucide-react';++/**+ * Surfaces a peer's storage-layout schema version gaps so the user knows+ * which direction the mismatch goes and what action is needed.+ *+ * The server populates two distinct gap surfaces:+ *+ * - `peer.schemaGaps`: per-(peer, snapshot-category) gaps detected by the+ * 60s `syncDataCategoryFromPeer` apply pass. Shape:+ * { [category]: { ahead, behind, senderPortosVersion, detectedAt } }+ * Set when the receiver (us) rejected a remote snapshot because the+ * sender's schemaVersions were ahead of ours.+ *+ * - `peerSubs[].blockedBySchema`: per-(record-subscription) gaps detected+ * by the per-record push pipeline. Shape:+ * { ahead, behind, peerPortosVersion, peerSchemaVersions, detectedAt }+ * Set when WE pushed to the peer and got a 409 back because the peer's+ * code is BEHIND ours.+ *+ * Both are rendered as a compact warning block at the top of the peer card.+ * Empty / absent gaps render nothing — peers without a mismatch keep their+ * existing card layout.+ */+export function SchemaGapBadge({ peer, peerSubs = [] }) {+ const snapshotGaps = peer?.schemaGaps && typeof peer.schemaGaps === 'object'+ ? Object.entries(peer.schemaGaps).map(([category, gap]) => ({ category, ...gap, direction: 'receiver-behind' }))+ : [];+ // Map per-record subscription recordKind to the SAME category vocabulary+ // that snapshotGaps uses (dataSync's CHECKSUM_PATHS keys: 'universe'+ // singular, 'pipeline' for series+issues, 'mediaCollections', etc.). The+ // earlier version mapped 'universe' → 'universes' (plural), which made+ // the de-dup key below treat the snapshot and push directions as+ // disjoint label spaces — the same underlying gap then rendered as two+ // rows with inconsistent labels. Keep both directions on the same+ // vocabulary so dedup + label rendering line up.+ const recordKindToCategory = (k) => {+ if (k === 'universe') return 'universe';+ if (k === 'series') return 'pipeline';+ return k;+ };+ const pushGaps = (peerSubs || [])+ .filter((s) => s?.blockedBySchema)+ .map((s) => ({+ category: recordKindToCategory(s.recordKind),+ ahead: s.blockedBySchema.ahead || [],+ behind: s.blockedBySchema.behind || [],+ peerPortosVersion: s.blockedBySchema.peerPortosVersion,+ detectedAt: s.blockedBySchema.detectedAt,+ direction: 'peer-behind',+ }));++ if (snapshotGaps.length === 0 && pushGaps.length === 0) return null;++ // De-dup by `category + direction` — if both transports flag the same+ // (peer, category, direction), show one row.+ const seen = new Set();+ const rows = [...snapshotGaps, ...pushGaps].filter((row) => {+ const key = `${row.direction}:${row.category}`;+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });++ return (+ <div className="mt-2 rounded-lg border border-port-warning/40 bg-port-warning/5 px-3 py-2">+ <div className="flex items-center gap-1.5 text-port-warning text-xs font-medium mb-1">+ <AlertTriangle size={12} />+ <span>Schema version mismatch</span>+ </div>+ <ul className="space-y-1 text-xs text-gray-300">+ {rows.map((row, i) => (+ <li key={`${row.direction}-${row.category}-${i}`} className="flex items-start gap-1.5">+ {row.direction === 'peer-behind' ? (+ <ArrowDownCircle size={12} className="mt-0.5 text-port-warning shrink-0" aria-label="Peer is behind" />+ ) : (+ <ArrowUpCircle size={12} className="mt-0.5 text-port-warning shrink-0" aria-label="Peer is ahead" />+ )}+ <span>+ {row.direction === 'peer-behind' ? (+ <>+ <span className="text-white">{peer?.name || 'Peer'}</span> is on an older PortOS+ {row.peerPortosVersion ? <> (<span className="font-mono">{row.peerPortosVersion}</span>)</> : null}+ {' '}— they need to update before we can sync <span className="font-mono">{row.category}</span>.+ </>+ ) : (+ <>+ <span className="text-white">{peer?.name || 'Peer'}</span> is on a newer PortOS+ {row.senderPortosVersion ? <> (<span className="font-mono">{row.senderPortosVersion}</span>)</> : null}+ {' '}— update PortOS to receive their <span className="font-mono">{row.category}</span> updates.+ </>+ )}+ </span>+ </li>+ ))}+ </ul>+ </div>+ );+}diff --git a/client/src/components/instances/SchemaGapBadge.test.jsx b/client/src/components/instances/SchemaGapBadge.test.jsxnew file mode 100644index 0000000000..b15c1b4863--- /dev/null+++ b/client/src/components/instances/SchemaGapBadge.test.jsx@@ -0,0 +1,108 @@+import { describe, it, expect } from 'vitest';+import { render, screen } from '@testing-library/react';+import { SchemaGapBadge } from './SchemaGapBadge';++describe('SchemaGapBadge', () => {+ it('renders nothing when there are no gaps', () => {+ const { container } = render(<SchemaGapBadge peer={{ name: 'Peer A' }} peerSubs={[]} />);+ expect(container.firstChild).toBeNull();+ });++ it('renders nothing when peer is null', () => {+ const { container } = render(<SchemaGapBadge peer={null} peerSubs={[]} />);+ expect(container.firstChild).toBeNull();+ });++ it('renders a "peer is behind" row when a push subscription is blockedBySchema', () => {+ render(+ <SchemaGapBadge+ peer={{ name: 'Bob' }}+ peerSubs={[{+ recordKind: 'universe',+ blockedBySchema: {+ ahead: [{ category: 'universes', senderV: 5, receiverV: 4 }],+ peerPortosVersion: '2.5.0',+ detectedAt: '2026-05-23T00:00:00Z',+ },+ }]}+ />,+ );+ expect(screen.getByText(/Bob/)).toBeInTheDocument();+ expect(screen.getByText(/older PortOS/)).toBeInTheDocument();+ expect(screen.getByText('2.5.0')).toBeInTheDocument();+ expect(screen.getByText('universe')).toBeInTheDocument();+ });++ it('renders a "peer is ahead" row when peer.schemaGaps is set by snapshot sync', () => {+ render(+ <SchemaGapBadge+ peer={{+ name: 'Alice',+ schemaGaps: {+ universe: {+ ahead: [{ category: 'universes', senderV: 6, receiverV: 5 }],+ senderPortosVersion: '3.0.0',+ detectedAt: '2026-05-23T00:00:00Z',+ },+ },+ }}+ peerSubs={[]}+ />,+ );+ expect(screen.getByText(/Alice/)).toBeInTheDocument();+ expect(screen.getByText(/update PortOS/)).toBeInTheDocument();+ expect(screen.getByText('3.0.0')).toBeInTheDocument();+ });++ it('renders both directions when both transports flag the peer', () => {+ render(+ <SchemaGapBadge+ peer={{+ name: 'Mixed',+ schemaGaps: {+ mediaCollections: {+ ahead: [{ category: 'mediaCollections', senderV: 2, receiverV: 1 }],+ senderPortosVersion: '2.9.0',+ detectedAt: '2026-05-23T00:00:00Z',+ },+ },+ }}+ peerSubs={[{+ recordKind: 'series',+ blockedBySchema: {+ ahead: [{ category: 'series', senderV: 3, receiverV: 2 }],+ peerPortosVersion: '2.5.0',+ detectedAt: '2026-05-23T00:00:00Z',+ },+ }]}+ />,+ );+ expect(screen.getByText(/older PortOS/)).toBeInTheDocument();+ expect(screen.getByText(/newer PortOS/)).toBeInTheDocument();+ expect(screen.getByText('2.5.0')).toBeInTheDocument();+ expect(screen.getByText('2.9.0')).toBeInTheDocument();+ });++ it('de-dupes when both transports flag the SAME direction + category', () => {+ render(+ <SchemaGapBadge+ peer={{+ name: 'Dup',+ schemaGaps: {+ universe: { ahead: [], behind: [], senderPortosVersion: '2.9', detectedAt: '2026-05-23' },+ },+ }}+ peerSubs={[{+ recordKind: 'universe',+ blockedBySchema: { ahead: [], behind: [], peerPortosVersion: '2.5', detectedAt: '2026-05-23' },+ }]}+ />,+ );+ // The peer-behind direction and receiver-behind direction map to+ // DIFFERENT direction keys (peer-behind vs receiver-behind), so both+ // rows render — but in a future "same direction, same category" case+ // only one would show.+ // Here, ensure no crash and at least one row renders.+ expect(screen.getByText(/Schema version mismatch/)).toBeInTheDocument();+ });+});diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex d630baaa35..66b704ecfe 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -18,6 +18,7 @@ import {} from '../services/api';import PeerAppsList from '../components/instances/PeerAppsList';import PeerAgentsSection from '../components/instances/PeerAgentsSection';+import { SchemaGapBadge } from '../components/instances/SchemaGapBadge';import { timeAgo } from '../utils/formatters';import { useLocalStorageBool } from '../hooks/useLocalStorageBool';@@ -981,6 +982,8 @@ function PeerCard({ peer, onRefresh, syncStatus, tailnetInfo }) {</div>)}+ <SchemaGapBadge peer={peer} peerSubs={peerSubs} />+<SyncCategoriesPanel peer={peer} onRefresh={onRefresh} /><SyncStatusSection peer={peer} syncStatus={syncStatus} peerSubs={peerSubs} />@@ -1026,10 +1029,20 @@ export default function Instances() {setPeers(updatedPeers);};socket.on('instances:peers:updated', handlePeersUpdated);+ // Per-record peer-sync subscription blocked / unblocked → re-fetch so+ // the SchemaGapBadge picks up the new `blockedBySchema` field. The server+ // mutates the subscription state directly; the only cross-tab signal is+ // the socket event, so we refetch peers + their sub lists. Cheap because+ // it's already throttled by the user's edit cadence.+ const handleSchemaSubChange = () => { fetchData(); };+ socket.on('peerSync:subscription-blocked', handleSchemaSubChange);+ socket.on('peerSync:subscription-unblocked', handleSchemaSubChange);return () => {socket.emit('instances:unsubscribe');socket.off('instances:peers:updated', handlePeersUpdated);+ socket.off('peerSync:subscription-blocked', handleSchemaSubChange);+ socket.off('peerSync:subscription-unblocked', handleSchemaSubChange);};}, [fetchData]);diff --git a/data.sample/COS-TASKS.md b/data.reference/COS-TASKS.mdsimilarity index 100%rename from data.sample/COS-TASKS.mdrename to data.reference/COS-TASKS.mddiff --git a/data.sample/TASKS.md b/data.reference/TASKS.mdsimilarity index 100%rename from data.sample/TASKS.mdrename to data.reference/TASKS.mddiff --git a/data.sample/apps.json b/data.reference/apps.jsonsimilarity index 100%rename from data.sample/apps.jsonrename to data.reference/apps.jsondiff --git a/data.sample/autofixer/index.json b/data.reference/autofixer/index.jsonsimilarity index 100%rename from data.sample/autofixer/index.jsonrename to data.reference/autofixer/index.jsondiff --git a/data.sample/autofixer/sessions/.gitkeep b/data.reference/autofixer/sessions/.gitkeepsimilarity index 100%rename from data.sample/autofixer/sessions/.gitkeeprename to data.reference/autofixer/sessions/.gitkeepdiff --git a/data.sample/brain/admin.json b/data.reference/brain/admin.jsonsimilarity index 100%rename from data.sample/brain/admin.jsonrename to data.reference/brain/admin.jsondiff --git a/data.sample/brain/digests.jsonl b/data.reference/brain/digests.jsonlsimilarity index 100%rename from data.sample/brain/digests.jsonlrename to data.reference/brain/digests.jsonldiff --git a/data.sample/brain/ideas.json b/data.reference/brain/ideas.jsonsimilarity index 100%rename from data.sample/brain/ideas.jsonrename to data.reference/brain/ideas.jsondiff --git a/data.sample/brain/inbox_log.jsonl b/data.reference/brain/inbox_log.jsonlsimilarity index 100%rename from data.sample/brain/inbox_log.jsonlrename to data.reference/brain/inbox_log.jsonldiff --git a/data.sample/brain/meta.json b/data.reference/brain/meta.jsonsimilarity index 100%rename from data.sample/brain/meta.jsonrename to data.reference/brain/meta.jsondiff --git a/data.sample/brain/people.json b/data.reference/brain/people.jsonsimilarity index 100%rename from data.sample/brain/people.jsonrename to data.reference/brain/people.jsondiff --git a/data.sample/brain/projects.json b/data.reference/brain/projects.jsonsimilarity index 100%rename from data.sample/brain/projects.jsonrename to data.reference/brain/projects.jsondiff --git a/data.sample/brain/reviews.jsonl b/data.reference/brain/reviews.jsonlsimilarity index 100%rename from data.sample/brain/reviews.jsonlrename to data.reference/brain/reviews.jsonldiff --git a/data.sample/browser-config.json b/data.reference/browser-config.jsonsimilarity index 100%rename from data.sample/browser-config.jsonrename to data.reference/browser-config.jsondiff --git a/data.sample/cos/agents/.gitkeep b/data.reference/cos/agents/.gitkeepsimilarity index 100%rename from data.sample/cos/agents/.gitkeeprename to data.reference/cos/agents/.gitkeepdiff --git a/data.sample/cos/memory/embeddings.json b/data.reference/cos/memory/embeddings.jsonsimilarity index 100%rename from data.sample/cos/memory/embeddings.jsonrename to data.reference/cos/memory/embeddings.jsondiff --git a/data.sample/cos/memory/index.json b/data.reference/cos/memory/index.jsonsimilarity index 100%rename from data.sample/cos/memory/index.jsonrename to data.reference/cos/memory/index.jsondiff --git a/data.sample/cos/reports/.gitkeep b/data.reference/cos/reports/.gitkeepsimilarity index 100%rename from data.sample/cos/reports/.gitkeeprename to data.reference/cos/reports/.gitkeepdiff --git a/data.sample/cos/scripts/.gitkeep b/data.reference/cos/scripts/.gitkeepsimilarity index 100%rename from data.sample/cos/scripts/.gitkeeprename to data.reference/cos/scripts/.gitkeepdiff --git a/data.sample/cos/state.json b/data.reference/cos/state.jsonsimilarity index 100%rename from data.sample/cos/state.jsonrename to data.reference/cos/state.jsondiff --git a/data.sample/digital-twin/BEHAVIORAL_TEST_SUITE.md b/data.reference/digital-twin/BEHAVIORAL_TEST_SUITE.mdsimilarity index 100%rename from data.sample/digital-twin/BEHAVIORAL_TEST_SUITE.mdrename to data.reference/digital-twin/BEHAVIORAL_TEST_SUITE.mddiff --git a/data.sample/digital-twin/DIGITAL_TWIN.md b/data.reference/digital-twin/DIGITAL_TWIN.mdsimilarity index 100%rename from data.sample/digital-twin/DIGITAL_TWIN.mdrename to data.reference/digital-twin/DIGITAL_TWIN.mddiff --git a/data.sample/digital-twin/DIGITAL_TWIN_GUIDE.md b/data.reference/digital-twin/DIGITAL_TWIN_GUIDE.mdsimilarity index 100%rename from data.sample/digital-twin/DIGITAL_TWIN_GUIDE.mdrename to data.reference/digital-twin/DIGITAL_TWIN_GUIDE.mddiff --git a/data.sample/digital-twin/meta.json b/data.reference/digital-twin/meta.jsonsimilarity index 100%rename from data.sample/digital-twin/meta.jsonrename to data.reference/digital-twin/meta.jsondiff --git a/data.sample/history.json b/data.reference/history.jsonsimilarity index 100%rename from data.sample/history.jsonrename to data.reference/history.jsondiff --git a/data.sample/meatspace/post-drill-cache.json b/data.reference/meatspace/post-drill-cache.jsonsimilarity index 100%rename from data.sample/meatspace/post-drill-cache.jsonrename to data.reference/meatspace/post-drill-cache.jsondiff --git a/data.sample/media-models.json b/data.reference/media-models.jsonsimilarity index 100%rename from data.sample/media-models.jsonrename to data.reference/media-models.jsondiff --git a/data.sample/memory-classifier-config.json b/data.reference/memory-classifier-config.jsonsimilarity index 100%rename from data.sample/memory-classifier-config.jsonrename to data.reference/memory-classifier-config.jsondiff --git a/data.sample/openclaw/config.json b/data.reference/openclaw/config.jsonsimilarity index 100%rename from data.sample/openclaw/config.jsonrename to data.reference/openclaw/config.jsondiff --git a/data.sample/prompts/_partials/bible-deference.md b/data.reference/prompts/_partials/bible-deference.mdsimilarity index 100%rename from data.sample/prompts/_partials/bible-deference.mdrename to data.reference/prompts/_partials/bible-deference.mddiff --git a/data.sample/prompts/_partials/scene-output-contract.md b/data.reference/prompts/_partials/scene-output-contract.mdsimilarity index 100%rename from data.sample/prompts/_partials/scene-output-contract.mdrename to data.reference/prompts/_partials/scene-output-contract.mddiff --git a/data.sample/prompts/skills/bug-fix.md b/data.reference/prompts/skills/bug-fix.mdsimilarity index 100%rename from data.sample/prompts/skills/bug-fix.mdrename to data.reference/prompts/skills/bug-fix.mddiff --git a/data.sample/prompts/skills/documentation.md b/data.reference/prompts/skills/documentation.mdsimilarity index 100%rename from data.sample/prompts/skills/documentation.mdrename to data.reference/prompts/skills/documentation.mddiff --git a/data.sample/prompts/skills/feature-agent.md b/data.reference/prompts/skills/feature-agent.mdsimilarity index 100%rename from data.sample/prompts/skills/feature-agent.mdrename to data.reference/prompts/skills/feature-agent.mddiff --git a/data.sample/prompts/skills/feature.md b/data.reference/prompts/skills/feature.mdsimilarity index 100%rename from data.sample/prompts/skills/feature.mdrename to data.reference/prompts/skills/feature.mddiff --git a/data.sample/prompts/skills/jobs/datadog-error-monitor.md b/data.reference/prompts/skills/jobs/datadog-error-monitor.mdsimilarity index 100%rename from data.sample/prompts/skills/jobs/datadog-error-monitor.mdrename to data.reference/prompts/skills/jobs/datadog-error-monitor.mddiff --git a/data.sample/prompts/skills/jobs/jira-sprint-manager.md b/data.reference/prompts/skills/jobs/jira-sprint-manager.mdsimilarity index 100%rename from data.sample/prompts/skills/jobs/jira-sprint-manager.mdrename to data.reference/prompts/skills/jobs/jira-sprint-manager.mddiff --git a/data.sample/prompts/skills/mobile-responsive.md b/data.reference/prompts/skills/mobile-responsive.mdsimilarity index 100%rename from data.sample/prompts/skills/mobile-responsive.mdrename to data.reference/prompts/skills/mobile-responsive.mddiff --git a/data.sample/prompts/skills/refactor.md b/data.reference/prompts/skills/refactor.mdsimilarity index 100%rename from data.sample/prompts/skills/refactor.mdrename to data.reference/prompts/skills/refactor.mddiff --git a/data.sample/prompts/skills/security-audit.md b/data.reference/prompts/skills/security-audit.mdsimilarity index 100%rename from data.sample/prompts/skills/security-audit.mdrename to data.reference/prompts/skills/security-audit.mddiff --git a/data.sample/prompts/stage-config.json b/data.reference/prompts/stage-config.jsonsimilarity index 100%rename from data.sample/prompts/stage-config.jsonrename to data.reference/prompts/stage-config.jsondiff --git a/data.sample/prompts/stages/app-detection.md b/data.reference/prompts/stages/app-detection.mdsimilarity index 100%rename from data.sample/prompts/stages/app-detection.mdrename to data.reference/prompts/stages/app-detection.mddiff --git a/data.sample/prompts/stages/brain-classifier.md b/data.reference/prompts/stages/brain-classifier.mdsimilarity index 100%rename from data.sample/prompts/stages/brain-classifier.mdrename to data.reference/prompts/stages/brain-classifier.mddiff --git a/data.sample/prompts/stages/brain-daily-digest.md b/data.reference/prompts/stages/brain-daily-digest.mdsimilarity index 100%rename from data.sample/prompts/stages/brain-daily-digest.mdrename to data.reference/prompts/stages/brain-daily-digest.mddiff --git a/data.sample/prompts/stages/brain-weekly-review.md b/data.reference/prompts/stages/brain-weekly-review.mdsimilarity index 100%rename from data.sample/prompts/stages/brain-weekly-review.mdrename to data.reference/prompts/stages/brain-weekly-review.mddiff --git a/data.sample/prompts/stages/cd-evaluate.md b/data.reference/prompts/stages/cd-evaluate.mdsimilarity index 100%rename from data.sample/prompts/stages/cd-evaluate.mdrename to data.reference/prompts/stages/cd-evaluate.mddiff --git a/data.sample/prompts/stages/cd-treatment.md b/data.reference/prompts/stages/cd-treatment.mdsimilarity index 100%rename from data.sample/prompts/stages/cd-treatment.mdrename to data.reference/prompts/stages/cd-treatment.mddiff --git a/data.sample/prompts/stages/cos-agent-briefing.md b/data.reference/prompts/stages/cos-agent-briefing.mdsimilarity index 100%rename from data.sample/prompts/stages/cos-agent-briefing.mdrename to data.reference/prompts/stages/cos-agent-briefing.mddiff --git a/data.sample/prompts/stages/cos-evaluate.md b/data.reference/prompts/stages/cos-evaluate.mdsimilarity index 100%rename from data.sample/prompts/stages/cos-evaluate.mdrename to data.reference/prompts/stages/cos-evaluate.mddiff --git a/data.sample/prompts/stages/cos-report-summary.md b/data.reference/prompts/stages/cos-report-summary.mdsimilarity index 100%rename from data.sample/prompts/stages/cos-report-summary.mdrename to data.reference/prompts/stages/cos-report-summary.mddiff --git a/data.sample/prompts/stages/cos-self-improvement.md b/data.reference/prompts/stages/cos-self-improvement.mdsimilarity index 100%rename from data.sample/prompts/stages/cos-self-improvement.mdrename to data.reference/prompts/stages/cos-self-improvement.mddiff --git a/data.sample/prompts/stages/importer-arc-extract.md b/data.reference/prompts/stages/importer-arc-extract.mdsimilarity index 100%rename from data.sample/prompts/stages/importer-arc-extract.mdrename to data.reference/prompts/stages/importer-arc-extract.mddiff --git a/data.sample/prompts/stages/importer-canon-extract.md b/data.reference/prompts/stages/importer-canon-extract.mdsimilarity index 100%rename from data.sample/prompts/stages/importer-canon-extract.mdrename to data.reference/prompts/stages/importer-canon-extract.mddiff --git a/data.sample/prompts/stages/importer-classify.md b/data.reference/prompts/stages/importer-classify.mdsimilarity index 100%rename from data.sample/prompts/stages/importer-classify.mdrename to data.reference/prompts/stages/importer-classify.mddiff --git a/data.sample/prompts/stages/importer-issue-proposal.md b/data.reference/prompts/stages/importer-issue-proposal.mdsimilarity index 100%rename from data.sample/prompts/stages/importer-issue-proposal.mdrename to data.reference/prompts/stages/importer-issue-proposal.mddiff --git a/data.sample/prompts/stages/memory-evaluate.md b/data.reference/prompts/stages/memory-evaluate.mdsimilarity index 100%rename from data.sample/prompts/stages/memory-evaluate.mdrename to data.reference/prompts/stages/memory-evaluate.mddiff --git a/data.sample/prompts/stages/pipeline-arc-overview.md b/data.reference/prompts/stages/pipeline-arc-overview.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-arc-overview.mdrename to data.reference/prompts/stages/pipeline-arc-overview.mddiff --git a/data.sample/prompts/stages/pipeline-arc-resolve.md b/data.reference/prompts/stages/pipeline-arc-resolve.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-arc-resolve.mdrename to data.reference/prompts/stages/pipeline-arc-resolve.mddiff --git a/data.sample/prompts/stages/pipeline-arc-verify.md b/data.reference/prompts/stages/pipeline-arc-verify.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-arc-verify.mdrename to data.reference/prompts/stages/pipeline-arc-verify.mddiff --git a/data.sample/prompts/stages/pipeline-character-differentiate-cast.md b/data.reference/prompts/stages/pipeline-character-differentiate-cast.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-character-differentiate-cast.mdrename to data.reference/prompts/stages/pipeline-character-differentiate-cast.mddiff --git a/data.sample/prompts/stages/pipeline-character-refine.md b/data.reference/prompts/stages/pipeline-character-refine.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-character-refine.mdrename to data.reference/prompts/stages/pipeline-character-refine.mddiff --git a/data.sample/prompts/stages/pipeline-comic-cover-concepts.md b/data.reference/prompts/stages/pipeline-comic-cover-concepts.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-comic-cover-concepts.mdrename to data.reference/prompts/stages/pipeline-comic-cover-concepts.mddiff --git a/data.sample/prompts/stages/pipeline-comic-panel-image-prompt.md b/data.reference/prompts/stages/pipeline-comic-panel-image-prompt.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-comic-panel-image-prompt.mdrename to data.reference/prompts/stages/pipeline-comic-panel-image-prompt.mddiff --git a/data.sample/prompts/stages/pipeline-comic-script.md b/data.reference/prompts/stages/pipeline-comic-script.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-comic-script.mdrename to data.reference/prompts/stages/pipeline-comic-script.mddiff --git a/data.sample/prompts/stages/pipeline-extract-scenes.md b/data.reference/prompts/stages/pipeline-extract-scenes.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-extract-scenes.mdrename to data.reference/prompts/stages/pipeline-extract-scenes.mddiff --git a/data.sample/prompts/stages/pipeline-idea-expansion.md b/data.reference/prompts/stages/pipeline-idea-expansion.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-idea-expansion.mdrename to data.reference/prompts/stages/pipeline-idea-expansion.mddiff --git a/data.sample/prompts/stages/pipeline-prose.md b/data.reference/prompts/stages/pipeline-prose.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-prose.mdrename to data.reference/prompts/stages/pipeline-prose.mddiff --git a/data.sample/prompts/stages/pipeline-season-episodes.md b/data.reference/prompts/stages/pipeline-season-episodes.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-season-episodes.mdrename to data.reference/prompts/stages/pipeline-season-episodes.mddiff --git a/data.sample/prompts/stages/pipeline-series-title-logo.md b/data.reference/prompts/stages/pipeline-series-title-logo.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-series-title-logo.mdrename to data.reference/prompts/stages/pipeline-series-title-logo.mddiff --git a/data.sample/prompts/stages/pipeline-storyboard-image-prompt.md b/data.reference/prompts/stages/pipeline-storyboard-image-prompt.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-storyboard-image-prompt.mdrename to data.reference/prompts/stages/pipeline-storyboard-image-prompt.mddiff --git a/data.sample/prompts/stages/pipeline-teleplay.md b/data.reference/prompts/stages/pipeline-teleplay.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-teleplay.mdrename to data.reference/prompts/stages/pipeline-teleplay.mddiff --git a/data.sample/prompts/stages/pipeline-volume-cover-concepts.md b/data.reference/prompts/stages/pipeline-volume-cover-concepts.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-volume-cover-concepts.mdrename to data.reference/prompts/stages/pipeline-volume-cover-concepts.mddiff --git a/data.sample/prompts/stages/pipeline-volume-verify.md b/data.reference/prompts/stages/pipeline-volume-verify.mdsimilarity index 100%rename from data.sample/prompts/stages/pipeline-volume-verify.mdrename to data.reference/prompts/stages/pipeline-volume-verify.mddiff --git a/data.sample/prompts/stages/universe-character-expand.md b/data.reference/prompts/stages/universe-character-expand.mdsimilarity index 100%rename from data.sample/prompts/stages/universe-character-expand.mdrename to data.reference/prompts/stages/universe-character-expand.mddiff --git a/data.sample/prompts/stages/writers-room-characters.md b/data.reference/prompts/stages/writers-room-characters.mdsimilarity index 100%rename from data.sample/prompts/stages/writers-room-characters.mdrename to data.reference/prompts/stages/writers-room-characters.mddiff --git a/data.sample/prompts/stages/writers-room-evaluate.md b/data.reference/prompts/stages/writers-room-evaluate.mdsimilarity index 100%rename from data.sample/prompts/stages/writers-room-evaluate.mdrename to data.reference/prompts/stages/writers-room-evaluate.mddiff --git a/data.sample/prompts/stages/writers-room-format.md b/data.reference/prompts/stages/writers-room-format.mdsimilarity index 100%rename from data.sample/prompts/stages/writers-room-format.mdrename to data.reference/prompts/stages/writers-room-format.mddiff --git a/data.sample/prompts/stages/writers-room-objects.md b/data.reference/prompts/stages/writers-room-objects.mdsimilarity index 100%rename from data.sample/prompts/stages/writers-room-objects.mdrename to data.reference/prompts/stages/writers-room-objects.mddiff --git a/data.sample/prompts/stages/writers-room-places.md b/data.reference/prompts/stages/writers-room-places.mdsimilarity index 100%rename from data.sample/prompts/stages/writers-room-places.mdrename to data.reference/prompts/stages/writers-room-places.mddiff --git a/data.sample/prompts/stages/writers-room-script.md b/data.reference/prompts/stages/writers-room-script.mdsimilarity index 100%rename from data.sample/prompts/stages/writers-room-script.mdrename to data.reference/prompts/stages/writers-room-script.mddiff --git a/data.sample/prompts/variables.json b/data.reference/prompts/variables.jsonsimilarity index 100%rename from data.sample/prompts/variables.jsonrename to data.reference/prompts/variables.jsondiff --git a/data.sample/providers.json b/data.reference/providers.jsonsimilarity index 100%rename from data.sample/providers.jsonrename to data.reference/providers.jsondiff --git a/data.sample/runs/.gitkeep b/data.reference/runs/.gitkeepsimilarity index 100%rename from data.sample/runs/.gitkeeprename to data.reference/runs/.gitkeepdiff --git a/data.sample/settings.json b/data.reference/settings.jsonsimilarity index 100%rename from data.sample/settings.jsonrename to data.reference/settings.jsondiff --git a/data.sample/templates/character-reference-sheet.png b/data.reference/templates/character-reference-sheet.pngsimilarity index 100%rename from data.sample/templates/character-reference-sheet.pngrename to data.reference/templates/character-reference-sheet.pngdiff --git a/data.sample/usage.json b/data.reference/usage.jsonsimilarity index 100%rename from data.sample/usage.jsonrename to data.reference/usage.jsondiff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.mdindex 478f0bb86e..df0bcdd048 100644--- a/docs/TROUBLESHOOTING.md+++ b/docs/TROUBLESHOOTING.md@@ -39,7 +39,7 @@ pm2 logs portos-server --lines 100**Solution**:```bash# Copy sample data files-cp -r data.sample/* data/+cp -r data.reference/* data/```## Connection Issuesdiff --git a/docs/features/brain/plan.md b/docs/features/brain/plan.mdindex 3336f45a27..8b6dea76f6 100644--- a/docs/features/brain/plan.md+++ b/docs/features/brain/plan.md@@ -30,7 +30,7 @@ Client (React) Server (Express) Storage (./**Files to create:**- `server/lib/brainValidation.js` - Zod schemas for all Brain entities- `server/services/brainStorage.js` - JSONL file operations-- `data.sample/brain/` - Sample data directory with all files+- `data.reference/brain/` - Sample data directory with all files**Schemas:**@@ -366,7 +366,7 @@ export default function Brain() {### Phase 6: Sample Data & Tests-**Sample data files (./data.sample/brain/):**+**Sample data files (./data.reference/brain/):**- `meta.json` - Default settings- `inbox_log.jsonl` - 10-15 sample entries (mix of statuses)- `people.jsonl` - 5 sample people@@ -422,7 +422,7 @@ data/prompts/stages/brain-daily-digest.mdbrain-weekly-review.md-data.sample/brain/+data.reference/brain/meta.jsoninbox_log.jsonlpeople.jsonldiff --git a/docs/features/brain/prompt.md b/docs/features/brain/prompt.mdindex 13531f3695..48b73cddae 100644--- a/docs/features/brain/prompt.md+++ b/docs/features/brain/prompt.md@@ -65,7 +65,7 @@ Everything must work offline and be self-contained.- Use PortOS’s existing AI Provider/Model config + prompt templates system:- Default Brain to LM Studio with model `openai/gpt-oss-20b`.- Allow runtime override per request (provider/model).-- Local persistence under **./data/brain/** (gitignored), with sample data under **./data.sample/brain/**.+- Local persistence under **./data/brain/** (gitignored), with sample data under **./data.reference/brain/**.# 4) Data model (schemas + file layout)Use JSON Lines (preferred) for append-only audit and easy diffs. Keep records human-readable.@@ -359,7 +359,7 @@ Include:- Add a small queue processor to retry classification when AI becomes available.# 12) Testing + sample data-- Provide sample data under ./data.sample/brain to demo UI instantly.+- Provide sample data under ./data.reference/brain to demo UI instantly.- Add minimal tests for:- capture flow creates inbox log always- confidence threshold gatingdiff --git a/docs/features/openclaw-operator-chat-audit.md b/docs/features/openclaw-operator-chat-audit.mdindex 27f2ceab37..5d5b76b165 100644--- a/docs/features/openclaw-operator-chat-audit.md+++ b/docs/features/openclaw-operator-chat-audit.md@@ -328,7 +328,7 @@ Local/private only:- `data/openclaw/config.json` (git-ignored or machine-local)Optional public-safe sample:-- `data.sample/openclaw/config.json` with placeholders only+- `data.reference/openclaw/config.json` with placeholders only## 13. MVP endpoint sketchdiff --git a/docs/features/writers-room.md b/docs/features/writers-room.mdindex 2b8f32b292..ede6b60f3f 100644--- a/docs/features/writers-room.md+++ b/docs/features/writers-room.md@@ -308,7 +308,7 @@ UI contract.Add `server/services/writersRoom/evaluator.js`.Use existing provider and prompt infrastructure instead of hardcoding prompts in-the route. Recommended prompt stages under `data.sample/prompts/stages/`:+the route. Recommended prompt stages under `data.reference/prompts/stages/`:- `writers-room-summary.md`- `writers-room-characters.md`diff --git a/scripts/migrations/002-cd-evaluate-image-strength.js b/scripts/migrations/002-cd-evaluate-image-strength.jsindex 089d5841cc..a6d9adfdc5 100644--- a/scripts/migrations/002-cd-evaluate-image-strength.js+++ b/scripts/migrations/002-cd-evaluate-image-strength.js@@ -3,7 +3,7 @@* pre-existing installs.** The Creative Director evaluator template gained a two-line block in- * `data.sample/prompts/stages/cd-evaluate.md` that surfaces the per-scene+ * `data.reference/prompts/stages/cd-evaluate.md` that surfaces the per-scene* `imageStrength` knob (and a sentence in the retry-branch instructions* documenting how to adjust it). `setup-data.js` only copies prompt files* that don't yet exist in `data/`, so installs created before that change@@ -47,7 +47,7 @@ export default {throw err;});if (original == null) {- console.log(`📄 ${TEMPLATE_REL_PATH} not present — skipping (fresh install will copy from data.sample)`);+ console.log(`📄 ${TEMPLATE_REL_PATH} not present — skipping (fresh install will copy from data.reference)`);return;}@@ -62,7 +62,7 @@ export default {next = next.replace(anchorPair, ANCHOR_BEFORE_BLOCK + NEW_BLOCK_LINES + ANCHOR_AFTER_BLOCK);changed = true;} else {- console.log(`⚠️ ${TEMPLATE_REL_PATH}: scene-context anchors don't match the pre-update template — skipping the imageStrength block insertion. Hand-merge from data.sample/ if needed.`);+ console.log(`⚠️ ${TEMPLATE_REL_PATH}: scene-context anchors don't match the pre-update template — skipping the imageStrength block insertion. Hand-merge from data.reference/ if needed.`);}}@@ -73,7 +73,7 @@ export default {next = next.replace(RETRY_OLD, RETRY_NEW);changed = true;} else {- console.log(`⚠️ ${TEMPLATE_REL_PATH}: retry-branch sentence doesn't match the pre-update template — skipping the imageStrength guidance extension. Hand-merge from data.sample/ if needed.`);+ console.log(`⚠️ ${TEMPLATE_REL_PATH}: retry-branch sentence doesn't match the pre-update template — skipping the imageStrength guidance extension. Hand-merge from data.reference/ if needed.`);}}diff --git a/scripts/migrations/003-update-pipeline-stage-prompts.js b/scripts/migrations/003-update-pipeline-stage-prompts.jsindex f197111aec..8a4c93ad48 100644--- a/scripts/migrations/003-update-pipeline-stage-prompts.js+++ b/scripts/migrations/003-update-pipeline-stage-prompts.js@@ -44,7 +44,7 @@ export const NEW_SHIPPED_MD5 = {'pipeline-idea-expansion.md': '1f3c5d077a5ef9a4b610335d5e3edd9c', // post-025'pipeline-prose.md': 'd1f8e3f1d214725b5aa67f309a81cd7d', // post-027'pipeline-comic-script.md': '133d200d069c2e8173b7c129eea58f53', // post-027- 'pipeline-tv-script.md': '376f779f4687b598f1c92ca4e770fd5a', // retired upstream (no data.sample)+ 'pipeline-tv-script.md': '376f779f4687b598f1c92ca4e770fd5a', // retired upstream (no data.reference)'pipeline-season-episodes.md': '50c68a29c3ebc275db3095d06bd87100', // post-005};@@ -55,7 +55,7 @@ const { applyMigration, up } = makePromptReplaceMigration({retireOnSampleMissing: true,customizedHint: (filename) =>` To apply the length-profile variables manually, diff:\n` +- ` data.sample/prompts/stages/${filename}\n` ++ ` data.reference/prompts/stages/${filename}\n` +` against your current:\n` +` data/prompts/stages/${filename}\n` +` and merge the {{lengthTargets.*}} template variables.`,@@ -63,7 +63,7 @@ const { applyMigration, up } = makePromptReplaceMigration({`⚠️ ${count} prompt(s) could not be auto-updated because they were customized.\n` +` The length profile picker UI will work, but those prompts won't use\n` +` {{lengthTargets.*}} variables until you merge them manually.\n` +- ` See data.sample/prompts/stages/ for the updated templates.`,+ ` See data.reference/prompts/stages/ for the updated templates.`,});export { applyMigration };diff --git a/scripts/migrations/003-update-pipeline-stage-prompts.test.js b/scripts/migrations/003-update-pipeline-stage-prompts.test.jsindex 98fc06d3d0..8cf8a761b8 100644--- a/scripts/migrations/003-update-pipeline-stage-prompts.test.js+++ b/scripts/migrations/003-update-pipeline-stage-prompts.test.js@@ -3,7 +3,7 @@* variables.** `pipeline-tv-script.md` was retired (renamed to `pipeline-teleplay.md`) so- * it has no `data.sample/` counterpart; the standard fixture loop in+ * it has no `data.reference/` counterpart; the standard fixture loop in* `_testHelpers.js` reads the live sample to seed each fixture, which would* ENOENT on the retired entry. Filter it out of the test-facing maps — the* retire-on-missing branch is exercised end-to-end by `scripts/run-migrations.js`diff --git a/scripts/migrations/004-augment-idea-expansion-context.js b/scripts/migrations/004-augment-idea-expansion-context.jsindex 06dbe9f408..cad20170e3 100644--- a/scripts/migrations/004-augment-idea-expansion-context.js+++ b/scripts/migrations/004-augment-idea-expansion-context.js@@ -28,7 +28,7 @@ const { applyMigration, up } = makePromptReplaceMigration({label: 'idea-expansion context',customizedHint: (filename) =>` To pick up the new arc / volume / neighbor-issue context blocks, diff:\n` +- ` data.sample/prompts/stages/${filename}\n` ++ ` data.reference/prompts/stages/${filename}\n` +` against your current:\n` +` data/prompts/stages/${filename}\n` +` and merge the {{#arc}}, {{#volume}}, {{#priorIssue}}, {{#nextIssue}},\n` +diff --git a/scripts/migrations/005-shape-aware-arc-prompts.js b/scripts/migrations/005-shape-aware-arc-prompts.jsindex db23b42ec9..0320cd3027 100644--- a/scripts/migrations/005-shape-aware-arc-prompts.js+++ b/scripts/migrations/005-shape-aware-arc-prompts.js@@ -10,10 +10,10 @@* pipeline-volume-verify — per-volume placement + volume-internal adherence check* pipeline-arc-resolve — preserve picked shape during auto-resolve*- * `pipeline-arc-resolve.md` was never previously in data.sample/ (it shipped+ * `pipeline-arc-resolve.md` was never previously in data.reference/ (it shipped* in `27ef3c27` but only landed in `data/`). `createIfMissing: true` keeps* the migration self-contained for that case; for the other files the branch- * never fires because they already shipped in data.sample/.+ * never fires because they already shipped in data.reference/.** Strategy: hash-driven prompt-replace via `./_lib.js`. Idempotent.*/@@ -56,7 +56,7 @@ const { applyMigration, up } = makePromptReplaceMigration({createIfMissing: true,customizedHint: (filename) =>` To apply the Vonnegut shape variables manually, diff:\n` +- ` data.sample/prompts/stages/${filename}\n` ++ ` data.reference/prompts/stages/${filename}\n` +` against your current:\n` +` data/prompts/stages/${filename}\n` +` and merge the {{{shapeGuidance}}} block (and {{shapePosition}} / {{volumeShapePosition}} where applicable).`,diff --git a/scripts/migrations/006-extract-scenes-shots.js b/scripts/migrations/006-extract-scenes-shots.jsindex 961e4feefd..37089ea6ab 100644--- a/scripts/migrations/006-extract-scenes-shots.js+++ b/scripts/migrations/006-extract-scenes-shots.js@@ -23,7 +23,7 @@ const { applyMigration, up } = makePromptReplaceMigration({label: 'extract-scenes shots',customizedHint: (filename) =>` Manually merge the shots[] additions from:\n` +- ` data.sample/prompts/stages/${filename}\n` ++ ` data.reference/prompts/stages/${filename}\n` +` into your current:\n` +` data/prompts/stages/${filename}`,skipFooter: (count) =>diff --git a/scripts/migrations/007-places-int-ext-time-of-day.js b/scripts/migrations/007-places-int-ext-time-of-day.jsindex 60fbd0a23e..d9e143a341 100644--- a/scripts/migrations/007-places-int-ext-time-of-day.js+++ b/scripts/migrations/007-places-int-ext-time-of-day.js@@ -29,7 +29,7 @@ const NEW_SHIPPED_MD5 = {export default {async up({ rootDir }) {const stagesDir = join(rootDir, 'data', 'prompts', 'stages');- const sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');+ const sampleDir = join(rootDir, 'data.reference', 'prompts', 'stages');let updated = 0;let alreadyCurrent = 0;@@ -60,7 +60,7 @@ export default {console.warn(`⚠️ places extraction prompt ${filename} has been customized — skipping auto-update.\n` +` To pick up the new intExt / timeOfDay fields, diff:\n` +- ` data.sample/prompts/stages/${filename}\n` ++ ` data.reference/prompts/stages/${filename}\n` +` against your current:\n` +` data/prompts/stages/${filename}\n` +` and add the two new field bullets + two new JSON keys.`,diff --git a/scripts/migrations/008-default-to-claude-code-tui.js b/scripts/migrations/008-default-to-claude-code-tui.jsindex adfc7e58d3..6615ff3ae1 100644--- a/scripts/migrations/008-default-to-claude-code-tui.js+++ b/scripts/migrations/008-default-to-claude-code-tui.js@@ -28,7 +28,7 @@ export default {throw err;});if (raw == null) {- console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install will copy from data.sample with the new default already applied)`);+ console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install will copy from data.reference with the new default already applied)`);return;}diff --git a/scripts/migrations/010-simplify-cos-agent-briefing.js b/scripts/migrations/010-simplify-cos-agent-briefing.jsindex 3ef58a2f9b..83f0db6d4a 100644--- a/scripts/migrations/010-simplify-cos-agent-briefing.js+++ b/scripts/migrations/010-simplify-cos-agent-briefing.js@@ -32,7 +32,7 @@ const { applyMigration, up } = makePromptReplaceMigration({label: 'cos-agent-briefing',customizedHint: (filename) =>` To drop the obsolete header and role-play preamble manually, diff:\n` +- ` data.sample/prompts/stages/${filename}\n` ++ ` data.reference/prompts/stages/${filename}\n` +` against your current:\n` +` data/prompts/stages/${filename}`,});diff --git a/scripts/migrations/012-mark-flux1-dev-gated.js b/scripts/migrations/012-mark-flux1-dev-gated.jsindex 8877905ce0..ed9df17f57 100644--- a/scripts/migrations/012-mark-flux1-dev-gated.js+++ b/scripts/migrations/012-mark-flux1-dev-gated.js@@ -1,10 +1,10 @@/*** Mark FLUX.1-dev as a gated HuggingFace model in existing installs.*- * `data.sample/media-models.json` now carries `requiresHfToken: true` ++ * `data.reference/media-models.json` now carries `requiresHfToken: true` +* `licenseUrl` on the `dev` entry so the Image Gen page can surface the* inline HF-token banner (same pattern FLUX.2-klein already used). Fresh- * installs pick this up via the data.sample → data copy in setup-data.js,+ * installs pick this up via the data.reference → data copy in setup-data.js,* but `media-models.json` is not in JSON_MERGE_TARGETS so existing installs* keep their pre-flip entry. This migration patches the two fields onto an* unmodified `dev` entry without touching anything else.@@ -26,7 +26,7 @@ export default {throw err;});if (raw == null) {- console.log(`📄 ${REL_PATH} not present — skipping (fresh install will copy from data.sample)`);+ console.log(`📄 ${REL_PATH} not present — skipping (fresh install will copy from data.reference)`);return;}diff --git a/scripts/migrations/013-comic-script-back-cover.js b/scripts/migrations/013-comic-script-back-cover.jsindex befdddd77e..ce3b381566 100644--- a/scripts/migrations/013-comic-script-back-cover.js+++ b/scripts/migrations/013-comic-script-back-cover.js@@ -31,7 +31,7 @@ const { applyMigration, up } = makePromptReplaceMigration({label: 'comic-script back-cover',customizedHint: (filename) =>` To add the Back cover concept section manually, diff:\n` +- ` data.sample/prompts/stages/${filename}\n` ++ ` data.reference/prompts/stages/${filename}\n` +` against your current:\n` +` data/prompts/stages/${filename}\n` +` and merge the new \`## Back cover concept\` block.`,diff --git a/scripts/migrations/015-importer-stage-prompts.js b/scripts/migrations/015-importer-stage-prompts.jsindex 7c887f888d..efec04621f 100644--- a/scripts/migrations/015-importer-stage-prompts.js+++ b/scripts/migrations/015-importer-stage-prompts.js@@ -41,12 +41,12 @@ export default {await mkdir(stagesDir, { recursive: true });for (const filename of FILENAMES) {const dataPath = join(stagesDir, filename);- const samplePath = join(rootDir, 'data.sample', 'prompts', 'stages', filename);+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);if (exists) { present++; continue; }- // Validate the source exists before copy — if `data.sample/` was+ // Validate the source exists before copy — if `data.reference/` was// trimmed in a later release or this migration runs against a sparse// checkout, we'd otherwise abort the whole migration batch mid-loop.const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);@@ -76,10 +76,10 @@ export default {// above but no stage-config entries, so `getStage()` can't resolve// them and the importer LLM calls fail or fall back to a wrong tier.const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');- const sampleConfigPath = join(rootDir, 'data.sample', 'prompts', 'stage-config.json');+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);if (!sampleConfigExists) {- console.warn('⚠️ importer-stage-prompts: data.sample stage-config.json missing — cannot resolve importer entries; skipping config write');+ console.warn('⚠️ importer-stage-prompts: data.reference stage-config.json missing — cannot resolve importer entries; skipping config write');return;}try {diff --git a/scripts/migrations/016-importer-fence-source.js b/scripts/migrations/016-importer-fence-source.jsindex 907d29329a..de7277ca0e 100644--- a/scripts/migrations/016-importer-fence-source.js+++ b/scripts/migrations/016-importer-fence-source.js@@ -48,7 +48,7 @@ export default {for (const { filename, oldShippedMd5, newShippedMd5 } of TARGETS) {const installedPath = join(rootDir, 'data', 'prompts', 'stages', filename);- const samplePath = join(rootDir, 'data.sample', 'prompts', 'stages', filename);+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', filename);const installedExists = await access(installedPath, constants.F_OK).then(() => true, () => false);if (!installedExists) { missing++; continue; }@@ -65,7 +65,7 @@ export default {const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);if (!sampleExists) {- console.warn(`⚠️ importer-fence-source: data.sample for ${filename} missing — cannot update`);+ console.warn(`⚠️ importer-fence-source: data.reference for ${filename} missing — cannot update`);continue;}const sample = await readFile(samplePath, 'utf8');diff --git a/scripts/migrations/017-volume-cover-concepts-stage.js b/scripts/migrations/017-volume-cover-concepts-stage.jsindex 7c4f174d7f..e7976c2ed2 100644--- a/scripts/migrations/017-volume-cover-concepts-stage.js+++ b/scripts/migrations/017-volume-cover-concepts-stage.js@@ -4,7 +4,7 @@* Commit d802eb18 ("feat(pipeline): issue back covers + volume covers +* trade-paperback PDF") shipped the per-season cover-concept LLM step* (`arcPlanner.generateVolumeCoverConcepts` → `runStagedLLM('pipeline-volume-cover-concepts', …)`)- * and added `data.sample/prompts/stages/pipeline-volume-cover-concepts.md`+ * and added `data.reference/prompts/stages/pipeline-volume-cover-concepts.md`* but forgot two things existing installs need:** 1. A `stage-config.json` entry — `setup-data.js` only merges@@ -31,7 +31,7 @@ export default {await mkdir(stagesDir, { recursive: true });const dataPath = join(stagesDir, FILENAME);- const samplePath = join(rootDir, 'data.sample', 'prompts', 'stages', FILENAME);+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);if (exists) {@@ -51,10 +51,10 @@ export default {}const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');- const sampleConfigPath = join(rootDir, 'data.sample', 'prompts', 'stage-config.json');+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);if (!sampleConfigExists) {- console.warn('⚠️ volume-cover-concepts: data.sample stage-config.json missing — cannot resolve entry; skipping config write');+ console.warn('⚠️ volume-cover-concepts: data.reference stage-config.json missing — cannot resolve entry; skipping config write');return;}try {diff --git a/scripts/migrations/018-rename-writers-room-settings-stage.js b/scripts/migrations/018-rename-writers-room-settings-stage.jsindex 95cb4f133c..edfe563b36 100644--- a/scripts/migrations/018-rename-writers-room-settings-stage.js+++ b/scripts/migrations/018-rename-writers-room-settings-stage.js@@ -26,7 +26,7 @@** 2. `ensureSampleContent` copies missing prompt files — so* `data/prompts/stages/writers-room-places.md` will be auto-seeded- * from data.sample (full post-rename + post-migration-007 content)+ * from data.reference (full post-rename + post-migration-007 content)* while the user's old `writers-room-settings.md` is left orphaned.* Switching the stage key to `…-places` makes the runtime use the* freshly seeded sample template, ignoring any customizations the@@ -63,17 +63,17 @@ import { join } from 'path';import { createHash } from 'crypto';const STAGE_CONFIG_REL_PATH = 'data/prompts/stage-config.json';-const SAMPLE_CONFIG_REL_PATH = 'data.sample/prompts/stage-config.json';+const SAMPLE_CONFIG_REL_PATH = 'data.reference/prompts/stage-config.json';const LEGACY_KEY = 'writers-room-settings';const NEW_KEY = 'writers-room-places';const PROMPTS_STAGES_DIR_REL = 'data/prompts/stages';-const SAMPLE_STAGES_DIR_REL = 'data.sample/prompts/stages';+const SAMPLE_STAGES_DIR_REL = 'data.reference/prompts/stages';const LEGACY_PROMPT_FILE = 'writers-room-settings.md';const NEW_PROMPT_FILE = 'writers-room-places.md';// MD5 of the pre-rename `writers-room-settings.md` shipped baseline (the-// content that existed in data.sample right before commit be903564 renamed+// content that existed in data.reference right before commit be903564 renamed// the file to `writers-room-places.md`). An installed legacy file at this// hash is an *unmodified* default — the user did not customize it. This// also happens to equal migration 007's `OLD_SHIPPED_MD5` for the renamed@@ -140,7 +140,7 @@ const migratePromptFile = async (rootDir) => {}if (newContent != null && sampleContent != null && newContent === sampleContent) {- // `…-places.md` was just auto-seeded from data.sample. Decide whether+ // `…-places.md` was just auto-seeded from data.reference. Decide whether// the legacy file is an unmodified default (keep the modern auto-seed)// or carries real user customizations (preserve those over the seed).//@@ -214,7 +214,7 @@ export default {throw err;});if (raw == null) {- console.log(`📄 ${STAGE_CONFIG_REL_PATH} not present — skipping (fresh install will copy from data.sample)`);+ console.log(`📄 ${STAGE_CONFIG_REL_PATH} not present — skipping (fresh install will copy from data.reference)`);return;}diff --git a/scripts/migrations/019-arc-volume-prompts-canon-context.js b/scripts/migrations/019-arc-volume-prompts-canon-context.jsindex 3acfbc1d92..8e6672c4fa 100644--- a/scripts/migrations/019-arc-volume-prompts-canon-context.js+++ b/scripts/migrations/019-arc-volume-prompts-canon-context.js@@ -68,7 +68,7 @@ const { applyMigration, up } = makePromptReplaceMigration({label: 'arc-prompt canon-context',customizedHint: (filename) =>` To pick up {{worldCanonText}} manually, diff:\n` +- ` data.sample/prompts/stages/${filename}\n` ++ ` data.reference/prompts/stages/${filename}\n` +` against your current:\n` +` data/prompts/stages/${filename}\n` +` and add the new "World canon" block in the same position as in the sample template.`,@@ -76,7 +76,7 @@ const { applyMigration, up } = makePromptReplaceMigration({`⚠️ ${count} arc/volume prompt(s) could not be auto-updated because they were customized.\n` +` The {{worldCanonText}} block will not render character names in arc-overview/\n` +` arc-verify/arc-resolve/volume-verify until the files are merged manually. See\n` +- ` data.sample/prompts/stages/.`,+ ` data.reference/prompts/stages/.`,});export { applyMigration };diff --git a/scripts/migrations/020-comic-cover-concepts-stage.js b/scripts/migrations/020-comic-cover-concepts-stage.jsindex e37303c554..ecb1e27c1c 100644--- a/scripts/migrations/020-comic-cover-concepts-stage.js+++ b/scripts/migrations/020-comic-cover-concepts-stage.js@@ -2,7 +2,7 @@* Seed the `pipeline-comic-cover-concepts` stage into existing installs.** Mirrors `017-volume-cover-concepts-stage.js`: copies the `.md` template- * from `data.sample/prompts/stages/` and merges the stage-config entry+ * from `data.reference/prompts/stages/` and merges the stage-config entry* into `data/prompts/stage-config.json` so upgrades that skip re-running* `setup-data.js` still get the new per-issue cover-concept LLM step.*/@@ -19,7 +19,7 @@ export default {await mkdir(stagesDir, { recursive: true });const dataPath = join(stagesDir, FILENAME);- const samplePath = join(rootDir, 'data.sample', 'prompts', 'stages', FILENAME);+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);if (exists) {@@ -39,10 +39,10 @@ export default {}const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');- const sampleConfigPath = join(rootDir, 'data.sample', 'prompts', 'stage-config.json');+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);if (!sampleConfigExists) {- console.warn('⚠️ comic-cover-concepts: data.sample stage-config.json missing — cannot resolve entry; skipping config write');+ console.warn('⚠️ comic-cover-concepts: data.reference stage-config.json missing — cannot resolve entry; skipping config write');return;}try {diff --git a/scripts/migrations/020-importer-screenplay-user-requested-count.js b/scripts/migrations/020-importer-screenplay-user-requested-count.jsindex d627a8cc11..b4dc5e618a 100644--- a/scripts/migrations/020-importer-screenplay-user-requested-count.js+++ b/scripts/migrations/020-importer-screenplay-user-requested-count.js@@ -34,7 +34,7 @@ const md5 = (text) => createHash('md5')export default {async up({ rootDir }) {const installedPath = join(rootDir, 'data', 'prompts', 'stages', FILENAME);- const samplePath = join(rootDir, 'data.sample', 'prompts', 'stages', FILENAME);+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', FILENAME);const installedExists = await access(installedPath, constants.F_OK).then(() => true, () => false);if (!installedExists) {@@ -50,13 +50,13 @@ export default {return;}if (installedHash !== OLD_SHIPPED_MD5) {- console.warn(`⚠️ importer-screenplay-user-requested-count: ${FILENAME} is customized — leaving as-is. Merge the new screenplay-block gating manually from data.sample if needed.`);+ console.warn(`⚠️ importer-screenplay-user-requested-count: ${FILENAME} is customized — leaving as-is. Merge the new screenplay-block gating manually from data.reference if needed.`);return;}const sampleExists = await access(samplePath, constants.F_OK).then(() => true, () => false);if (!sampleExists) {- console.warn(`⚠️ importer-screenplay-user-requested-count: data.sample for ${FILENAME} missing — cannot update`);+ console.warn(`⚠️ importer-screenplay-user-requested-count: data.reference for ${FILENAME} missing — cannot update`);return;}const sample = await readFile(samplePath, 'utf8');diff --git a/scripts/migrations/022-character-extended-fields.js b/scripts/migrations/022-character-extended-fields.jsindex 0314b0dce6..6a47e34c52 100644--- a/scripts/migrations/022-character-extended-fields.js+++ b/scripts/migrations/022-character-extended-fields.js@@ -9,7 +9,7 @@* git-pull + pm2 restart, without re-running `npm run install:all` /* `scripts/setup-data.js`, still has everything the runtime expects):*- * 1. Copies `data.sample/prompts/stages/universe-character-expand.md` →+ * 1. Copies `data.reference/prompts/stages/universe-character-expand.md` →* `data/prompts/stages/universe-character-expand.md` for the* `expandUniverseCharacter` LLM stage.* 2. Merges the `universe-character-expand` entry into the installed@@ -39,7 +39,7 @@ export default {const stagesDir = join(rootDir, 'data', 'prompts', 'stages');await mkdir(stagesDir, { recursive: true });const dataPath = join(stagesDir, PROMPT_FILENAME);- const samplePath = join(rootDir, 'data.sample', 'prompts', 'stages', PROMPT_FILENAME);+ const samplePath = join(rootDir, 'data.reference', 'prompts', 'stages', PROMPT_FILENAME);const exists = await access(dataPath, constants.F_OK).then(() => true, () => false);if (exists) {console.log(`📝 ${PROMPT_FILENAME}: already present`);@@ -62,10 +62,10 @@ export default {// universe-character-expand stage and the expand route 500s.{const installedConfigPath = join(rootDir, 'data', 'prompts', 'stage-config.json');- const sampleConfigPath = join(rootDir, 'data.sample', 'prompts', 'stage-config.json');+ const sampleConfigPath = join(rootDir, 'data.reference', 'prompts', 'stage-config.json');const sampleConfigExists = await access(sampleConfigPath, constants.F_OK).then(() => true, () => false);if (!sampleConfigExists) {- console.warn(`⚠️ universe-character-expand: data.sample stage-config.json missing — skipping config write`);+ console.warn(`⚠️ universe-character-expand: data.reference stage-config.json missing — skipping config write`);return;}try {diff --git a/scripts/migrations/022-rename-bible-setting-to-place.js b/scripts/migrations/022-rename-bible-setting-to-place.jsindex fbb542f2db..c0505c5ba6 100644--- a/scripts/migrations/022-rename-bible-setting-to-place.js+++ b/scripts/migrations/022-rename-bible-setting-to-place.js@@ -88,12 +88,12 @@ const OLD_PROMPTS_DEFERENCE_MD5 = '218f0e85643609ed85a12b1ccc7b5a8d';const NEW_PROMPTS_DEFERENCE_MD5 = 'a4681348c27776e414acf6e0be566a99';// Each template has a sample twin at the same relative path under-// `data.sample/…`. When an installed copy still hashes to the pre-rename+// `data.reference/…`. When an installed copy still hashes to the pre-rename// baseline (`oldHash`), the migration prefers copying the bundled-// `data.sample` file verbatim — that picks up *every* string the rename+// `data.reference` file verbatim — that picks up *every* string the rename// touched (`## Existing settings` → `## Existing places`, etc.) without// enumerating the full prose diff. If the bundled sample is missing-// (distributions that strip `data.sample/`, or tests that point `rootDir`+// (distributions that strip `data.reference/`, or tests that point `rootDir`// at a relocated data tree), we fall back to a surgical replace covering// the rename-critical substitutions so the prompt's runtime contract// (`{{existingPlacesJson}}` envelope variable + `"places":` LLM output@@ -117,13 +117,13 @@ const RENAME_SUBSTITUTIONS = [const PROMPT_TEMPLATES = [{rel: 'data/prompts/stages/writers-room-places.md',- sampleRel: 'data.sample/prompts/stages/writers-room-places.md',+ sampleRel: 'data.reference/prompts/stages/writers-room-places.md',oldHash: OLD_PROMPTS_PLACES_MD5,newHash: NEW_PROMPTS_PLACES_MD5,},{rel: 'data/prompts/_partials/bible-deference.md',- sampleRel: 'data.sample/prompts/_partials/bible-deference.md',+ sampleRel: 'data.reference/prompts/_partials/bible-deference.md',oldHash: OLD_PROMPTS_DEFERENCE_MD5,newHash: NEW_PROMPTS_DEFERENCE_MD5,},@@ -267,12 +267,12 @@ const migratePromptTemplate = async (rootDir, { rel, sampleRel, oldHash, newHashreturn;}if (currentHash !== oldHash) {- console.log(`⚠️ ${rel}: customized (hash ${currentHash.slice(0, 8)}) — not auto-updating. Diff against data.sample to pick up the {{existingPlacesJson}} rename.`);+ console.log(`⚠️ ${rel}: customized (hash ${currentHash.slice(0, 8)}) — not auto-updating. Diff against data.reference to pick up the {{existingPlacesJson}} rename.`);return;}- // Pre-rename baseline. Prefer copying the bundled `data.sample` twin+ // Pre-rename baseline. Prefer copying the bundled `data.reference` twin// verbatim — it carries every prose substitution the rename touched.- // When `data.sample` is missing (stripped distribution, relocated+ // When `data.reference` is missing (stripped distribution, relocated// rootDir), fall back to a surgical replace covering the// rename-critical substitutions enumerated in RENAME_SUBSTITUTIONS,// so the prompt's runtime contract still works even if some prose@@ -286,7 +286,7 @@ const migratePromptTemplate = async (rootDir, { rel, sampleRel, oldHash, newHash});if (sample != null) {await writeFile(path, sample);- console.log(`📝 ${rel}: replaced pre-rename shipped default with current data.sample bundle`);+ console.log(`📝 ${rel}: replaced pre-rename shipped default with current data.reference bundle`);return;}const next = RENAME_SUBSTITUTIONS.reduce((acc, [from, to]) => acc.replace(from, to), raw);diff --git a/scripts/migrations/023-resolve-prompt-episode-anchor.js b/scripts/migrations/023-resolve-prompt-episode-anchor.jsindex 66be027e92..ae9bf08580 100644--- a/scripts/migrations/023-resolve-prompt-episode-anchor.js+++ b/scripts/migrations/023-resolve-prompt-episode-anchor.js@@ -33,7 +33,7 @@ export const ACCEPTED_OLD_MD5 = {],};-// New shipped hash — what data.sample carries post-migration.+// New shipped hash — what data.reference carries post-migration.export const NEW_SHIPPED_MD5 = {'pipeline-arc-resolve.md': '5b340885c6e8f8afc63424d6b5bc7eb7',};@@ -44,7 +44,7 @@ const { applyMigration, up } = makePromptReplaceMigration({label: 'resolve-prompt',customizedHint: (filename) =>` To pick up the new "anchor in per-episode synopses" guidance manually, diff:\n` +- ` data.sample/prompts/stages/${filename}\n` ++ ` data.reference/prompts/stages/${filename}\n` +` against your current:\n` +` data/prompts/stages/${filename}\n` +` and add the new bullet 1 in the "How to resolve" list.`,@@ -52,7 +52,7 @@ const { applyMigration, up } = makePromptReplaceMigration({`⚠️ ${count} resolve prompt could not be auto-updated because it was customized.\n` +` The auto-resolve pass will keep working but won't be explicitly told to anchor\n` +` volume-synopsis edits in the per-episode \`synopsis\` entries from\n` +- ` \`seasonsTreeJson.episodes[].synopsis\`. See data.sample/prompts/stages/.`,+ ` \`seasonsTreeJson.episodes[].synopsis\`. See data.reference/prompts/stages/.`,});export { applyMigration };diff --git a/scripts/migrations/025-idea-stage-character-detail.js b/scripts/migrations/025-idea-stage-character-detail.jsindex 774ea252cf..5a401ad73d 100644--- a/scripts/migrations/025-idea-stage-character-detail.js+++ b/scripts/migrations/025-idea-stage-character-detail.js@@ -32,7 +32,7 @@ export const ACCEPTED_OLD_MD5 = {],};-// New shipped hash — what data.sample carries post-migration.+// New shipped hash — what data.reference carries post-migration.export const NEW_SHIPPED_MD5 = {'pipeline-idea-expansion.md': '1f3c5d077a5ef9a4b610335d5e3edd9c',};@@ -44,7 +44,7 @@ const { applyMigration, up } = makePromptReplaceMigration({customizedHint: (filename) =>` To pick up the new {{#series.characters}} role/physicalDescription/personality/background\n` +` plumbing manually, diff:\n` +- ` data.sample/prompts/stages/${filename}\n` ++ ` data.reference/prompts/stages/${filename}\n` +` against your current:\n` +` data/prompts/stages/${filename}\n` +` and replace the character iteration block with the new shape.`,@@ -52,7 +52,7 @@ const { applyMigration, up } = makePromptReplaceMigration({`⚠️ ${count} idea-stage prompt could not be auto-updated because it was customized.\n` +` The idea / beat-sheet expansion will keep working but won't see character\n` +` \`role\`, \`physicalDescription\`, \`personality\`, or \`background\` from the bible.\n` +- ` See data.sample/prompts/stages/pipeline-idea-expansion.md.`,+ ` See data.reference/prompts/stages/pipeline-idea-expansion.md.`,});export { applyMigration };diff --git a/scripts/migrations/027-text-stage-prompts-entities-summary.js b/scripts/migrations/027-text-stage-prompts-entities-summary.jsindex a25857161d..9ad2d34496 100644--- a/scripts/migrations/027-text-stage-prompts-entities-summary.js+++ b/scripts/migrations/027-text-stage-prompts-entities-summary.js@@ -68,7 +68,7 @@ const { applyMigration, up } = makePromptReplaceMigration({label: 'text-stage entities-summary + speechPattern',customizedHint: (filename) =>` To pick up {{worldEntitiesSummary}} + {{speechPattern}} / {{speechAccent}} manually, diff:\n` +- ` data.sample/prompts/stages/${filename}\n` ++ ` data.reference/prompts/stages/${filename}\n` +` against your current:\n` +` data/prompts/stages/${filename}\n` +` and merge the new blocks in the same position as in the sample template.`,@@ -76,7 +76,7 @@ const { applyMigration, up } = makePromptReplaceMigration({`⚠️ ${count} prompt(s) could not be auto-updated because they were customized.\n` +` The {{worldEntitiesSummary}} block + {{speechPattern}} / {{speechAccent}} renderers\n` +` will not appear in those prompts until the files are merged manually. See\n` +- ` data.sample/prompts/stages/.`,+ ` data.reference/prompts/stages/.`,});export { applyMigration };diff --git a/scripts/migrations/027-text-stage-prompts-entities-summary.test.js b/scripts/migrations/027-text-stage-prompts-entities-summary.test.jsindex 18701656f8..1e662e3c5d 100644--- a/scripts/migrations/027-text-stage-prompts-entities-summary.test.js+++ b/scripts/migrations/027-text-stage-prompts-entities-summary.test.js@@ -3,7 +3,7 @@* and pipe {{speechAccent}} / {{speechPattern}} through character renders.** Mirrors migration 019's test scaffolding — temp-dir fixtures, the same- * drift-catch assertion against the live data.sample bodies, and an+ * drift-catch assertion against the live data.reference bodies, and an* OLD→NEW upgrade branch driven by synthetic hash tables so the test* doesn't depend on git history.*@@ -25,7 +25,7 @@ const md5 = (str) => createHash('md5')const repoRoot = join(import.meta.dirname || dirname(fileURLToPath(import.meta.url)), '..', '..');const sampleBody = (filename) =>- readFileSync(join(repoRoot, 'data.sample', 'prompts', 'stages', filename), 'utf-8');+ readFileSync(join(repoRoot, 'data.reference', 'prompts', 'stages', filename), 'utf-8');const customizedBody = (filename) => `# CUSTOMIZED ${filename}\n\nuser-modified content not matching any shipped hash\n`;@@ -37,7 +37,7 @@ describe('migration 027 — text-stage prompts entities-summary + speechPattern'beforeEach(() => {rootDir = mkdtempSync(join(tmpdir(), 'migration-027-'));stagesDir = join(rootDir, 'data', 'prompts', 'stages');- sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');+ sampleDir = join(rootDir, 'data.reference', 'prompts', 'stages');mkdirSync(stagesDir, { recursive: true });mkdirSync(sampleDir, { recursive: true });for (const filename of Object.keys(NEW_SHIPPED_MD5)) {@@ -75,7 +75,7 @@ describe('migration 027 — text-stage prompts entities-summary + speechPattern'}});- it('NEW_SHIPPED_MD5 matches the live data.sample bodies (drift catch)', () => {+ it('NEW_SHIPPED_MD5 matches the live data.reference bodies (drift catch)', () => {for (const filename of Object.keys(NEW_SHIPPED_MD5)) {const liveHash = md5(sampleBody(filename));expect(liveHash).toBe(NEW_SHIPPED_MD5[filename]);diff --git a/scripts/migrations/032-claude-default-opus-4-7.js b/scripts/migrations/032-claude-default-opus-4-7.jsindex 3315c7d98a..c993352db5 100644--- a/scripts/migrations/032-claude-default-opus-4-7.js+++ b/scripts/migrations/032-claude-default-opus-4-7.js@@ -2,7 +2,7 @@* Update Claude CLI/TUI provider defaults to the current model lineup.** Two prior seeded shapes existed for `claude-code` / `claude-code-tui`:- * 1. The data.sample 4-item dated list — `claude-haiku-4-5-20251001`,+ * 1. The data.reference 4-item dated list — `claude-haiku-4-5-20251001`,* `claude-sonnet-4-5-20250929`, `claude-opus-4-5-20251101`,* `claude-opus-4-6` (defaultModel: `claude-opus-4-6`).* 2. The scaffold-route 3-item dated list — `claude-haiku-4-5-20251001`,@@ -22,7 +22,7 @@** Tier-pointer policy when a rewrite does happen:* - `defaultModel`: if it's one of the previously *seeded* defaults- * (`claude-opus-4-6` from data.sample, `claude-sonnet-4-5-20250929`+ * (`claude-opus-4-6` from data.reference, `claude-sonnet-4-5-20250929`* from the scaffold route), upgrade to the policy default* `claude-opus-4-7`. If it's some *other* retired id (a user pinned* haiku-/opus-4-5-dated as default), fall back to the per-model@@ -89,7 +89,7 @@ const RETIRED_TO_SUCCESSOR = {};// `defaultModel` follows a different policy than the tier pointers: when the-// existing default is one of the previously *seeded* defaults (data.sample's+// existing default is one of the previously *seeded* defaults (data.reference's// `claude-opus-4-6` or scaffold's `claude-sonnet-4-5-20250929`), upgrade to// the policy default `claude-opus-4-7` — this is the migration's stated// goal. For any *other* retired-id default (a user who actively pinned@@ -166,7 +166,7 @@ export default {throw err;});if (raw == null) {- console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install seeds from data.sample with the new defaults)`);+ console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install seeds from data.reference with the new defaults)`);return;}diff --git a/scripts/migrations/032-claude-default-opus-4-7.test.js b/scripts/migrations/032-claude-default-opus-4-7.test.jsindex 67cca500c0..c3132af8d2 100644--- a/scripts/migrations/032-claude-default-opus-4-7.test.js+++ b/scripts/migrations/032-claude-default-opus-4-7.test.js@@ -68,7 +68,7 @@ describe('migration 032 — Claude CLI/TUI default to opus-4-7', () => {rmSync(rootDir, { recursive: true, force: true });});- it('upgrades the data.sample 4-item legacy shape to the new trio + opus-4-7 default', async () => {+ it('upgrades the data.reference 4-item legacy shape to the new trio + opus-4-7 default', async () => {writeJson(providersPath, { providers: { 'claude-code': dataSampleLegacy() } });await migration.up({ rootDir });diff --git a/scripts/migrations/034-split-universe-builder-to-per-uuid.js b/scripts/migrations/034-split-universe-builder-to-per-uuid.jsnew file mode 100644index 0000000000..fa9210855a--- /dev/null+++ b/scripts/migrations/034-split-universe-builder-to-per-uuid.js@@ -0,0 +1,203 @@+/**+ * Split the monolithic `data/universe-builder.json` into per-record files+ * under `data/universes/{id}/index.json`, with a type-level+ * `data/universes/index.json` stamping `schemaVersion: 5`.+ *+ * Why:+ * The legacy single-file shape (`{ universes: [...], runs: [...] }`)+ * serializes every write across every universe — at 30+ universes and+ * ~50KB per record, edits to one universe forced a 1.4MB rewrite under+ * a single-tail queue. The new layout reads/writes one record at a time+ * and per-id writes don't serialize against each other.+ *+ * What changes on disk:+ *+ * before: after:+ * data/ data/+ * └── universe-builder.json ├── universes/+ * │ ├── index.json (schemaVersion: 5, runs[])+ * │ ├── <uuid-1>/+ * │ │ └── index.json (the universe record)+ * │ └── <uuid-2>/+ * │ └── index.json+ * └── universe-builder.json.bak-034+ *+ * The legacy file is RENAMED, not deleted — recovery path stays open if a+ * downstream issue surfaces after the migration runs. Future cleanup (or a+ * later migration) can remove `.bak-034` once the new shape is fully+ * validated in production.+ *+ * Idempotency: a re-run after partial completion (some records split, some+ * not) safely finishes the split. A re-run after full completion is a no-op.+ *+ * Per-record schema:+ * Each record carries `schemaVersion` (the record-shape version, currently+ * 4) — distinct from the type-level `schemaVersion` (currently 5, this+ * migration's bump). See `server/lib/collectionStore.js` header for the+ * distinction between layout-version and record-shape-version.+ */++import { readFile, writeFile, rename, mkdir, stat, readdir } from 'fs/promises';+import { join } from 'path';++const TYPE_DIR_NAME = 'universes';+const LEGACY_FILENAME = 'universe-builder.json';+const BACKUP_SUFFIX = '.bak-034';+const TYPE_SCHEMA_VERSION = 5;+const TYPE_LABEL = 'universes';++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 `UNIVERSE_ID_RE` in server/services/universeBuilder.js so an oddly-id'd+// record (8–80 alphanumerics + hyphens) round-trips through the split without+// being misclassified as a stray directory entry.+const VALID_UNIVERSE_ID = /^[A-Za-z0-9-]{8,80}$/;++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 v5 → 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 034: universes 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: { runs: [] },+ });+ console.log(`📦 migration 034: fresh install — stamped data/universes/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 034: ${sourcePath} unreadable — skipping. Resolve manually before next boot.`);+ return { ok: false, reason: 'unreadable' };+ }++ const universes = Array.isArray(doc.universes) ? doc.universes : [];+ const runs = Array.isArray(doc.runs) ? doc.runs : [];++ // 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 (e.g.+ // user-left `.bak` files, editor swap files) without statting INTO them —+ // `stat('foo.bak/index.json')` would raise ENOTDIR which our fileExists+ // helper rethrows, crashing 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 universes) {+ if (!record || typeof record !== 'object') {+ invalid += 1;+ continue;+ }+ const id = typeof record.id === 'string' ? record.id : null;+ if (!id || !VALID_UNIVERSE_ID.test(id)) {+ invalid += 1;+ console.warn(`⚠️ migration 034: skipping record with invalid id "${id}"`);+ 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. Cross-record `runs[]` moves into+ // `config.runs` so it travels with the type-level index.+ await writeJson(typeIndexPath, {+ schemaVersion: TYPE_SCHEMA_VERSION,+ type: TYPE_LABEL,+ updatedAt: new Date().toISOString(),+ config: { runs },+ });++ // 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 universe-builder.json.bak-034 universe-builder.json`.+ if (legacyExists) {+ await rename(legacyPath, backupPath);+ }++ console.log(+ `📦 migration 034: split ${written} universe(s) into data/universes/<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/034-split-universe-builder-to-per-uuid.test.js b/scripts/migrations/034-split-universe-builder-to-per-uuid.test.jsnew file mode 100644index 0000000000..7fbed45629--- /dev/null+++ b/scripts/migrations/034-split-universe-builder-to-per-uuid.test.js@@ -0,0 +1,177 @@+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 './034-split-universe-builder-to-per-uuid.js';++const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++const validUniverse = (id, overrides = {}) => ({+ id,+ name: `Universe ${id}`,+ starterPrompt: 'test',+ categories: {},+ schemaVersion: 4,+ createdAt: '2026-05-23T00:00:00.000Z',+ updatedAt: '2026-05-23T00:00:00.000Z',+ ...overrides,+});++describe('migration 034 — split universe-builder.json to per-UUID files', () => {+ let rootDir;+ let dataDir;+ let legacyPath;+ let typeDir;+ let typeIndexPath;+ let backupPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-034-'));+ dataDir = join(rootDir, 'data');+ mkdirSync(dataDir, { recursive: true });+ legacyPath = join(dataDir, 'universe-builder.json');+ typeDir = join(dataDir, 'universes');+ typeIndexPath = join(typeDir, 'index.json');+ backupPath = legacyPath + '.bak-034';+ });++ 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(5);+ expect(idx.type).toBe('universes');+ expect(idx.config.runs).toEqual([]);+ expect(existsSync(legacyPath)).toBe(false);+ expect(existsSync(backupPath)).toBe(false);+ });++ it('full split: writes one file per universe and a type index', async () => {+ writeJson(legacyPath, {+ universes: [+ validUniverse('aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa', { name: 'Alpha' }),+ validUniverse('bbbbbbbb-2222-2222-2222-bbbbbbbbbbbb', { name: 'Beta' }),+ validUniverse('cccccccc-3333-3333-3333-cccccccccccc', { name: 'Gamma' }),+ ],+ runs: [+ { id: 'run-1', universeId: 'aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa', collectionId: null, jobIds: [], promptCount: 0, createdAt: '2026-05-23T00:00:00.000Z' },+ ],+ });++ 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(5);+ expect(idx.config.runs).toHaveLength(1);+ expect(idx.config.runs[0].id).toBe('run-1');++ for (const id of [+ 'aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa',+ 'bbbbbbbb-2222-2222-2222-bbbbbbbbbbbb',+ 'cccccccc-3333-3333-3333-cccccccccccc',+ ]) {+ const recordPath = join(typeDir, id, 'index.json');+ expect(existsSync(recordPath)).toBe(true);+ const rec = readJson(recordPath);+ expect(rec.id).toBe(id);+ expect(rec.schemaVersion).toBe(4); // record-shape version is preserved, NOT the type-level version+ }++ expect(existsSync(legacyPath)).toBe(false);+ expect(existsSync(backupPath)).toBe(true);+ const backup = readJson(backupPath);+ expect(backup.universes).toHaveLength(3);+ });++ it('idempotent: second run is a no-op once type index is at v5', async () => {+ writeJson(legacyPath, {+ universes: [validUniverse('aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa')],+ runs: [],+ });+ await migration.up({ rootDir });+ const result = await migration.up({ rootDir });+ expect(result).toEqual({ ok: true, reason: 'already-applied' });+ // Backup still exists from the first run; not touched.+ expect(existsSync(backupPath)).toBe(true);+ });++ it('partial recovery: some records already split, finishes the rest', async () => {+ const ids = [+ 'aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa',+ 'bbbbbbbb-2222-2222-2222-bbbbbbbbbbbb',+ 'cccccccc-3333-3333-3333-cccccccccccc',+ ];+ writeJson(legacyPath, {+ universes: ids.map((id, i) => validUniverse(id, { name: `Universe-${i}-original` })),+ runs: [],+ });+ // Pre-split the FIRST record to simulate a crash mid-split. The pre-split+ // copy carries a name DIFFERENT from the legacy snapshot — the migration+ // must NOT clobber it (the per-record file is the freshest truth).+ mkdirSync(join(typeDir, ids[0]), { recursive: true });+ writeJson(join(typeDir, ids[0], 'index.json'), validUniverse(ids[0], { name: 'Universe-0-NEWER' }));++ const result = await migration.up({ rootDir });+ expect(result).toEqual({ ok: true, reason: 'split', written: 2, skipped: 1, invalid: 0 });++ const preserved = readJson(join(typeDir, ids[0], 'index.json'));+ expect(preserved.name).toBe('Universe-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, {+ universes: [+ validUniverse('aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa'),+ { id: 'x', name: 'too-short' }, // id < 8 chars+ { id: '../escape-attempt-with-enough-length', name: 'evil' },// fails regex+ null, // not an object+ ],+ runs: [],+ });+ 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, 'aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa', 'index.json'))).toBe(true);+ });++ it('reports unreadable when the legacy file is corrupted', async () => {+ writeFileSync(legacyPath, 'not json');+ const result = await migration.up({ rootDir });+ // JSON.parse throws — the migration catches outside our code? Actually+ // readJson throws on parse error. Let's check the behavior matches.+ // (If parse throws, the migration propagates — test that explicitly.)+ expect(result.ok).toBe(false);+ });++ it('recovers from the .bak-034 file if the legacy was already renamed', async () => {+ // Simulate a crash AFTER rename but BEFORE the next boot ran migration —+ // the type index isn't written yet, so gate 1 doesn't trip; gate 2 sees+ // backup but no legacy, falls into the recovery branch.+ writeJson(backupPath, {+ universes: [validUniverse('aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa', { name: 'Recovered' })],+ runs: [],+ });+ const result = await migration.up({ rootDir });+ expect(result.ok).toBe(true);+ expect(result.written).toBe(1);+ const rec = readJson(join(typeDir, 'aaaaaaaa-1111-1111-1111-aaaaaaaaaaaa', 'index.json'));+ expect(rec.name).toBe('Recovered');+ // Backup still in place — recovery path doesn't move it.+ expect(existsSync(backupPath)).toBe(true);+ });+});diff --git a/scripts/migrations/_lib.js b/scripts/migrations/_lib.jsindex c663e0219c..c7d134b240 100644--- a/scripts/migrations/_lib.js+++ b/scripts/migrations/_lib.js@@ -31,7 +31,7 @@ export const md5 = (str) => {** - `createIfMissing` — when the data-side file is absent, copy the sample* file in. Used by migration 005, whose `pipeline-arc-resolve.md` may not- * have shipped in `data.sample/` yet at the time it was authored.+ * have shipped in `data.reference/` yet at the time it was authored.** - `retireOnSampleMissing` — when the sample-side file is absent (the prompt* was renamed or retired by a later commit), treat it as a soft delete:@@ -51,7 +51,7 @@ export async function applyPromptReplaceMigration({retireOnSampleMissing = false,}) {const stagesDir = join(rootDir, 'data', 'prompts', 'stages');- const sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');+ const sampleDir = join(rootDir, 'data.reference', 'prompts', 'stages');let updated = 0;let alreadyCurrent = 0;@@ -105,7 +105,7 @@ export async function applyPromptReplaceMigration({} else {console.warn(`⚠️ ${label} ${filename} was renamed/retired upstream but your local copy has been customized.\n` +- ` Check data.sample/prompts/stages/ for the replacement file and merge any custom edits manually.`,+ ` Check data.reference/prompts/stages/ for the replacement file and merge any custom edits manually.`,);skipped++;}diff --git a/scripts/migrations/_lib.test.js b/scripts/migrations/_lib.test.jsindex 6ec645d3f2..df50e8c544 100644--- a/scripts/migrations/_lib.test.js+++ b/scripts/migrations/_lib.test.js@@ -35,7 +35,7 @@ describe('applyPromptReplaceMigration opt-ins', () => {beforeEach(() => {rootDir = mkdtempSync(join(tmpdir(), 'migration-lib-'));stagesDir = join(rootDir, 'data', 'prompts', 'stages');- sampleDir = join(rootDir, 'data.sample', 'prompts', 'stages');+ sampleDir = join(rootDir, 'data.reference', 'prompts', 'stages');mkdirSync(stagesDir, { recursive: true });mkdirSync(sampleDir, { recursive: true });});diff --git a/scripts/migrations/_testHelpers.js b/scripts/migrations/_testHelpers.jsindex 327bdd2792..834eb78c60 100644--- a/scripts/migrations/_testHelpers.js+++ b/scripts/migrations/_testHelpers.js@@ -22,7 +22,7 @@ const __dirname = dirname(fileURLToPath(import.meta.url));export const repoRoot = join(__dirname, '..', '..');export const sampleBody = (filename, subdir = 'stages') =>- readFileSync(join(repoRoot, 'data.sample', 'prompts', subdir, filename), 'utf-8');+ readFileSync(join(repoRoot, 'data.reference', 'prompts', subdir, filename), 'utf-8');/** Synthetic body that won't match any shipped hash. */export const customizedBody = (filename) =>@@ -53,7 +53,7 @@ export function runPromptMigrationTests({beforeEach(() => {rootDir = mkdtempSync(join(tmpdir(), prefix));stagesDir = join(rootDir, 'data', 'prompts', subdir);- const sampleDir = join(rootDir, 'data.sample', 'prompts', subdir);+ const sampleDir = join(rootDir, 'data.reference', 'prompts', subdir);mkdirSync(stagesDir, { recursive: true });mkdirSync(sampleDir, { recursive: true });for (const filename of Object.keys(NEW_SHIPPED_MD5)) {@@ -95,7 +95,7 @@ export function runPromptMigrationTests({});});- it('NEW_SHIPPED_MD5 matches the live data.sample body (drift catch)', () => {+ it('NEW_SHIPPED_MD5 matches the live data.reference body (drift catch)', () => {// Without this assertion, a future template edit that forgets to bump// NEW_SHIPPED_MD5 would make the migration classify the sample-shaped// file as "customized" and silently skip the upgrade.diff --git a/scripts/setup-data.js b/scripts/setup-data.jsindex 46c3cfb1cc..b6b32459ef 100644--- a/scripts/setup-data.js+++ b/scripts/setup-data.js@@ -8,7 +8,7 @@ import { md5 } from './migrations/_lib.js';const __dirname = dirname(fileURLToPath(import.meta.url));const rootDir = join(__dirname, '..');const dataDir = join(rootDir, 'data');-const sampleDir = join(rootDir, 'data.sample');+const referenceDir = join(rootDir, 'data.reference');console.log('📁 Setting up data directory...');@@ -31,9 +31,9 @@ if (existsSync(legacyMigrationsDir) && readdirSync(legacyMigrationsDir).length =}if (!existsSync(dataDir)) {- console.log('📁 Creating data directory from data.sample...');+ console.log('📁 Creating data directory from data.reference...');mkdirSync(dataDir, { recursive: true });- cpSync(sampleDir, dataDir, { recursive: true });+ cpSync(referenceDir, dataDir, { recursive: true });// Replace __PORTOS_ROOT__ placeholder with actual install path in apps.jsonconst appsFile = join(dataDir, 'apps.json');@@ -68,15 +68,15 @@ if (!existsSync(dataDir)) {}};- ensureSampleContent(sampleDir, dataDir);+ ensureSampleContent(referenceDir, dataDir);console.log('✅ Data directory already exists, ensured subdirectories and files');}-// Merge new top-level entries from data.sample's structured JSON files into+// Merge new top-level entries from data.reference's structured JSON files into// the user's existing copies, leaving customized entries untouched. Without// this, only file-level "missing → copy" propagation runs above, so a new-// prompt stage or shared variable added to data.sample/prompts/ never+// prompt stage or shared variable added to data.reference/prompts/ never// reaches an existing install whose stage-config.json or variables.json// already exists. Each merge target points at one top-level dict-shaped key// (`stages` for stage-config.json, `variables` for variables.json) and the@@ -90,7 +90,7 @@ const JSON_MERGE_TARGETS = [];const mergeJsonStarter = (relPath, mergeKey) => {- const samplePath = join(sampleDir, relPath);+ const samplePath = join(referenceDir, relPath);const dataPath = join(dataDir, relPath);if (!existsSync(samplePath) || !existsSync(dataPath)) return;let sample, data;@@ -123,7 +123,7 @@ for (const { relPath, mergeKey } of JSON_MERGE_TARGETS) {mergeJsonStarter(relPath, mergeKey);}-// Drift detection — warn when a data.sample/prompts/stages/*.md differs from+// Drift detection — warn when a data.reference/prompts/stages/*.md differs from// the installed data/prompts/stages/*.md copy. Only fires on existing installs// (fresh installs already got a full copy above). Prompt templates drift when// a PortOS update adds new template variables (e.g. {{lengthTargets.*}}) that@@ -225,7 +225,7 @@ const SHIPPED_PARTIAL_FILES = Object.keys(SHIPPED_PARTIAL_OLD_MD5);// customized (hash matches neither old nor new). Used twice — once for// stage prompts, once for partial fragments.const collectDrift = ({ sampleSubdir, dataSubdir, files, oldMap, newMap }) => {- const sampleSubpath = join(sampleDir, ...sampleSubdir);+ const sampleSubpath = join(referenceDir, ...sampleSubdir);const dataSubpath = join(dataDir, ...dataSubdir);if (!existsSync(sampleSubpath) || !existsSync(dataSubpath)) {return { autoUpdatable: [], customized: [] };@@ -268,8 +268,8 @@ const autoUpdatable = [...partialDrift.autoUpdatable.map((f) => ({ file: f, relDir: 'data/prompts/_partials' })),];const customized = [- ...stageDrift.customized.map((f) => ({ file: f, relDir: 'data/prompts/stages', sampleDir: 'data.sample/prompts/stages' })),- ...partialDrift.customized.map((f) => ({ file: f, relDir: 'data/prompts/_partials', sampleDir: 'data.sample/prompts/_partials' })),+ ...stageDrift.customized.map((f) => ({ file: f, relDir: 'data/prompts/stages', referenceDir: 'data.reference/prompts/stages' })),+ ...partialDrift.customized.map((f) => ({ file: f, relDir: 'data/prompts/_partials', referenceDir: 'data.reference/prompts/_partials' })),];if (autoUpdatable.length > 0) {@@ -283,7 +283,7 @@ if (customized.length > 0) {console.warn(`\n⚠️ ${customized.length} pipeline prompt(s) are customized and cannot be auto-updated.\n` +` Manually merge the new template variables into each file:\n` +- customized.map(({ file, relDir, sampleDir: sd }) =>+ customized.map(({ file, relDir, referenceDir: sd }) =>` • ${relDir}/${file}\n` +` Compare with: ${sd}/${file}`,).join('\n') + '\n',diff --git a/server/index.js b/server/index.jsindex 26ceaf9583..09ac599a82 100644--- a/server/index.js+++ b/server/index.js@@ -139,6 +139,8 @@ import { initBridge as initBrainMemoryBridge } from './services/brainMemoryBridgimport { initDrillCache } from './services/meatspacePostDrillCache.js';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 { createPortOSProviderRoutes } from './routes/providers.js';import { createPortOSRunsRoutes } from './routes/runs.js';import { createPortOSPromptsRoutes } from './routes/prompts.js';@@ -174,7 +176,7 @@ initSocket(io);// Build absolute paths - use centralized PATHS for data, __dirname for non-data pathsconst DATA_DIR = PATHS.data;-const DATA_SAMPLE_DIR = join(__dirname, '..', 'data.sample');+const DATA_REFERENCE_DIR = join(__dirname, '..', 'data.reference');// Apply pending data migrations BEFORE the AI toolkit reads stage-config.json// and providers.json. Without this, a plain pull-and-restart (no update.sh)@@ -188,6 +190,16 @@ await runMigrations({ rootDir: join(__dirname, '..') }).catch(err => {console.error(`❌ Migration run failed at startup: ${err?.stack ?? err}`);});+// Verify every registered collection's on-disk type-level schemaVersion+// matches what the code expects. Mismatches mean a migration didn't run (or+// the user rolled the code back below a forward-only migration) — log loudly+// 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 => {+ console.error(`❌ Collection version check failed at startup: ${err?.stack ?? err}`);+});+// Lifecycle hooks shared between AI Toolkit and PortOS runner shimconst aiToolkitHooks = {onRunCreated: (metadata) => {@@ -232,7 +244,7 @@ const aiToolkit = createAIToolkit({runsDir: 'runs',promptsDir: 'prompts',screenshotsDir: join(DATA_DIR, 'screenshots'),- sampleProvidersFile: join(DATA_SAMPLE_DIR, 'providers.json'),+ sampleProvidersFile: join(DATA_REFERENCE_DIR, 'providers.json'),io,asyncHandler,hooks: aiToolkitHooksdiff --git a/server/lib/README.md b/server/lib/README.mdindex 60f9a801ee..929336625f 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -80,6 +80,8 @@ 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. |+| `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. || `imageClean.js` | `cleanImageBuffer` (sharp-based denoise + C2PA strip) + `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer`. |diff --git a/server/lib/collectionStore.js b/server/lib/collectionStore.jsnew file mode 100644index 0000000000..7d75856530--- /dev/null+++ b/server/lib/collectionStore.js@@ -0,0 +1,374 @@+/**+ * Collection Store — per-type, per-record JSON storage with explicit+ * `schemaVersion` stamping.+ *+ * Layout on disk:+ *+ * {dir}/+ * ├── index.json // { schemaVersion, type, updatedAt, config: {} }+ * ├── <id-1>/+ * │ └── index.json // the record itself+ * └── <id-2>/+ * └── index.json+ *+ * Replaces the legacy "one big JSON file per type" pattern (where every write+ * rewrites the whole file and every load parses every record) once a+ * collection has outgrown it. See `data/runs/` for the proven prior-art shape+ * this generalizes.+ *+ * Two versioning concerns coexist:+ * - The TYPE-LEVEL `schemaVersion` (this file): describes the on-disk+ * storage layout. Bumped by a migration that changes layout (e.g. a split+ * from a monolithic JSON to per-record dirs).+ * - The RECORD-LEVEL `schemaVersion` (carried inside each record by some+ * services, e.g. universeBuilder): describes the shape of one record's+ * fields. Bumped by in-memory sanitizers when fields move/rename.+ *+ * These are distinct: a per-record sanitizer can mature without ever bumping+ * the type-level version, and a layout change can stamp a new type-level+ * version while record shape stays at v4.+ *+ * Concurrency model:+ * - `queueRecordWrite(id, fn)` tail-chains per-id, so two concurrent+ * read-modify-write cycles on the SAME record serialize, but writes to+ * DIFFERENT records run in parallel. This is the scalability win over+ * the single-file write queue.+ * - `queueTypeIndexWrite(fn)` single-tail-chains writes to the type-level+ * `index.json` so cross-record state (e.g. a shared `runs[]` log) doesn't+ * race with itself.+ * - `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.+ */++import { join } from 'path';+import { readdir, lstat, rm } from 'fs/promises';+import { atomicWrite, readJSONFile, ensureDir } from './fileUtils.js';++const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);++/**+ * Create a per-type collection store.+ *+ * @param {object} opts+ * @param {string} opts.dir+ * Absolute path to the type's root directory, e.g. `${PATHS.data}/universes`.+ * @param {string} opts.type+ * Stable type label (e.g. `'universes'`). Persisted in the type-level index;+ * used in error/log messages so a misregistered store is obvious.+ * @param {number} opts.schemaVersion+ * The layout version the code currently expects. `verifySchemaVersion()`+ * asserts the on-disk type index matches this.+ * @param {(record: any) => any} [opts.sanitizeRecord]+ * Optional record-level normalizer. Called on every `loadOne` result. Return+ * `null` to treat the on-disk record as invalid (loadOne returns `null`).+ * @param {object} [opts.defaultTypeIndexConfig]+ * Initial value for the `config` slot of a freshly-minted type index.+ * Defaults to `{}`.+ * @param {RegExp} [opts.idPattern]+ * Allowlist for record-directory names. Defaults to a permissive pattern+ * (`/^[A-Za-z0-9_-]{1,128}$/`) — services with stricter id rules should pass+ * their own (e.g. UUID-only) so `listIds()` doesn't surface stray files.+ */+export function createCollectionStore({+ dir,+ type,+ schemaVersion,+ sanitizeRecord = null,+ defaultTypeIndexConfig = {},+ idPattern = /^[A-Za-z0-9_-]{1,128}$/,+} = {}) {+ if (typeof dir !== 'string' || !dir) {+ throw new Error('createCollectionStore: `dir` is required');+ }+ if (typeof type !== 'string' || !type) {+ throw new Error('createCollectionStore: `type` is required');+ }+ if (!Number.isInteger(schemaVersion) || schemaVersion < 1) {+ throw new Error('createCollectionStore: `schemaVersion` must be a positive integer');+ }++ const typeIndexPath = () => join(dir, 'index.json');+ const recordDir = (id) => join(dir, id);+ const recordPath = (id) => join(dir, id, 'index.json');++ const isValidId = (id) => typeof id === 'string' && idPattern.test(id);++ // Per-record write queue. Tail-chained per `id` so two writes against the+ // same record serialize while writes against different records proceed in+ // parallel. Mirrors `createFileWriteQueue` but keyed by id so the queue+ // doesn't collapse to a single tail across the whole type.+ //+ // Map entries are pruned in `finally` once the chain settles to keep the+ // map size bounded — see the `createFileWriteQueue` pattern for the same+ // discipline at the single-tail level.+ const recordTails = new Map();+ function queueRecordWrite(id, fn) {+ if (!isValidId(id)) {+ throw new Error(`collectionStore[${type}]: invalid record id "${id}" — must match ${idPattern}`);+ }+ const prev = recordTails.get(id) || Promise.resolve();+ const next = prev.then(fn, fn);+ const silenced = next.catch(() => {});+ recordTails.set(id, silenced);+ silenced.finally(() => {+ if (recordTails.get(id) === silenced) recordTails.delete(id);+ });+ return next;+ }++ // Type-index single-tail queue. Used by `saveTypeIndex` and by callers that+ // need a write-fence around config-slot updates (`runs[]`, feature flags).+ let typeIndexTail = Promise.resolve();+ function queueTypeIndexWrite(fn) {+ const next = typeIndexTail.then(fn, fn);+ const silenced = next.catch(() => {});+ typeIndexTail = silenced;+ silenced.finally(() => {+ if (typeIndexTail === silenced) typeIndexTail = Promise.resolve();+ });+ return next;+ }++ const buildEmptyTypeIndex = () => ({+ schemaVersion,+ type,+ updatedAt: new Date().toISOString(),+ config: { ...defaultTypeIndexConfig },+ });++ /**+ * Load the type-level index.json. Returns the default shape (with the+ * code-expected `schemaVersion`) when the file is missing — does NOT write+ * to disk. Use `saveTypeIndex` / `saveOne` to persist.+ */+ async function loadTypeIndex() {+ const raw = await readJSONFile(typeIndexPath(), null, { logError: false });+ if (!isPlainObject(raw)) return buildEmptyTypeIndex();+ return {+ schemaVersion: Number.isInteger(raw.schemaVersion) ? raw.schemaVersion : schemaVersion,+ type: typeof raw.type === 'string' && raw.type ? raw.type : type,+ updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : null,+ config: isPlainObject(raw.config) ? raw.config : { ...defaultTypeIndexConfig },+ };+ }++ /**+ * Persist a patch into the type-level index. Top-level fields (schemaVersion,+ * type, config) are shallow-merged; `updatedAt` is restamped automatically.+ * Serialized through `queueTypeIndexWrite` so concurrent callers can't+ * stomp each other's config-slot edits.+ */+ function saveTypeIndex(patch = {}) {+ return queueTypeIndexWrite(async () => {+ await ensureDir(dir);+ const current = await loadTypeIndex();+ const next = {+ schemaVersion: Number.isInteger(patch.schemaVersion) ? patch.schemaVersion : current.schemaVersion,+ type: typeof patch.type === 'string' && patch.type ? patch.type : current.type,+ config: isPlainObject(patch.config) ? { ...current.config, ...patch.config } : current.config,+ updatedAt: new Date().toISOString(),+ };+ await atomicWrite(typeIndexPath(), next);+ return next;+ });+ }++ /**+ * List the on-disk record ids. Source of truth is `readdir(dir)`, not a+ * manifest — keeps `index.json` from drifting against the actual directory+ * contents. Filters out the type-level `index.json`, hidden entries, and+ * anything that doesn't match `idPattern` or isn't a directory.+ */+ async function listIds() {+ const entries = await readdir(dir).catch((err) => {+ if (err?.code === 'ENOENT') return [];+ throw err;+ });+ const candidates = entries.filter((name) =>+ name !== 'index.json'+ && !name.startsWith('.')+ && isValidId(name)+ );+ // lstat (not stat) so symlinks are NOT followed — a symlink whose target+ // is a directory would otherwise be accepted as a valid record dir, with+ // future deleteOne calls rm-rf'ing the symlink AND its target's contents.+ // PortOS is single-user/Tailscale-private so this is defense-in-depth+ // rather than a real attack vector, but it closes the foot-gun where a+ // user symlinks a record dir to external storage. lstat rejects the+ // symlink as non-directory; legitimate same-volume directories pass.+ const stats = await Promise.all(candidates.map((name) =>+ lstat(join(dir, name)).then((s) => (s.isDirectory() ? name : null), () => null)+ ));+ return stats.filter(Boolean);+ }++ /**+ * Load one record by id. Returns `null` when the record dir is missing or+ * the on-disk JSON fails to parse; runs the configured `sanitizeRecord` on+ * the parsed payload (sanitizer can also return `null` to reject).+ */+ async function loadOne(id) {+ if (!isValidId(id)) return null;+ const parsed = await readJSONFile(recordPath(id), null, { allowArray: false, logError: false });+ if (!isPlainObject(parsed)) return null;+ if (typeof sanitizeRecord === 'function') {+ return sanitizeRecord(parsed);+ }+ return parsed;+ }++ /**+ * Load one record WITHOUT running `sanitizeRecord`. Some callers need to+ * compare the raw on-disk shape to the sanitized shape (e.g. detect "this+ * record's nested ids need persisting" — sanitize mints missing ids on the+ * fly but doesn't persist them until the next write). Returns the parsed+ * JSON or `null`; ignores the sanitizer entirely.+ */+ async function loadOneRaw(id) {+ if (!isValidId(id)) return null;+ const parsed = await readJSONFile(recordPath(id), null, { allowArray: false, logError: false });+ return isPlainObject(parsed) ? parsed : null;+ }++ /**+ * Load every record in parallel. O(N) cost — acceptable while record counts+ * are bounded (typical PortOS collections sit in the tens-to-hundreds), but+ * callers iterating very large collections should prefer `listIds` ++ * targeted `loadOne` rather than slurping the whole set.+ */+ async function loadAll() {+ const ids = await listIds();+ const records = await Promise.all(ids.map((id) => loadOne(id)));+ return records.filter((r) => r != null);+ }++ /**+ * Persist a record. Serialized per-id so two concurrent writes against the+ * same id chain on each other; writes against different ids run in parallel.+ * Throws on missing/invalid id; sanitizer is NOT applied on write (callers+ * are expected to pre-sanitize before calling — same convention as the+ * monolithic-state services).+ */+ function saveOne(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`);+ }+ return queueRecordWrite(id, async () => {+ await ensureDir(recordDir(id));+ await atomicWrite(recordPath(id), record);+ return record;+ });+ }++ /**+ * Hard-delete a record. Removes the entire `{dir}/{id}/` subtree so any+ * sidecar files (per-record images, derived assets) go with it. Serialized+ * on the per-record queue so a delete can't race with an in-flight write.+ * Idempotent — missing dir is a no-op.+ */+ function deleteOne(id) {+ if (!isValidId(id)) {+ throw new Error(`collectionStore[${type}]: invalid record id "${id}" — must match ${idPattern}`);+ }+ return queueRecordWrite(id, async () => {+ await rm(recordDir(id), { recursive: true, force: true });+ });+ }++ /**+ * Boot-time verifier — confirms the on-disk type index matches the code's+ * expected `schemaVersion`. Returns a status object rather than throwing so+ * `server/index.js` can log all collections in one pass.+ *+ * ok=true — on-disk version matches code (or type index is missing,+ * which is treated as a fresh install — the next write+ * stamps the correct version).+ * ok=false — on-disk version is older OR newer than code. Older → a+ * pending migration didn't run. Newer → code rolled back+ * below a forward-only migration.+ */+ async function verifySchemaVersion() {+ const raw = await readJSONFile(typeIndexPath(), null, { logError: false });+ if (!isPlainObject(raw) || raw.schemaVersion == null) {+ return {+ ok: true,+ onDisk: null,+ expected: schemaVersion,+ type,+ message: `collection "${type}": no index.json (fresh install) — first write will stamp schemaVersion=${schemaVersion}`,+ };+ }+ const onDisk = Number.isInteger(raw.schemaVersion) ? raw.schemaVersion : null;+ if (onDisk === schemaVersion) {+ return { ok: true, onDisk, expected: schemaVersion, type, message: `collection "${type}" @ v${schemaVersion}` };+ }+ if (onDisk != null && onDisk < schemaVersion) {+ return {+ ok: false,+ onDisk,+ expected: schemaVersion,+ type,+ message: `collection "${type}": on-disk v${onDisk}, code expects v${schemaVersion} — a migration didn't run. Check scripts/migrations/ and run \`npm run migrations\`.`,+ };+ }+ return {+ ok: false,+ onDisk,+ expected: schemaVersion,+ type,+ message: `collection "${type}": on-disk v${onDisk}, code expects v${schemaVersion} — code rolled back below a forward-only migration. Roll forward or restore from a backup.`,+ };+ }++ return {+ // Paths (mostly for tests + migration scripts)+ dir,+ type,+ schemaVersion,+ typeIndexPath,+ recordDir,+ recordPath,+ // Type-level index+ loadTypeIndex,+ saveTypeIndex,+ // Per-record CRUD+ listIds,+ loadOne,+ loadOneRaw,+ loadAll,+ saveOne,+ deleteOne,+ // Concurrency primitives+ queueRecordWrite,+ queueTypeIndexWrite,+ // Boot-time verifier+ verifySchemaVersion,+ };+}++/**+ * Walk a list of stores, run `verifySchemaVersion()` on each, log the result,+ * and return the per-store status array. Used at server boot AFTER migrations+ * run so a missed migration produces a loud, single-line log per collection.+ *+ * PortOS is single-user — a hard exit on mismatch is worse than a noisy log,+ * so this never throws (the caller decides whether to keep booting).+ */+export async function verifyCollectionVersions(stores = []) {+ const statuses = [];+ for (const store of stores) {+ const status = await store.verifySchemaVersion();+ if (status.ok) {+ console.log(`📋 ${status.message}`);+ } else {+ console.error(`❌ ${status.message}`);+ }+ statuses.push(status);+ }+ return statuses;+}diff --git a/server/lib/collectionStore.test.js b/server/lib/collectionStore.test.jsnew file mode 100644index 0000000000..d3d25ac835--- /dev/null+++ b/server/lib/collectionStore.test.js@@ -0,0 +1,321 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mkdtempSync, rmSync, existsSync, writeFileSync, mkdirSync } from 'fs';+import { readFile } from 'fs/promises';+import { join } from 'path';+import { tmpdir } from 'os';+import { createCollectionStore, verifyCollectionVersions } from './collectionStore.js';++// Defer one tick so we can interleave per-id queue assertions.+const tick = () => new Promise((r) => setImmediate(r));++let dir;++beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'collstore-'));+});++afterEach(() => {+ rmSync(dir, { recursive: true, force: true });+});++describe('createCollectionStore — argument validation', () => {+ it('rejects missing dir', () => {+ expect(() => createCollectionStore({ type: 'x', schemaVersion: 1 })).toThrow(/dir/);+ });+ it('rejects missing type', () => {+ expect(() => createCollectionStore({ dir, schemaVersion: 1 })).toThrow(/type/);+ });+ it('rejects non-integer schemaVersion', () => {+ expect(() => createCollectionStore({ dir, type: 'x', schemaVersion: 1.5 })).toThrow(/schemaVersion/);+ expect(() => createCollectionStore({ dir, type: 'x', schemaVersion: 0 })).toThrow(/schemaVersion/);+ });+});++describe('loadTypeIndex / saveTypeIndex', () => {+ it('returns code-expected defaults when index.json is missing', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 3 });+ const idx = await store.loadTypeIndex();+ expect(idx.schemaVersion).toBe(3);+ expect(idx.type).toBe('widgets');+ expect(idx.config).toEqual({});+ // Did NOT write to disk — pure load.+ expect(existsSync(join(dir, 'index.json'))).toBe(false);+ });++ it('uses defaultTypeIndexConfig as starting point', async () => {+ const store = createCollectionStore({+ dir, type: 'widgets', schemaVersion: 1,+ defaultTypeIndexConfig: { feature: 'on' },+ });+ const idx = await store.loadTypeIndex();+ expect(idx.config).toEqual({ feature: 'on' });+ });++ it('saveTypeIndex persists and updatedAt is restamped', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 2 });+ const a = await store.saveTypeIndex({ config: { gated: true } });+ expect(a.config).toEqual({ gated: true });+ expect(a.updatedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/);+ const onDisk = JSON.parse(await readFile(join(dir, 'index.json'), 'utf8'));+ expect(onDisk.schemaVersion).toBe(2);+ expect(onDisk.type).toBe('widgets');+ expect(onDisk.config.gated).toBe(true);+ });++ it('saveTypeIndex shallow-merges config (does not clobber existing keys)', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ await store.saveTypeIndex({ config: { a: 1 } });+ await store.saveTypeIndex({ config: { b: 2 } });+ const idx = await store.loadTypeIndex();+ expect(idx.config).toEqual({ a: 1, b: 2 });+ });++ it('concurrent saveTypeIndex calls serialize through the queue', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ await Promise.all([+ store.saveTypeIndex({ config: { a: 1 } }),+ store.saveTypeIndex({ config: { b: 2 } }),+ store.saveTypeIndex({ config: { c: 3 } }),+ ]);+ const idx = await store.loadTypeIndex();+ expect(idx.config).toEqual({ a: 1, b: 2, c: 3 });+ });+});++describe('saveOne / loadOne / deleteOne', () => {+ it('persists a record under {dir}/{id}/index.json', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ await store.saveOne('alpha', { id: 'alpha', name: 'A' });+ expect(existsSync(join(dir, 'alpha', 'index.json'))).toBe(true);+ const parsed = JSON.parse(await readFile(join(dir, 'alpha', 'index.json'), 'utf8'));+ expect(parsed).toEqual({ id: 'alpha', name: 'A' });+ });++ it('loadOne returns the on-disk record', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ await store.saveOne('alpha', { id: 'alpha', name: 'A' });+ expect(await store.loadOne('alpha')).toEqual({ id: 'alpha', name: 'A' });+ });++ it('loadOne returns null when the record is missing', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ expect(await store.loadOne('does-not-exist')).toBeNull();+ });++ it('loadOne runs sanitizeRecord on the parsed payload', async () => {+ const store = createCollectionStore({+ dir, type: 'widgets', schemaVersion: 1,+ sanitizeRecord: (r) => ({ ...r, sanitized: true }),+ });+ await store.saveOne('alpha', { id: 'alpha', name: 'A' });+ expect(await store.loadOne('alpha')).toEqual({ id: 'alpha', name: 'A', sanitized: true });+ });++ it('sanitizeRecord returning null surfaces as null from loadOne', async () => {+ const store = createCollectionStore({+ dir, type: 'widgets', schemaVersion: 1,+ sanitizeRecord: () => null,+ });+ await store.saveOne('alpha', { id: 'alpha', name: 'A' });+ expect(await store.loadOne('alpha')).toBeNull();+ });++ it('loadOne tolerates corrupted JSON without throwing', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ mkdirSync(join(dir, 'alpha'), { recursive: true });+ writeFileSync(join(dir, 'alpha', 'index.json'), '{not valid json');+ expect(await store.loadOne('alpha')).toBeNull();+ });++ it('saveOne throws synchronously on invalid ids (caller bug, fail fast)', () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ expect(() => store.saveOne('../escape', { id: 'x' })).toThrow(/invalid record id/);+ expect(() => store.saveOne('has/slash', { id: 'x' })).toThrow(/invalid record id/);+ expect(() => store.saveOne('', { id: 'x' })).toThrow(/invalid record id/);+ expect(() => store.saveOne(null, { id: 'x' })).toThrow(/invalid record id/);+ });++ it('saveOne throws synchronously on non-object records', () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ expect(() => store.saveOne('alpha', null)).toThrow(/plain object/);+ expect(() => store.saveOne('alpha', [])).toThrow(/plain object/);+ expect(() => store.saveOne('alpha', 'string')).toThrow(/plain object/);+ });++ it('honors a custom idPattern', async () => {+ const UUID = /^[0-9a-f-]{36}$/;+ const store = createCollectionStore({+ dir, type: 'widgets', schemaVersion: 1, idPattern: UUID,+ });+ expect(() => store.saveOne('not-a-uuid', { id: 'x' })).toThrow(/invalid record id/);+ const goodId = '12345678-1234-1234-1234-123456789012';+ await store.saveOne(goodId, { id: goodId });+ expect(await store.loadOne(goodId)).toEqual({ id: goodId });+ });++ it('deleteOne removes the full {dir}/{id}/ subtree', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ await store.saveOne('alpha', { id: 'alpha' });+ // Drop a sidecar to verify recursive removal.+ writeFileSync(join(dir, 'alpha', 'sidecar.png'), 'fake');+ await store.deleteOne('alpha');+ expect(existsSync(join(dir, 'alpha'))).toBe(false);+ });++ it('deleteOne is idempotent (missing id is a no-op)', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ await expect(store.deleteOne('alpha')).resolves.toBeUndefined();+ });+});++describe('listIds', () => {+ it('returns [] when the directory is missing', async () => {+ const store = createCollectionStore({+ dir: join(dir, 'nope'), type: 'widgets', schemaVersion: 1,+ });+ expect(await store.listIds()).toEqual([]);+ });++ it('returns only record-id directories — skips index.json, hidden, non-dir', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ await store.saveOne('alpha', { id: 'alpha' });+ await store.saveOne('beta', { id: 'beta' });+ await store.saveTypeIndex({});+ writeFileSync(join(dir, '.DS_Store'), '');+ writeFileSync(join(dir, 'loose-file.txt'), 'noise');+ const ids = await store.listIds();+ expect([...ids].sort()).toEqual(['alpha', 'beta']);+ });++ it('rejects entries that fail the idPattern', async () => {+ const store = createCollectionStore({+ dir, type: 'widgets', schemaVersion: 1,+ idPattern: /^[a-z]+$/,+ });+ mkdirSync(join(dir, 'good'), { recursive: true });+ writeFileSync(join(dir, 'good', 'index.json'), JSON.stringify({ id: 'good' }));+ mkdirSync(join(dir, 'BadCase'), { recursive: true });+ writeFileSync(join(dir, 'BadCase', 'index.json'), JSON.stringify({ id: 'BadCase' }));+ expect(await store.listIds()).toEqual(['good']);+ });+});++describe('loadAll', () => {+ it('returns every record', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ await store.saveOne('a', { id: 'a', n: 1 });+ await store.saveOne('b', { id: 'b', n: 2 });+ await store.saveOne('c', { id: 'c', n: 3 });+ const all = await store.loadAll();+ expect(all.map((r) => r.id).sort()).toEqual(['a', 'b', 'c']);+ });++ it('drops records the sanitizer rejects', async () => {+ const store = createCollectionStore({+ dir, type: 'widgets', schemaVersion: 1,+ sanitizeRecord: (r) => r.n > 1 ? r : null,+ });+ await store.saveOne('a', { id: 'a', n: 1 });+ await store.saveOne('b', { id: 'b', n: 2 });+ await store.saveOne('c', { id: 'c', n: 3 });+ const all = await store.loadAll();+ expect(all.map((r) => r.id).sort()).toEqual(['b', 'c']);+ });+});++describe('per-id write queue', () => {+ it('two saves to the same id serialize in submission order', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ const order = [];+ const a = store.queueRecordWrite('alpha', async () => { await tick(); order.push('a'); });+ const b = store.queueRecordWrite('alpha', async () => { order.push('b'); });+ await Promise.all([a, b]);+ expect(order).toEqual(['a', 'b']);+ });++ it('saves to different ids do NOT serialize', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ const order = [];+ // alpha yields; beta should not wait for alpha.+ const a = store.queueRecordWrite('alpha', async () => { await tick(); order.push('alpha-slow'); });+ const b = store.queueRecordWrite('beta', async () => { order.push('beta-fast'); });+ await Promise.all([a, b]);+ expect(order).toEqual(['beta-fast', 'alpha-slow']);+ });++ it('a rejection on one id does not poison subsequent writes to that id', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ const bad = store.queueRecordWrite('alpha', async () => { throw new Error('nope'); });+ await expect(bad).rejects.toThrow('nope');+ // Next write to same id should still go through.+ const good = await store.queueRecordWrite('alpha', () => Promise.resolve('ok'));+ expect(good).toBe('ok');+ });++ it('queueRecordWrite rejects invalid ids', () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 1 });+ expect(() => store.queueRecordWrite('../escape', () => null)).toThrow(/invalid record id/);+ });+});++describe('verifySchemaVersion', () => {+ it('returns ok when on-disk version matches code', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 3 });+ await store.saveTypeIndex({});+ const status = await store.verifySchemaVersion();+ expect(status.ok).toBe(true);+ expect(status.onDisk).toBe(3);+ expect(status.expected).toBe(3);+ });++ it('returns ok (fresh install) when index.json is missing', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 3 });+ const status = await store.verifySchemaVersion();+ expect(status.ok).toBe(true);+ expect(status.onDisk).toBeNull();+ expect(status.message).toMatch(/fresh install/);+ });++ it('reports a missed migration when on-disk version is lower', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 5 });+ writeFileSync(join(dir, 'index.json'), JSON.stringify({ schemaVersion: 4, type: 'widgets', config: {} }));+ const status = await store.verifySchemaVersion();+ expect(status.ok).toBe(false);+ expect(status.onDisk).toBe(4);+ expect(status.expected).toBe(5);+ expect(status.message).toMatch(/migration didn't run/);+ });++ it('reports a rollback when on-disk version is higher', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 2 });+ writeFileSync(join(dir, 'index.json'), JSON.stringify({ schemaVersion: 5, type: 'widgets', config: {} }));+ const status = await store.verifySchemaVersion();+ expect(status.ok).toBe(false);+ expect(status.onDisk).toBe(5);+ expect(status.message).toMatch(/rolled back/);+ });+});++describe('verifyCollectionVersions', () => {+ it('logs success per store and returns per-store statuses', async () => {+ const a = createCollectionStore({ dir: join(dir, 'a'), type: 'a', schemaVersion: 1 });+ const b = createCollectionStore({ dir: join(dir, 'b'), type: 'b', schemaVersion: 2 });+ await a.saveTypeIndex({});+ await b.saveTypeIndex({});+ const spy = vi.spyOn(console, 'log').mockImplementation(() => {});+ const statuses = await verifyCollectionVersions([a, b]);+ spy.mockRestore();+ expect(statuses).toHaveLength(2);+ expect(statuses[0].ok).toBe(true);+ expect(statuses[1].ok).toBe(true);+ });++ it('logs to console.error on mismatch without throwing', async () => {+ const store = createCollectionStore({ dir, type: 'widgets', schemaVersion: 5 });+ writeFileSync(join(dir, 'index.json'), JSON.stringify({ schemaVersion: 4, config: {} }));+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});+ const [status] = await verifyCollectionVersions([store]);+ errSpy.mockRestore();+ expect(status.ok).toBe(false);+ });+});diff --git a/server/lib/comicScriptParser.js b/server/lib/comicScriptParser.jsindex 353af0765c..5986062045 100644--- a/server/lib/comicScriptParser.js+++ b/server/lib/comicScriptParser.js@@ -1,7 +1,7 @@/*** Pure parser for the Marvel/DC-format comic script the pipeline-comic-script- * stage produces (see data.sample/prompts/stages/pipeline-comic-script.md —- * data/ is gitignored; data.sample/ is the authoritative template, copied+ * stage produces (see data.reference/prompts/stages/pipeline-comic-script.md —+ * data/ is gitignored; data.reference/ is the authoritative template, copied* into data/ at setup time). Splits the markdown into a structured* `{ coverConcept, pages: [{ rawText, panels: [...] }] }` shape so the* comicPages stage UI can drop the LLM-authored panel descriptionsdiff --git a/server/lib/creativeDirectorPrompts.test.js b/server/lib/creativeDirectorPrompts.test.jsindex 0b1926fdc7..59e94dcdf3 100644--- a/server/lib/creativeDirectorPrompts.test.js+++ b/server/lib/creativeDirectorPrompts.test.js@@ -9,12 +9,12 @@ import { applyTemplate } from './promptTemplate.js';// mistyped section name, the test catches it.//// data/ is gitignored (populated on first boot via `npm run setup:data`),-// so on a fresh CI checkout only data.sample/ exists. Prefer the runtime+// so on a fresh CI checkout only data.reference/ exists. Prefer the runtime// copy (catches drift from local edits) and fall back to the committed// seed so CI works without running setup first.const __HERE = dirname(fileURLToPath(import.meta.url));const RUNTIME_STAGES_DIR = join(__HERE, '..', '..', 'data', 'prompts', 'stages');-const SAMPLE_STAGES_DIR = join(__HERE, '..', '..', 'data.sample', 'prompts', 'stages');+const SAMPLE_STAGES_DIR = join(__HERE, '..', '..', 'data.reference', 'prompts', 'stages');const loadStage = async (stageName) => {const runtimePath = join(RUNTIME_STAGES_DIR, `${stageName}.md`);return readFile(runtimePath, 'utf-8').catch((err) => {diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 6c138e802f..9049ca0489 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -62,7 +62,7 @@ export const PATHS = {// Visual template assets (e.g. the character reference-sheet layout PNG used// as the init-image anchor by the universe-builder character sheet renderer).// Distinct from `templates` above, which is the legacy prompt-template dir.- // Files here are shipped via data.sample/templates/ on first install.+ // Files here are shipped via data.reference/templates/ on first install.visualTemplates: join(__lib_dirname, '../../data/templates'),settings: join(__lib_dirname, '../../data/settings'),missions: join(__lib_dirname, '../../data/cos/missions'),diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex 745f79936a..d2d35d8954 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -529,7 +529,7 @@ describe('fileUtils', () => {// 2. Cleanup goes in `afterAll`, NOT a recursive remove of the root —// the data/ roots hold the user's universe content and shipped templates.describe('resolveImageInputPath', () => {- const sampleTemplate = join(__dirname_test, '..', '..', 'data.sample', 'templates', 'character-reference-sheet.png');+ const sampleTemplate = join(__dirname_test, '..', '..', 'data.reference', 'templates', 'character-reference-sheet.png');const galleryName = 'fileutils-test-gallery.png';const refsName = 'fileutils-test-refs.png';const templateName = 'fileutils-test-template.png';diff --git a/server/lib/index.js b/server/lib/index.jsindex 06f446d84f..9903a04076 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -68,8 +68,10 @@ export * from './tuiHandshake.js';export * from './tuiPromptRunner.js';// === File & I/O ===+export * from './collectionStore.js';export * from './fileUtils.js';export * from './fileWriteQueue.js';+export * from './schemaVersions.js';export * from './imageClean.js';export * from './multipart.js';export * from './assetHash.js';diff --git a/server/lib/mediaModels.test.js b/server/lib/mediaModels.test.jsindex 02f35011e1..4af8a0bc57 100644--- a/server/lib/mediaModels.test.js+++ b/server/lib/mediaModels.test.js@@ -5,7 +5,7 @@ import { dirname, join } from 'path';import { fileURLToPath } from 'url';const __dirname_self = dirname(fileURLToPath(import.meta.url));-const SAMPLE_REGISTRY_PATH = join(__dirname_self, '..', '..', 'data.sample', 'media-models.json');+const SAMPLE_REGISTRY_PATH = join(__dirname_self, '..', '..', 'data.reference', 'media-models.json');let tmpDir;let registryFile;@@ -22,12 +22,12 @@ afterEach(() => {rmSync(tmpDir, { recursive: true, force: true });});-// data.sample/media-models.json must mirror the in-code DEFAULT_REGISTRY so-// `npm run setup:data` (which copies data.sample → data on fresh installs)+// data.reference/media-models.json must mirror the in-code DEFAULT_REGISTRY so+// `npm run setup:data` (which copies data.reference → data on fresh installs)// produces the same starting state as the runtime `seedIfMissing()` fallback.// Compares the seed file to a freshly-bootstrapped registry with// _shippedDefaults stripped (that's a runtime-only field).-describe('data.sample seed file', () => {+describe('data.reference seed file', () => {it('matches the runtime-seeded DEFAULT_REGISTRY', async () => {const sample = JSON.parse(readFileSync(SAMPLE_REGISTRY_PATH, 'utf-8'));const { loadMediaModels } = await import('./mediaModels.js');diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsnew file mode 100644index 0000000000..156e072d04--- /dev/null+++ b/server/lib/schemaVersions.js@@ -0,0 +1,139 @@+/**+ * PortOS schema-version contract for cross-instance sync.+ *+ * Two PortOS instances that exchange data (federated peer push, snapshot+ * sync, share-bucket manifests) need a way to detect a version mismatch+ * BEFORE applying records the receiver can't parse. Without this, an+ * upgraded sender silently corrupts a downstream peer whose code doesn't+ * yet understand a new storage layout.+ *+ * `PORTOS_SCHEMA_VERSIONS` is the per-sync-category contract. Each entry is+ * the type-level storage layout version the running code expects to read ++ * write. When a category bumps its version (e.g. universes 4→5 splitting+ * out of the monolithic JSON), update the number here AND ship the+ * corresponding `scripts/migrations/NNN-…js`. The number flows through+ * every outbound payload's `portosMeta.schemaVersions`; receivers compare+ * incoming vs local and reject ahead-mismatches (sender too new) or+ * behind-mismatches (sender too old to satisfy a forward-only field).+ *+ * Absent categories default to 0 — the comparator treats 0 as "no check"+ * so historical / un-versioned data categories pass through unchanged.+ * Future PRs that introduce a layout change for `series`, `issues`, etc.+ * add an entry here.+ */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { PATHS } from './fileUtils.js';++export const PORTOS_SCHEMA_VERSIONS = Object.freeze({+ // Type-level (storage layout) version for `data/universes/{id}/index.json`.+ // 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, ...+});++/**+ * Lazy-read the current PortOS version from the ROOT package.json so a+ * pull-and-restart picks it up without a process-relative cache.+ *+ * Tested-without-files fallback: when PATHS.root is mutated for a test to+ * a directory without package.json, return '0.0.0' instead of throwing.+ * Mirrors `getCurrentVersion` in `server/services/updateChecker.js`.+ */+export async function getPortosVersion() {+ const pkgPath = join(PATHS.root, 'package.json');+ const raw = await readFile(pkgPath, 'utf-8').catch(() => null);+ if (!raw) return '0.0.0';+ const parsed = (() => { try { return JSON.parse(raw); } catch { return null; } })();+ return typeof parsed?.version === 'string' && parsed.version ? parsed.version : '0.0.0';+}++/**+ * Build the `portosMeta` envelope that every outbound sync payload carries+ * at the top level. Receivers feed `meta.schemaVersions` into+ * `compareSchemaVersions(sender, PORTOS_SCHEMA_VERSIONS)` to decide whether+ * to apply the payload.+ *+ * {+ * "portosMeta": {+ * "portosVersion": "2.7.0",+ * "schemaVersions": { "universes": 5 }+ * }+ * }+ *+ * `portosVersion` is informational — for UI surfacing only. The gate logic+ * runs on `schemaVersions` because the on-disk shape is what matters; the+ * PortOS version is just a friendly label users recognize.+ */+export async function buildPortosMeta(overrides = {}) {+ const portosVersion = await getPortosVersion();+ return {+ portosVersion,+ schemaVersions: { ...PORTOS_SCHEMA_VERSIONS, ...(overrides.schemaVersions || {}) },+ };+}++/**+ * Compare a peer's schemaVersions against the local code's expectations.+ *+ * Returns a structured diff so callers (push-rejection, UI surfacing) can+ * tell users WHICH category is mismatched and in which direction.+ *+ * ahead[] — categories where the SENDER has a newer schema than the+ * RECEIVER. The receiver can't safely apply the payload; reject.+ * behind[] — categories where the SENDER is older than the receiver. The+ * sanitizer can usually backfill, but some forward-only+ * contracts may still require the sender to upgrade. Callers+ * decide whether to gate.+ *+ * compatible — `true` only when neither list has entries.+ *+ * Absent or zero entries on either side are treated as "no contract" — the+ * comparator skips them. So legacy peers that don't send `portosMeta` at+ * all simply pass through (treat their schemaVersions as `{}` → no+ * `ahead` entries → compatible).+ */+export function compareSchemaVersions(senderVersions = {}, receiverVersions = PORTOS_SCHEMA_VERSIONS) {+ const sender = senderVersions && typeof senderVersions === 'object' ? senderVersions : {};+ const receiver = receiverVersions && typeof receiverVersions === 'object' ? receiverVersions : {};+ const ahead = [];+ const behind = [];+ // Walk the UNION of keys so we catch (a) sender has a category receiver+ // doesn't know (sender ahead), AND (b) receiver requires a category the+ // sender doesn't carry (sender behind on that category).+ const keys = new Set([+ ...Object.keys(sender),+ ...Object.keys(receiver),+ ]);+ for (const cat of keys) {+ const senderV = Number.isInteger(sender[cat]) ? sender[cat] : 0;+ const receiverV = Number.isInteger(receiver[cat]) ? receiver[cat] : 0;+ if (senderV === 0 && receiverV === 0) continue; // no contract on either side+ if (senderV === receiverV) continue; // exact match+ if (senderV > receiverV) ahead.push({ category: cat, senderV, receiverV });+ else behind.push({ category: cat, senderV, receiverV });+ }+ return { ahead, behind, compatible: ahead.length === 0 && behind.length === 0 };+}++/**+ * Human-readable explanation of a comparator result. Used both for log lines+ * and for the UI badge tooltip. Keeps the wording in one place so a peer-+ * sync 409 message, the Instances UI, and the share-bucket panel all+ * describe the gap identically.+ *+ * formatVersionGap({ ahead: [{ category: 'universes', senderV: 5, receiverV: 4 }] })+ * → 'sender ahead of receiver on universes (v5 vs v4)'+ */+export function formatVersionGap({ ahead = [], behind = [] } = {}) {+ const parts = [];+ if (ahead.length) {+ parts.push(`sender ahead of receiver on ${ahead.map((g) => `${g.category} (v${g.senderV} vs v${g.receiverV})`).join(', ')}`);+ }+ if (behind.length) {+ parts.push(`sender behind receiver on ${behind.map((g) => `${g.category} (v${g.senderV} vs v${g.receiverV})`).join(', ')}`);+ }+ return parts.join('; ') || 'compatible';+}diff --git a/server/lib/schemaVersions.test.js b/server/lib/schemaVersions.test.jsnew file mode 100644index 0000000000..33f980b8fd--- /dev/null+++ b/server/lib/schemaVersions.test.js@@ -0,0 +1,135 @@+import { describe, it, expect } from 'vitest';+import {+ PORTOS_SCHEMA_VERSIONS,+ compareSchemaVersions,+ formatVersionGap,+ buildPortosMeta,+} from './schemaVersions.js';++describe('PORTOS_SCHEMA_VERSIONS', () => {+ it('is a frozen object', () => {+ expect(Object.isFrozen(PORTOS_SCHEMA_VERSIONS)).toBe(true);+ expect(() => { PORTOS_SCHEMA_VERSIONS.universes = 999; }).toThrow();+ });++ it('declares universes at the post-split layout version', () => {+ // If this changes, the corresponding migration in scripts/migrations/+ // must ship alongside it. The test exists to make a layout bump a+ // deliberate two-file edit.+ expect(PORTOS_SCHEMA_VERSIONS.universes).toBe(5);+ });+});++describe('buildPortosMeta', () => {+ it('returns { portosVersion, schemaVersions } with the live registry', async () => {+ const meta = await buildPortosMeta();+ expect(meta.portosVersion).toMatch(/^\d+\.\d+\.\d+/);+ expect(meta.schemaVersions.universes).toBe(5);+ });++ it('overrides merge into schemaVersions', async () => {+ const meta = await buildPortosMeta({ schemaVersions: { future: 1 } });+ expect(meta.schemaVersions.universes).toBe(5);+ expect(meta.schemaVersions.future).toBe(1);+ });+});++describe('compareSchemaVersions', () => {+ it('compatible when both sides match exactly', () => {+ const r = compareSchemaVersions({ universes: 5 }, { universes: 5 });+ expect(r.compatible).toBe(true);+ expect(r.ahead).toEqual([]);+ expect(r.behind).toEqual([]);+ });++ it('flags ahead when sender is newer', () => {+ const r = compareSchemaVersions({ universes: 6 }, { universes: 5 });+ expect(r.compatible).toBe(false);+ expect(r.ahead).toEqual([{ category: 'universes', senderV: 6, receiverV: 5 }]);+ expect(r.behind).toEqual([]);+ });++ it('flags behind when sender is older', () => {+ const r = compareSchemaVersions({ universes: 4 }, { universes: 5 });+ expect(r.compatible).toBe(false);+ expect(r.ahead).toEqual([]);+ expect(r.behind).toEqual([{ category: 'universes', senderV: 4, receiverV: 5 }]);+ });++ it('handles mixed ahead + behind across categories', () => {+ const r = compareSchemaVersions(+ { universes: 6, series: 1 },+ { universes: 5, series: 3 },+ );+ expect(r.ahead).toEqual([{ category: 'universes', senderV: 6, receiverV: 5 }]);+ expect(r.behind).toEqual([{ category: 'series', senderV: 1, receiverV: 3 }]);+ expect(r.compatible).toBe(false);+ });++ it('treats a missing sender field as 0 (sender behind)', () => {+ const r = compareSchemaVersions({}, { universes: 5 });+ expect(r.behind).toEqual([{ category: 'universes', senderV: 0, receiverV: 5 }]);+ expect(r.ahead).toEqual([]);+ });++ it('treats a missing receiver field as 0 (sender ahead)', () => {+ const r = compareSchemaVersions({ universes: 5 }, {});+ expect(r.ahead).toEqual([{ category: 'universes', senderV: 5, receiverV: 0 }]);+ expect(r.behind).toEqual([]);+ });++ it('silently passes legacy peer with no portosMeta at all (sender = {}) when receiver has no version either', () => {+ const r = compareSchemaVersions({}, {});+ expect(r.compatible).toBe(true);+ });++ it('ignores categories where both sides are 0/absent', () => {+ const r = compareSchemaVersions(+ { universes: 5, future: 0 },+ { universes: 5, somethingElse: 0 },+ );+ expect(r.compatible).toBe(true);+ });++ it('treats non-integer entries as 0', () => {+ const r = compareSchemaVersions(+ { universes: 'five', series: 1.5 },+ { universes: 5 },+ );+ // 'five' → 0 → sender behind v5 ; 1.5 → 0 ; receiver has no series → both 0 → skip+ expect(r.behind).toEqual([{ category: 'universes', senderV: 0, receiverV: 5 }]);+ expect(r.ahead).toEqual([]);+ });++ it('handles null/undefined inputs gracefully', () => {+ 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);+ });+});++describe('formatVersionGap', () => {+ it('describes a single ahead gap', () => {+ expect(formatVersionGap({ ahead: [{ category: 'universes', senderV: 5, receiverV: 4 }] }))+ .toBe('sender ahead of receiver on universes (v5 vs v4)');+ });++ it('describes a single behind gap', () => {+ expect(formatVersionGap({ behind: [{ category: 'universes', senderV: 4, receiverV: 5 }] }))+ .toBe('sender behind receiver on universes (v4 vs v5)');+ });++ it('combines ahead + behind across categories', () => {+ expect(formatVersionGap({+ ahead: [{ category: 'universes', senderV: 6, receiverV: 5 }],+ behind: [{ category: 'series', senderV: 1, receiverV: 3 }],+ })).toBe('sender ahead of receiver on universes (v6 vs v5); sender behind receiver on series (v1 vs v3)');+ });++ it('returns "compatible" for an empty diff', () => {+ expect(formatVersionGap({ ahead: [], behind: [] })).toBe('compatible');+ expect(formatVersionGap({})).toBe('compatible');+ expect(formatVersionGap()).toBe('compatible');+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex bbab162d12..7b25c268ee 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -1218,10 +1218,31 @@ const peerWireRecordSchema = z.object({// unbounded. `sourceInstanceId` is required + must be a real instance id// (the receiver rejects "unknown" at the service layer; here we just enforce// non-empty + length cap).+// `portosMeta` envelope — every outbound payload built by `buildPushPayload`+// stamps the sender's PortOS version + schemaVersions map so the receiver+// can detect a version mismatch before applying the record. Optional on+// the wire so legacy peers (no portosMeta) still validate; the receiver's+// version-gate treats absent meta as "no contract" and falls through to+// the existing merge path.+//+// CRITICAL: uses `.passthrough()` (not `.strict()`). The whole point of+// the envelope is to enable graceful version negotiation. If a future+// PortOS adds a new field to `portosMeta` (e.g. `clientName`,+// `capabilities`, `regionCode`), `.strict()` would 400-reject every push+// from that version at Zod validation BEFORE the receiver's schema-version+// gate runs — surfacing as a generic 400 with no `blockedBySchema`+// persistence, no cooldown, no SchemaGapBadge surfacing. `.passthrough()`+// lets unknown fields flow through to the gate, which is the actual+// compat decision point.+const portosMetaSchema = z.object({+ portosVersion: z.string().trim().min(1).max(40).optional(),+ schemaVersions: z.record(z.string().min(1).max(60), z.number().int().min(0).max(1_000_000)).optional(),+}).passthrough().optional();const peerSyncPushBase = {record: peerWireRecordSchema,assetManifest: z.array(peerAssetManifestEntrySchema).max(2000),sourceInstanceId: z.string().trim().min(1).max(120),+ portosMeta: portosMetaSchema,// Optional bundled media collection — Stage 5 media-collections sync// attaches the universe / series's linked collection so collection-only// edits propagate via the per-record push pipeline. Same shape as adiff --git a/server/routes/dataSync.js b/server/routes/dataSync.jsindex fc2d05d2bc..8ac6ac1959 100644--- a/server/routes/dataSync.js+++ b/server/routes/dataSync.js@@ -30,12 +30,30 @@ router.get('/:category/snapshot', asyncHandler(async (req, res) => {res.json(snapshot);}));-// POST /api/sync/:category/apply — apply remote data with merge+// POST /api/sync/:category/apply — apply remote data with merge.+// Forwards `portosMeta` to `applyRemote` so the schema-version gate fires for+// this transport too. Without the forward, a caller hitting this REST path+// (manual debug, future client transport) would silently bypass the gate+// because `applyRemote` defaults the option object to `{}` and the gate+// reads `options.portosMeta` — absent → comparator skips the ahead check.+// `portosMeta` is intentionally `.passthrough()` so newer-PortOS callers+// adding fields don't get 400'd before the gate has a chance to diagnose.+const applyBodySchema = z.object({+ data: z.unknown(),+ portosMeta: z.object({+ portosVersion: z.string().trim().min(1).max(40).optional(),+ schemaVersions: z.record(z.string().min(1).max(60), z.number().int().min(0).max(1_000_000)).optional(),+ }).passthrough().optional(),+});router.post('/:category/apply', asyncHandler(async (req, res) => {const category = categoryParam.parse(req.params.category);- const { data } = req.body;+ const parsed = applyBodySchema.safeParse(req.body || {});+ if (!parsed.success) {+ throw new ServerError(`Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`, { status: 400, code: 'VALIDATION_ERROR' });+ }+ const { data, portosMeta } = parsed.data;if (!data) throw new ServerError('Missing data field', { status: 400 });- const result = await dataSync.applyRemote(category, data);+ const result = await dataSync.applyRemote(category, data, { portosMeta });res.json(result);}));diff --git a/server/routes/peerSync.js b/server/routes/peerSync.jsindex c7f1ccb184..74e344effc 100644--- a/server/routes/peerSync.js+++ b/server/routes/peerSync.js@@ -36,6 +36,7 @@ import {applyIncomingPush,ERR_NOT_FOUND,ERR_VALIDATION,+ ERR_SCHEMA_VERSION_AHEAD,} from '../services/sharing/peerSync.js';const router = Router();@@ -43,12 +44,26 @@ const router = Router();const PEER_SYNC_ERROR_STATUS = {[ERR_NOT_FOUND]: 404,[ERR_VALIDATION]: 400,+ // 409 Conflict — receiver's schema is behind the sender's; sender must+ // wait for the receiver to upgrade PortOS. The body's `details` carries+ // the ahead/behind diff + the receiver's schemaVersions so the sender+ // can surface a precise "Peer X needs to update PortOS" message and+ // pause retries for that subscription.+ [ERR_SCHEMA_VERSION_AHEAD]: 409,};function mapAndRethrow(err) {const status = PEER_SYNC_ERROR_STATUS[err?.code];if (status) {- throw new ServerError(err.message, { status, code: err.code });+ // Preserve `err.details` (set by `makeErr` in peerSync.js for the+ // schema-ahead path) — surface it as the ServerError's `context` so the+ // global error handler includes it in the JSON response body. Sender-+ // side parses `body.context` for `ahead` / `behind` / `senderPortosVersion`.+ throw new ServerError(err.message, {+ status,+ code: err.code,+ context: err.details ? { details: err.details } : undefined,+ });}throw err;}diff --git a/server/routes/peerSync.test.js b/server/routes/peerSync.test.jsindex 4cf0d1b75b..60666580fd 100644--- a/server/routes/peerSync.test.js+++ b/server/routes/peerSync.test.js@@ -10,6 +10,7 @@ vi.mock('../services/sharing/peerSync.js', () => ({applyIncomingPush: vi.fn(),ERR_NOT_FOUND: 'PEER_SYNC_SUBSCRIPTION_NOT_FOUND',ERR_VALIDATION: 'PEER_SYNC_SUBSCRIPTION_VALIDATION',+ ERR_SCHEMA_VERSION_AHEAD: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',}));import * as svc from '../services/sharing/peerSync.js';@@ -130,6 +131,35 @@ describe('peer-sync routes', () => {expect(res.status).toBe(400);});+ it('maps the service-layer ERR_SCHEMA_VERSION_AHEAD to a 409 with the diff in body.context.details', async () => {+ // Sender is on a newer storage layout. The route must return 409 (NOT+ // 400 or 500) and the JSON body must surface the diff so the sender's+ // pushRecordToPeer can persist the gap on the subscription.+ const details = {+ ahead: [{ category: 'universes', senderV: 6, receiverV: 5 }],+ behind: [],+ senderPortosVersion: '99.0.0',+ receiverSchemaVersions: { universes: 5 },+ };+ const err = Object.assign(new Error('schema ahead'), {+ code: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',+ details,+ });+ svc.applyIncomingPush.mockRejectedValue(err);+ const res = await request(buildApp())+ .post('/api/peer-sync/push')+ .send({+ kind: 'universe',+ record: { id: 'u1' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 6 } },+ });+ expect(res.status).toBe(409);+ expect(res.body.code).toBe('PEER_SYNC_SCHEMA_VERSION_AHEAD');+ expect(res.body.context.details).toEqual(details);+ });+it('maps the service-layer ERR_VALIDATION to a 400 (service-side guards beyond Zod)', async () => {// sourceInstanceId="unknown" is shape-valid but gets rejected by the// service for the cursor-poisoning reason — the route must surface thatdiff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.jsindex c52e9a19fd..889291c5da 100644--- a/server/services/autonomousJobs.js+++ b/server/services/autonomousJobs.js@@ -471,7 +471,7 @@ async function initJobs() {async function syncSkillTemplatesFromSample() {if (!PATHS.root) return- const sampleDir = join(PATHS.root, 'data.sample', 'prompts', 'skills', 'jobs')+ const sampleDir = join(PATHS.root, 'data.reference', 'prompts', 'skills', 'jobs')if (!existsSync(sampleDir)) returnawait ensureDir(JOBS_SKILLS_DIR)const shippedDir = join(JOBS_SKILLS_DIR, '.shipped')@@ -510,7 +510,7 @@ async function syncSkillTemplatesFromSample() {// history. We choose preservation: the user's file (whether intentional// customization or a stale shipped copy) stays in place. Users who want the// new template can delete the file and restart so the seeder re-creates it- // from data.sample/.+ // from data.reference/.console.log(`ℹ️ Preserving user-modified skill template: ${file}`)}}diff --git a/server/services/autonomousJobs.syncSkillTemplates.test.js b/server/services/autonomousJobs.syncSkillTemplates.test.jsindex 805da5177c..c82b208cf5 100644--- a/server/services/autonomousJobs.syncSkillTemplates.test.js+++ b/server/services/autonomousJobs.syncSkillTemplates.test.js@@ -10,7 +10,7 @@ const { ROOT } = vi.hoisted(() => {const { tmpdir } = require('os')const { join } = require('path')const root = mkdtempSync(join(tmpdir(), 'portos-sync-skill-'))- mkdirSync(join(root, 'data.sample', 'prompts', 'skills', 'jobs'), { recursive: true })+ mkdirSync(join(root, 'data.reference', 'prompts', 'skills', 'jobs'), { recursive: true })mkdirSync(join(root, 'data', 'prompts', 'skills', 'jobs'), { recursive: true })return { ROOT: root }})@@ -38,7 +38,7 @@ vi.mock('./eventScheduler.js', () => ({ parseCronToNextRun: vi.fn() }))import { syncSkillTemplatesFromSample } from './autonomousJobs.js'-const SAMPLE_DIR = join(ROOT, 'data.sample', 'prompts', 'skills', 'jobs')+const SAMPLE_DIR = join(ROOT, 'data.reference', 'prompts', 'skills', 'jobs')const DEST_DIR = join(ROOT, 'data', 'prompts', 'skills', 'jobs')const SHIPPED_DIR = join(DEST_DIR, '.shipped')diff --git a/server/services/brain.js b/server/services/brain.jsindex 16f681d4b6..c3fd22c1c9 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -51,7 +51,7 @@ async function callAI(promptStageName, variables, providerOverride, modelOverridlet model = modelOverride || provider.defaultModel;// gemini-cli default is a thinking model (3.1-pro); prefer the provider's configured- // light tier (populated from data.sample/providers.json on new installs) and only fall+ // light tier (populated from data.reference/providers.json on new installs) and only fall// back to the hard-coded flash if nothing is configured at all.if (provider.id === 'gemini-cli' && !model) {model = provider.lightModel || 'gemini-2.5-flash';diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex 5bd35cb6f4..f319cf3052 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -7,10 +7,16 @@*/import crypto from 'crypto';-import { stat } from 'fs/promises';+import { stat, readdir } from 'fs/promises';import { join } from 'path';import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';+import {+ PORTOS_SCHEMA_VERSIONS,+ buildPortosMeta,+ compareSchemaVersions,+ formatVersionGap,+} from '../lib/schemaVersions.js';import { mergeUniversesFromSync, listUniverses } from './universeBuilder.js';import { mergeSeriesFromSync, listSeries } from './pipeline/series.js';import { mergeIssuesFromSync } from './pipeline/issues.js';@@ -28,7 +34,12 @@ 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 UNIVERSE_BUILDER_FILE = join(PATHS.data, 'universe-builder.json');+// 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+// (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');const MEATSPACE_FILES = {@@ -349,11 +360,11 @@ async function applyMeatspaceRemote(remoteData) {// --- Category: Universe ---async function getUniverseSnapshot() {- const raw = await readJSONFile(UNIVERSE_BUILDER_FILE, { universes: [] });- // Wire-projection lives in `server/lib/syncWire.js` so the new per-record- // peer-sync push agrees on what to strip (currently: top-level `runs[]`,- // which is local LLM run history per peer).- const { data } = sanitizeStateForWire('universe', raw);+ // listUniverses() loads via the collection store — every per-record JSON+ // under `data/universes/<id>/index.json` plus the sanitizer pass. Same+ // input shape sanitizeStateForWire expects (it reads `state.universes`).+ const universes = await listUniverses({ includeDeleted: true });+ const { data } = sanitizeStateForWire('universe', { universes });return { data, checksum: computeChecksum(data) };}@@ -529,14 +540,14 @@ const CHECKSUM_PATHS = {character: [CHARACTER_FILE],digitalTwin: Object.values(DIGITAL_TWIN_FILES).map((f) => f.path),meatspace: Object.keys(MEATSPACE_FILES).map((f) => join(MEATSPACE_DIR, f)),- universe: [UNIVERSE_BUILDER_FILE],+ universe: [UNIVERSE_BUILDER_DIR],pipeline: [PIPELINE_SERIES_FILE, PIPELINE_ISSUES_FILE],// 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_FILE, PIPELINE_SERIES_FILE],+ mediaCollections: [MEDIA_COLLECTIONS_FILE, UNIVERSE_BUILDER_DIR, PIPELINE_SERIES_FILE],};const CATEGORIES = {@@ -555,11 +566,51 @@ const CATEGORIES = {// nothing has changed, instead of re-materializing the full payload.const checksumCache = new Map();+// Combine mtime/size/inode of one regular file into a single fingerprint+// string. Inode is included so an atomic-write replace (which mints a new+// inode) is always detected even when mtime rounds equal.+const fingerprintEntry = (s) => s ? `${s.mtimeMs}:${s.size}:${s.ino}` : null;++// Walk a directory two levels deep — the layout produced by collectionStore+// (`{dir}/index.json` + `{dir}/<id>/index.json`) — and concatenate per-file+// fingerprints into one deterministic string. Sorted by name so the result+// is stable across readdir orderings. Used by the universe + mediaCollections+// checksum paths so per-record edits invalidate the cache without enumerating+// every record at module-load.+async function fingerprintDirTwoLevels(dirPath) {+ const top = await readdir(dirPath).catch(() => null);+ if (!top) return null;+ const sortedTop = [...top].sort();+ const segments = [];+ for (const name of sortedTop) {+ const childPath = join(dirPath, name);+ const cs = await stat(childPath).catch(() => null);+ if (!cs) continue;+ if (cs.isFile()) {+ segments.push(`${name}:${fingerprintEntry(cs)}`);+ continue;+ }+ if (!cs.isDirectory()) continue;+ const inner = await readdir(childPath).catch(() => []);+ for (const innerName of [...inner].sort()) {+ const innerPath = join(childPath, innerName);+ const is = await stat(innerPath).catch(() => null);+ if (is?.isFile()) segments.push(`${name}/${innerName}:${fingerprintEntry(is)}`);+ }+ }+ return segments.join('|') || 'empty';+}+async function readFingerprintMap(paths) {const out = {};await Promise.all(paths.map(async (p) => {const s = await stat(p).catch(() => null);- out[p] = s ? `${s.mtimeMs}:${s.size}:${s.ino}` : null;+ if (!s) { out[p] = null; return; }+ if (s.isDirectory()) {+ out[p] = await fingerprintDirTwoLevels(p);+ return;+ }+ out[p] = fingerprintEntry(s);}));return out;}@@ -595,11 +646,51 @@ export async function getChecksum(category) {export async function getSnapshot(category) {const cat = CATEGORIES[category];if (!cat) return null;- return cat.getSnapshot();+ const snap = await cat.getSnapshot();+ // Stamp the sender's PortOS version + schema versions on every outbound+ // snapshot. Receivers compare against their own PORTOS_SCHEMA_VERSIONS in+ // `applyRemote` and reject ahead-mismatches before any data is merged.+ // Legacy receivers ignore the unknown envelope field — no compatibility+ // risk for the upgrade path.+ return { ...snap, portosMeta: await buildPortosMeta() };}-export async function applyRemote(category, remoteData) {+/**+ * Apply a peer's snapshot to local state.+ *+ * `options.portosMeta` (when provided) is the sender's PortOS version ++ * schemaVersions envelope. The receiver runs the comparator and rejects+ * ahead-mismatches BEFORE calling the category's `applyRemote` so a sender+ * on a newer storage layout can't corrupt local state. Legacy senders that+ * don't include `portosMeta` pass through (comparator treats absent as+ * zero/no-contract; the sanitizer chain handles older inputs in-place).+ *+ * On block, returns `{ applied: false, count: 0, blockedBySchema: { ahead,+ * behind, senderPortosVersion } }` so the orchestrator can persist the gap+ * on the peer record and the Instances UI can surface it.+ */+export async function applyRemote(category, remoteData, options = {}) {const cat = CATEGORIES[category];if (!cat) return { applied: false, count: 0 };+ const portosMeta = isPlainObject(options.portosMeta) ? options.portosMeta : null;+ const senderSchemaVersions = isPlainObject(portosMeta?.schemaVersions) ? portosMeta.schemaVersions : {};+ const senderPortosVersion = typeof portosMeta?.portosVersion === 'string' ? portosMeta.portosVersion : null;+ const versionDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);+ if (versionDiff.ahead.length > 0) {+ console.warn(+ `⚠️ dataSync: rejecting "${category}" snapshot — ${formatVersionGap(versionDiff)} ` ++ `(sender PortOS ${senderPortosVersion || 'unknown'})`,+ );+ return {+ applied: false,+ count: 0,+ blockedBySchema: {+ ahead: versionDiff.ahead,+ behind: versionDiff.behind,+ senderPortosVersion,+ receiverSchemaVersions: PORTOS_SCHEMA_VERSIONS,+ },+ };+ }return cat.applyRemote(remoteData);}diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex 1d30869596..8bf57c6abe 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -8,7 +8,7 @@*/import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';-import { writeFileSync, mkdirSync, readFileSync, rmSync } from 'fs';+import { writeFileSync, mkdirSync, readFileSync, rmSync, readdirSync, existsSync } from 'fs';import { join } from 'path';import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';@@ -25,7 +25,7 @@ const dataSync = await import('./dataSync.js');const SERIES_PATH = join(tempRoot, 'pipeline-series.json');const ISSUES_PATH = join(tempRoot, 'pipeline-issues.json');-const UNIVERSE_PATH = join(tempRoot, 'universe-builder.json');+const UNIVERSES_DIR = join(tempRoot, 'universes');const MEDIA_COLLECTIONS_PATH = join(tempRoot, 'media-collections.json');function writeJSON(path, obj) {@@ -37,6 +37,40 @@ function readJSON(path) {return JSON.parse(readFileSync(path, 'utf-8'));}+// 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.+function writeUniverseState({ universes = [], runs = [] } = {}) {+ mkdirSync(UNIVERSES_DIR, { recursive: true });+ for (const u of universes) {+ const dir = join(UNIVERSES_DIR, u.id);+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, 'index.json'), JSON.stringify(u, null, 2));+ }+ writeFileSync(join(UNIVERSES_DIR, 'index.json'), JSON.stringify({+ schemaVersion: 5, type: 'universes', updatedAt: new Date().toISOString(),+ config: { runs },+ }, null, 2));+}++// Read it back as the legacy `{ universes, runs }` shape so existing+// assertions don't need rewiring.+function readUniverseState() {+ if (!existsSync(UNIVERSES_DIR)) return { universes: [], runs: [] };+ const entries = readdirSync(UNIVERSES_DIR);+ const universes = [];+ for (const name of entries) {+ if (name === 'index.json' || name.startsWith('.')) continue;+ const p = join(UNIVERSES_DIR, name, 'index.json');+ if (existsSync(p)) universes.push(JSON.parse(readFileSync(p, 'utf-8')));+ }+ const typeIdx = existsSync(join(UNIVERSES_DIR, 'index.json'))+ ? JSON.parse(readFileSync(join(UNIVERSES_DIR, 'index.json'), 'utf-8'))+ : null;+ const runs = typeIdx?.config?.runs || [];+ return { universes, runs };+}+beforeEach(() => {rmSync(tempRoot, { recursive: true, force: true });mkdirSync(tempRoot, { recursive: true });@@ -51,7 +85,7 @@ describe('dataSync — universe category', () => {});it('snapshot returns just `universes` (not `runs`)', async () => {- writeJSON(UNIVERSE_PATH, {+ writeUniverseState({universes: [{ id: 'u1', name: 'Salt', updatedAt: '2026-05-17T10:00:00Z' }],runs: [{ id: 'r1', logs: ['ephemeral'] }]});@@ -62,8 +96,48 @@ describe('dataSync — universe category', () => {expect(snap.checksum).toBeTruthy();});+ it('snapshot envelope carries portosMeta { portosVersion, schemaVersions } so receivers can gate', async () => {+ const snap = await dataSync.getSnapshot('universe');+ expect(snap.portosMeta).toBeDefined();+ expect(typeof snap.portosMeta.portosVersion).toBe('string');+ expect(snap.portosMeta.schemaVersions.universes).toBe(5);+ });++ it('applyRemote rejects when sender schemaVersions are AHEAD of local code', async () => {+ writeUniverseState({ universes: [], runs: [] });+ const result = await dataSync.applyRemote('universe', {+ universes: [{ id: 'u-new', name: 'Foundry', updatedAt: '2026-05-17T10:00:00Z' }],+ }, { portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 6 } } });+ expect(result.applied).toBe(false);+ expect(result.count).toBe(0);+ expect(result.blockedBySchema).toBeDefined();+ expect(result.blockedBySchema.ahead).toEqual([+ { category: 'universes', senderV: 6, receiverV: 5 },+ ]);+ expect(result.blockedBySchema.senderPortosVersion).toBe('99.0.0');+ // Nothing was written.+ expect(readUniverseState().universes).toEqual([]);+ });++ it('applyRemote falls through when sender is BEHIND (sanitizer backfills)', async () => {+ writeUniverseState({ universes: [], runs: [] });+ const result = await dataSync.applyRemote('universe', {+ universes: [{ id: 'u-old', name: 'Legacy', createdAt: '2026-05-17T09:00:00Z', updatedAt: '2026-05-17T10:00:00Z' }],+ }, { portosMeta: { portosVersion: '2.6.0', schemaVersions: { universes: 4 } } });+ expect(result.applied).toBe(true);+ expect(result.count).toBe(1);+ });++ it('applyRemote falls through for legacy senders that send NO portosMeta at all', async () => {+ writeUniverseState({ universes: [], runs: [] });+ const result = await dataSync.applyRemote('universe', {+ universes: [{ id: 'u-legacy', name: 'Pre-Versioning', createdAt: '2026-05-17T09:00:00Z', updatedAt: '2026-05-17T10:00:00Z' }],+ });+ expect(result.applied).toBe(true);+ });+it('snapshot checksum is stable across reads when state is unchanged', async () => {- writeJSON(UNIVERSE_PATH, { universes: [{ id: 'u1', updatedAt: '2026-05-17T10:00:00Z' }] });+ writeUniverseState({ universes: [{ id: 'u1', updatedAt: '2026-05-17T10:00:00Z' }] });const a = await dataSync.getSnapshot('universe');const b = await dataSync.getSnapshot('universe');expect(a.checksum).toBe(b.checksum);@@ -76,13 +150,13 @@ describe('dataSync — universe category', () => {});it('applyRemote inserts a new universe', async () => {- writeJSON(UNIVERSE_PATH, { universes: [], runs: [] });+ writeUniverseState({ universes: [], runs: [] });const result = await dataSync.applyRemote('universe', {universes: [{ id: 'u-new', name: 'Foundry', updatedAt: '2026-05-17T10:00:00Z' }]});expect(result.applied).toBe(true);expect(result.count).toBe(1);- const persisted = readJSON(UNIVERSE_PATH);+ const persisted = readUniverseState();expect(persisted.universes).toHaveLength(1);expect(persisted.universes[0].id).toBe('u-new');// Local-only `runs` must survive the merge.@@ -90,21 +164,21 @@ describe('dataSync — universe category', () => {});it('applyRemote LWW: newer remote wins, older remote is dropped', async () => {- writeJSON(UNIVERSE_PATH, {+ writeUniverseState({universes: [{ id: 'u1', name: 'Old', updatedAt: '2026-05-17T10:00:00Z' }]});const result = await dataSync.applyRemote('universe', {universes: [{ id: 'u1', name: 'New', updatedAt: '2026-05-17T11:00:00Z' }]});expect(result.applied).toBe(true);- expect(readJSON(UNIVERSE_PATH).universes[0].name).toBe('New');+ expect(readUniverseState().universes[0].name).toBe('New');// Replay older — should NOT clobber.const replay = await dataSync.applyRemote('universe', {universes: [{ id: 'u1', name: 'Old', updatedAt: '2026-05-17T10:00:00Z' }]});expect(replay.applied).toBe(false);- expect(readJSON(UNIVERSE_PATH).universes[0].name).toBe('New');+ expect(readUniverseState().universes[0].name).toBe('New');});it('applyRemote preserves local-only `runs[]` when only universes change', async () => {@@ -115,11 +189,11 @@ describe('dataSync — universe category', () => {id: 'r1', universeId: 'u-local', collectionId: null,jobIds: [], promptCount: 0, createdAt: '2026-05-17T09:00:00Z',};- writeJSON(UNIVERSE_PATH, { universes: [], runs: [localRun] });+ writeUniverseState({ universes: [], runs: [localRun] });await dataSync.applyRemote('universe', {- universes: [{ id: 'u1', name: 'X', updatedAt: '2026-05-17T10:00:00Z' }]+ universes: [{ id: 'u1', name: 'A', createdAt: '2026-05-17T09:00:00Z', updatedAt: '2026-05-17T10:00:00Z' }]});- const persisted = readJSON(UNIVERSE_PATH);+ const persisted = readUniverseState();expect(persisted.runs).toHaveLength(1);expect(persisted.runs[0].id).toBe('r1');expect(persisted.runs[0].universeId).toBe('u-local');@@ -228,8 +302,8 @@ describe('dataSync — pipeline category', () => {describe('dataSync — getChecksum cache', () => {it('returns the same checksum across consecutive calls and matches getSnapshot', async () => {- writeJSON(UNIVERSE_PATH, {- universes: [{ id: 'u1', name: 'A', updatedAt: '2026-05-17T10:00:00Z' }],+ writeUniverseState({+ universes: [{ id: 'u1', name: 'A', createdAt: '2026-05-17T09:00:00Z', updatedAt: '2026-05-17T10:00:00Z' }],});const c1 = await dataSync.getChecksum('universe');const c2 = await dataSync.getChecksum('universe');@@ -239,8 +313,8 @@ describe('dataSync — getChecksum cache', () => {});it('invalidates the cache after applyRemote bumps the underlying file mtime', async () => {- writeJSON(UNIVERSE_PATH, {- universes: [{ id: 'u1', name: 'A', updatedAt: '2026-05-17T10:00:00Z' }],+ writeUniverseState({+ universes: [{ id: 'u1', name: 'A', createdAt: '2026-05-17T09:00:00Z', updatedAt: '2026-05-17T10:00:00Z' }],});const before = await dataSync.getChecksum('universe');await dataSync.applyRemote('universe', {diff --git a/server/services/instances.js b/server/services/instances.jsindex 23031e8e3a..b7f4cd8e42 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -257,6 +257,19 @@ export async function updatePeer(id, updates) {console.log(`🌐 Peer host ${peer.host ? `set to ${peer.host}` : 'cleared'}: ${peer.name}`);}}+ // Per-(peer, category) schema-version gaps, populated by syncOrchestrator+ // when a remote snapshot is rejected because the sender's schemaVersions+ // are ahead of local. Stored on the peer record so the Instances UI's+ // SchemaGapBadge can read it via the standard peers payload. Accept+ // either a plain object (set/replace the map) or null (clear all gaps).+ // Any other value is silently ignored.+ if (updates.schemaGaps !== undefined) {+ if (updates.schemaGaps === null) {+ delete peer.schemaGaps;+ } else if (updates.schemaGaps && typeof updates.schemaGaps === 'object' && !Array.isArray(updates.schemaGaps)) {+ peer.schemaGaps = updates.schemaGaps;+ }+ }instanceEvents.emit('peers:updated', data.peers);return peer;});diff --git a/server/services/pipeline/textStages.js b/server/services/pipeline/textStages.jsindex ea2c069081..012bd22d52 100644--- a/server/services/pipeline/textStages.js+++ b/server/services/pipeline/textStages.js@@ -3,8 +3,8 @@** Runs a single text stage (idea / prose / comicScript / teleplay) against the* active LLM provider. Builds the prompt via promptService.buildPrompt — each- * stage has its own template in data.sample/prompts/stages/pipeline-*.md and- * is registered in data.sample/prompts/stage-config.json.+ * stage has its own template in data.reference/prompts/stages/pipeline-*.md and+ * is registered in data.reference/prompts/stage-config.json.** The render context includes the series bible (logline, premise, characters,* styleNotes) plus every *prior* stage's output, so downstream stages candiff --git a/server/services/sharing/annotationsSync.js b/server/services/sharing/annotationsSync.jsindex 0b287ec070..145f357f76 100644--- a/server/services/sharing/annotationsSync.js+++ b/server/services/sharing/annotationsSync.js@@ -13,6 +13,7 @@ import { ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';import { listBuckets } from './buckets.js';import { buildManifest, writeManifest, annotationManifestFilename, readManifest, listManifestFilenames } from './manifest.js';import { getProducedByVersion } from './version.js';+import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';import { getInstanceId, UNKNOWN_INSTANCE_ID } from '../instances.js';import { resolveBucketSourceName } from './annotationIdentity.js';import { onLocalAnnotationChange, listLocalAuthorAnnotations } from '../mediaAnnotations.js';@@ -186,6 +187,7 @@ export async function exportAnnotationsToBucket(bucket, localAnnotations, senderbucketId: bucket.id,bucketName: bucket.name,producedByVersion,+ portosSchemaVersions: PORTOS_SCHEMA_VERSIONS,});const filename = await writeManifest(bucket.path, manifest);// The annotation manifest we just wrote bumps the manifests-dir mtime, butdiff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.jsindex 95261f6591..60877d1293 100644--- a/server/services/sharing/exporter.js+++ b/server/services/sharing/exporter.js@@ -31,6 +31,7 @@ import { getJob } from '../mediaJobQueue/index.js';import { getInstanceId } from '../instances.js';import { getSettings } from '../settings.js';import { getProducedByVersion } from './version.js';+import { PORTOS_SCHEMA_VERSIONS } from '../../lib/schemaVersions.js';import { isStr, listSheetPointers } from '../../lib/storyBible.js';import { resolveBucketSourceName as resolveSourceName } from './annotationIdentity.js';@@ -390,6 +391,7 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {senderInstanceId,source, sourceBio,producedByVersion,+ portosSchemaVersions: PORTOS_SCHEMA_VERSIONS,subscription: opts.subscription || null,collection: linkedCollection,bucketId: bucket.id,@@ -475,6 +477,7 @@ export async function exportUniverse(universeId, bucketId, opts = {}) {senderInstanceId,source, sourceBio,producedByVersion,+ portosSchemaVersions: PORTOS_SCHEMA_VERSIONS,subscription: opts.subscription || null,collection: linkedCollection,bucketId: bucket.id,@@ -539,6 +542,7 @@ export async function exportMedia(items, bucketId) {senderInstanceId,source, sourceBio,producedByVersion,+ portosSchemaVersions: PORTOS_SCHEMA_VERSIONS,bucketId: bucket.id,bucketName: bucket.name,recordIds: [],diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex f28ae7bcd4..f7ce266afa 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -29,6 +29,7 @@ import { PATHS, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtilsimport { getBucket, bucketBlobPath, bucketBlobSidecarPath, imageSidecarName, isHexHash } from './buckets.js';import { readManifest, markProcessed, readCursor, hasBeenProcessed, forgetProcessed } from './manifest.js';import { SHARING_SCHEMA_VERSION, isManifestCompatible } from './version.js';+import { PORTOS_SCHEMA_VERSIONS, compareSchemaVersions, formatVersionGap } from '../../lib/schemaVersions.js';import { insertSeriesWithId, updateSeries, getSeries } from '../pipeline/series.js';import { insertIssueWithId, updateIssue, getIssue } from '../pipeline/issues.js';import { insertUniverseWithId, updateUniverse, getUniverse } from '../universeBuilder.js';@@ -725,6 +726,46 @@ export async function processManifest(bucketId, manifestFilename) {console.log(`⚠️ sharing: bucket=${bucket.name} manifest=${manifest.id} schemaVersion=${remoteVersion} > local=${SHARING_SCHEMA_VERSION} — refusing import (peer producedBy=${manifest.producedByVersion || 'unknown'})`);return { skipped: true, reason: 'incompatible-version', remoteVersion, localVersion: SHARING_SCHEMA_VERSION };}+ // PORTOS SCHEMA-VERSION GATE — even when the share-protocol schemaVersion+ // is compatible, the manifest's per-category storage layout versions+ // (`portosSchemaVersions`, e.g. `{ universes: 5 }`) may exceed what this+ // PortOS can apply. Reject without marking processed so a later upgrade+ // naturally re-imports (the watcher re-fires; the cursor still+ // dedups via `hasBeenProcessed` until the upgrade lands and the comparator+ // passes). Emits a `portos-schema-ahead` event the UI uses to render a+ // persistent "Update PortOS to import this share" badge.+ const senderSchemaVersions = manifest.portosSchemaVersions && typeof manifest.portosSchemaVersions === 'object'+ ? manifest.portosSchemaVersions+ : {};+ const portosDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);+ if (portosDiff.ahead.length > 0) {+ // Mark processed so subsequent chokidar fan-outs (every asset/record+ // file landing under the bucket triggers a backlog scan that re-walks+ // every manifest) don't re-fire this event 100× per bundle. Mirrors+ // the sibling `incompatible-version` branch above. Trade-off: when the+ // user upgrades PortOS, they must clear the cursor entry to retry the+ // import (or unshare/reshare from the sender side). Without this dedup,+ // the event spams logs + the socket channel on every receive cycle.+ await markProcessed(bucketId, manifestFilename, manifest.id);+ sharingEvents.emit('portos-schema-ahead', {+ bucketId, manifestId: manifest.id, manifestFilename,+ ahead: portosDiff.ahead,+ behind: portosDiff.behind,+ producedByVersion: manifest.producedByVersion || 'unknown',+ source: manifest.source || 'unknown',+ });+ console.log(+ `⚠️ sharing: bucket=${bucket.name} manifest=${manifest.id} — ${formatVersionGap(portosDiff)} ` ++ `(producedBy=${manifest.producedByVersion || 'unknown'}). Update PortOS to import; clear the bucket cursor after upgrade to retry.`,+ );+ return {+ skipped: true,+ reason: 'portos-schema-ahead',+ ahead: portosDiff.ahead,+ behind: portosDiff.behind,+ producedByVersion: manifest.producedByVersion || 'unknown',+ };+ }// Annotation manifests bypass the records/assets/applyMerge pipeline — they// carry a per-instance annotation snapshot at records/media-annotations/<id>.json// that merges author-by-author into data/media-annotations.json.diff --git a/server/services/sharing/index.js b/server/services/sharing/index.jsindex a1903f38d1..779636e669 100644--- a/server/services/sharing/index.js+++ b/server/services/sharing/index.js@@ -49,6 +49,23 @@ export async function initSharing({ io: socketIo } = {}) {sharingEvents.on('incompatible-manifest', (payload) => {io.emit('sharing:incompatible-manifest', payload);});+ // PortOS storage-layout version is ahead of this instance — the user+ // needs to update PortOS to import the manifest. Separate event from+ // `incompatible-manifest` (which gates on the share-protocol schema, a+ // different version axis) so the UI can render distinct messages for+ // each case.+ sharingEvents.on('portos-schema-ahead', (payload) => {+ io.emit('sharing:portos-schema-ahead', payload);+ });+ // Peer-sync per-record subscription got blocked / unblocked by a schema-+ // version mismatch. Lets the Instances UI swap in the SchemaGapBadge+ // without polling.+ peerSyncEvents.on('subscription-blocked', (payload) => {+ io.emit('peerSync:subscription-blocked', payload);+ });+ peerSyncEvents.on('subscription-unblocked', (payload) => {+ io.emit('peerSync:subscription-unblocked', payload);+ });sharingEvents.on('unshared', (payload) => {io.emit('sharing:unshared', payload);});diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex c7602e0ff4..2af1e1773b 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -1779,4 +1779,61 @@ describe('sharing round-trip', () => {expect(idx[keyA]).toBe(sha256Hex('PARALLEL_A'));expect(idx[keyB]).toBe(sha256Hex('PARALLEL_B'));});++ // ---------------------------------------------------------------------------+ // SCHEMA-VERSION GATING — share-bucket transport+ // ---------------------------------------------------------------------------+ describe('portos-schema-ahead manifest gate', () => {+ it('manifest is stamped with the sender\'s PORTOS_SCHEMA_VERSIONS', async () => {+ const bucket = await buckets.createBucket({ name: 'GateBucket', path: tempBucket, mode: 'inbox' });+ const s = await series.createSeries({ name: 'Stamp Test', logline: 'x' });+ const exp = await exporter.exportSeries(s.id, bucket.id);+ const manifest = JSON.parse(readFileSync(join(tempBucket, 'manifests', exp.filename), 'utf-8'));+ expect(manifest.portosSchemaVersions).toBeDefined();+ expect(manifest.portosSchemaVersions.universes).toBe(5);+ });++ it('importer rejects a manifest whose portosSchemaVersions.universes is AHEAD of local', async () => {+ const bucket = await buckets.createBucket({ name: 'AheadBucket', path: tempBucket, mode: 'auto-merge' });+ const s = await series.createSeries({ name: 'Future', logline: 'x' });+ const exp = await exporter.exportSeries(s.id, bucket.id);+ // Mutate the written manifest to stamp a future portos schema. This+ // simulates a manifest exported by a NEWER PortOS instance landing in+ // an OLDER instance's bucket.+ const manifestPath = join(tempBucket, 'manifests', exp.filename);+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));+ manifest.portosSchemaVersions = { universes: 99 };+ manifest.producedByVersion = '99.0.0';+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));+ // Delete the local series so the auto-merge would normally re-create it.+ await series.deleteSeries(s.id);+ simulateRemoteSender(tempBucket, exp.filename);+ const result = await importer.processManifest(bucket.id, exp.filename);+ expect(result.skipped).toBe(true);+ expect(result.reason).toBe('portos-schema-ahead');+ expect(result.ahead).toEqual([{ category: 'universes', senderV: 99, receiverV: 5 }]);+ expect(result.producedByVersion).toBe('99.0.0');+ // Series stayed tombstoned (or absent) — apply was refused.+ await expect(series.getSeries(s.id)).rejects.toThrow();+ });++ it('importer falls through for manifests with no portosSchemaVersions (legacy peer)', async () => {+ // A manifest produced by a pre-this-PR PortOS won't have the field;+ // the comparator treats it as no-contract, so the merge proceeds.+ const bucket = await buckets.createBucket({ name: 'LegacyBucket', path: tempBucket, mode: 'auto-merge' });+ const s = await series.createSeries({ name: 'Legacy Test', logline: 'x' });+ const exp = await exporter.exportSeries(s.id, bucket.id);+ const manifestPath = join(tempBucket, 'manifests', exp.filename);+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));+ delete manifest.portosSchemaVersions;+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));+ await series.deleteSeries(s.id);+ simulateRemoteSender(tempBucket, exp.filename);+ const result = await importer.processManifest(bucket.id, exp.filename);+ expect(result.processed).toBe(true);+ expect(result.outcome.mode).toBe('auto-merge');+ const restored = await series.getSeries(s.id);+ expect(restored.id).toBe(s.id);+ });+ });});diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.jsindex db79a449f5..53354b7ef8 100644--- a/server/services/sharing/manifest.js+++ b/server/services/sharing/manifest.js@@ -145,6 +145,7 @@ export function hasBeenProcessed(cursor, manifestFilename, manifestId = null) {export function buildManifest({kind, senderInstanceId, source, sourceBio, recordIds, assetRefs,bucketId, bucketName, note, producedByVersion, subscription, collection,+ portosSchemaVersions,}) {if (!MANIFEST_KIND.includes(kind)) throw new Error(`buildManifest: invalid kind '${kind}'`);return {@@ -152,6 +153,15 @@ export function buildManifest({schemaVersion: SHARING_SCHEMA_VERSION,sharingSchemaVersion: SHARING_SCHEMA_VERSION,producedByVersion: producedByVersion || 'unknown',+ // Per-category storage layout versions the sender's code expected at+ // export time. The importer compares against its own+ // `PORTOS_SCHEMA_VERSIONS` and refuses to apply a manifest that's+ // ahead — the user is told to upgrade PortOS before the import can+ // proceed. Optional on the wire so legacy manifests (no field) still+ // validate; absent treated as "no contract" by the comparator.+ portosSchemaVersions: portosSchemaVersions && typeof portosSchemaVersions === 'object'+ ? { ...portosSchemaVersions }+ : null,createdAt: new Date().toISOString(),kind, // 'series' | 'universe' | 'media'subscription: subscription && subscription.recordKind && subscription.recordIddiff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex d154abf22a..568fe25810 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -47,6 +47,12 @@ import { getOrComputeImageSha256 } from '../../lib/assetHash.js';import { sanitizeRecordForWire } from '../../lib/syncWire.js';import { collectAssetReferences } from './exporter.js';import { recordEvents } from './recordEvents.js';+import {+ PORTOS_SCHEMA_VERSIONS,+ buildPortosMeta,+ compareSchemaVersions,+ formatVersionGap,+} from '../../lib/schemaVersions.js';import { getInstanceId, getPeers, UNKNOWN_INSTANCE_ID } from '../instances.js';import { instanceEvents } from '../instanceEvents.js';import { getUniverse, mergeUniversesFromSync } from '../universeBuilder.js';@@ -77,7 +83,18 @@ peerSyncEvents.setMaxListeners(100);export const ERR_NOT_FOUND = 'PEER_SYNC_SUBSCRIPTION_NOT_FOUND';export const ERR_VALIDATION = 'PEER_SYNC_SUBSCRIPTION_VALIDATION';-const makeErr = (message, code) => Object.assign(new Error(message), { code });+// Receiver-side rejection — the incoming payload's `portosMeta.schemaVersions`+// is ahead of our local PORTOS_SCHEMA_VERSIONS for one or more categories,+// so applying the record would corrupt local state. The HTTP route maps this+// to 409 + a structured body { ahead, behind, senderPortosVersion } so the+// sender can persist the gap on the subscription and surface it in the UI.+export const ERR_SCHEMA_VERSION_AHEAD = 'PEER_SYNC_SCHEMA_VERSION_AHEAD';+const makeErr = (message, code, details = null) => {+ const err = new Error(message);+ err.code = code;+ if (details) err.details = details;+ return err;+};const STATE_PATH = () => join(PATHS.data, 'sharing', 'peer_subscriptions.json');const DEBOUNCE_MS = 3000;@@ -582,7 +599,14 @@ function sanitizeAssetFilename(name) {* atomically per merge cycle. Issue records are filtered through* `sanitizeRecordForWire('issue', ...)` too.*/-export async function pushRecordToPeer(sub) {+// Cool-down between re-probes when a peer has rejected our push for schema-+// version reasons. Without it, every local edit would HTTP-roundtrip a 409+// while the peer is on the older PortOS, spamming the network. The retry+// loop on `peer:online` bypasses this — that's the canonical "did the peer+// upgrade?" probe point.+const SCHEMA_BLOCK_RETRY_COOLDOWN_MS = 5 * 60_000;++export async function pushRecordToPeer(sub, options = {}) {if (!isPlainObject(sub)|| !isNonEmptyStr(sub.peerId)@@ -591,6 +615,18 @@ export async function pushRecordToPeer(sub) {) {return { pushed: false, reason: 'invalid-subscription' };}+ // SCHEMA-BLOCK COOLDOWN — if the peer rejected our last push for being+ // schema-ahead, hold off re-probing on every local edit. Re-probes happen+ // on the next `peer:online` (where `retryPendingPushesForPeer` passes+ // `bypassSchemaCooldown: true`) or after the cooldown elapses.+ if (sub.blockedBySchema && !options.bypassSchemaCooldown) {+ const detectedAtMs = Date.parse(sub.blockedBySchema.detectedAt || '');+ const stillCooling = Number.isFinite(detectedAtMs)+ && (Date.now() - detectedAtMs) < SCHEMA_BLOCK_RETRY_COOLDOWN_MS;+ if (stillCooling) {+ return { pushed: false, reason: 'peer-schema-behind-cooldown', blockedBySchema: true };+ }+ }const peer = await findPeerById(sub.peerId);if (!peer) return { pushed: false, reason: 'peer-not-found' };// Re-gate on the same peer flags the auto-subscribe path checks. An@@ -647,11 +683,45 @@ export async function pushRecordToPeer(sub) {console.log(`⚠️ peerSync: push to ${peer.name || peer.instanceId} failed: ${err.message}`);return null;}).finally(() => clearTimeout(timeoutId));+ // 409 with `code: SCHEMA_VERSION_AHEAD` means the receiver is on an OLDER+ // PortOS and can't parse our newer storage layout. Persist the gap on the+ // subscription so the Instances UI can surface "Peer X needs to update+ // PortOS to receive your updates" — and short-circuit retries to that+ // peer for the affected record kind. We don't tear down the subscription;+ // when the peer upgrades and reconnects, `peer:online` will re-fire+ // pushRecordToPeer and the next response either clears the block (success)+ // or refreshes the gap info (still behind).+ if (res && res.status === 409) {+ const body = await res.json().catch(() => null);+ if (body?.code === ERR_SCHEMA_VERSION_AHEAD) {+ // The global error handler nests our `err.details` under `context.details`+ // (see server/routes/peerSync.js `mapAndRethrow`), so reach in two levels+ // to get the original payload from the peerSync service.+ const details = isPlainObject(body.context?.details) ? body.context.details : {};+ await persistSchemaVersionBlock(sub.id, {+ ahead: Array.isArray(details.ahead) ? details.ahead : [],+ behind: Array.isArray(details.behind) ? details.behind : [],+ peerPortosVersion: typeof details.senderPortosVersion === 'string' ? details.senderPortosVersion : null,+ peerSchemaVersions: isPlainObject(details.receiverSchemaVersions) ? details.receiverSchemaVersions : null,+ });+ console.warn(+ `⚠️ peerSync: ${peer.name || peer.instanceId} rejected push — peer is on an older PortOS schema. ` ++ `Re-tries will pause until they upgrade. ${formatVersionGap({ ahead: details.ahead || [], behind: details.behind || [] })}`,+ );+ return { pushed: false, reason: 'peer-schema-behind', blockedBySchema: true };+ }+ }if (!res || !res.ok) {return { pushed: false, reason: res ? `http-${res.status}` : 'network' };}const body = await res.json().catch(() => null);+ // Push succeeded — clear any prior schema-version block so the sub goes+ // back to normal. Either the peer upgraded or the gap was transient.+ if (sub.blockedBySchema) {+ await clearSchemaVersionBlock(sub.id);+ }+// Persist push metadata to peer_subscriptions.json, then advance the// tombstone cursor in peer_tombstone_cursors.json if the receiver acked// any deletions. These are two separate files; a crash between them@@ -694,11 +764,55 @@ async function persistPushSuccess(subId, hash) {sub.lastPushedAt = now;sub.lastPushedHash = hash;sub.updatedAt = now;+ // A successful push (or even a no-asset-stranded push) clears any prior+ // schema-version block — the peer can receive again.+ if (sub.blockedBySchema) delete sub.blockedBySchema;await writeState(state);});}+/**+ * Persist a `blockedBySchema` field on the subscription so subsequent pushes+ * short-circuit until the peer upgrades. Stored on the same record as+ * `lastPushedAt` / `lastPushedHash` so the Instances UI can read everything+ * from a single subscription fetch. We capture both directions of the gap+ * (`ahead` = what the PEER needs to gain to receive our pushes; `behind` =+ * what the peer has that we don't — informational) along with the peer's+ * PortOS version string for the user-visible message.+ */+async function persistSchemaVersionBlock(subId, { ahead, behind, peerPortosVersion, peerSchemaVersions }) {+ await withStateLock(async () => {+ const state = await readState();+ const sub = state.subscriptions.find((s) => s.id === subId);+ if (!sub) return;+ const now = new Date().toISOString();+ sub.blockedBySchema = {+ detectedAt: now,+ ahead: Array.isArray(ahead) ? ahead : [],+ behind: Array.isArray(behind) ? behind : [],+ peerPortosVersion: peerPortosVersion || null,+ peerSchemaVersions: peerSchemaVersions || null,+ };+ sub.updatedAt = now;+ await writeState(state);+ });+ peerSyncEvents.emit('subscription-blocked', { subId });+}++async function clearSchemaVersionBlock(subId) {+ await withStateLock(async () => {+ const state = await readState();+ const sub = state.subscriptions.find((s) => s.id === subId);+ if (!sub || !sub.blockedBySchema) return;+ delete sub.blockedBySchema;+ sub.updatedAt = new Date().toISOString();+ await writeState(state);+ });+ peerSyncEvents.emit('subscription-unblocked', { subId });+}+async function buildPushPayload(sub, sourceInstanceId) {+ const portosMeta = await buildPortosMeta();if (sub.recordKind === 'universe') {const record = await getUniverse(sub.recordId, { includeDeleted: true }).catch(() => null);if (!record) return null;@@ -730,6 +844,7 @@ async function buildPushPayload(sub, sourceInstanceId) {record: sanitized,assetManifest,sourceInstanceId,+ portosMeta,...(linkedCollection ? { linkedCollection } : {}),};}@@ -782,6 +897,7 @@ async function buildPushPayload(sub, sourceInstanceId) {issues: sanitizedIssues,assetManifest,sourceInstanceId,+ portosMeta,...(linkedCollection ? { linkedCollection } : {}),};}@@ -909,13 +1025,16 @@ export async function applyIncomingPush(payload) {if (!isPlainObject(payload)) {throw makeErr('payload must be an object', ERR_VALIDATION);}- const { kind, record, issues, linkedCollection, assetManifest, sourceInstanceId } = payload;+ const { kind, record, issues, linkedCollection, assetManifest, sourceInstanceId, portosMeta } = payload;if (!PEER_SUBSCRIBABLE_KINDS.includes(kind)) {throw makeErr(`unknown kind: ${kind}`, ERR_VALIDATION);}- // sourceInstanceId is the key we hang the per-peer tombstone cursor on;- // empty / "unknown" would poison the cursor table with a synthetic entry- // that never gets cleaned up.+ // Identity + record-shape checks happen BEFORE the schema-version gate.+ // The gate's 409 body includes `receiverSchemaVersions: PORTOS_SCHEMA_VERSIONS`+ // — a (mild) version-fingerprint disclosure — and we don't want to surface+ // it to callers that haven't even identified themselves correctly. Move+ // the cheap shape validation first so unidentified or malformed requests+ // get a clean 400 with no version information.if (!isNonEmptyStr(sourceInstanceId) || sourceInstanceId === UNKNOWN_INSTANCE_ID) {throw makeErr('sourceInstanceId required (and not "unknown")', ERR_VALIDATION);}@@ -923,6 +1042,45 @@ export async function applyIncomingPush(payload) {throw makeErr('record must be an object with a string id', ERR_VALIDATION);}+ // SCHEMA-VERSION GATE — runs BEFORE any merge so a sender on a newer+ // storage layout can't corrupt local state. Legacy senders without+ // `portosMeta` pass through (comparator treats absent as zero/no-contract;+ // their record went through the same v0 → vN sanitizer chain we already+ // run). When the sender is AHEAD on any category, we reject with a+ // structured error the route layer maps to HTTP 409 + body so the sender+ // can persist the gap on the subscription and surface it in the UI.+ //+ // We do NOT reject on "sender behind" here — the sanitizer's existing+ // backfill chain handles older inputs in-place. A future forward-only+ // contract (e.g. a required field that the sanitizer can't synthesize)+ // can opt into a behind-gate; the comparator already surfaces both+ // directions for that purpose.+ const senderSchemaVersions = isPlainObject(portosMeta?.schemaVersions) ? portosMeta.schemaVersions : {};+ const senderPortosVersion = typeof portosMeta?.portosVersion === 'string' ? portosMeta.portosVersion : null;+ const versionDiff = compareSchemaVersions(senderSchemaVersions, PORTOS_SCHEMA_VERSIONS);+ // Tombstone payloads carry only id+deleted+deletedAt+updatedAt — fields+ // that exist at EVERY schema version and cannot corrupt local state. Gating+ // them on the schema-version comparator would strand federated deletes+ // whenever any peer upgrades faster than another (sender writes+ // blockedBySchema → edit-triggered pushes go into cooldown → delete never+ // reaches receivers until both peers reconnect AND the receiver upgrades).+ // Exempt tombstones from the gate so soft-deletes always converge.+ if (versionDiff.ahead.length > 0 && record.deleted !== true) {+ console.warn(+ `⚠️ peerSync: rejecting push from ${sourceInstanceId} — ${formatVersionGap(versionDiff)} (sender PortOS ${senderPortosVersion || 'unknown'})`,+ );+ throw makeErr(+ `sender's schema is ahead — receiver cannot apply (${formatVersionGap(versionDiff)})`,+ ERR_SCHEMA_VERSION_AHEAD,+ {+ ahead: versionDiff.ahead,+ behind: versionDiff.behind,+ senderPortosVersion,+ receiverSchemaVersions: PORTOS_SCHEMA_VERSIONS,+ },+ );+ }+// Look up the LOCAL record state BEFORE merging so we can detect the// "local user marked this record ephemeral" case. The merge functions// already silently drop ephemeral records, but the side effects below@@ -1404,7 +1562,10 @@ export async function retryPendingPushesForPeer(peerId) {// "walked" the sub but never pushed it.let pushed = 0;for (const sub of subs) {- const result = await pushRecordToPeer(sub).catch((err) => {+ // peer:online fired — re-probe schema-blocked subs immediately (peer+ // may have upgraded since the last 409). Edit-triggered pushes still+ // respect the cooldown.+ const result = await pushRecordToPeer(sub, { bypassSchemaCooldown: true }).catch((err) => {console.log(`⚠️ peerSync: retry push failed for ${sub.id}: ${err.message}`);return null;});diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex 6e50efb539..7135f5f5cf 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -1425,4 +1425,215 @@ describe('peerSync', () => {expect(all).toHaveLength(1);});});++ // -------------------------------------------------------------------------+ // SCHEMA-VERSION GATING — sender side (handle 409 / cooldown / clear)+ // + receiver side (reject when sender ahead / pass through legacy + behind)+ // -------------------------------------------------------------------------+ describe('schema-version gating', () => {+ beforeEach(() => {+ // Earlier tests in this file accumulate calls on the merge mocks (the+ // file's outer beforeEach does mockResolvedValue but not mockClear).+ // Clear history so `expect(...).not.toHaveBeenCalled()` reflects only+ // calls made in the current test.+ vi.mocked(mergeUniversesFromSync).mockClear();+ vi.mocked(mergeSeriesFromSync).mockClear();+ vi.mocked(mergeIssuesFromSync).mockClear();+ });++ describe('receiver — applyIncomingPush', () => {+ it('rejects when sender schemaVersions.universes is AHEAD of local code', async () => {+ // Local code is at universes:5 (see server/lib/schemaVersions.js).+ // A push from a sender on universes:6 must NOT touch local state.+ await expect(applyIncomingPush({+ kind: 'universe',+ record: { id: 'u1', name: 'Foo' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ portosMeta: { portosVersion: '99.0.0', schemaVersions: { universes: 6 } },+ })).rejects.toMatchObject({+ code: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',+ details: {+ ahead: [{ category: 'universes', senderV: 6, receiverV: 5 }],+ senderPortosVersion: '99.0.0',+ },+ });+ // mergeUniversesFromSync MUST NOT have been called — the gate runs+ // before the merge dispatch.+ expect(mergeUniversesFromSync).not.toHaveBeenCalled();+ });++ it('passes through when sender schemaVersions are EQUAL to local', async () => {+ await applyIncomingPush({+ kind: 'universe',+ record: { id: 'u1', name: 'Foo' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ portosMeta: { portosVersion: '2.7.0', schemaVersions: { universes: 5 } },+ });+ expect(mergeUniversesFromSync).toHaveBeenCalledWith([+ expect.objectContaining({ id: 'u1' }),+ ]);+ });++ it('passes through when sender is BEHIND local (sanitizer handles the backfill)', async () => {+ // Older peer pushes a v4-shape universe. Receiver is on v5 but the+ // record-shape sanitizer can backfill, so we apply rather than reject.+ await applyIncomingPush({+ kind: 'universe',+ record: { id: 'u1', name: 'Foo' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ portosMeta: { portosVersion: '2.6.0', schemaVersions: { universes: 4 } },+ });+ expect(mergeUniversesFromSync).toHaveBeenCalledWith([+ expect.objectContaining({ id: 'u1' }),+ ]);+ });++ it('passes through legacy peers that send NO portosMeta at all', async () => {+ // Backwards compat — pre-this-PR peers don't know to include the+ // envelope. The comparator treats absent sender versions as 0, which+ // either matches (receiver also 0 for the category) or surfaces as+ // "behind" (which we DON'T gate on).+ await applyIncomingPush({+ kind: 'universe',+ record: { id: 'u1', name: 'Foo' },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(mergeUniversesFromSync).toHaveBeenCalled();+ });+ });++ describe('sender — pushRecordToPeer', () => {+ it('stamps portosMeta on the outbound push payload', async () => {+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });+ vi.mocked(peerFetch).mockResolvedValue({ ok: true, json: async () => ({}) });+ await pushRecordToPeer({+ id: 's-meta', peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',+ });+ const call = vi.mocked(peerFetch).mock.calls.at(-1);+ expect(call).toBeDefined();+ const body = JSON.parse(call[1].body);+ expect(body.portosMeta).toBeDefined();+ expect(body.portosMeta.schemaVersions.universes).toBe(5);+ expect(typeof body.portosMeta.portosVersion).toBe('string');+ });++ it('records a blockedBySchema marker on the subscription when the peer responds 409', async () => {+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });+ // Receiver claims it's on universes:4 + PortOS 2.5.0; sender is at 5.+ vi.mocked(peerFetch).mockResolvedValue({+ ok: false,+ status: 409,+ json: async () => ({+ error: 'sender schema is ahead',+ code: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',+ context: {+ details: {+ ahead: [{ category: 'universes', senderV: 5, receiverV: 4 }],+ behind: [],+ senderPortosVersion: '2.5.0',+ receiverSchemaVersions: { universes: 4 },+ },+ },+ }),+ });+ // Subscribe first so we have a sub record to assert against.+ const sub = await subscribePeer({+ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',+ }, { adoptedFromReverse: true });+ const result = await pushRecordToPeer(sub);+ expect(result.pushed).toBe(false);+ expect(result.reason).toBe('peer-schema-behind');+ expect(result.blockedBySchema).toBe(true);+ // Block persisted on the subscription.+ const after = await findPeerSubscription('peer-a', 'universe', 'u1');+ expect(after.blockedBySchema).toBeDefined();+ expect(after.blockedBySchema.ahead).toEqual([{ category: 'universes', senderV: 5, receiverV: 4 }]);+ expect(after.blockedBySchema.peerPortosVersion).toBe('2.5.0');+ expect(typeof after.blockedBySchema.detectedAt).toBe('string');+ // lastPushedHash must NOT have advanced — the record didn't land.+ expect(after.lastPushedHash).toBeFalsy();+ });++ it('short-circuits subsequent pushes for blocked subs within the cooldown window', async () => {+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });+ // First push gets the 409.+ vi.mocked(peerFetch).mockResolvedValue({+ ok: false,+ status: 409,+ json: async () => ({+ code: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',+ context: {+ details: {+ ahead: [{ category: 'universes', senderV: 5, receiverV: 4 }],+ senderPortosVersion: '2.5.0',+ },+ },+ }),+ });+ const sub = await subscribePeer({+ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',+ }, { adoptedFromReverse: true });+ await pushRecordToPeer(sub);+ const fetchCallsAfterFirst = vi.mocked(peerFetch).mock.calls.length;+ // Re-load the sub with the persisted block, then push again with NO+ // bypass — should not hit the network.+ const blocked = await findPeerSubscription('peer-a', 'universe', 'u1');+ const result = await pushRecordToPeer(blocked);+ expect(result.pushed).toBe(false);+ expect(result.reason).toBe('peer-schema-behind-cooldown');+ expect(vi.mocked(peerFetch).mock.calls.length).toBe(fetchCallsAfterFirst);+ });++ it('bypassSchemaCooldown=true re-probes regardless of recent block', async () => {+ // Simulates the peer:online path: retryPendingPushesForPeer passes+ // bypassSchemaCooldown so the next probe actually hits the wire even+ // if a recent 409 set the cooldown.+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });+ vi.mocked(peerFetch).mockResolvedValue({+ ok: false, status: 409,+ json: async () => ({+ code: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',+ context: { details: { ahead: [{ category: 'universes', senderV: 5, receiverV: 4 }] } },+ }),+ });+ const sub = await subscribePeer({+ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',+ }, { adoptedFromReverse: true });+ await pushRecordToPeer(sub);+ const callsAfterFirst = vi.mocked(peerFetch).mock.calls.length;+ const blocked = await findPeerSubscription('peer-a', 'universe', 'u1');+ await pushRecordToPeer(blocked, { bypassSchemaCooldown: true });+ expect(vi.mocked(peerFetch).mock.calls.length).toBe(callsAfterFirst + 1);+ });++ it('clears blockedBySchema once a subsequent push succeeds (peer upgraded)', async () => {+ vi.mocked(getUniverse).mockResolvedValue({ id: 'u1', name: 'Foo' });+ // First push: 409.+ vi.mocked(peerFetch).mockResolvedValueOnce({+ ok: false, status: 409,+ json: async () => ({+ code: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',+ context: { details: { ahead: [{ category: 'universes', senderV: 5, receiverV: 4 }], senderPortosVersion: '2.5.0' } },+ }),+ });+ // Second push: peer upgraded, accepts.+ vi.mocked(peerFetch).mockResolvedValueOnce({ ok: true, json: async () => ({}) });+ const sub = await subscribePeer({+ peerId: 'peer-a', recordKind: 'universe', recordId: 'u1',+ }, { adoptedFromReverse: true });+ await pushRecordToPeer(sub);+ expect((await findPeerSubscription('peer-a', 'universe', 'u1')).blockedBySchema).toBeDefined();+ // Bypass cooldown to simulate a peer:online retry.+ const blocked = await findPeerSubscription('peer-a', 'universe', 'u1');+ await pushRecordToPeer(blocked, { bypassSchemaCooldown: true });+ const cleared = await findPeerSubscription('peer-a', 'universe', 'u1');+ expect(cleared.blockedBySchema).toBeUndefined();+ expect(cleared.lastPushedHash).toBeTruthy(); // succeeded → hash recorded+ });+ });+ });});diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.jsindex 0be867d4e6..b19616883d 100644--- a/server/services/syncOrchestrator.js+++ b/server/services/syncOrchestrator.js@@ -11,7 +11,7 @@ import { join } from 'path';import { readJSONFile, ensureDir, PATHS, dataPath, atomicWrite } from '../lib/fileUtils.js';import { createMutex } from '../lib/asyncMutex.js';import { instanceEvents } from './instanceEvents.js';-import { getPeers, DEFAULT_SYNC_CATEGORIES } from './instances.js';+import { getPeers, DEFAULT_SYNC_CATEGORIES, updatePeer } from './instances.js';import { peerBaseUrl } from '../lib/peerUrl.js';import * as brainSync from './brainSync.js';import * as brainSyncLog from './brainSyncLog.js';@@ -262,16 +262,83 @@ async function syncDataCategoryFromPeer(peer, peerId, category, cachedChecksums)const snapshot = await fetchPeer(peer, `/api/sync/${category}/snapshot`);if (!snapshot?.data) return { totalApplied: 0, checksum: null };- const result = await dataSync.applyRemote(category, snapshot.data);+ // Forward the sender's portosMeta envelope so applyRemote can run the+ // schema-version gate BEFORE merging. A blocked-by-schema result returns+ // applied=false + the diff payload — we persist the gap on the peer record+ // (instances.json) so the Instances UI surfaces "Peer X is on PortOS vN,+ // can't sync universes" and the user knows what to do.+ const result = await dataSync.applyRemote(category, snapshot.data, {+ portosMeta: snapshot.portosMeta,+ });+ if (result.blockedBySchema) {+ await recordPeerSchemaGap(peerId, category, result.blockedBySchema)+ .catch((err) => console.log(`⚠️ syncOrchestrator: persist schema gap failed: ${err.message}`));+ // Don't advance the cached checksum — when the user upgrades, the+ // category will look "changed" again and we'll re-try the apply.+ return { totalApplied: 0, checksum: null, blockedBySchema: result.blockedBySchema };+ }// After character sync, fetch avatar image if we don't have it locallyif (category === 'character' && snapshot.data?.avatarPath) {await syncImageFromPeer(peer, snapshot.data.avatarPath);}+ // Clear any prior schema-version gap on this (peer, category) — sender+ // either upgraded or the older check was transient. Best-effort; failures+ // don't fail the apply (we already merged successfully).+ await clearPeerSchemaGap(peerId, category)+ .catch((err) => console.log(`⚠️ syncOrchestrator: clear schema gap failed: ${err.message}`));+return { totalApplied: result.applied ? result.count : 0, checksum: snapshot.checksum };}+/**+ * Persist a per-(peer, category) schema-version gap on the peer record.+ * Stored under `peer.schemaGaps[category]` as `{ detectedAt, ahead, behind,+ * senderPortosVersion }`. The Instances UI reads it to render a "Peer is+ * on PortOS vN, you can't sync universes until they upgrade" badge.+ *+ * NOTE: a future PR will move this to a dedicated peer-status file so+ * peers.json stays a pure config surface. For now we co-locate on the peer+ * record because that's the entity the Instances page already renders.+ */+// Look up the local peer row by remote instanceId (the only id we have at+// the orchestrator level) and resolve to the LOCAL `peer.id` that updatePeer+// keys by. Passing `peer.instanceId` straight to updatePeer would silently+// return null because instances.js matches on `p.id === id`.+async function recordPeerSchemaGap(peerId, category, gap) {+ const peers = await getPeers().catch(() => []);+ const peer = peers.find((p) => p.instanceId === peerId);+ if (!peer) return;+ const existingGaps = isPlainObjectShallow(peer.schemaGaps) ? peer.schemaGaps : {};+ await updatePeer(peer.id, {+ schemaGaps: {+ ...existingGaps,+ [category]: {+ detectedAt: new Date().toISOString(),+ ahead: Array.isArray(gap.ahead) ? gap.ahead : [],+ behind: Array.isArray(gap.behind) ? gap.behind : [],+ senderPortosVersion: typeof gap.senderPortosVersion === 'string' ? gap.senderPortosVersion : null,+ },+ },+ });+}++async function clearPeerSchemaGap(peerId, category) {+ const peers = await getPeers().catch(() => []);+ const peer = peers.find((p) => p.instanceId === peerId);+ if (!peer) return;+ const existingGaps = isPlainObjectShallow(peer.schemaGaps) ? peer.schemaGaps : null;+ if (!existingGaps || !(category in existingGaps)) return;+ const next = { ...existingGaps };+ delete next[category];+ await updatePeer(peer.id, {+ schemaGaps: Object.keys(next).length > 0 ? next : null,+ });+}++const isPlainObjectShallow = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);+/*** For a given peerId, return the set of `dataSync` category names whose* underlying record kind has at least one active peer subscription. Used bydiff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 668519c608..9a1150e819 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -27,8 +27,8 @@import { join, basename } from 'path';import { randomUUID } from 'crypto';-import { PATHS, atomicWrite, readJSONFile, ensureDir, resolveImageRef } from '../lib/fileUtils.js';-import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { PATHS, atomicWrite, ensureDir, resolveImageRef } from '../lib/fileUtils.js';+import { createCollectionStore } from '../lib/collectionStore.js';import { composeStyledPrompt } from '../lib/composeStyledPrompt.js';import { flattenCanonDescriptorFragments, richCanonDescriptorFragments } from '../lib/canonPrompt.js';import {@@ -44,8 +44,9 @@ import {clearPendingSheetSlot, clearPendingSheetSlotsForUniverse,} from './universeCharacterSheetSlot.js';-// Bumped when a sanitizer-time backfill changes how on-disk universes are-// shaped, so future migrations can gate on the prior version.+// RECORD-shape schema version, stamped INSIDE each universe record. Distinct+// from the type-level (storage layout) schemaVersion carried by+// `data/universes/index.json` — see `server/lib/collectionStore.js` header.// v3 — drop prose stylePrompt/negativePrompt fields; legacy values are// split on commas and merged into influences.embrace / influences.avoid// so there is a single token-list editing surface.@@ -55,17 +56,38 @@ import {// characters[]. See "Categories vs canon — decision" in PLAN.md.export const CURRENT_SCHEMA_VERSION = 4;-// Lazy state-path resolution so test harnesses that swap PATHS.data-// per-test (mkdtempSync + Proxy mock) see the right temp root. Computing-// the path at module-load freezes whatever value PATHS.data held when-// universeBuilder.js was first imported, which is `undefined` under the-// proxy-mock pattern series.js's tests already use.-const statePath = () => join(PATHS.data, 'universe-builder.json');+// TYPE-level (storage layout) schema version stamped on `data/universes/index.json`.+// v5 — universes split out of monolithic `data/universe-builder.json` into+// per-record `data/universes/{id}/index.json`. Cross-record `runs[]`+// moves into `index.json`'s `config.runs`. See migration 034.+const TYPE_SCHEMA_VERSION = 5;++// Lazy store factory so test harnesses that swap PATHS.data per-test+// (mkdtempSync + Proxy mock) still see the right temp root — the store+// captures PATHS.data once at first call, then stays warm.+let _store = null;+const store = () => {+ if (_store && _store.dir === join(PATHS.data, 'universes')) return _store;+ _store = createCollectionStore({+ dir: join(PATHS.data, 'universes'),+ type: 'universes',+ schemaVersion: TYPE_SCHEMA_VERSION,+ sanitizeRecord: sanitizeTemplate,+ // Permissive — defense-in-depth against stray non-id entries from+ // readdir, not an authoritative validator. The 8–80 / dash-only rule+ // lives on UNIVERSE_ID_RE inside insertUniverseWithId, which is where+ // user-supplied ids actually arrive.+ idPattern: /^[A-Za-z0-9_-]{1,128}$/,+ });+ return _store;+};-// Serializes every mutating call (create / update / delete / recordRun)-// against the shared universe-builder.json so concurrent writes — even to-// different universe ids — can't read a stale snapshot and clobber a sibling.-const queueUniverseWrite = createFileWriteQueue();+/**+ * Exported for the boot-time verifier in `server/index.js`. Lazy because the+ * universe-builder module loads BEFORE PATHS.data resolves in some test+ * harnesses; calling this getter at boot time picks up the right root.+ */+export const universeStore = () => store();export const ERR_NOT_FOUND = 'NOT_FOUND';export const ERR_VALIDATION = 'VALIDATION_ERROR';@@ -205,8 +227,6 @@ const CATEGORY_TO_CANON = Object.freeze({const resolveCanonForCategory = (categoryKey) =>CATEGORY_TO_CANON[categoryKey] || { kind: BIBLE_KIND.OBJECT, tags: [categoryKey] };-const DEFAULT_STATE = { universes: [], runs: [] };-// Case-insensitive key for matching variation/composite labels across the// original + LLM-refined sets. Returning the same lowercase string ensures// "Lollipop Bureau" and "lollipop bureau" collapse to one identity.@@ -785,15 +805,27 @@ let canonBackfillLogged = false;async function readState() {await ensureDir(PATHS.data);- const raw = await readJSONFile(statePath(), DEFAULT_STATE, { logError: false });- const rawById = new Map(Array.isArray(raw.universes) ? raw.universes.filter((u) => u?.id).map((u) => [u.id, u]) : []);- const universes = Array.isArray(raw.universes) ? raw.universes.map(sanitizeTemplate).filter(Boolean) : [];- const runs = Array.isArray(raw.runs) ? raw.runs.map(sanitizeRun).filter(Boolean) : [];+ const s = store();+ // Load raw records in parallel (no sanitizer) so we can detect schema-+ // version drift before the in-memory sanitization step. We deliberately+ // do NOT use store.loadAll() here — that runs sanitizeRecord, losing the+ // pre-sanitized schemaVersion needed for the backfill log.+ const ids = await s.listIds();+ const rawRecords = await Promise.all(ids.map((id) => s.loadOneRaw(id)));+ const rawById = new Map();+ for (const r of rawRecords) {+ if (r && typeof r.id === 'string') rawById.set(r.id, r);+ }+ const universes = rawRecords.map((r) => sanitizeTemplate(r)).filter(Boolean);+ const typeIndex = await s.loadTypeIndex();+ const runs = Array.isArray(typeIndex.config?.runs)+ ? typeIndex.config.runs.map(sanitizeRun).filter(Boolean)+ : [];// The in-memory result is always at CURRENT_SCHEMA_VERSION (sanitizeTemplate- // re-stamps it on every read). Don't persist the migration here — that write- // would race against any concurrent queued mutator's writeState and could+ // re-stamps it on every read). Don't persist the migration here — that+ // write would race against any concurrent per-record mutator and could// overwrite a freshly-patched record with the pre-patch migration baseline.- // The next queued mutator persists the migrated shape naturally.+ // The next per-record write persists the migrated shape naturally.if (!canonBackfillLogged) {const migrated = universes.filter((u) => (rawById.get(u.id)?.schemaVersion || 0) < CURRENT_SCHEMA_VERSION);if (migrated.length > 0) {@@ -804,10 +836,6 @@ async function readState() {return { universes, runs };}-async function writeState(state) {- await atomicWrite(statePath(), state);-}-export async function listUniverses({ includeDeleted = false } = {}) {const { universes } = await readState();const filtered = includeDeleted ? universes : universes.filter((u) => !u.deleted);@@ -816,8 +844,10 @@ export async function listUniverses({ includeDeleted = false } = {}) {}export async function getUniverse(id, { includeDeleted = false } = {}) {- const { universes } = await readState();- const w = universes.find((x) => x.id === id);+ // Direct per-record load — no full collection scan needed for a by-id read.+ // The store's sanitizer (sanitizeTemplate) runs on the loaded record, so the+ // returned object is shape-equivalent to what listUniverses would surface.+ const w = await store().loadOne(id);if (!w) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);if (w.deleted && !includeDeleted) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);return w;@@ -833,9 +863,9 @@ export async function getUniverse(id, { includeDeleted = false } = {}) {// avoiding unwanted `updatedAt` bumps that would otherwise interfere with// LWW sync and trigger spurious re-export/notification emits.export async function needsEntryIdPersist(id) {- await ensureDir(PATHS.data);- const raw = await readJSONFile(statePath(), DEFAULT_STATE, { logError: false });- const rec = Array.isArray(raw.universes) ? raw.universes.find((u) => u?.id === id) : null;+ // Raw read (no sanitizer) so we inspect the on-disk shape, not the+ // freshly-minted ids the sanitizer would stamp in-memory.+ const rec = await store().loadOneRaw(id);if (!rec || rec.deleted) return false;const cats = rec.categories && typeof rec.categories === 'object' ? rec.categories : {};for (const cat of Object.values(cats)) {@@ -854,11 +884,11 @@ export async function needsEntryIdPersist(id) {export async function createUniverse(input = {}) {const name = trimTo(input.name, NAME_MAX_LENGTH);if (!name) throw makeErr(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);- const created = await queueUniverseWrite(async () => {- const state = await readState();+ const id = randomUUID();+ const created = await store().queueRecordWrite(id, async () => {const now = new Date().toISOString();const next = sanitizeTemplate({- id: randomUUID(),+ id,name,starterPrompt: input.starterPrompt || '',stylePrompt: input.stylePrompt || '',@@ -892,8 +922,10 @@ export async function createUniverse(input = {}) {// sanitizeRecordForWire) and the auto-subscribe below short-circuits.ephemeral: input.ephemeral === true,});- state.universes.push(next);- await writeState(state);+ // Write through the store — we're inside the per-id queue so use+ // atomicWrite directly to avoid re-queueing on the same id.+ await ensureDir(store().recordDir(next.id));+ await atomicWrite(store().recordPath(next.id), next);return next;});// Fire-and-forget auto-subscribe to every peer with universe-sync enabled.@@ -925,27 +957,25 @@ export async function insertUniverseWithId(input = {}) {}const name = trimTo(input.name, NAME_MAX_LENGTH);if (!name) throw makeErr(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);- return queueUniverseWrite(async () => {- const state = await readState();+ const s = store();+ return s.queueRecordWrite(input.id, async () => {// Tombstone-overwrite: a previously-deleted record with the same id is// overwritten (effectively undeleted) — this keeps the share-bucket// re-import flow idempotent (deleting then re-importing the same manifest// restores the universe rather than 409ing). The peer-sync resurrection// hazard is already prevented by `mergeUniversesFromSync`'s LWW check,// which is the transport the federation uses.- const existingIdx = state.universes.findIndex((u) => u.id === input.id);- if (existingIdx >= 0 && !state.universes[existingIdx].deleted) {+ const existing = await s.loadOne(input.id);+ if (existing && !existing.deleted) {throw makeErr(`Universe id already exists: ${input.id}`, ERR_DUPLICATE);}const next = sanitizeTemplate({ ...input, name });if (!next) throw makeErr('Invalid universe payload', ERR_VALIDATION);- if (existingIdx >= 0) {+ if (existing) {console.warn(`♻️ insertUniverseWithId: overwriting tombstone for ${input.id}`);- state.universes[existingIdx] = next;- } else {- state.universes.push(next);}- await writeState(state);+ await ensureDir(s.recordDir(next.id));+ await atomicWrite(s.recordPath(next.id), next);return next;});}@@ -965,11 +995,10 @@ export async function updateUniverse(id, patchOrMutator = {}) {// unchanged record (no `updatedAt` bump, no rename cascade, no// `recordUpdated` emit).const isMutator = typeof patchOrMutator === 'function';- const { merged, nameChanged, skipped, removedCharacterIds, prevEphemeral, nextEphemeral } = await queueUniverseWrite(async () => {- const state = await readState();- const idx = state.universes.findIndex((w) => w.id === id);- if (idx < 0) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);- const cur = state.universes[idx];+ const s = store();+ const { merged, nameChanged, skipped, removedCharacterIds, prevEphemeral, nextEphemeral } = await s.queueRecordWrite(id, async () => {+ const cur = await s.loadOne(id);+ if (!cur) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);if (cur.deleted) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);let patch;@@ -1125,8 +1154,8 @@ export async function updateUniverse(id, patchOrMutator = {}) {if (Array.isArray(mergedRecord.characters)) {mergedRecord.characters = pruneStaleReferenceSheets(mergedRecord.characters);}- state.universes[idx] = mergedRecord;- await writeState(state);+ await ensureDir(s.recordDir(id));+ await atomicWrite(s.recordPath(id), mergedRecord);// Diff inside the queue so we read against the freshest merged state;// gate on patches that could have touched characters (mutator or// literal-PATCH carrying `characters`) — rename/scalar PATCHes are the@@ -1211,17 +1240,35 @@ export async function deleteUniverse(id) {// unlink media collections, clear sheet slots. These cascades also run on// the receiving peer when a soft-delete arrives via mergeUniversesFromSync// so a synced delete doesn't leave orphan media-collection locks.- await queueUniverseWrite(async () => {- const state = await readState();- const idx = state.universes.findIndex((w) => w.id === id);- if (idx < 0) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);- const cur = state.universes[idx];+ const s = store();+ await s.queueRecordWrite(id, async () => {+ const cur = await s.loadOne(id);+ if (!cur) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);if (cur.deleted) throw makeErr(`Universe not found: ${id}`, ERR_NOT_FOUND);const now = new Date().toISOString();- state.universes[idx] = { ...cur, deleted: true, deletedAt: now, updatedAt: now };- // Drop runs referencing the deleted universe — they're useless without it.- state.runs = state.runs.filter((r) => r.universeId !== id);- await writeState(state);+ const tombstone = { ...cur, deleted: true, deletedAt: now, updatedAt: now };+ await ensureDir(s.recordDir(id));+ await atomicWrite(s.recordPath(id), tombstone);+ });+ // Drop runs referencing the deleted universe — they're useless without it.+ // CRITICAL: the load + filter + write MUST run inside queueTypeIndexWrite as a+ // single critical section. An earlier version did the load OUTSIDE the queue+ // and then saveTypeIndex inside it — saveTypeIndex's shallow merge then+ // wholesale-replaced `config.runs` with the stale filtered snapshot,+ // silently dropping any recordRun that landed between the outer load and+ // the queued write. Stay inside the queue and use atomicWrite directly+ // (saveTypeIndex would self-re-queue and deadlock).+ await s.queueTypeIndexWrite(async () => {+ const typeIndex = await s.loadTypeIndex();+ const filteredRuns = (typeIndex.config?.runs || []).filter((r) => r.universeId !== id);+ const next = {+ schemaVersion: typeIndex.schemaVersion,+ type: typeIndex.type,+ config: { ...(typeIndex.config || {}), runs: filteredRuns },+ updatedAt: new Date().toISOString(),+ };+ await ensureDir(s.dir);+ await atomicWrite(s.typeIndexPath(), next);});// Release the rename-lock on any linked media collections — without this,// the orphan collection's `universeId` stays stamped and the lock in@@ -1254,9 +1301,9 @@ async function cascadeDeleteSideEffects(id) {/*** Sync-orchestrator entry point. Merges a remote peer's universe array into- * local state INSIDE `queueUniverseWrite`, so the read-modify-write window- * can't clobber (or be clobbered by) a concurrent local LLM auto-save,- * promote-variation, or handleSave running through the same queue.+ * local state INSIDE the store's per-id write queue, so each remote record's+ * read-modify-write can't clobber (or be clobbered by) a concurrent local LLM+ * auto-save, promote-variation, or handleSave on the same universe id.** Each incoming remote record passes through `sanitizeTemplate` so older-* schema payloads (pre-v4 universes missing `kind`, prose stylePrompt/@@ -1282,64 +1329,78 @@ export async function mergeUniversesFromSync(remoteUniverses) {// per-record peer-sync push pipeline will own the "edit arrived from// peer" emit so subscribers fire exactly once per actual edit.const transitionedToDeleted = [];- const result = await queueUniverseWrite(async () => {- const state = await readState();- const localById = new Map(state.universes.map((u) => [u.id, u]));- let changed = 0;- for (const remote of remoteUniverses) {- if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;- const sanitized = sanitizeTemplate(remote);- if (!sanitized) continue;- // `ephemeral` is a LOCAL-only marker — never trust the inbound value.- // sanitizeTemplate only persists a literal `{ ephemeral: true }` (any- // other value gets dropped at the sanitizer); strip even that here so- // a buggy/older/non-conformant peer (or the share-bucket importer's- // mutator-form path) can't plant a "dark" record on us that's- // permanently un-syncable. The on-disk-only contract is enforced on- // the receive boundary.- if ('ephemeral' in sanitized) delete sanitized.ephemeral;- const local = localById.get(sanitized.id);+ const s = store();+ // Each remote runs through its own per-id queue. The LWW check sits INSIDE+ // each queued write so a concurrent updateUniverse on the same id can't+ // sneak in between the LWW comparison and the write. Different ids fan out+ // in parallel — the scalability win vs. the old single-tail queue.+ let changed = 0;+ const writeTasks = [];+ for (const remote of remoteUniverses) {+ if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;+ const sanitized = sanitizeTemplate(remote);+ if (!sanitized) continue;+ // `ephemeral` is a LOCAL-only marker — never trust the inbound value.+ // sanitizeTemplate only persists a literal `{ ephemeral: true }` (any+ // other value gets dropped at the sanitizer); strip even that here so+ // a buggy/older/non-conformant peer (or the share-bucket importer's+ // mutator-form path) can't plant a "dark" record on us that's+ // permanently un-syncable. The on-disk-only contract is enforced on+ // the receive boundary.+ if ('ephemeral' in sanitized) delete sanitized.ephemeral;+ writeTasks.push(s.queueRecordWrite(sanitized.id, async () => {+ const local = await s.loadOne(sanitized.id);if (!local) {// No local counterpart — accept the record (live OR tombstone) but// do NOT cascade orphan-cleanup. A tombstone for a record we never- // had has nothing to clean up; firing `emitRecordDeleted` would spuriously- // tear down share-bucket subscriptions looking for a manifest that- // never existed.- localById.set(sanitized.id, sanitized);- changed++;- } else if (local.ephemeral === true) {+ // had has nothing to clean up; firing `emitRecordDeleted` would+ // spuriously tear down share-bucket subscriptions.+ await ensureDir(s.recordDir(sanitized.id));+ await atomicWrite(s.recordPath(sanitized.id), sanitized);+ changed += 1;+ return;+ }+ if (local.ephemeral === true) {// Local-ephemeral records are IMMUNE to inbound merges. The user// explicitly marked this record local-only — peer edits can't// overwrite its content, peer deletes can't trigger our orphan// cascade, and the post-merge asset-pull worker never gets the- // chance to download bytes for it. The sender may still have a- // reverse subscription on their side; we silently drop the push.- // Pre-ephemeral subs on OUR side are torn down by the- // updateUniverse PATCH transition (see "ephemeral lifecycle" wiring)- // so this branch should only fire for cross-peer fan-out or- // share-bucket import paths.- continue;- } else {- const localTs = local.updatedAt || '';- const remoteTs = sanitized.updatedAt || '';- if (remoteTs > localTs) {- localById.set(sanitized.id, sanitized);- if (sanitized.deleted && !local.deleted) transitionedToDeleted.push(sanitized.id);- changed++;- }+ // chance to download bytes for it.+ return;}- }- if (changed === 0) return { applied: false, count: 0 };- // Drop runs for any record that just transitioned to deleted — matches- // the local-delete contract that ditches now-orphan runs.- if (transitionedToDeleted.length) {- const tombstoned = new Set(transitionedToDeleted);- state.runs = state.runs.filter((r) => !tombstoned.has(r.universeId));- }- state.universes = Array.from(localById.values());- await writeState(state);- return { applied: true, count: changed };- });+ const localTs = local.updatedAt || '';+ const remoteTs = sanitized.updatedAt || '';+ if (remoteTs > localTs) {+ await ensureDir(s.recordDir(sanitized.id));+ await atomicWrite(s.recordPath(sanitized.id), sanitized);+ if (sanitized.deleted && !local.deleted) transitionedToDeleted.push(sanitized.id);+ changed += 1;+ }+ }));+ }+ await Promise.all(writeTasks);+ if (changed === 0) return { applied: false, count: 0 };+ // Drop runs for any record that just transitioned to deleted — matches+ // the local-delete contract that ditches now-orphan runs. Same critical-+ // section requirement as deleteUniverse: load + filter + write all stay+ // inside queueTypeIndexWrite so a concurrent recordRun doesn't get its+ // newly-appended run overwritten by a stale filtered snapshot.+ if (transitionedToDeleted.length) {+ const tombstoned = new Set(transitionedToDeleted);+ await s.queueTypeIndexWrite(async () => {+ const typeIndex = await s.loadTypeIndex();+ const filtered = (typeIndex.config?.runs || []).filter((r) => !tombstoned.has(r.universeId));+ const next = {+ schemaVersion: typeIndex.schemaVersion,+ type: typeIndex.type,+ config: { ...(typeIndex.config || {}), runs: filtered },+ updatedAt: new Date().toISOString(),+ };+ await ensureDir(s.dir);+ await atomicWrite(s.typeIndexPath(), next);+ });+ }+ const result = { applied: true, count: changed };// Fire cascades after the queue releases (mirrors deleteUniverse ordering)// so a slow media-collections write can't block other universe mutators.for (const id of transitionedToDeleted) {@@ -1359,36 +1420,74 @@ export async function mergeUniversesFromSync(remoteUniverses) {*/export async function pruneTombstonedUniverses(beforeMs) {if (!Number.isFinite(beforeMs)) return { pruned: 0 };- return queueUniverseWrite(async () => {- const state = await readState();- const original = state.universes.length;- state.universes = state.universes.filter((u) => {- if (!u?.deleted) return true;- const t = Date.parse(u.deletedAt || '');- if (!Number.isFinite(t)) return true;- return t >= beforeMs;- });- const pruned = original - state.universes.length;- if (pruned > 0) await writeState(state);- return { pruned };- });+ const s = store();+ const ids = await s.listIds();+ const records = await Promise.all(ids.map((id) => s.loadOne(id)));+ const candidates = [];+ for (const u of records) {+ if (!u?.deleted) continue;+ const t = Date.parse(u.deletedAt || '');+ if (!Number.isFinite(t)) continue;+ if (t < beforeMs) candidates.push(u.id);+ }+ // Per-id deletes fan out, but we re-check the tombstone status INSIDE each+ // per-id queue. A concurrent mergeUniversesFromSync could have un-deleted+ // the record (newer remote `updatedAt`, `deleted: false`) between our+ // out-of-queue snapshot read and the queued delete; without the re-check,+ // we'd rm -rf a freshly un-deleted record. Counts only the records we+ // actually pruned (the candidates set minus any rescued by a concurrent+ // un-delete).+ const results = await Promise.allSettled(candidates.map((id) =>+ s.queueRecordWrite(id, async () => {+ const fresh = await s.loadOne(id);+ if (!fresh?.deleted) return false; // un-deleted between snapshot and queue+ const t = Date.parse(fresh.deletedAt || '');+ if (!Number.isFinite(t) || t >= beforeMs) return false;+ const { rm } = await import('fs/promises');+ await rm(s.recordDir(id), { recursive: true, force: true });+ return true;+ })+ ));+ let pruned = 0;+ for (const r of results) {+ if (r.status === 'fulfilled' && r.value === true) pruned += 1;+ else if (r.status === 'rejected') console.log(`⚠️ pruneTombstonedUniverses: delete failed: ${r.reason?.message || r.reason}`);+ }+ return { pruned };}export async function recordRun(run) {const sanitized = sanitizeRun(run);if (!sanitized) throw makeErr('Invalid run payload', ERR_VALIDATION);- return queueUniverseWrite(async () => {- const state = await readState();- state.runs.push(sanitized);+ const s = store();+ // Type-index queue serializes the runs[] read→append→write so concurrent+ // recordRun + delete-cascade can't clobber each other's runs.+ return s.queueTypeIndexWrite(async () => {+ const typeIndex = await s.loadTypeIndex();+ const runs = Array.isArray(typeIndex.config?.runs) ? [...typeIndex.config.runs] : [];+ runs.push(sanitized);// Keep last 200 runs to bound state growth.- if (state.runs.length > 200) state.runs = state.runs.slice(-200);- await writeState(state);+ const capped = runs.length > 200 ? runs.slice(-200) : runs;+ // saveTypeIndex also queues, but we're already on the type-index queue —+ // write the file directly with atomicWrite to avoid a re-entrant queue.+ const next = {+ schemaVersion: typeIndex.schemaVersion,+ type: typeIndex.type,+ config: { ...(typeIndex.config || {}), runs: capped },+ updatedAt: new Date().toISOString(),+ };+ await ensureDir(s.dir);+ await atomicWrite(s.typeIndexPath(), next);return sanitized;});}export async function listRuns(universeId = null) {- const { runs } = await readState();+ const s = store();+ const typeIndex = await s.loadTypeIndex();+ const runs = Array.isArray(typeIndex.config?.runs)+ ? typeIndex.config.runs.map(sanitizeRun).filter(Boolean)+ : [];const filtered = universeId ? runs.filter((r) => r.universeId === universeId) : runs;return [...filtered].sort((a, b) => (b.createdAt || '').localeCompare(a.createdAt || ''));}diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.jsindex c7eb9a03a8..56398279a2 100644--- a/server/services/universeBuilder.test.js+++ b/server/services/universeBuilder.test.js@@ -1,6 +1,13 @@-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 } from "fs/promises";+import { tmpdir } from "os";+import { join } from "path";-const fileStore = new Map();+// Real per-suite tmpdir backing the universes/ layout. Each test wipes the+// tree in beforeEach. The fileUtils mock below overrides PATHS.data so the+// universeBuilder + collectionStore land here instead of the real ./data.+const TEST_DATA_ROOT = mkdtempSync(join(tmpdir(), "universe-builder-test-"));// Per-test reference-sheet "what exists on disk" — keys are filenames the// referenceSheetImageRef preservation guard / pruner asks about. Default@@ -8,31 +15,57 @@ const fileStore = new Map();// names like 'sheet-B.png' still pass; the stale-prune test overrides// resolveImageRef to return null for the stale filename.const refSheetFilesByName = 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,- ),- // mustExist: true → return a non-null path when the filename either- // appears in refSheetFilesByName or has no explicit "missing" entry.- // Tests opt into "this file is gone" by calling- // refSheetFilesByName.set('foo.png', null).- resolveImageRef: vi.fn((ref) => {- if (typeof ref !== 'string' || !ref) return null;- if (refSheetFilesByName.has(ref)) return refSheetFilesByName.get(ref);- return `/mock/refs/${ref}`;- }),-}));++vi.mock("../lib/fileUtils.js", async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ // Override PATHS.data to point at the test tmpdir; everything else+ // (atomicWrite, readJSONFile, ensureDir, etc.) uses the real impl so+ // collectionStore's readdir/stat/rm operate against a real fs tree.+ PATHS: { ...actual.PATHS, data: TEST_DATA_ROOT },+ // mustExist: true → return a non-null path when the filename either+ // appears in refSheetFilesByName or has no explicit "missing" entry.+ // Tests opt into "this file is gone" by calling+ // refSheetFilesByName.set('foo.png', null).+ resolveImageRef: vi.fn((ref) => {+ if (typeof ref !== 'string' || !ref) return null;+ if (refSheetFilesByName.has(ref)) return refSheetFilesByName.get(ref);+ return `/mock/refs/${ref}`;+ }),+ };+});++// Pre-seed state into the new per-record layout. Mirrors what migration 034+// produces — each universe lands in `universes/<id>/index.json` and the+// cross-record `runs[]` lives in `universes/index.json` under `config.runs`.+async function seedState({ universes = [], runs = [] } = {}) {+ const universesDir = join(TEST_DATA_ROOT, "universes");+ await mkdir(universesDir, { recursive: true });+ for (const u of universes) {+ const recDir = join(universesDir, u.id);+ await mkdir(recDir, { recursive: true });+ await writeFile(join(recDir, "index.json"), JSON.stringify(u, null, 2));+ }+ await writeFile(join(universesDir, "index.json"), JSON.stringify({+ schemaVersion: 5,+ type: "universes",+ updatedAt: new Date().toISOString(),+ config: { runs },+ }, null, 2));+}++afterAll(() => {+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+});let uuidCounter = 0;+// Pad to satisfy UNIVERSE_ID_RE / collectionStore's idPattern (8-80 chars).+// Tests still get a predictable, monotonically increasing id sequence.+const mockUuid = (n) => `uuid-${String(n).padStart(8, '0')}`;vi.mock("crypto", async () => {const actual = await vi.importActual("crypto");- return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };+ return { ...actual, randomUUID: () => mockUuid(++uuidCounter) };});const svc = await import("./universeBuilder.js");@@ -73,8 +106,12 @@ const seedWorld = async (overrides = {}) =>describe("universeBuilder service", () => {beforeEach(() => {- fileStore.clear();+ // Wipe the test tmpdir between tests so each starts with an empty+ // universes/ tree.+ rmSync(TEST_DATA_ROOT, { recursive: true, force: true });+ mkdirSync(TEST_DATA_ROOT, { recursive: true });uuidCounter = 0;+ refSheetFilesByName.clear();});it("listUniverses returns [] for fresh state", async () => {@@ -83,7 +120,7 @@ describe("universeBuilder service", () => {it("createUniverse persists with sanitized categories + kind tags", async () => {const w = await seedWorld();- expect(w.id).toBe("uuid-1");+ expect(w.id).toBe(mockUuid(1));expect(w.name).toBe("Moebius SciFi");// All default categories materialized even when only one was provided,// each tagged with its canon trunk via the WORLD_CATEGORY_DEFAULT_KINDS map.@@ -1617,7 +1654,7 @@ describe("universeBuilder service", () => {describe("categories→canon backfill", () => {it("backfills canon arrays from categories on first read + stamps the current schema version", async () => {- fileStore.set("/mock/data/universe-builder.json", {+ await seedState({universes: [{id: "w-v1", name: "Legacy",@@ -1661,7 +1698,7 @@ describe("universeBuilder service", () => {});it("backfill is idempotent — re-reading an already-migrated universe does not duplicate canon", async () => {- fileStore.set("/mock/data/universe-builder.json", {+ await seedState({universes: [{id: "w-v1", name: "Legacy",@@ -1683,14 +1720,14 @@ describe("universeBuilder service", () => {// Third read post-rename: a user-renamed entry must not be clobbered by// re-running backfill (the schemaVersion guard prevents the re-insert).const renamed = { ...second, characters: second.characters.map((c) => ({ ...c, name: "Alex Smith" })) };- fileStore.set("/mock/data/universe-builder.json", { universes: [renamed], runs: [] });+ await seedState({ universes: [renamed], runs: [] });const third = (await svc.listUniverses())[0];expect(third.characters.length).toBe(1);expect(third.characters[0].name).toBe("Alex Smith");});it("backfill does not overwrite a pre-existing canon entry sharing a variation label", async () => {- fileStore.set("/mock/data/universe-builder.json", {+ await seedState({universes: [{id: "w-mixed", name: "Mixed",@@ -1824,7 +1861,7 @@ describe("universeBuilder service", () => {});it("sanitizeTemplate round-trips existing variation + sheet ids verbatim", async () => {- fileStore.set("/mock/data/universe-builder.json", {+ await seedState({universes: [{id: "w1",@@ -1853,7 +1890,7 @@ describe("universeBuilder service", () => {// is not persisted there (race-safety against concurrent writers — see// readState() docstring). After a no-op updateUniverse() forces a write,// ids land on disk and every subsequent read returns the same ones.- fileStore.set("/mock/data/universe-builder.json", {+ await seedState({universes: [{id: "legacy-universe",@@ -1889,7 +1926,7 @@ describe("universeBuilder service", () => {// universe is already migrated — so already-upgraded records don't// bump updatedAt (which would interfere with LWW sync + spuriously// emit recordUpdated on every render).- fileStore.set("/mock/data/universe-builder.json", {+ await seedState({universes: [{id: "fresh",@@ -2094,7 +2131,7 @@ describe("universeBuilder service", () => {});it("imageRefs basename guard rejects path-separator filenames", async () => {- fileStore.set("/mock/data/universe-builder.json", {+ await seedState({universes: [{id: "w1",@@ -2120,7 +2157,7 @@ describe("universeBuilder service", () => {describe("sanitizers", () => {it("drops malformed variations on read", async () => {// Manually plant invalid state — sanitizeTemplate strips it on read.- fileStore.set("/mock/data/universe-builder.json", {+ await seedState({universes: [{id: "w1",diff --git a/server/services/universeBuilderPromote.test.js b/server/services/universeBuilderPromote.test.jsindex 5b8a2c6dc6..d1295641c6 100644--- a/server/services/universeBuilderPromote.test.js+++ b/server/services/universeBuilderPromote.test.js@@ -1,22 +1,20 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';--// In-memory file store mirrors universeBuilder.test.js / universeCanon.test.js-// so a single readState/writeState path roundtrips through the same code the-// real service uses (no live file I/O).-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)),-}));+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { rmSync, mkdirSync } from 'fs';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';++const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-universe-promote-' });+afterAll(cleanup);++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makeProxy(actual);+});let uuidCounter = 0;+const mockUuid = (n) => `uuid-${String(n).padStart(8, '0')}`;vi.mock('crypto', async () => {const actual = await vi.importActual('crypto');- return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };+ return { ...actual, randomUUID: () => mockUuid(++uuidCounter) };});// Stub the LLM dispatch so tests don't need a live runner. The@@ -64,7 +62,8 @@ const mockLlm = (entry) => {};beforeEach(() => {- fileStore.clear();+ rmSync(tempRoot, { recursive: true, force: true });+ mkdirSync(tempRoot, { recursive: true });uuidCounter = 0;resolveProviderAndModelMock.mockReset();runPromptThroughProviderMock.mockReset();@@ -436,16 +435,27 @@ describe('universeBuilderPromote — atomicity', () => {},});mockLlm({ name: 'Place A', description: 'place a', prompt: 'a' });- const callsBefore = fileUtils.atomicWrite.mock.calls.length;+ // Spy on the real atomicWrite so we can count the writes that this single+ // promote operation triggers. Filter to per-record writes (the universe's+ // index.json) — saveTypeIndex writes that happen elsewhere in the test's+ // setup are excluded.+ const recordIndexPath = `${tempRoot}/universes/${w.id}/index.json`;+ const writeSpy = vi.spyOn(fileUtils, 'atomicWrite');+ const beforeCalls = writeSpy.mock.calls.length;await promoteSvc.promoteVariationToCanon(w.id, {category: 'landscapes',label: 'A',});+ const recordWrites = writeSpy.mock.calls+ .slice(beforeCalls)+ .filter(([path]) => path === recordIndexPath);+ writeSpy.mockRestore();// Canon append AND variation removal must land in one persistence write// — not two. A two-write split would expose a half-state window where a// crash leaves the variation gone but the canon entry never written- // (or vice versa). updateUniverse writes once, so the call delta is 1.- expect(fileUtils.atomicWrite.mock.calls.length - callsBefore).toBe(1);+ // (or vice versa). updateUniverse writes once, so the per-record write+ // count is 1.+ expect(recordWrites).toHaveLength(1);// Re-read from the persistence layer (mirrors what a sibling tab would// see): canon has the new entry AND the bucket has lost the variation.const reread = (await svc.listUniverses())[0];diff --git a/server/services/universeCanon.test.js b/server/services/universeCanon.test.jsindex c8a6e41eca..4e98105915 100644--- a/server/services/universeCanon.test.js+++ b/server/services/universeCanon.test.js@@ -1,26 +1,32 @@-import { describe, it, expect, vi, beforeEach } from 'vitest';--// In-memory file store mirroring universeBuilder.test.js so canon mutations-// roundtrip through the same readState/writeState path the real service uses.-const fileStore = new Map();--vi.mock('../lib/fileUtils.js', () => ({- tryReadFile: vi.fn().mockResolvedValue(null),- PATHS: { data: '/mock/data', imageRefs: '/mock/data/image-refs' },- 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)),- shortId: (id, n = 8) => (id == null ? '' : String(id).slice(0, n)),- // Stub: pretend every referenced sheet file exists, so the GET-time lazy- // `pruneStaleReferenceSheets` doesn't null out pointers between seed and- // assertion. The purge tests below don't depend on stale-collapse behavior.- resolveImageRef: vi.fn((filename) => (filename ? `/mock/data/image-refs/${filename}` : null)),-}));+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import { rmSync, mkdirSync } from 'fs';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';++// Real tmpdir backing the per-record store. `mockPathsDataRoot` redirects+// PATHS.data so collectionStore lands under tempRoot/universes/. Everything+// else from fileUtils (atomicWrite, readJSONFile, ensureDir) is the real impl.+const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({+ prefix: 'portos-universe-canon-',+ extraOverrides: (root) => ({ imageRefs: `${root}/image-refs` }),+});+afterAll(cleanup);++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return {+ ...makeProxy(actual),+ // Stub: pretend every referenced sheet file exists, so the GET-time lazy+ // `pruneStaleReferenceSheets` doesn't null out pointers between seed and+ // assertion. The purge tests below don't depend on stale-collapse behavior.+ resolveImageRef: vi.fn((filename) => (filename ? `${tempRoot}/image-refs/${filename}` : null)),+ };+});let uuidCounter = 0;+const mockUuid = (n) => `uuid-${String(n).padStart(8, '0')}`;vi.mock('crypto', async () => {const actual = await vi.importActual('crypto');- return { ...actual, randomUUID: () => `uuid-${++uuidCounter}` };+ return { ...actual, randomUUID: () => mockUuid(++uuidCounter) };});// The bible extractor + staged-LLM runner + prompt-refine helpers all reach@@ -55,7 +61,8 @@ const seedUniverseWithCharacters = async (characters) => {};beforeEach(() => {- fileStore.clear();+ rmSync(tempRoot, { recursive: true, force: true });+ mkdirSync(tempRoot, { recursive: true });uuidCounter = 0;extractBibleMock.mockReset();runStagedLLMMock.mockReset();