Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: federate FableLoom stories
Adam Eivy43d919da8a3e
diff --git a/client/src/components/sharing/SyncToPeerButton.jsx b/client/src/components/sharing/SyncToPeerButton.jsxindex f69d20bf56..dce7c6c62c 100644--- a/client/src/components/sharing/SyncToPeerButton.jsx+++ b/client/src/components/sharing/SyncToPeerButton.jsx@@ -1,6 +1,6 @@/*** SyncToPeerButton — dropdown of federated PortOS peers that toggles per-record- * peer-sync subscriptions for universes + series.+ * peer-sync subscriptions for supported creative records.** Sibling of `ShareToButton` (which targets cloud-synced share buckets); this* targets *other PortOS instances over Tailnet*. The contract is the same:@@ -16,7 +16,7 @@* from this UI; the Instances page shows the bidirectional picture.** Props:- * recordKind: 'universe' | 'series'+ * recordKind: 'universe' | 'series' | 'fableLoom'* recordId: string (required — the record's id)* label?: string* compact?: boolean@@ -87,9 +87,13 @@ export default function SyncToPeerButton({// (peerAllowsOutbound + peerHasCategory). Without this triple gate the// UI would let the user subscribe to a peer that silently rejects every// push (with peer-disabled, peer-disallows-outbound, or- // category-disabled), leaving the row checked but no records ever- // landing. universe → 'universe' category, series → 'pipeline'.- const requiredCategory = recordKind === 'universe' ? 'universe' : 'pipeline';+ // category-disabled), leaving the row checked but no records ever landing.+ const categoryMeta = {+ universe: { key: 'universe', label: 'Universe' },+ series: { key: 'pipeline', label: 'Pipeline' },+ fableLoom: { key: 'fableLoom', label: 'FableLoom' },+ }[recordKind] || { key: recordKind, label: recordKind };+ const requiredCategory = categoryMeta.key;const peerCanReceiveOutbound = (peer) => {if (!peer) return false;// Global sync flag off → server's pushRecordToPeer refuses.@@ -196,7 +200,7 @@ export default function SyncToPeerButton({// only directions, or the per-record category is off. UI// mirrors server-side guards in pushRecordToPeer.const canSync = peerCanReceiveOutbound(p);- const categoryLabel = requiredCategory === 'universe' ? 'Universe' : 'Pipeline';+ const categoryLabel = categoryMeta.label;// Compute the most-specific reason for the inline hint.const disabledReason = !canSync? (p.syncEnabled === falsediff --git a/client/src/components/sharing/SyncToPeerButton.test.jsx b/client/src/components/sharing/SyncToPeerButton.test.jsxindex 466c5a27f1..32371c1d21 100644--- a/client/src/components/sharing/SyncToPeerButton.test.jsx+++ b/client/src/components/sharing/SyncToPeerButton.test.jsx@@ -74,6 +74,31 @@ describe('SyncToPeerButton', () => {));});+ it('uses the FableLoom category when sharing a loom', async () => {+ api.getInstances.mockResolvedValue({+ peers: [{+ instanceId: 'peer-fable',+ name: 'Peer Fable',+ enabled: true,+ status: 'online',+ syncCategories: { fableLoom: true },+ }],+ });+ api.subscribeToPeer.mockResolvedValue({+ subscription: { id: 'peer-fableLoom-loom-1-peer-fable' },+ });+ const user = userEvent.setup();+ render(<SyncToPeerButton recordKind="fableLoom" recordId="loom-1" />);+ await user.click(screen.getByRole('button', { name: /Sync/i }));+ const row = await screen.findByRole('button', { name: /Peer Fable/i });+ expect(row).not.toBeDisabled();+ await user.click(row);+ await waitFor(() => expect(api.subscribeToPeer).toHaveBeenCalledWith(+ { peerId: 'peer-fable', recordKind: 'fableLoom', recordId: 'loom-1' },+ { silent: true },+ ));+ });+it('shows a filled check when already subscribed to that peer', async () => {api.listPeerSubscriptions.mockResolvedValue({subscriptions: [{diff --git a/client/src/pages/FableLoom.jsx b/client/src/pages/FableLoom.jsxindex 82c5a52aac..ba9a301555 100644--- a/client/src/pages/FableLoom.jsx+++ b/client/src/pages/FableLoom.jsx@@ -12,6 +12,7 @@ import { useNavigate } from 'react-router';import { Plus, Sparkles, Trash2, Waypoints } from 'lucide-react';import ProviderModelSelector from '../components/ProviderModelSelector';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';+import SyncToPeerButton from '../components/sharing/SyncToPeerButton';import { FormField } from '../components/ui/FormField.jsx';import PageSkeleton from '../components/ui/PageSkeleton';import Pill from '../components/ui/Pill';@@ -290,22 +291,25 @@ export default function FableLoom() {{loom.logline && <p className="text-xs text-port-text-muted mt-0.5 line-clamp-2">{loom.logline}</p>}</div><div onClick={(e) => e.stopPropagation()} onKeyDown={(e) => e.stopPropagation()} role="none">- {del.isConfirming(loom.id) ? (- <ConfirmButtonPair- prompt="Delete?"- onConfirm={() => handleDelete(loom.id)}- onCancel={del.cancelDelete}- />- ) : (- <button- type="button"- aria-label={`Delete ${loom.name}`}- onClick={() => del.requestDelete(loom.id)}- className="text-port-text-muted hover:text-port-error p-1"- >- <Trash2 size={15} />- </button>- )}+ <div className="flex items-center gap-1">+ <SyncToPeerButton recordKind="fableLoom" recordId={loom.id} compact />+ {del.isConfirming(loom.id) ? (+ <ConfirmButtonPair+ prompt="Delete?"+ onConfirm={() => handleDelete(loom.id)}+ onCancel={del.cancelDelete}+ />+ ) : (+ <button+ type="button"+ aria-label={`Delete ${loom.name}`}+ onClick={() => del.requestDelete(loom.id)}+ className="text-port-text-muted hover:text-port-error p-1"+ >+ <Trash2 size={15} />+ </button>+ )}+ </div></div></div><div className="flex items-center gap-3 mt-3 text-xs text-port-text-muted flex-wrap">diff --git a/client/src/pages/FableLoom.test.jsx b/client/src/pages/FableLoom.test.jsxindex c8977e6698..f82d2f238e 100644--- a/client/src/pages/FableLoom.test.jsx+++ b/client/src/pages/FableLoom.test.jsx@@ -12,6 +12,9 @@ vi.mock('../services/api', () => ({listUniverses: vi.fn(),listPipelineSeries: vi.fn(),}));+vi.mock('../components/sharing/SyncToPeerButton', () => ({+ default: ({ recordKind, recordId }) => <button type="button">sync {recordKind} {recordId}</button>,+}));const navigate = vi.fn();vi.mock('react-router', async (importOriginal) => {@@ -62,6 +65,7 @@ describe('FableLoom index', () => {expect(screen.getByText('3 scenes')).toBeInTheDocument();expect(screen.getByText('2 endings')).toBeInTheDocument();expect(screen.getByText('Audience helper')).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'sync fableLoom loom-1' })).toBeInTheDocument();await waitFor(() => expect(screen.getByText('Aria Verse')).toBeInTheDocument());});diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex 8129f331ec..c7a142eb0d 100644--- a/client/src/pages/Instances.jsx+++ b/client/src/pages/Instances.jsx@@ -7,7 +7,7 @@ import {Database, Brain, CheckCircle2, AlertCircle, Clock,RefreshCcw, Timer,Target, Sword, Fingerprint, HeartPulse, ChevronDown, ChevronRight,- Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard, Palette, BookText, FolderTree, Video+ Lock, Globe, Info, Sparkles, Film, Images, Library, BookOpen, FilePen, Music, Music2, Disc3, Clapperboard, Palette, BookText, FolderTree, Video, Waypoints} from 'lucide-react';import toast from '../components/ui/Toast';import Pill from '../components/ui/Pill';@@ -528,6 +528,7 @@ const SYNC_CATEGORY_META = [{ key: 'mediaCollections', label: 'Media Collections', icon: Images, description: 'Per-universe/series image + video buckets' },{ key: 'videoHistory', label: 'Video History', icon: Film, description: 'Generated-video metadata rows (so synced collection videos render)' },{ key: 'storyBuilder', label: 'Story Builder', icon: BookOpen, description: 'Resumable Story Builder sessions you marked for cross-machine sync' },+ { key: 'fableLoom', label: 'FableLoom', icon: Waypoints, description: 'Branching stories, series plans, episode graphs, and rendered scene references' },{ key: 'authors', label: 'Authors', icon: FilePen, description: 'Author personas + headshots used as series bylines (PostgreSQL)' },{ key: 'artists', label: 'Artists', icon: Music, description: 'Music artist personas + portraits (PostgreSQL)' },{ key: 'albums', label: 'Albums', icon: Disc3, description: 'Music albums + cover art and ordered track lists (PostgreSQL)' },@@ -544,9 +545,9 @@ const SYNC_CATEGORY_META = [];// Snapshot categories — exclude the per-record / delta-based categories that-// have no 60s snapshot checksum: brain + memory (delta), catalog + authors/music-// (PostgreSQL, per-record peer-push only — no snapshot loop).-const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards', 'writersRoomWorks', 'writersRoomFolders', 'writersRoomExercises', 'musicVideoProjects', 'commissionFeedback', 'creativeCommissions']);+// have no 60s snapshot checksum: brain + memory (delta), catalog, and creative+// record kinds handled by the per-record peer-push pipeline.+const NON_SNAPSHOT_KEYS = new Set(['brain', 'memory', 'catalog', 'authors', 'artists', 'albums', 'tracks', 'creativeDirectorProjects', 'moodBoards', 'fableLoom', 'writersRoomWorks', 'writersRoomFolders', 'writersRoomExercises', 'musicVideoProjects', 'commissionFeedback', 'creativeCommissions']);const SNAPSHOT_CATEGORIES = SYNC_CATEGORY_META.filter(m => !NON_SNAPSHOT_KEYS.has(m.key));// Indicator backed by REAL coverage diffing (record IDs vs confirmed pushes),diff --git a/client/src/services/README.md b/client/src/services/README.mdindex d7ae256727..bdbade9a3d 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -122,7 +122,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiSharing.js` | Share buckets + federation sync. || `apiRounds.js` | Rounds workbench CRUD (a cappella round writing + arranging voice layers + learning tracking). || `apiSongbook.js` | SongBook repertoire tracker (`/songbook` — Brain `songs` entity): song CRUD + stage PATCH, `practiceSong(id, quality)` (logs a 0..5-graded practice run; the server owns the SM-2 advance and the resulting `stage`/`practice`), URL import draft, and attachments (base64 upload, present-flag list, raw serve URL via `songAttachmentUrl`). |-| `apiPeerSync.js` | Per-record peer sync subscriptions (universe + series → other PortOS instances over Tailnet). |+| `apiPeerSync.js` | Per-record federated sync subscriptions, integrity checks, and manual push/pull controls (including Universe, Pipeline, Media Collections, and FableLoom). || `apiSyncReview.js` | Sync hygiene: duplicate-record detection + smart merge (universe/series) and the non-blocking edit-conflict journal (list/resolve). Surfaced in Sharing → Duplicates / Conflicts. |## Tools / integrationsdiff --git a/client/src/services/apiPeerSync.js b/client/src/services/apiPeerSync.jsindex 151b0a1231..c5c62b26b4 100644--- a/client/src/services/apiPeerSync.js+++ b/client/src/services/apiPeerSync.js@@ -16,7 +16,9 @@import { request } from './apiCore.js';-export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection']);+export const PEER_SUBSCRIBABLE_KINDS = Object.freeze([+ 'universe', 'series', 'mediaCollection', 'fableLoom',+]);export const listPeerSubscriptions = (filter = {}, options) => {const qs = new URLSearchParams();diff --git a/docs/STORAGE.md b/docs/STORAGE.mdindex 256d731559..3f4b411366 100644--- a/docs/STORAGE.md+++ b/docs/STORAGE.md@@ -38,7 +38,7 @@ PostgreSQL is a **required** install/runtime dependency (see [Backup & Restore](- `tribe_people` / `tribe_touchpoints` / `tribe_memory_links` — the Tribe relationship/CRM graph (people + their care cadence, contact touchpoints, and cross-links into brain `memories`). **Intentionally machine-local — never federated** (ADR [tribe + universe-runs local](./decisions/2026-06-26-tribe-and-universe-runs-local.md), #1724): it is relationship-graph data, mirroring the deliberate "memory_links are instance-local" boundary in `memorySync.js` (memory *nodes* federate, the link graph does not), and is coupled to machine-local domains — `tribe_memory_links` extends the non-federated `memory_links` layer and `tribe_touchpoints` carry per-machine calendar-account refs. NO `sync_sequence`, no peer-sync record kind, no `dataSync` category. Adapter: `server/services/tribe.js`.- `creative_commissions` — Creative Commissions (Autonomous Creation Engine, #2657/#2686): standing recurring creative briefs that fire on a cron cadence and drive the Creative Director directive pipeline unattended. One row per commission, the full sanitized record in `data` JSONB with `name`/`enabled`/`created_at`/`updated_at` mirrored into columns for the scheduler's "arm every enabled commission" query. The brief/identity federates as `creativeCommission` so synced feedback can attach to the same commission; `schedule`, `runs`, `assignment`, `enabled`, and feedback view stay machine-local (the per-reaction `commissionFeedback` records federate separately). The opt-in Digital Twin music-taste configuration is bounded brief metadata; raw taste sources and per-run recipes never cross the wire. The file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only. Adapter: `server/services/creativeCommissions/db.js`, selected pg-vs-file by `server/services/creativeCommissions/store.js` (file backend is the `NODE_ENV=test`/`MEMORY_BACKEND=file` escape hatch only).- `games` — Game studio workspaces (#3177): one row per managed-app asset plan, with the full reusable sprite/music binding set, current compiled-manifest pointer, compile history, and user-requested AI feedback history in `data` JSONB; `app_id`/`name`/`updated_at` are mirrored for list and relationship queries. The record is **machine-local** because managed-app registration, sprite atlases, and music-library bytes are machine-local; there is no peer-sync cursor or tombstone, and deletes are hard deletes. Compiled manifests are immutable, SHA-256-addressed artifacts under `data/games/{id}/manifests/`; their pointers and hashes live in the DB record. Adapter: `server/services/games/db.js`, selected pg-vs-collectionStore by `server/services/games/store.js` (collectionStore is test/unsupported file escape hatch only).-- `fableloom_stories` — FableLoom branching narratives: one row per loom (a branching-narrative story), with episodes, scene-node graphs, and intent transitions in `data` JSONB; `name`/`universe_id`/`series_id`/`updated_at` are mirrored for list and relationship queries (both refs are soft — no FK). `db-primary` because looms relate to universes and series and the index queries by recency. **Intentionally machine-local — never federated** in this first slice: no dataSync category, no sync cursor, no tombstones, and deletes are hard deletes (same posture as `games`); scene renders live under `data/images/` and the node stores only the filename. Adapter: `server/services/fableLoom/db.js`, selected pg-vs-collectionStore by `server/services/fableLoom/store.js` (collectionStore is the test/unsupported file escape hatch only). Feature doc: [FableLoom](./features/fableloom.md).+- `fableloom_stories` — FableLoom branching narratives: one row per loom (a branching-narrative story), with episodes, scene-node graphs, and intent transitions in `data` JSONB; `name`/`universe_id`/`series_id`/`updated_at` are mirrored for list and relationship queries (both refs are soft — no FK). `db-primary` because looms relate to universes and series and the index queries by recency. Federates through the opt-in per-record `fableLoom` category: whole-record LWW merges carry soft-delete tombstones, conflict-journal recovery, and hashed manifests for scene images/videos; there is no snapshot cursor or `sync_sequence`. Adapter: `server/services/fableLoom/db.js`, selected pg-vs-collectionStore by `server/services/fableLoom/store.js` (collectionStore is the test/unsupported file escape hatch only). Feature doc: [FableLoom](./features/fableloom.md).- `threejs_models` — generated procedural 3D-model workspaces: one row per model with gallery-image lineage, provider/model attribution, generation/refinement status, and the validated declarative scene spec in `data` JSONB. The referenced image bytes remain under `data/images/`; deterministic Three.js source is derived from the stored spec rather than persisted as a second mutable artifact. The table is local-only in this first slice, with soft-delete columns retained so federation can be added without a record-shape migration.- `privacy_subjects` / `privacy_vault_records` / `privacy_consents` / `privacy_orgs` / `privacy_org_holdings` / `privacy_change_events` / `privacy_brokers` / `privacy_broker_cases` — the Privacy Center (epic #2138): the household subjects the suite works on behalf of (`self` plus consenting partners/children/parents — every other table carries a `subject_id` FK defaulted to the seeded `self` row, #3658), the encrypted PII vault, the trusted-organization registry with per-field holdings, the change-of-address inventory, and the data-broker opt-out ledger. Relational by nature (org ↔ holdings ↔ vault records ↔ change events ↔ broker cases), which is why they are `db-primary`. Vault *values* are AES-256-GCM ciphertext (`v1:<iv>:<tag>:<ct>`, key from `PRIVACY_VAULT_KEY`) — the DB holds bytes of ciphertext, never plaintext PII, and plaintext never appears in logs (`server/lib/vaultCrypto.js`). **Intentionally machine-local — never federated**, and this is a product *guarantee*, not a deferred feature (ADR [privacy records machine-local](./decisions/2026-08-08-privacy-records-machine-local.md), #2148). NO `sync_sequence`, NO peer-sync record kind, NO `dataSync` category, NO `PORTOS_SCHEMA_VERSIONS` entry, and no `deleted`/`deleted_at` tombstones — deletes are hard deletes, mirroring `tribe`. The reasoning is the same class as the Tribe graph but stronger: the peer-sync **pull** path (`GET /api/peer-sync/record`) carries no peer identity, `masked_value` is plaintext by design so even ciphertext-only sync would leak a PII fingerprint, and a shared `PRIVACY_VAULT_KEY` would widen the at-rest blast radius to every peer's `.env`. A second machine gets the vault by restoring a backup and copying the key by hand — a deliberate act, not continuous replication. Enforced by `server/services/sharing/privacyNeverFederates.test.js`. Adapters: `server/services/privacySubjects.js`, `privacyVault.js`, `privacyOrgs.js`, `privacyChanges.js`, `privacyBrokers.js`, `privacyOptOut.js`.diff --git a/docs/features/fableloom.md b/docs/features/fableloom.mdindex b252282490..49c2c9e514 100644--- a/docs/features/fableloom.md+++ b/docs/features/fableloom.md@@ -217,16 +217,20 @@ branch convergence, is specified in## Storage`fableloom_stories` (db-primary; one row per loom, full record in `data`-JSONB, `universe_id`/`series_id` mirrored as soft refs). **Machine-local — no-federation**: no dataSync category, no sync cursor, hard deletes (same posture-as Games / Writers Room). Service: `server/services/fableLoom/` (records /-weave / store / db); routes: `server/routes/fableLoom.js` (`/api/fableloom`).+JSONB, `universe_id`/`series_id` mirrored as soft refs). The opt-in+**FableLoom** sharing category uses per-record peer subscriptions rather than+the snapshot loop: creates auto-subscribe to eligible peers, edits push the+whole sanitized loom under LWW, and deletes travel as tombstones. Scene image+and video bytes ride hashed asset manifests; true three-way story conflicts+archive the losing local version for restore from Sharing > Conflicts. Service:+`server/services/fableLoom/` (records / weave / store / db); routes:+`server/routes/fableLoom.js` (`/api/fableloom`).## Relationship to the series pipelineA loom can *link* to a pipeline series (`seriesId`) but is its own recordtype — branching narratives don't run the linear issue/stage pipeline-(manuscript formats, autopilot, federation semantics don't apply to a graph).+(manuscript formats and linear-stage autopilot don't apply to a graph).There is deliberately **no `seriesType: 'branching'` enum** on`pipeline_series`: a scene graph has no linear stage chain, and a type enumwould force a special case into every pipeline surface. The integration is adiff --git a/scripts/migrations/312-fableloom-federation.js b/scripts/migrations/312-fableloom-federation.jsnew file mode 100644index 0000000000..8e5837809c--- /dev/null+++ b/scripts/migrations/312-fableloom-federation.js@@ -0,0 +1,20 @@+/**+ * Registration stub for FableLoom federation.+ *+ * Existing `fableloom_stories` rows need the additive `deleted` and+ * `deleted_at` columns so deletes can travel as LWW tombstones. The migration+ * runner starts before PostgreSQL is initialized, so the idempotent DDL lives+ * in `server/lib/db/schema/pipeline.js` and runs through ensureSchema at boot.+ * Fresh installs carry the same columns in `server/scripts/init-db.sql`.+ *+ * Existing records remain live through the `deleted = FALSE` default. This+ * stub records when the store became federated in the per-install migration+ * ledger; no file-backed record rewrite is required because sanitizeLoom+ * backfills the tombstone fields on read.+ */++export default {+ async up() {+ console.log('🧶 FableLoom federation: additive tombstone columns apply at boot via ensureSchema(); nothing to do in the file runner');+ },+};diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex 3ea7b5df32..602dd5b409 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -10902,7 +10902,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 125+ "line": 126}]},@@ -10913,7 +10913,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 140+ "line": 141}]},@@ -10924,7 +10924,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 263+ "line": 264}]},@@ -10935,7 +10935,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 291+ "line": 292}]},@@ -10946,7 +10946,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 277+ "line": 278}]},@@ -10957,7 +10957,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 298+ "line": 299}]},@@ -10968,7 +10968,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 363+ "line": 364}]},@@ -10979,7 +10979,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 335+ "line": 336}]},@@ -10990,7 +10990,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 378+ "line": 379}]},@@ -11001,7 +11001,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 323+ "line": 324}]},@@ -11012,7 +11012,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 347+ "line": 348}]},@@ -11023,7 +11023,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 236+ "line": 237}]},@@ -11034,7 +11034,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 308+ "line": 309}]},@@ -11045,7 +11045,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 205+ "line": 206}]},@@ -11056,7 +11056,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 215+ "line": 216}]},@@ -11067,7 +11067,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 228+ "line": 229}]},@@ -11078,7 +11078,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 166+ "line": 167}]},@@ -11089,7 +11089,7 @@"sources": [{"source": "server/routes/instances.js",- "line": 181+ "line": 182}]},diff --git a/server/lib/conflictJournal.js b/server/lib/conflictJournal.jsindex fd2470cec1..646eb5cb8b 100644--- a/server/lib/conflictJournal.js+++ b/server/lib/conflictJournal.js@@ -487,6 +487,9 @@ export const RESTORABLE_FIELDS = Object.freeze({// machine-local schedule/runs/assignment/enabled are never in a snapshot// (stripped from the wire) so they're excluded.creativeCommission: ['name', 'targetAbility', 'brief', 'generation', 'feedbackWindow'],+ // FableLoom restores the authored story graph and playback configuration.+ // Universe/series ids are structural links and stay on the live record.+ fableLoom: ['name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'seriesPlan', 'participationMode', 'audienceCommunicationMedium', 'episodes'],// Writers Room exercises (#1645): the user-authored sprint fields the merge can// restore through `restoreExercise` — the appended prose + the sprint config.// Server-owned / structural fields are excluded (`id`/`createdAt`/`startedAt`/diff --git a/server/lib/db/schema/pipeline.js b/server/lib/db/schema/pipeline.jsindex 88e02cbc78..f82e7e2823 100644--- a/server/lib/db/schema/pipeline.js+++ b/server/lib/db/schema/pipeline.js@@ -95,9 +95,10 @@ export const pipelineDdl = [// FableLoom branching narratives. One row per loom (a branching-narrative// story), the full sanitized record (episodes, scene-node graphs, intent// transitions) in `data` JSONB. `universe_id`/`series_id` are soft refs- // mirrored for relationship queries only. Machine-local like Writers Room —- // no dataSync category, no sync cursor, no tombstones; deletes are hard- // deletes (games precedent). Mirrors init-db.sql.+ // mirrored for relationship queries only. FableLoom federates through the+ // per-record peer-sync pipeline (record kind/category `fableLoom`), so the+ // LWW tombstone trio is mirrored in columns while the record stays in JSONB.+ // No sync_sequence: pushes are driven by recordEvents subscriptions.`CREATE TABLE IF NOT EXISTS fableloom_stories (id TEXT PRIMARY KEY,name TEXT NOT NULL,@@ -105,9 +106,14 @@ export const pipelineDdl = [series_id TEXT,data JSONB NOT NULL DEFAULT '{}'::jsonb,created_at TIMESTAMPTZ DEFAULT NOW(),- updated_at TIMESTAMPTZ DEFAULT NOW()+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ)`,+ `ALTER TABLE fableloom_stories ADD COLUMN IF NOT EXISTS deleted BOOLEAN DEFAULT FALSE`,+ `ALTER TABLE fableloom_stories ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ`,`CREATE INDEX IF NOT EXISTS idx_fableloom_universe ON fableloom_stories (universe_id)`,`CREATE INDEX IF NOT EXISTS idx_fableloom_updated ON fableloom_stories (updated_at)`,+ `CREATE INDEX IF NOT EXISTS idx_fableloom_live ON fableloom_stories (deleted) WHERE deleted = FALSE`,];diff --git a/server/lib/peerSyncValidation.js b/server/lib/peerSyncValidation.jsindex d98cb43b8c..52dd9c2d03 100644--- a/server/lib/peerSyncValidation.js+++ b/server/lib/peerSyncValidation.js@@ -15,7 +15,7 @@ import { catalogSyncIngredientSchema, catalogSyncRefSchema } from './catalogVali// subscriptions target another PortOS instance over Tailnet.export const peerSubscribeSchema = z.object({peerId: z.string().trim().min(1).max(120),- recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']),+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']),recordId: z.string().trim().min(1).max(120),}).strict();@@ -203,6 +203,12 @@ const moodBoardPushSchema = z.object({kind: z.literal('moodBoard'),...peerSyncPushBase,}).strict();+// FableLoom stories push the whole branching graph plus scene image/video+// bytes through the base asset manifest. No child records or extra bundles.+const fableLoomPushSchema = z.object({+ kind: z.literal('fableLoom'),+ ...peerSyncPushBase,+}).strict();// Writers Room works (#1565) push the bare work manifest (the decomposed// draft-version metadata rides inside the record's `drafts[]`). The file-primary// `.md` prose bodies do NOT ride `assetManifest` (which keys on a flat basename +@@ -277,6 +283,7 @@ export const peerSyncPushSchema = z.discriminatedUnion('kind', [trackPushSchema,creativeDirectorProjectPushSchema,moodBoardPushSchema,+ fableLoomPushSchema,writersRoomWorkPushSchema,writersRoomFolderPushSchema,writersRoomExercisePushSchema,@@ -289,7 +296,7 @@ export const peerSyncPushSchema = z.discriminatedUnion('kind', [export const peerSyncRecordSchema = z.object({peerId: z.string().trim().min(1).max(120),- recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']),+ recordKind: z.enum(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']),recordId: z.string().trim().min(1).max(200),}).strict();diff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 802a36c7c7..c557ea4286 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -347,6 +347,11 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// to 2 then (where a v1 peer would round-trip the new shape through an// unaware sanitizer).storyBuilder: 1,+ // v1 = FableLoom stories federate through the per-record push pipeline+ // (record kind/category `fableLoom`). A pre-feature receiver has no merge+ // path for the whole-record story graph, so only this category pauses until+ // both peers upgrade; unrelated categories continue syncing.+ fableLoom: 1,// v1 = Creative Director projects (PostgreSQL `creative_director_projects`)// federated via the per-record peer-sync push pipeline (record kind// `creativeDirectorProject`, sync category `creativeDirectorProjects`, #1564).@@ -635,6 +640,7 @@ export const RECORD_KIND_SCHEMA_CATEGORIES = Object.freeze({'cat-ingredient': Object.freeze(['catalog']),'cat-scrap': Object.freeze(['catalog']),storyBuilder: Object.freeze(['storyBuilder']),+ fableLoom: Object.freeze(['fableLoom']),creativeDirectorProject: Object.freeze(['creativeDirectorProjects']),moodBoard: Object.freeze(['moodBoards']),writersRoomWork: Object.freeze(['writersRoomWorks']),diff --git a/server/lib/socketEventCatalog.generated.json b/server/lib/socketEventCatalog.generated.jsonindex 7d9d1cd56e..dff2495778 100644--- a/server/lib/socketEventCatalog.generated.json+++ b/server/lib/socketEventCatalog.generated.json@@ -2457,7 +2457,7 @@{"direction": "server-to-client","source": "client/src/pages/Instances.jsx",- "line": 1422+ "line": 1423},{"direction": "server-to-client",@@ -2475,7 +2475,7 @@{"direction": "client-to-server","source": "client/src/pages/Instances.jsx",- "line": 1418+ "line": 1419},{"direction": "client-to-server",@@ -2506,7 +2506,7 @@{"direction": "client-to-server","source": "client/src/pages/Instances.jsx",- "line": 1430+ "line": 1431},{"direction": "client-to-server",@@ -3568,7 +3568,7 @@{"direction": "server-to-client","source": "client/src/pages/Instances.jsx",- "line": 1183+ "line": 1184},{"direction": "server-to-client",@@ -3586,7 +3586,7 @@{"direction": "server-to-client","source": "client/src/pages/Instances.jsx",- "line": 1184+ "line": 1185},{"direction": "server-to-client",@@ -3604,7 +3604,7 @@{"direction": "server-to-client","source": "client/src/pages/Instances.jsx",- "line": 1191+ "line": 1192},{"direction": "server-to-client",@@ -4382,7 +4382,7 @@{"direction": "server-to-client","source": "client/src/pages/Instances.jsx",- "line": 1144+ "line": 1145},{"direction": "server-to-client",diff --git a/server/lib/syncWire.js b/server/lib/syncWire.jsindex 651feb020f..d34406728a 100644--- a/server/lib/syncWire.js+++ b/server/lib/syncWire.js@@ -225,10 +225,11 @@ export function sanitizeRecordForWire(kind, record) {return { ...rest, ...sanitizeSoftDeleteFields(record) };}case 'moodBoard':+ case 'fableLoom':case 'writersRoomFolder':case 'writersRoomExercise':case 'commissionFeedback': {- // Persona/music/mood-board records: like mediaCollection,+ // Persona/music/mood-board/FableLoom records: like mediaCollection,// no `ephemeral` flag — always wire-syncable when present. Strip-then-tail-// re-add the soft-delete pair for byte-stable checksums. The whole record// is LWW-overwritten on merge (no item-union), so the wire form convergesdiff --git a/server/routes/instances.js b/server/routes/instances.jsindex e061d6116f..78d06c02ed 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -62,6 +62,7 @@ const syncCategoriesSchema = z.object({mediaCollections: z.boolean().optional(),videoHistory: z.boolean().optional(),storyBuilder: z.boolean().optional(),+ fableLoom: z.boolean().optional(),authors: z.boolean().optional(),artists: z.boolean().optional(),albums: z.boolean().optional(),diff --git a/server/routes/peerSync.test.js b/server/routes/peerSync.test.jsindex 2c19d764ca..fd9de1cb9c 100644--- a/server/routes/peerSync.test.js+++ b/server/routes/peerSync.test.js@@ -18,7 +18,7 @@ vi.mock('../services/sharing/peerSync.js', () => ({ERR_NOT_FOUND: 'PEER_SYNC_SUBSCRIPTION_NOT_FOUND',ERR_VALIDATION: 'PEER_SYNC_SUBSCRIPTION_VALIDATION',ERR_SCHEMA_VERSION_AHEAD: 'PEER_SYNC_SCHEMA_VERSION_AHEAD',- PEER_SUBSCRIBABLE_KINDS: Object.freeze(['universe', 'series', 'mediaCollection']),+ PEER_SUBSCRIBABLE_KINDS: Object.freeze(['universe', 'series', 'mediaCollection', 'fableLoom']),}));vi.mock('../services/sharing/integrity.js', () => ({@@ -89,6 +89,30 @@ describe('peer-sync routes', () => {}));});+ it('accepts a FableLoom push with scene-media assets', async () => {+ svc.applyIncomingPush.mockResolvedValue({+ missingAssets: [],+ reverseSubscriptionCreated: true,+ ackedDeletesUpTo: 0,+ });+ const res = await request(buildApp())+ .post('/api/peer-sync/push')+ .send({+ kind: 'fableLoom',+ record: { id: 'loom-1', name: 'Example Story', episodes: [] },+ assetManifest: [+ { filename: 'scene.png', kind: 'image', sha256: 'a'.repeat(64) },+ { filename: 'scene.mp4', kind: 'video', sha256: 'b'.repeat(64) },+ ],+ sourceInstanceId: 'peer-a',+ });+ expect(res.status).toBe(200);+ expect(svc.applyIncomingPush).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'fableLoom',+ record: expect.objectContaining({ id: 'loom-1' }),+ }));+ });+it('accepts a universe push that bundles a linkedCollection (Stage 5 media-collections sync)', async () => {// Regression: peerSyncPushSchema's strict() branches must include// `linkedCollection` — without it, every production push from a@@ -476,6 +500,22 @@ describe('peer-sync routes', () => {expect(res.body.subscription.peerId).toBe('peer-a');});+ it('accepts a per-record FableLoom subscription', async () => {+ svc.subscribePeer.mockResolvedValue({+ id: 'peer-fableLoom-loom-1-peer-a',+ peerId: 'peer-a',+ recordKind: 'fableLoom',+ recordId: 'loom-1',+ });+ const res = await request(buildApp())+ .post('/api/peer-sync/subscriptions')+ .send({ peerId: 'peer-a', recordKind: 'fableLoom', recordId: 'loom-1' });+ expect(res.status).toBe(201);+ expect(svc.subscribePeer).toHaveBeenCalledWith(expect.objectContaining({+ recordKind: 'fableLoom', recordId: 'loom-1',+ }));+ });+it('400s when recordKind is "issue" (only universe + series subscribable)', async () => {const res = await request(buildApp()).post('/api/peer-sync/subscriptions')diff --git a/server/scripts/init-db.sql b/server/scripts/init-db.sqlindex a802fe2296..62a817118d 100644--- a/server/scripts/init-db.sql+++ b/server/scripts/init-db.sql@@ -1164,10 +1164,10 @@ CREATE INDEX IF NOT EXISTS idx_wr_exercises_work ON writers_room_exercises (work-- FableLoom branching narratives. One row per loom (a branching-narrative-- story), the full sanitized record (episodes, scene-node graphs, intent-- transitions) in `data` JSONB. `universe_id`/`series_id` are soft refs--- mirrored for relationship queries only. Machine-local like Writers Room —--- no dataSync category, no sync cursor, no tombstones; deletes are hard--- deletes (games precedent). Mirrors the fableloom_stories block in--- db/schema/pipeline.js.+-- mirrored for relationship queries only. FableLoom federates through the+-- per-record peer-sync pipeline (record kind/category `fableLoom`), so deletes+-- are LWW tombstones. No sync_sequence: recordEvents subscriptions drive pushes.+-- Mirrors the fableloom_stories block in db/schema/pipeline.js.CREATE TABLE IF NOT EXISTS fableloom_stories (id TEXT PRIMARY KEY,name TEXT NOT NULL,@@ -1175,10 +1175,13 @@ CREATE TABLE IF NOT EXISTS fableloom_stories (series_id TEXT,data JSONB NOT NULL DEFAULT '{}'::jsonb,created_at TIMESTAMPTZ DEFAULT NOW(),- updated_at TIMESTAMPTZ DEFAULT NOW()+ updated_at TIMESTAMPTZ DEFAULT NOW(),+ deleted BOOLEAN DEFAULT FALSE,+ deleted_at TIMESTAMPTZ);CREATE INDEX IF NOT EXISTS idx_fableloom_universe ON fableloom_stories (universe_id);CREATE INDEX IF NOT EXISTS idx_fableloom_updated ON fableloom_stories (updated_at);+CREATE INDEX IF NOT EXISTS idx_fableloom_live ON fableloom_stories (deleted) WHERE deleted = FALSE;-- LoRA training runs (character LoRA training, /api/lora-training). One row-- per run: id/status/character_id mirrored as columns for filtering, thediff --git a/server/services/conflictJournalResolver.js b/server/services/conflictJournalResolver.jsindex cb83d57c13..ab60d33a67 100644--- a/server/services/conflictJournalResolver.js+++ b/server/services/conflictJournalResolver.js@@ -41,6 +41,7 @@ import { restoreBoard } from './moodBoard/index.js';import { updateWork, restoreFolder, restoreExercise } from './writersRoom/local.js';import { restoreCommissionFeedback } from './creativeCommissions/feedbackStore.js';import { restoreCommission } from './creativeCommissions/store.js';+import { restoreLoom } from './fableLoom/index.js';export const ERR_NOT_FOUND = 'CONFLICT_JOURNAL_NOT_FOUND';export const ERR_VALIDATION = 'CONFLICT_JOURNAL_VALIDATION';@@ -177,6 +178,10 @@ async function applyToRecord(kind, recordId, patch, { replace = false } = {}) {// runs/assignment are kept as-is. Returns null for a missing record (#2686).const restored = await restoreCommission(recordId, patch).catch(translateGone);if (!restored) throw makeErr(`The ${kind} this conflict targets no longer exists — discard the entry.`, ERR_TARGET_GONE);+ } else if (kind === 'fableLoom') {+ // Restore the authored story graph and playback settings through the normal+ // loom mutation path so the edit is sanitized, timestamped, and re-pushed.+ await restoreLoom(recordId, patch).catch(translateGone);} else {throw makeErr(`Unsupported conflict kind: ${kind}`, ERR_VALIDATION);}diff --git a/server/services/conflictJournalResolver.test.js b/server/services/conflictJournalResolver.test.jsindex e3daaed5aa..a375282333 100644--- a/server/services/conflictJournalResolver.test.js+++ b/server/services/conflictJournalResolver.test.js@@ -21,6 +21,7 @@ const resolver = await import('./conflictJournalResolver.js');const universeSvc = await import('./universeBuilder.js');const collSvc = await import('./mediaCollections.js');const issueSvc = await import('./pipeline/issues.js');+const fableLoomSvc = await import('./fableLoom/index.js');const cj = await import('../lib/conflictJournal.js');afterAll(() => rmSync(TEST_DATA_ROOT, { recursive: true, force: true }));@@ -160,6 +161,26 @@ describe('conflictJournalResolver', () => {.rejects.toMatchObject({ code: resolver.ERR_VALIDATION });});+ it('restore-all reapplies an archived FableLoom story graph', async () => {+ const loom = await fableLoomSvc.createLoom({ name: 'Remote story', premise: 'Remote premise' });+ const entryId = await seedEntry(loom.id, {+ ...loom,+ name: 'Local story',+ premise: 'Local premise',+ episodes: [{+ id: 'ep-local',+ number: 1,+ title: 'Local opening',+ nodes: [{ id: 'node-local', title: 'A local scene' }],+ }],+ }, 'fableLoom');++ await resolver.resolveConflict(entryId, { action: 'restore-all' });+ const restored = await fableLoomSvc.getLoom(loom.id);+ expect(restored).toMatchObject({ name: 'Local story', premise: 'Local premise' });+ expect(restored.episodes[0]).toMatchObject({ id: 'ep-local', title: 'Local opening' });+ });+it('discard marks resolved without touching the record', async () => {const u = await universeSvc.createUniverse({ name: 'X', starterPrompt: 'REMOTE' });const entryId = await seedEntry(u.id, { id: u.id, name: 'X', starterPrompt: 'local' });diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsindex d84293e5e7..85a4fffc5c 100644--- a/server/services/dataSync.pipelineUniverse.test.js+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -1154,6 +1154,10 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {// file-snapshot category). Gated at applyIncomingPush via// compareSchemaVersions / RECORD_KIND_SCHEMA_CATEGORIES.creativeCommission.'creativeCommissions',+ // FableLoom stories → per-record peer-push only (no 60s snapshot+ // category). Gated at applyIncomingPush via compareSchemaVersions /+ // RECORD_KIND_SCHEMA_CATEGORIES.fableLoom.+ 'fableLoom',// Standalone media library (#1566) → its own receiver-pull endpoint// (GET /api/peer-sync/library-manifest), NOT the file-snapshot transfer.// Versioned for the manifest envelope and gated by syncMediaLibraryFromPeer'sdiff --git a/server/services/fableLoom/README.md b/server/services/fableLoom/README.mdindex e1057df41e..0e75a20a24 100644--- a/server/services/fableLoom/README.md+++ b/server/services/fableLoom/README.md@@ -7,11 +7,12 @@ intent to a transition and moves them through the graph until an ending.| Module | Purpose ||---|---|-| `records.js` | Sanitizer + CRUD for looms/episodes/nodes; transitions are addressable one at a time (`addNodeTransition` / `updateNodeTransition` / `deleteNodeTransition`) as well as replaceable as a whole array via the node patch; `attachNodeImage` and `attachNodeVideo` for media-job hooks. |+| `records.js` | Sanitizer + CRUD + peer LWW/tombstone merge for looms/episodes/nodes; transitions are addressable one at a time (`addNodeTransition` / `updateNodeTransition` / `deleteNodeTransition`) as well as replaceable as a whole array via the node patch; `attachNodeImage` and `attachNodeVideo` for media-job hooks. || `weave.js` | AI ops via `runStagedLLM`: `generateSeriesPlan` (full arc / plot-point / side-quest scaffold), `weaveEpisode` (single-camera-cut graph with automatic cuts and looping decisions), `branchNode` (grow paths), `feedbackEpisode` (apply a conversational sparse patch to one episode), `reviewEpisode` (critique + deterministic analysis), `playTurn` (reader intent → transition; tapped/automatic paths resolve with NO LLM call), `reformatEpisodeScenes` (rewrite ONE episode's scenes into another format; the loom's format pin lands only once every episode is converted). || `formats.js` | Scene formats (`prose` / `teleplay`) and the prompt contracts each generative stage renders for them. || `store.js` | PostgreSQL/file backend facade (`fableloom_stories`; collectionStore escape hatch for tests). || `db.js` | PostgreSQL leaf I/O. |Pure graph analysis (validation, BFS layering, prompt rendering) lives in-`server/lib/fableLoomGraph.js`. Machine-local — no federation.+`server/lib/fableLoomGraph.js`. Federation uses the opt-in per-record+`fableLoom` category, conflict-journal recovery, and scene-media asset manifests.diff --git a/server/services/fableLoom/db.js b/server/services/fableLoom/db.jsindex a8cb5cc172..5a4a3b8489 100644--- a/server/services/fableLoom/db.js+++ b/server/services/fableLoom/db.js@@ -1,7 +1,7 @@/*** PostgreSQL leaf I/O for FableLoom records. The full sanitized record lives* in JSONB; name/universe_id/series_id/updated_at are mirrored for the common- * list/filter paths.+ * list/filter paths; delete markers are mirrored for federated tombstone GC.*/import { query } from '../../lib/db.js';@@ -22,15 +22,27 @@ export async function writeRaw(id, record) {const createdAt = mirrorTimestamp(record?.createdAt, now);const updatedAt = mirrorTimestamp(record?.updatedAt, createdAt);await query(- `INSERT INTO fableloom_stories (id, name, universe_id, series_id, data, created_at, updated_at)- VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7)+ `INSERT INTO fableloom_stories (id, name, universe_id, series_id, data, created_at, updated_at, deleted, deleted_at)+ VALUES ($1, $2, $3, $4, $5::jsonb, $6, $7, $8, $9)ON CONFLICT (id) DO UPDATE SETname = EXCLUDED.name,universe_id = EXCLUDED.universe_id,series_id = EXCLUDED.series_id,data = EXCLUDED.data,- updated_at = EXCLUDED.updated_at`,- [id, record.name, record.universeId ?? null, record.seriesId ?? null, JSON.stringify(record), createdAt, updatedAt],+ updated_at = EXCLUDED.updated_at,+ deleted = EXCLUDED.deleted,+ deleted_at = EXCLUDED.deleted_at`,+ [+ id,+ record.name,+ record.universeId ?? null,+ record.seriesId ?? null,+ JSON.stringify(record),+ createdAt,+ updatedAt,+ record.deleted === true,+ mirrorTimestamp(record.deletedAt, null),+ ],);return record;}diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.jsindex f2bd2a8d79..7199daa5f0 100644--- a/server/services/fableLoom/index.js+++ b/server/services/fableLoom/index.js@@ -16,7 +16,10 @@ export {getLoom,listLooms,listLoomSummaries,+ mergeLoomsFromSync,mutateLoom,+ pruneTombstonedLooms,+ restoreLoom,sanitizeLoom,updateEpisode,updateLoom,diff --git a/server/services/fableLoom/records.js b/server/services/fableLoom/records.jsindex c9119eb3c8..fb27de30a2 100644--- a/server/services/fableLoom/records.js+++ b/server/services/fableLoom/records.js@@ -15,8 +15,23 @@ import { randomUUID } from 'crypto';import { ServerError } from '../../lib/errorHandler.js';import { isStr, trimTo } from '../../lib/storyBible.js';import { sanitizeLlmRoutePin } from '../../lib/llmRoutePin.js';+import { compareNewerWins } from '../../lib/lwwTimestamp.js';+import { sanitizeSoftDeleteFields } from '../../lib/syncWire.js';+import {+ contentHashForRecord,+ deleteSyncBaseHash,+ flushBaseHashes,+ maybeJournalBeforeOverwrite,+ setSyncBaseHash,+ withBaseHashFlushBatch,+} from '../../lib/conflictJournal.js';import { getUniverse } from '../universeBuilder.js';import { getSeries } from '../pipeline/series.js';+import {+ autoSubscribeRecordToAllPeers,+ emitRecordDeleted,+ emitRecordUpdated,+} from '../sharing/recordEvents.js';import {deleteRaw,isValidLoomId,@@ -166,6 +181,7 @@ export function sanitizeLoom(raw) {const name = trimTo(raw.name, LOOM_LIMITS.NAME_MAX);if (!name) return null;const now = new Date().toISOString();+ const { deleted, deletedAt } = sanitizeSoftDeleteFields(raw);const episodes = (Array.isArray(raw.episodes) ? raw.episodes : []).map(sanitizeEpisode).filter(Boolean)@@ -194,6 +210,8 @@ export function sanitizeLoom(raw) {episodes,createdAt: isStr(raw.createdAt) && raw.createdAt ? raw.createdAt : now,updatedAt: isStr(raw.updatedAt) && raw.updatedAt ? raw.updatedAt : now,+ deleted,+ deletedAt,};}@@ -220,13 +238,14 @@ async function assertRefsExist({ universeId, seriesId } = {}) {const requireLoomRaw = async (id) => {if (!isValidLoomId(id)) throw notFound();const loom = sanitizeLoom(await readRaw(id));- if (!loom) throw notFound();+ if (!loom || loom.deleted) throw notFound();return loom;};-export async function listLooms() {+export async function listLooms({ includeDeleted = false } = {}) {const records = (await listRaw()).map(sanitizeLoom).filter(Boolean);- return records.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.name.localeCompare(b.name));+ const visible = includeDeleted ? records : records.filter((loom) => !loom.deleted);+ return visible.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt) || a.name.localeCompare(b.name));}/**@@ -261,9 +280,10 @@ export async function listLoomSummaries({ seriesId: scopeSeriesId } = {}) {}));}-export async function getLoom(id) {+export async function getLoom(id, { includeDeleted = false } = {}) {if (!isValidLoomId(id)) return null;- return sanitizeLoom(await readRaw(id));+ const loom = sanitizeLoom(await readRaw(id));+ return loom && (includeDeleted || !loom.deleted) ? loom : null;}const assertParticipationConfigured = ({ participationMode, audienceCommunicationMedium }) => {@@ -303,6 +323,8 @@ export async function createLoom({});if (!loom) throw new ServerError('Loom needs a name', { status: 400, code: 'VALIDATION_ERROR' });await writeRaw(loom.id, loom);+ emitRecordUpdated('fableLoom', loom.id);+ autoSubscribeRecordToAllPeers('fableLoom', loom.id).catch(() => {});return loom;}@@ -311,17 +333,19 @@ export async function createLoom({* (or a falsy value to skip the write). The result is re-sanitized before* persisting so a mutation can never store a malformed record.*/-export function mutateLoom(id, mutator) {+export async function mutateLoom(id, mutator) {if (!isValidLoomId(id)) throw notFound();- return queueLoomWrite(id, async () => {+ const result = await queueLoomWrite(id, async () => {const current = await requireLoomRaw(id);const changed = await mutator(current);- if (!changed) return current;+ if (!changed) return { loom: current, changed: false };const next = sanitizeLoom({ ...changed, id, updatedAt: new Date().toISOString() });if (!next) throw new ServerError('Invalid loom record', { status: 400, code: 'VALIDATION_ERROR' });await writeRaw(id, next);- return next;+ return { loom: next, changed: true };});+ if (result.changed) emitRecordUpdated('fableLoom', id);+ return result.loom;}const PATCH_FIELDS = [@@ -329,6 +353,11 @@ const PATCH_FIELDS = ['participationMode', 'audienceCommunicationMedium', 'universeId', 'seriesId',];+const RESTORABLE_FIELDS = [+ 'name', 'logline', 'premise', 'styleNotes', 'format', 'playSettings', 'seriesPlan',+ 'participationMode', 'audienceCommunicationMedium', 'episodes',+];+export async function updateLoom(id, patch = {}) {await assertRefsExist({universeId: 'universeId' in patch ? nullableRef(patch.universeId) : null,@@ -344,9 +373,96 @@ export async function updateLoom(id, patch = {}) {});}+/** Reapply a conflict snapshot through the normal mutation/push lifecycle. */+export function restoreLoom(id, patch = {}) {+ return mutateLoom(id, (loom) => {+ const next = { ...loom };+ for (const key of RESTORABLE_FIELDS) {+ if (key in patch) next[key] = patch[key];+ }+ assertParticipationConfigured(next);+ return next;+ });+}+export async function deleteLoom(id) {- await requireLoomRaw(id);- await deleteRaw(id);+ if (!isValidLoomId(id)) throw notFound();+ await queueLoomWrite(id, async () => {+ const current = await requireLoomRaw(id);+ const now = new Date().toISOString();+ await writeRaw(id, sanitizeLoom({+ ...current,+ deleted: true,+ deletedAt: now,+ updatedAt: now,+ }));+ });+ emitRecordDeleted('fableLoom', id);+}++/**+ * Merge FableLoom records received from a federated peer. Records are+ * sanitized before persistence, unioned by id, and resolved by whole-record+ * LWW on `updatedAt`; tombstones travel through the same path.+ */+export async function mergeLoomsFromSync(+ remoteLooms,+ { source = { via: 'sync', peerId: null } } = {},+) {+ if (!Array.isArray(remoteLooms)) return { applied: false, count: 0 };+ const byId = new Map();+ for (const raw of remoteLooms) {+ const remote = sanitizeLoom(raw);+ if (!remote || !isValidLoomId(remote.id) || byId.has(remote.id)) continue;+ byId.set(remote.id, remote);+ }+ let changed = 0;+ for (const remote of byId.values()) {+ const applied = await queueLoomWrite(remote.id, async () => {+ const local = sanitizeLoom(await readRaw(remote.id));+ if (local && !compareNewerWins(remote.updatedAt, local.updatedAt)) return false;+ if (local) {+ await maybeJournalBeforeOverwrite({+ kind: 'fableLoom', id: remote.id, local, remote, source,+ });+ } else {+ await setSyncBaseHash(+ 'fableLoom',+ remote.id,+ contentHashForRecord('fableLoom', remote),+ );+ }+ await writeRaw(remote.id, remote);+ return true;+ });+ if (applied) changed += 1;+ }+ await flushBaseHashes();+ if (changed > 0) console.log(`🧶 FableLoom sync: merged ${changed} loom(s)`);+ return { applied: changed > 0, count: changed };+}++/** Hard-prune tombstones only after the shared federation GC computes a safe cutoff. */+export async function pruneTombstonedLooms(olderThanMs) {+ if (!Number.isFinite(olderThanMs)) return { pruned: 0 };+ const candidates = (await listLooms({ includeDeleted: true }))+ .filter((loom) => loom.deleted && Number.isFinite(Date.parse(loom.deletedAt))+ && Date.parse(loom.deletedAt) < olderThanMs);+ let pruned = 0;+ await withBaseHashFlushBatch(async () => {+ for (const candidate of candidates) {+ const removed = await queueLoomWrite(candidate.id, async () => {+ const current = sanitizeLoom(await readRaw(candidate.id));+ const deletedAtMs = Date.parse(current?.deletedAt || '');+ if (!current?.deleted || !Number.isFinite(deletedAtMs) || deletedAtMs >= olderThanMs) return false;+ await deleteRaw(candidate.id);+ await deleteSyncBaseHash('fableLoom', candidate.id);+ return true;+ });+ if (removed) pruned += 1;+ }+ });+ return { pruned };}// --- Episodes ---------------------------------------------------------------diff --git a/server/services/fableLoom/records.test.js b/server/services/fableLoom/records.test.jsindex 670e0d207b..4d6324e2ea 100644--- a/server/services/fableLoom/records.test.js+++ b/server/services/fableLoom/records.test.js@@ -26,19 +26,29 @@ vi.mock('../pipeline/series.js', () => ({ getSeries: getSeriesMock }));const {LOOM_LIMITS, addEpisode, addNode, addNodeTransition, attachNodeImage, attachNodeVideo, createLoom,deleteEpisode, deleteLoom, deleteNode, deleteNodeTransition, getLoom,- listLooms, listLoomSummaries, sanitizeLoom, updateEpisode, updateLoom,+ listLooms, listLoomSummaries, mergeLoomsFromSync, pruneTombstonedLooms,+ restoreLoom, sanitizeLoom, updateEpisode, updateLoom,updateNode, updateNodeTransition,} = await import('./records.js');const { _resetFableLoomBackend } = await import('./store.js');+const conflictJournal = await import('../../lib/conflictJournal.js');+const { registerSubscriptionAdapter, __resetSubscriptionAdapter } = await import('../sharing/recordEvents.js');+const autoSubscribeMock = vi.fn(async () => []);beforeEach(() => {rmSync(join(TEST_DATA_ROOT, 'fableloom'), { recursive: true, force: true });+ rmSync(join(TEST_DATA_ROOT, 'sharing'), { recursive: true, force: true });+ rmSync(join(TEST_DATA_ROOT, 'conflict-journal'), { recursive: true, force: true });+ conflictJournal.__resetBaseHashCacheForTests();_resetFableLoomBackend();getUniverseMock.mockClear().mockImplementation(async (id) => ({ id }));getSeriesMock.mockClear().mockImplementation(async (id) => ({ id }));+ autoSubscribeMock.mockClear();+ registerSubscriptionAdapter({ autoSubscribeRecordToAllPeers: autoSubscribeMock });});afterAll(() => {+ __resetSubscriptionAdapter();rmSync(TEST_DATA_ROOT, { recursive: true, force: true });});@@ -178,6 +188,7 @@ describe('loom CRUD', () => {const loom = await makeLoom({ logline: 'A crown that remembers.', universeId: 'uni-1' });expect(loom.id).toMatch(/^loom-/);expect(loom.universeId).toBe('uni-1');+ expect(autoSubscribeMock).toHaveBeenCalledWith('fableLoom', loom.id);expect((await listLooms()).map((l) => l.id)).toEqual([loom.id]);@@ -189,6 +200,87 @@ describe('loom CRUD', () => {await deleteLoom(loom.id);expect(await getLoom(loom.id)).toBeNull();+ expect(await getLoom(loom.id, { includeDeleted: true })).toMatchObject({+ id: loom.id,+ deleted: true,+ });+ expect(await listLooms()).toEqual([]);+ expect(await listLooms({ includeDeleted: true })).toHaveLength(1);+ });++ it('merges peer records by updatedAt and lets tombstones converge', async () => {+ const local = await makeLoom({ name: 'Local draft' });+ const newer = {+ ...local,+ name: 'Peer draft',+ updatedAt: '2099-01-01T00:00:00.000Z',+ };+ expect(await mergeLoomsFromSync([newer])).toEqual({ applied: true, count: 1 });+ expect((await getLoom(local.id)).name).toBe('Peer draft');++ const stale = { ...newer, name: 'Stale peer draft', updatedAt: '2000-01-01T00:00:00.000Z' };+ expect(await mergeLoomsFromSync([stale])).toEqual({ applied: false, count: 0 });+ expect((await getLoom(local.id)).name).toBe('Peer draft');++ const tombstone = {+ ...newer,+ deleted: true,+ deletedAt: '2100-01-01T00:00:00.000Z',+ updatedAt: '2100-01-01T00:00:00.000Z',+ };+ expect(await mergeLoomsFromSync([tombstone])).toEqual({ applied: true, count: 1 });+ expect(await getLoom(local.id)).toBeNull();+ });++ it('journals divergent story edits and can restore the authored snapshot', async () => {+ const local = await makeLoom({ name: 'Local story', premise: 'Local premise' });+ const base = { ...local, name: 'Shared story', premise: 'Shared premise' };+ await conflictJournal.setSyncBaseHash(+ 'fableLoom',+ local.id,+ conflictJournal.contentHashForRecord('fableLoom', base),+ );++ const remote = {+ ...local,+ name: 'Remote story',+ premise: 'Remote premise',+ updatedAt: '2099-01-01T00:00:00.000Z',+ };+ await mergeLoomsFromSync([remote], {+ source: { via: 'peer-push', peerId: 'peer-example' },+ });++ const entries = await conflictJournal.conflictJournalStore().loadAll();+ expect(entries).toHaveLength(1);+ expect(entries[0]).toMatchObject({+ recordKind: 'fableLoom',+ recordId: local.id,+ source: { via: 'peer-push', peerId: 'peer-example' },+ localSnapshot: { name: 'Local story', premise: 'Local premise' },+ remoteSnapshot: { name: 'Remote story', premise: 'Remote premise' },+ });++ await restoreLoom(local.id, entries[0].localSnapshot);+ expect(await getLoom(local.id)).toMatchObject({+ name: 'Local story',+ premise: 'Local premise',+ });+ });++ it('hard-prunes only tombstones older than the safe federation cutoff', async () => {+ const loom = await makeLoom();+ await mergeLoomsFromSync([{+ ...loom,+ deleted: true,+ deletedAt: '2099-01-01T00:00:00.000Z',+ updatedAt: '2099-01-01T00:00:00.000Z',+ }]);+ expect(await conflictJournal.getSyncBaseHash('fableLoom', loom.id)).not.toBeNull();+ expect(await pruneTombstonedLooms(Date.parse('2999-01-01T00:00:00.000Z')))+ .toEqual({ pruned: 1 });+ expect(await getLoom(loom.id, { includeDeleted: true })).toBeNull();+ expect(await conflictJournal.getSyncBaseHash('fableLoom', loom.id)).toBeNull();});it('rejects creating a loom without a name', async () => {diff --git a/server/services/fableLoom/store.js b/server/services/fableLoom/store.jsindex 8687181fc0..66289607f1 100644--- a/server/services/fableLoom/store.js+++ b/server/services/fableLoom/store.js@@ -4,7 +4,8 @@* Looms are db-primary in normal installs (`fableloom_stories`). The* collectionStore backend keeps the domain runnable in tests and under the* unsupported MEMORY_BACKEND=file development escape hatch — same split as- * games (server/services/games/store.js).+ * games (server/services/games/store.js). Federation is backend-neutral and+ * operates through the sanitized record lifecycle above this facade.*/import { join } from 'path';diff --git a/server/services/instances.js b/server/services/instances.jsindex 9d3de1831c..e20defbbda 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -319,6 +319,7 @@ const DEFAULT_SYNC_CATEGORIES = {mediaCollections: false,videoHistory: false,storyBuilder: false,+ fableLoom: false,authors: false,artists: false,albums: false,@@ -364,6 +365,7 @@ const PER_RECORD_CATEGORY_KINDS = Object.freeze([['tracks', 'track'],['creativeDirectorProjects', 'creativeDirectorProject'],['moodBoards', 'moodBoard'],+ ['fableLoom', 'fableLoom'],['writersRoomWorks', 'writersRoomWork'],['writersRoomFolders', 'writersRoomFolder'],['writersRoomExercises', 'writersRoomExercise'],diff --git a/server/services/sharing/integrity.js b/server/services/sharing/integrity.jsindex be68e34356..331d59a95f 100644--- a/server/services/sharing/integrity.js+++ b/server/services/sharing/integrity.js@@ -15,6 +15,7 @@ import { computeRecordIntegrity } from '../../lib/syncIntegrity.js';import { listCollections } from '../mediaCollections.js';import { listUniverses } from '../universeBuilder.js';import { listSeries } from '../pipeline/series.js';+import { listLooms } from '../fableLoom/index.js';import { getPeers } from '../instances.js';import { assetIntegrityForRecord } from './peerSync.js';import { peerBaseUrl } from '../../lib/peerUrl.js';@@ -26,6 +27,7 @@ async function recordsForKind(kind) {if (kind === 'mediaCollection') return listCollections({ includeDeleted: true });if (kind === 'universe') return listUniverses({ includeDeleted: true });if (kind === 'series') return listSeries({ includeDeleted: true });+ if (kind === 'fableLoom') return listLooms({ includeDeleted: true });return [];}@@ -34,7 +36,7 @@ async function recordsForKind(kind) {* One row per record: `{ id, name, updatedAt, deleted, assetHashes }`.* Includes tombstoned records so deletes surface correctly in the diff.*- * @param {'universe'|'series'|'mediaCollection'} kind+ * @param {'universe'|'series'|'mediaCollection'|'fableLoom'} kind* @returns {Promise<Array>}*/export async function buildLocalManifest(kind) {diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.jsindex 64de0f14f8..a70224c185 100644--- a/server/services/sharing/peerSync.js+++ b/server/services/sharing/peerSync.js@@ -37,6 +37,7 @@ import { listTracks } from '../tracks/index.js';import { listProjects } from '../creativeDirector/local.js';import { listProjects as listMusicVideoProjects } from '../musicVideo/projects.js';import { listBoards } from '../moodBoard/index.js';+import { listLooms } from '../fableLoom/index.js';import { listWorksForSync, listFoldersForSync, listExercisesForSync } from '../writersRoom/sync.js';import { listCommissionFeedbackForSync } from '../creativeCommissions/feedbackStore.js';import { listCommissionsForSync } from '../creativeCommissions/store.js';@@ -408,6 +409,7 @@ const RECORD_KIND_LISTERS = {track: () => listTracks({ includeDeleted: false }).catch(() => []),creativeDirectorProject: () => listProjects({ includeDeleted: false }).catch(() => []),moodBoard: () => listBoards({ includeDeleted: false }).catch(() => []),+ fableLoom: () => listLooms({ includeDeleted: false }).catch(() => []),// Live works as { id, updatedAt } (full-sync coverage compares updatedAt to// detect a stale confirmed push; bare {id} stubs would report a changed// manuscript as fully mirrored). Without this branch, enabling thediff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.jsindex ce10bfd766..9e046234fe 100644--- a/server/services/sharing/peerSync.test.js+++ b/server/services/sharing/peerSync.test.js@@ -146,6 +146,11 @@ vi.mock('../moodBoard/index.js', async (importOriginal) => ({...(await importOriginal()),listBoards: vi.fn().mockResolvedValue([]),}));+vi.mock('../fableLoom/index.js', () => ({+ getLoom: vi.fn(),+ listLooms: vi.fn().mockResolvedValue([]),+ mergeLoomsFromSync: vi.fn().mockResolvedValue({ applied: true, count: 1 }),+}));vi.mock('../writersRoom/sync.js', async (importOriginal) => ({...(await importOriginal()),listWorksForSync: vi.fn().mockResolvedValue([]),@@ -243,6 +248,7 @@ import {import { listAuthors } from '../authors/index.js';import { listProjects as listCreativeDirectorProjects } from '../creativeDirector/local.js';import { listBoards } from '../moodBoard/index.js';+import { getLoom, listLooms, mergeLoomsFromSync } from '../fableLoom/index.js';import { listWorksForSync, listFoldersForSync, listExercisesForSync } from '../writersRoom/sync.js';import { listCommissionFeedbackForSync } from '../creativeCommissions/feedbackStore.js';import { listCommissionsForSync } from '../creativeCommissions/store.js';@@ -351,6 +357,9 @@ beforeEach(async () => {vi.mocked(listAuthors).mockReset().mockResolvedValue([]);vi.mocked(listCreativeDirectorProjects).mockReset().mockResolvedValue([]);vi.mocked(listBoards).mockReset().mockResolvedValue([]);+ vi.mocked(getLoom).mockReset().mockResolvedValue(null);+ vi.mocked(listLooms).mockReset().mockResolvedValue([]);+ vi.mocked(mergeLoomsFromSync).mockReset().mockResolvedValue({ applied: true, count: 1 });vi.mocked(listWorksForSync).mockReset().mockResolvedValue([]);vi.mocked(listFoldersForSync).mockReset().mockResolvedValue([]);vi.mocked(listExercisesForSync).mockReset().mockResolvedValue([]);@@ -392,12 +401,12 @@ afterEach(async () => {describe('peerSync', () => {describe('PEER_SUBSCRIBABLE_KINDS', () => {- it('is exactly [universe, series, mediaCollection, author, artist, album, track, creativeDirectorProject, moodBoard, writersRoomWork]', () => {+ it('lists every record kind handled by the peer-sync pipeline', () => {// Exact equality (not toContain) so an accidental add/remove/reorder is// caught — this list is canonical and its order can affect iteration// elsewhere (e.g. syncNow's per-kind backfill). Issues piggyback on series// subscriptions; direct issue subs are intentionally rejected (Stage 2).- expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']);+ expect(PEER_SUBSCRIBABLE_KINDS).toEqual(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']);});});@@ -937,6 +946,26 @@ describe('peerSync', () => {expect(created.map(c => c.recordId).sort()).toEqual(['s1', 's2']);});+ it('backfills every local FableLoom when its category is enabled', async () => {+ vi.mocked(getPeers).mockResolvedValue([{+ instanceId: 'peer-a',+ name: 'A',+ enabled: true,+ syncEnabled: true,+ directions: ['outbound'],+ syncCategories: { fableLoom: true },+ }]);+ vi.mocked(listLooms).mockResolvedValue([{ id: 'loom-1' }, { id: 'loom-2' }]);+ vi.mocked(getLoom).mockImplementation(async (id) => ({+ id, name: `Story ${id}`, episodes: [], updatedAt: '2026-01-01T00:00:00.000Z',+ }));++ const created = await autoSubscribePeerToAllRecords('peer-a', 'fableLoom');++ expect(created.map((sub) => sub.recordId).sort()).toEqual(['loom-1', 'loom-2']);+ expect(await findPeerSubscription('peer-a', 'fableLoom', 'loom-1')).not.toBeNull();+ });+it('returns [] when the peer is disabled', async () => {// Guard against backfill pushing to a peer the user has explicitly// disabled — the category bit can be stale even after `enabled: false`.@@ -2268,6 +2297,38 @@ describe('peerSync', () => {expect(captured.assetManifest).toEqual([]);});+ it('ships FableLoom tombstones without scene assets', async () => {+ vi.mocked(getPeers).mockResolvedValue([+ {+ instanceId: 'peer-a', name: 'Peer A', host: null, address: '192.0.2.10', port: 5555,+ enabled: true, syncEnabled: true,+ directions: ['outbound', 'inbound'],+ syncCategories: { fableLoom: true },+ },+ ]);+ vi.mocked(getLoom).mockResolvedValue({+ id: 'loom-tomb',+ name: 'Example Loom',+ episodes: [{ scenes: [{ imageUrl: '/data/images/doomed.png', videoHistoryId: 'doomed' }] }],+ updatedAt: '2026-01-01T00:00:00Z',+ deleted: true,+ deletedAt: '2026-01-01T00:00:00Z',+ });+ let captured = null;+ vi.mocked(peerFetch).mockImplementation(async (_url, opts) => {+ captured = JSON.parse(opts.body);+ return { ok: true, json: async () => ({}) };+ });++ await pushRecordToPeer({+ id: 'sub-loom', peerId: 'peer-a', recordKind: 'fableLoom', recordId: 'loom-tomb',+ });++ expect(captured.kind).toBe('fableLoom');+ expect(captured.record).toMatchObject({ id: 'loom-tomb', deleted: true });+ expect(captured.assetManifest).toEqual([]);+ });+it('drops deleted child issues from the asset manifest input', async () => {// Deleted issues' tombstones must still ride along in `issues` (so// the receiver's delete cascade runs), but their asset filenames@@ -2812,6 +2873,19 @@ describe('peerSync', () => {);});+ it('dispatches FableLoom pushes through the story merge path', async () => {+ await applyIncomingPush({+ kind: 'fableLoom',+ record: { id: 'loom-1', name: 'Example Story', episodes: [] },+ assetManifest: [],+ sourceInstanceId: 'peer-a',+ });+ expect(mergeLoomsFromSync).toHaveBeenCalledWith(+ [expect.objectContaining({ id: 'loom-1' })],+ { source: { via: 'peer-push', peerId: 'peer-a' } },+ );+ });+it('dispatches music pushes through their merge entry points', async () => {await applyIncomingPush({kind: 'artist',diff --git a/server/services/sharing/peerSyncAssets.js b/server/services/sharing/peerSyncAssets.jsindex 7e02024bee..f5c4ce0683 100644--- a/server/services/sharing/peerSyncAssets.js+++ b/server/services/sharing/peerSyncAssets.js@@ -141,6 +141,7 @@ async function buildIntegrityAssetManifest(kind, record) {if (kind === 'creativeDirectorProject') return buildProjectAssetManifest(record);if (kind === 'musicVideoProject') return buildMusicVideoAssetManifest(record);if (kind === 'moodBoard') return buildBoardAssetManifest(record);+ if (kind === 'fableLoom') return buildFableLoomAssetManifest(record);if (kind === 'series') {const childIssues = await listIssues({ seriesId: record?.id, includeDeleted: true }).catch(() => []);const manifestIssues = childIssues.filter(@@ -548,6 +549,34 @@ export async function buildMusicVideoAssetManifest(project) {return [...dedup.values()];}+/**+ * Hash every rendered scene asset referenced by a FableLoom story. Scene stills+ * are gallery basenames; clips point at video-history ids and the FableLoom+ * player resolves them directly as managed `<id>.mp4` files.+ */+export async function buildFableLoomAssetManifest(loom) {+ const nodes = (Array.isArray(loom?.episodes) ? loom.episodes : [])+ .flatMap((episode) => (Array.isArray(episode?.nodes) ? episode.nodes : []));+ const dedup = new Map();+ const imageNames = [...new Set(+ nodes.map((node) => (isStr(node?.image) ? node.image : null)).filter(Boolean),+ )];+ for (const entry of await Promise.all(imageNames.map((name) => hashImageForManifest(name)))) {+ if (entry) dedup.set(`${entry.kind}:${entry.filename}`, entry);+ }+ const videoIds = [...new Set(+ nodes.map((node) => (isStr(node?.videoHistoryId) ? node.videoHistoryId : null)).filter(Boolean),+ )];+ if (videoIds.length > 0) {+ const entries = await Promise.all(videoIds.map((id) =>+ hashSimpleAsset(collectionVideoRefToFilename(id), 'video', PATHS.videos)));+ for (const entry of entries) {+ if (entry) dedup.set(`${entry.kind}:${entry.filename}`, entry);+ }+ }+ return [...dedup.values()];+}+/*** Hash the local image bytes a mood board's items reference so the receiver can* pull them from `/data/{images,image-refs,videos}/`. An image item points atdiff --git a/server/services/sharing/peerSyncAssets.test.js b/server/services/sharing/peerSyncAssets.test.jsindex 71765fd09d..6c0041f984 100644--- a/server/services/sharing/peerSyncAssets.test.js+++ b/server/services/sharing/peerSyncAssets.test.js@@ -38,6 +38,7 @@ const {buildMusicVideoAssetManifest,buildProjectAssetManifest,buildBoardAssetManifest,+ buildFableLoomAssetManifest,inflightPulls,pullMissingAssetsFromPeer,} = await import('./peerSyncAssets.js');@@ -302,6 +303,37 @@ describe('buildBoardAssetManifest — video items (#4188)', () => {});});+describe('buildFableLoomAssetManifest — scene renders', () => {+ beforeEach(() => {+ tempRoot = mkdtempSync(join(tmpdir(), 'portos-fableloom-assets-'));+ });+ afterEach(() => {+ if (tempRoot) rmSync(tempRoot, { recursive: true, force: true });+ });++ it('bundles and deduplicates scene stills plus managed video-history clips', async () => {+ const imageBytes = Buffer.from('scene-image');+ const videoBytes = Buffer.from('scene-video');+ writeImage('scene.png', imageBytes);+ writeVideo('video-1.mp4', videoBytes);++ const manifest = await buildFableLoomAssetManifest({+ episodes: [+ { nodes: [{ id: 'node-1', image: 'scene.png', videoHistoryId: 'video-1' }] },+ { nodes: [{ id: 'node-2', image: 'scene.png', videoHistoryId: 'video-1' }] },+ ],+ });++ expect(manifest).toContainEqual(expect.objectContaining({+ filename: 'scene.png', kind: 'image', sha256: sha(imageBytes),+ }));+ expect(manifest).toContainEqual({+ filename: 'video-1.mp4', kind: 'video', sha256: sha(videoBytes),+ });+ expect(manifest).toHaveLength(2);+ });+});+describe('pullMissingAssetsFromPeer — unsafe and incomplete downloads (#5230)', () => {beforeEach(() => {tempRoot = mkdtempSync(join(tmpdir(), 'portos-peer-pull-safety-'));diff --git a/server/services/sharing/peerSyncPush.js b/server/services/sharing/peerSyncPush.jsindex 096f435df5..6870cb9680 100644--- a/server/services/sharing/peerSyncPush.js+++ b/server/services/sharing/peerSyncPush.js@@ -36,6 +36,7 @@ import { getTrack } from '../tracks/index.js';import { getProject } from '../creativeDirector/local.js';import { getProject as getMusicVideoProject } from '../musicVideo/projects.js';import { getBoard } from '../moodBoard/index.js';+import { getLoom } from '../fableLoom/index.js';import {getWorkForSync,buildWorkBodyManifest,@@ -55,6 +56,7 @@ import {buildTrackAssetManifest,buildProjectAssetManifest,buildBoardAssetManifest,+ buildFableLoomAssetManifest,buildMusicVideoAssetManifest,} from './peerSyncAssets.js';import {@@ -133,6 +135,10 @@ async function isSubscriptionRecordTombstone(sub) {const record = await getBoard(sub.recordId, { includeDeleted: true }).catch(() => null);return record?.deleted === true;}+ if (sub.recordKind === 'fableLoom') {+ const record = await getLoom(sub.recordId, { includeDeleted: true }).catch(() => null);+ return record?.deleted === true;+ }if (sub.recordKind === 'writersRoomWork') {const record = await getWorkForSync(sub.recordId).catch(() => null);return record?.deleted === true;@@ -492,7 +498,7 @@ export async function pushRecordToPeer(sub, options = {}) {}// Conflict-journal base hash: this record's content now lives on the peer too// (the record always lands even when assets are still pulling), so stamp the- // shared-state base for the two journaled kinds. This is the symmetric+ // shared-state base for conflict-journal-aware kinds. This is the symmetric// convergence point to the receiver advancing its base in mergeXxxFromSync —// it keeps a peer's echo (reverse-subscription push-back) from later looking// like a divergence. Best-effort; never block the push result on a slow DISK@@ -817,6 +823,14 @@ export async function buildPushPayload(sub, sourceInstanceId) {const assetManifest = record.deleted === true ? [] : await buildBoardAssetManifest(record);return { kind: 'moodBoard', record: sanitized, assetManifest, sourceInstanceId, portosMeta };}+ if (sub.recordKind === 'fableLoom') {+ const record = await getLoom(sub.recordId, { includeDeleted: true }).catch(() => null);+ if (!record) return null;+ const sanitized = sanitizeRecordForWire('fableLoom', record);+ if (!sanitized) return null;+ const assetManifest = record.deleted === true ? [] : await buildFableLoomAssetManifest(record);+ return { kind: 'fableLoom', record: sanitized, assetManifest, sourceInstanceId, portosMeta };+ }if (sub.recordKind === 'writersRoomWork') {const record = await getWorkForSync(sub.recordId).catch(() => null);if (!record) return null;@@ -937,4 +951,4 @@ function simplePayloadHash(record) {h = ((h << 5) - h + json.charCodeAt(i)) | 0;}return h.toString(16);-}\ No newline at end of file+}diff --git a/server/services/sharing/peerSyncReceive.js b/server/services/sharing/peerSyncReceive.jsindex 6c52b55247..3537e8be3b 100644--- a/server/services/sharing/peerSyncReceive.js+++ b/server/services/sharing/peerSyncReceive.js@@ -31,6 +31,7 @@ import { getTrack, mergeTracksFromSync } from '../tracks/index.js';import { getProject, mergeProjectsFromSync } from '../creativeDirector/local.js';import { getProject as getMusicVideoProject, mergeProjectsFromSync as mergeMusicVideoProjectsFromSync } from '../musicVideo/projects.js';import { getBoard, mergeBoardsFromSync } from '../moodBoard/index.js';+import { mergeLoomsFromSync } from '../fableLoom/index.js';import {getWorkForSync,mergeWorksFromSync,@@ -338,6 +339,8 @@ export async function applyIncomingPush(payload) {await mergeProjectsFromSync([record], { source });} else if (kind === 'moodBoard') {await mergeBoardsFromSync([record], { source });+ } else if (kind === 'fableLoom') {+ await mergeLoomsFromSync([record], { source });} else if (kind === 'writersRoomWork') {const mergeResult = await mergeWorksFromSync([record], { source });// Did the receiver accept the remote work (insert / remote-won LWW)? Thisdiff --git a/server/services/sharing/peerSyncShared.js b/server/services/sharing/peerSyncShared.jsindex dd0fb116c9..1a8e1832f1 100644--- a/server/services/sharing/peerSyncShared.js+++ b/server/services/sharing/peerSyncShared.js@@ -16,7 +16,7 @@ import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtilsimport { getPeers } from '../instances.js';-export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']);+export const PEER_SUBSCRIBABLE_KINDS = Object.freeze(['universe', 'series', 'mediaCollection', 'author', 'artist', 'album', 'track', 'creativeDirectorProject', 'moodBoard', 'fableLoom', 'writersRoomWork', 'writersRoomFolder', 'writersRoomExercise', 'musicVideoProject', 'commissionFeedback', 'creativeCommission']);/*** Cross-cutting event bus for the peer-sync receiver. The asset-pull worker@@ -97,6 +97,7 @@ export const KIND_TO_CATEGORY = Object.freeze({track: 'tracks',creativeDirectorProject: 'creativeDirectorProjects',moodBoard: 'moodBoards',+ fableLoom: 'fableLoom',writersRoomWork: 'writersRoomWorks',writersRoomFolder: 'writersRoomFolders',writersRoomExercise: 'writersRoomExercises',diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.jsindex b225f5948b..3b83846f78 100644--- a/server/services/sharing/tombstoneGc.js+++ b/server/services/sharing/tombstoneGc.js@@ -50,6 +50,7 @@ import {listProjectIds as listMusicVideoProjectIds,} from '../musicVideo/projects.js';import { pruneTombstonedBoards, listBoardIds } from '../moodBoard/index.js';+import { pruneTombstonedLooms, listLooms } from '../fableLoom/index.js';import {pruneTombstonedWorks, listWorkIdsForSync,pruneTombstonedFolders, listFolderIdsForSync,@@ -84,6 +85,7 @@ const LIVE_ID_LISTERS = Object.freeze({creativeDirectorProject: () => listProjectIds(),musicVideoProject: () => listMusicVideoProjectIds(),moodBoard: () => listBoardIds(),+ fableLoom: async () => (await listLooms()).map((r) => r.id),writersRoomWork: () => listWorkIdsForSync(),writersRoomFolder: () => listFolderIdsForSync(),writersRoomExercise: () => listExerciseIdsForSync(),@@ -109,6 +111,7 @@ const ALL_ID_LISTERS = Object.freeze({creativeDirectorProject: () => listProjectIds({ includeDeleted: true }),musicVideoProject: () => listMusicVideoProjectIds({ includeDeleted: true }),moodBoard: () => listBoardIds({ includeDeleted: true }),+ fableLoom: async () => (await listLooms({ includeDeleted: true })).map((r) => r.id),writersRoomWork: () => listWorkIdsForSync({ includeDeleted: true }),writersRoomFolder: () => listFolderIdsForSync({ includeDeleted: true }),writersRoomExercise: () => listExerciseIdsForSync({ includeDeleted: true }),@@ -354,6 +357,7 @@ function refusedFromCutoffs(cutoffs) {projectCutoff,musicVideoProjectCutoff,boardCutoff,+ fableLoomCutoff,workCutoff,folderCutoff,exerciseCutoff,@@ -377,6 +381,7 @@ function refusedFromCutoffs(cutoffs) {if (projectCutoff === null) refused.push('creativeDirectorProject');if (musicVideoProjectCutoff === null) refused.push('musicVideoProject');if (boardCutoff === null) refused.push('moodBoard');+ if (fableLoomCutoff === null) refused.push('fableLoom');if (workCutoff === null) refused.push('writersRoomWork');if (folderCutoff === null) refused.push('writersRoomFolder');if (exerciseCutoff === null) refused.push('writersRoomExercise');@@ -409,6 +414,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =projectCutoff,musicVideoProjectCutoff,boardCutoff,+ fableLoomCutoff,workCutoff,folderCutoff,exerciseCutoff,@@ -425,6 +431,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =cutoffForKind('creativeDirectorProject', { peers, subs, now, graceMs }),cutoffForKind('musicVideoProject', { peers, subs, now, graceMs }),cutoffForKind('moodBoard', { peers, subs, now, graceMs }),+ cutoffForKind('fableLoom', { peers, subs, now, graceMs }),cutoffForKind('writersRoomWork', { peers, subs, now, graceMs }),cutoffForKind('writersRoomFolder', { peers, subs, now, graceMs }),cutoffForKind('writersRoomExercise', { peers, subs, now, graceMs }),@@ -432,7 +439,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =cutoffForKind('creativeCommission', { peers, subs, now, graceMs }),]);const issueCutoff = seriesCutoff;- const [u, s, i, c, a, ar, al, t, cd, mv, mb, wr, wrf, wre, cfb, cc] = await Promise.all([+ const [u, s, i, c, a, ar, al, t, cd, mv, mb, fl, wr, wrf, wre, cfb, cc] = await Promise.all([universeCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedUniverses(universeCutoff),seriesCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedSeries(seriesCutoff),issueCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedIssues(issueCutoff),@@ -444,6 +451,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =projectCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedProjects(projectCutoff),musicVideoProjectCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedMusicVideoProjects(musicVideoProjectCutoff),boardCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedBoards(boardCutoff),+ fableLoomCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedLooms(fableLoomCutoff),workCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedWorks(workCutoff),folderCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedFolders(folderCutoff),exerciseCutoff === null ? Promise.resolve({ pruned: 0 }) : pruneTombstonedExercises(exerciseCutoff),@@ -476,6 +484,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =creativeDirectorProjects: cd.pruned,musicVideoProjects: mv.pruned,moodBoards: mb.pruned,+ fableLooms: fl.pruned,writersRoomWorks: wr.pruned,writersRoomFolders: wrf.pruned,writersRoomExercises: wre.pruned,@@ -483,7 +492,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =creativeCommissions: cc.pruned,orphanBaseHashes: orphan.pruned,orphanSubscriptions: orphanSubs.pruned,- refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff }),+ refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, fableLoomCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff }),};}@@ -492,7 +501,7 @@ export async function sweepTombstones({ now = Date.now(), graceMs = GRACE_MS } =// coverage matters), so this hardcodes graceMs:0 internally.export async function getSweepStatus({ now = Date.now() } = {}) {const { peers, subs } = await loadState();- const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff] = await Promise.all([+ const [universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, fableLoomCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff] = await Promise.all([cutoffForKind('universe', { peers, subs, now, graceMs: 0 }),cutoffForKind('series', { peers, subs, now, graceMs: 0 }),cutoffForKind('mediaCollection', { peers, subs, now, graceMs: 0 }),@@ -503,13 +512,14 @@ export async function getSweepStatus({ now = Date.now() } = {}) {cutoffForKind('creativeDirectorProject', { peers, subs, now, graceMs: 0 }),cutoffForKind('musicVideoProject', { peers, subs, now, graceMs: 0 }),cutoffForKind('moodBoard', { peers, subs, now, graceMs: 0 }),+ cutoffForKind('fableLoom', { peers, subs, now, graceMs: 0 }),cutoffForKind('writersRoomWork', { peers, subs, now, graceMs: 0 }),cutoffForKind('writersRoomFolder', { peers, subs, now, graceMs: 0 }),cutoffForKind('writersRoomExercise', { peers, subs, now, graceMs: 0 }),cutoffForKind('commissionFeedback', { peers, subs, now, graceMs: 0 }),cutoffForKind('creativeCommission', { peers, subs, now, graceMs: 0 }),]);- return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff }) };+ return { refused: refusedFromCutoffs({ universeCutoff, seriesCutoff, collectionCutoff, authorCutoff, artistCutoff, albumCutoff, trackCutoff, projectCutoff, musicVideoProjectCutoff, boardCutoff, fableLoomCutoff, workCutoff, folderCutoff, exerciseCutoff, commissionFeedbackCutoff, creativeCommissionCutoff }) };}export const TOMBSTONE_GRACE_MS = GRACE_MS;diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.jsindex 312169fad5..d3567f0a25 100644--- a/server/services/sharing/tombstoneGc.test.js+++ b/server/services/sharing/tombstoneGc.test.js@@ -48,6 +48,10 @@ vi.mock('../moodBoard/index.js', () => ({pruneTombstonedBoards: vi.fn().mockResolvedValue({ pruned: 0 }),listBoardIds: vi.fn().mockResolvedValue([]),}));+vi.mock('../fableLoom/index.js', () => ({+ pruneTombstonedLooms: vi.fn().mockResolvedValue({ pruned: 0 }),+ listLooms: vi.fn().mockResolvedValue([]),+}));vi.mock('../writersRoom/sync.js', () => ({pruneTombstonedWorks: vi.fn().mockResolvedValue({ pruned: 0 }),listWorkIdsForSync: vi.fn().mockResolvedValue([]),@@ -94,6 +98,7 @@ import { pruneTombstonedTracks, listTrackIds } from '../tracks/index.js';import { pruneTombstonedProjects } from '../creativeDirector/local.js';import { pruneTombstonedProjects as pruneTombstonedMusicVideoProjects } from '../musicVideo/projects.js';import { pruneTombstonedBoards } from '../moodBoard/index.js';+import { pruneTombstonedLooms } from '../fableLoom/index.js';import { pruneTombstonedWorks, pruneTombstonedFolders, pruneTombstonedExercises } from '../writersRoom/sync.js';import { pruneOrphanedBaseHashes } from '../../lib/conflictJournal.js';import { listPeerSubscriptions, pruneOrphanedPeerSubscriptions } from './peerSync.js';@@ -148,6 +153,7 @@ describe('sweepTombstones — no peers subscribed', () => {expect(pruneTombstonedSeries).toHaveBeenCalledWith(expectedCutoff);expect(pruneTombstonedIssues).toHaveBeenCalledWith(expectedCutoff);expect(pruneTombstonedCollections).toHaveBeenCalledWith(expectedCutoff);+ expect(pruneTombstonedLooms).toHaveBeenCalledWith(expectedCutoff);expect(pruneTombstonedAuthors).toHaveBeenCalledWith(expectedCutoff);expect(pruneTombstonedArtists).toHaveBeenCalledWith(expectedCutoff);expect(pruneTombstonedAlbums).toHaveBeenCalledWith(expectedCutoff);@@ -467,6 +473,7 @@ describe('sweepTombstones — return shape', () => {albums: 6,tracks: 7,creativeDirectorProjects: 8,+ fableLooms: 0,musicVideoProjects: 13,moodBoards: 9,writersRoomWorks: 10,