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([extend-syncorchestrator-to-cover-pipeline-universe]): pipeline + universe sync over Tailscale (#302)
[._.]/ Adam Eivy5e10256e6c7b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 57d6beadbb..8c0727221a 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,6 +8,10 @@- **slashdo submodule bumped to v2.15.0.** Brings drift detection in `do:replan` (flags pending items whose execution would regress newer features) and a persistent `Monitor` in `do:rpr` (one stream emits events for new Copilot reviews + CI bucket transitions, replacing the 5+ background subshells that previously accumulated per multi-round review).- **`/claim` slash command.** Human-driven counterpart to the scheduled `plan-task` agent — at `.claude/commands/claim.md`. Reads PLAN.md, picks the first `- [ ]` whose `[<slug>]` isn't in flight (scans `git branch -a` + `gh pr list` for slug-as-path-segment, skips drift-flagged + NEEDS_INPUT items), creates a `claim/<slug>` worktree off `origin/main`, walks the user through verify → implement → archive (PLAN.md → DONE.md with slug preserved verbatim) → `/simplify` + `/do:pr` → merge → cleanup. Coexists with CoS sub-agents' `cos/<task>/<slug>/<agent>` claims because both place the slug as a `/`-segment visible to either side's in-flight scan. Optional argument lets you target a specific slug for out-of-order work.+### Data Sync++- **Pipeline + universe categories sync over Tailscale.** Sync orchestrator now covers the creative pipeline state — `series.json`, `issues.json`, and `universe-builder.json` — alongside the existing goals / character / digitalTwin / meatspace categories. Record-level only (no image/video blobs; those stay on the share-bucket path). LWW by `updatedAt`; local-only `runs[]` survives every universe merge. The merge runs through dedicated service-level entry points (`mergeUniversesFromSync` in `universeBuilder.js`, `mergeSeriesFromSync` in `pipeline/series.js`, `mergeIssuesFromSync` in `pipeline/issues.js`) so the read-modify-write window lives INSIDE the existing per-file write queue (`queueUniverseWrite` / `queueSeriesWrite` / `queueIssueWrite`) — a concurrent local edit, bible PATCH, season-cover render, or LLM auto-save can't clobber (or be clobbered by) the sync apply. Each entry point also passes incoming remote records through the service's sanitizer (`sanitizeTemplate` / `sanitizeSeries` / `sanitizeIssue`) so older-schema peers (pre-v4 universes missing the canon `kind` field, etc.) land already-migrated. `applyPipelineRemote` returns `{ applied, count, seriesChanged, issuesChanged }` where `count` is records actually changed/added this cycle (NOT total post-merge records — the prior shape over-reported when callers summed cycle deltas). Client `Instances` page adds Universe + Pipeline category meta with Sparkles + Film icons.+### Universe Builder- **CanonCard provenance chip now names the source series.** The "from series" chip on `CanonCard` (rendered by both the Universe Canon section and the per-issue Nouns stage) now reads `from <Series Name>` when an entry's `sourceSeriesId` resolves through a new `seriesNameMap` prop; the tooltip carries both name and id (`Introduced by series "<name>" (<id>)`). Map is sourced from a new top-level `seriesNameMap` field on the `GET /api/universe-builder/:id/canon-usage` response, which now lists every linked series — not just ones with a prose-match row — so an entry whose `sourceSeriesId` points at a series with no matching prose still resolves to a name. Missing-map / unknown-id cases keep the legacy `from series` label + id-only tooltip. New `SourceSeriesChip` helper extracted in `client/src/components/pipeline/CanonCard.jsx`; 4 vitest cases in `CanonCard.test.jsx` + 2 vitest cases in `server/services/canonUsage.test.js`.diff --git a/DONE.md b/DONE.mdindex 6510a376dd..47d5c5e91c 100644--- a/DONE.md+++ b/DONE.md@@ -16,6 +16,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./### 2026-05-17- **[sharing-v2-per-sender-subscription-filenames] Per-sender subscription filenames.** `subscriptionFilename()` now keys on the `senderInstanceId` segment (`sub-<kind>-<recordId>-<senderInstanceId>.json`) so two peers subscribed to the same record write to distinct bucket files instead of clobbering each other. Touched `server/services/sharing/manifest.js` (signature + new `legacySubscriptionFilename` export + `manifestFilename` plumbs `manifest.senderInstanceId` through to the helper + extracted `SUBSCRIPTION_FILE_PREFIX` constant shared with the prune filter), `subscriptions.js` (`unsubscribe` now reads `getInstanceId()` for the new name AND best-effort cleans up the pre-v2 legacy file only when its `senderInstanceId` matches this instance — so a still-subscribed peer's pre-upgrade file isn't stomped), `importer.js` (inbox dedup now keys on `(recordKind, recordId, senderInstanceId)` so peerB's update no longer wipes peerA's inbox row), and the `exporter.js` doc comment. Coverage: 3 new tests in `subscriptions.test.js` (filename-with-sender, legacy cleanup gated on own instance, legacy preserved for other peer's instance), 2 new in `manifest.test.js` (per-sender determinism + two-peer-distinct + `legacySubscriptionFilename` shape), and integration test updated to assert the new naming. All 5,315 server tests pass. Follow-up captured in PLAN.md as `[sharing-inbox-orphans-on-peer-instance-id-rotation]` — per-sender dedup means a peer that rotates its instanceId leaves their old inbox row as an orphan (pre-v2 dedup wiped it implicitly).+- **[extend-syncorchestrator-to-cover-pipeline-universe] Extend `syncOrchestrator` to cover pipeline + universe categories.** Two new snapshot-based sync categories (`pipeline`, `universe`) in `server/services/dataSync.js`, registered in `CATEGORIES`, added to `DEFAULT_SYNC_CATEGORIES` in `server/services/instances.js`, exposed via `categoryParam` enum in `server/routes/dataSync.js`, and surfaced in the peer-config UI via `SYNC_CATEGORY_META` entries (Sparkles / Film icons) in `client/src/pages/Instances.jsx`. Pipeline bundles `pipeline-series.json` + `pipeline-issues.json` into one snapshot; universe ships only `universe-builder.json` `universes[]` (skips ephemeral `runs[]`). Merge is array-by-id LWW on `updatedAt` — routed through dedicated service-level merge entry points (`mergeUniversesFromSync` / `mergeSeriesFromSync` / `mergeIssuesFromSync`) so the read-modify-write runs INSIDE the per-file write queue and each incoming record passes through the service's sanitizer (`sanitizeTemplate` / `sanitizeSeries` / `sanitizeIssue`) on the way in — concurrent local edits can't clobber the merged remote payload, and older-schema peers land already-migrated. `applyPipelineRemote` returns `{ applied, count, seriesChanged, issuesChanged }` where `count` is records actually changed/added this cycle. Sync is record-level only — image/video blobs continue to flow through the share-bucket system. 13 vitest cases in `server/services/dataSync.pipelineUniverse.test.js` (snapshot shape, checksum stability, missing-file tolerance, LWW merge for insert/update/no-op, local-only `runs[]` preservation, partial-write skip, count-semantics for changed-side-only). Deferred follow-ups: `[datasync-migrate-categories-to-atomicwrite]` (collapse the 6+ duplicate `ensureDir + writeFile + JSON.stringify` sites to `atomicWrite`) and `[datasync-checksum-only-fast-path]` (avoid materializing the full payload just to hash it).- **[extract-upsertbyidprepend-helper-universe-builder] Extract `upsertByIdPrepend(list, item)` helper.** New `client/src/lib/upsertByIdPrepend.js` collapses the "filter-by-id then prepend" worlds-list upsert into one helper. The PLAN line called out 3 sites; the actual count was 7 — all collapsed to `setWorlds((prev) => upsertByIdPrepend(prev, entity))`: 1 in `client/src/hooks/useUniverseAction.js` (LLM-action result merge) + 6 in `client/src/pages/UniverseBuilder.jsx` (`handleCreate`, `handleSave`, expand auto-save, refine auto-save, `handleMoveCategoryToTrunk`, `handleGenerateInCategory`). 4 new vitest cases in `upsertByIdPrepend.test.js` (new-id prepend, id replacement, empty-list, no input mutation).- **[universe-builder-redesign-trunks-sub-buckets] Universe Builder redesign — trunks + sub-buckets layout (Phases A–D + Phase C follow-ups).** Multi-phase rewrite landing across 2026-05-15 → 2026-05-17. Phase A added a `kind: 'characters'|'settings'|'objects'|'other'` field to every category bucket + a migration to backfill the built-in defaults; Phase B taught `buildExpansionPrompt()` + `isExpansionShape()` to emit and accept rich canon arrays alongside categories, with client-side `handleExpand` merging canon entries into `universe.{characters,settings,objects}` (dedupe by name, respect locks); Phase C rewrote the page as a tabbed-trunk layout (Bible / Cast / Places / Objects / Other / Composites / Render) with URL state, a unified `EntryCard` rendering both canon entries and category variations, and per-trunk / per-bucket / all-canon batch-render targeting; Phase D shipped `POST /:id/promote-variation` to LLM-expand a variation into a full canon entry (atomic canon append + variation removal in one `updateUniverse` patch, duplicate-name 409 before the LLM call, trunk picker for `kind: 'other'` buckets). Phase C follow-ups closed today: (1) `updateUniverse(id, mutator)` now accepts an async `mutator(latest) => patch` callback that runs INSIDE `queueUniverseWrite` — `autoSortOtherBuckets` and `promoteVariationToCanon` route their read-modify-write through this so a slow LLM call can't admit a concurrent edit between read and persist; promote's variation removal also re-locates by label inside the queue rather than relying on the stale pre-LLM index, and the duplicate-name 409 is re-checked against the latest canon (returns `UNIVERSE_PROMOTE_CATEGORY_GONE` / `UNIVERSE_PROMOTE_VARIATION_GONE` when the bucket/variation disappears mid-flight); (2) `handleAutoSort` / `handlePromoteVariation` / `handleGenerateInCategory` now flush a dirty draft via `handleSave()` before kicking off — `UniverseBuilder.jsx` tracks a `savedDraftSnapshotRef` baseline (compared via `draftSnapshotForDirty`) that updates on universe-load, manual save, expand auto-save, refine auto-save, generate auto-save, and after each LLM mutator's `onFreshResult` merge. `useUniverseAction` gained a `preflight` option that runs AFTER the ref/savedId guard so double-clicks short-circuit before flushing. 5 new server tests (`updateUniverse` mutator overload — happy path, null-skip, throw-propagation, non-object validation, queue-ordering against a parallel literal-patch write) + 4 new client tests (`useUniverseAction` preflight — returns-false abort, throw-as-false, returns-true continue, post-ref-guard ordering).- **[canoncard-from-series-name-full-provenance-label] CanonCard "from series: <name>" full provenance label.** The provenance chip now reads `seriesNameMap?.[entry.sourceSeriesId]` to render `from <Series Name>` with `Introduced by series "<name>" (<id>)` in the tooltip; missing-name fallback preserves the existing `from series` label + id-only tooltip. Chip rendering extracted into a `SourceSeriesChip` helper alongside `ChipPicker` / `ReadonlyChip` in `client/src/components/pipeline/CanonCard.jsx`. Map plumbed from both parents: `UniverseCanonSection.jsx` passes `usage?.seriesNameMap` (no new fetch — reuses the canon-usage call it already makes), and `NounsStage.jsx` fetches `getUniverseCanonUsage(series.universeId)` once on universe load. Server-side `getUniverseCanonUsage` (`server/services/canonUsage.js`) gains a top-level `seriesNameMap: { [seriesId]: name }` field built from every `linkedSeries` (not just ones with prose-match rows) so an entry whose `sourceSeriesId` points at a series with no matching prose still resolves to a name. Coverage: 4 new vitest cases in `CanonCard.test.jsx` (chip omitted with no `sourceSeriesId`; generic fallback when map missing; resolved name + dual-tooltip when present; fallback when id not in map) and 2 new `canonUsage.test.js` cases (linked-with-no-prose-match included; empty map when no series link). NounsStage's per-render fetch is acknowledged as quadratic-cost relative to need; deferred to `[nounsstage-cheaper-seriesnamemap-fetch]` for a thin-endpoint follow-up.diff --git a/PLAN.md b/PLAN.mdindex 52564b0f4d..08dfcf1344 100644--- a/PLAN.md+++ b/PLAN.md@@ -12,7 +12,6 @@ _Nothing currently parked — pick the next item from the Backlog._### Sharing-- [ ] [extend-syncorchestrator-to-cover-pipeline-universe] **Extend `syncOrchestrator` to cover pipeline/universe over Tailscale.** Same-network peers should sync these categories without going through a bucket.- [ ] [multi-hop-provenance-chains-re-share-authors-a] **Multi-hop provenance chains.** Re-share authors a fresh `origin` block; `chain[]` would preserve full attribution. Defer until users ask.- [ ] [same-collection-export-pattern-for-pipeline-series] **Same collection-export pattern for pipeline series with auto-collections.** Series renders that get auto-filed into a per-series collection should also flow through `manifest.collection`.- [ ] [sharing-inbox-live-subscription-badge] **"🔄 live" badge on inbox subscription rows.** No badge UI today; mark rows whose subscription file has updated within the last sync window.@@ -123,6 +122,8 @@ _Nothing currently parked — pick the next item from the Backlog._- [ ] [skip-the-text-accumulator-in-promptrunner] **Skip the `text` accumulator in `promptRunner.runPromptThroughProvider` for TUI providers.** `APPEND_CHUNK(acc, chunk)` runs per stream chunk regardless of provider type, but the TUI branch (post `fix-prose-stage-override`) discards the accumulated `text` and uses `result.text` from `executeTuiRun` instead. Streams can hit hundreds of KB of screen redraws per run — gate the accumulator on `effectiveProvider.type !== 'tui'` in `onData` to skip the per-chunk string concat. Pre-existing buffer cap on `outputBuffer` inside `executeTuiRun` already bounds memory; this is a CPU/alloc micro-opt, not a correctness fix.- [ ] [aitoolkit-loadproviders-corrupt-fallback] **`loadProviders` JSON.parse `try/catch` with `.corrupt` rename fallback.** `server/lib/aiToolkit/providers.js:58-79` calls `JSON.parse` unguarded (lines 65, 71); a corrupt file crashes startup. Catch + rename to `.corrupt` + start from empty, with a single-line `console.error` log.- [ ] [aitoolkit-createprovider-field-parity-test] **`createProvider` field-parity test.** Existing `providers.test.js` covers basic fields only. Add an exhaustive assertion that every field in `providerSchema` survives the `createProvider → save → loadProviders` round-trip — guards against the `createProvider` field-list regression noted in CLAUDE.md ("`updateProvider` uses spread but `createProvider` has explicit field list").+- [ ] [datasync-migrate-categories-to-atomicwrite] **Migrate all `dataSync.js` categories to `atomicWrite`.** Every category (`goals`, `character`, `digitalTwin`, `meatspace`, `universe`, `pipeline`) inlines `ensureDir + writeFile + JSON.stringify(..., null, 2)` — 6+ duplicate sites. `server/lib/fileUtils.js:124` exports `atomicWrite(path, data)` that handles all three steps as a temp+rename atomic write. One-line collapse per site + meaningful partial-write protection for the larger pipeline JSON files (which other services write concurrently). Surfaced by /simplify during `extend-syncorchestrator-to-cover-pipeline-universe`; deferred to keep that PR focused on the new categories.+- [ ] [datasync-checksum-only-fast-path] **Add a checksum-only fast path to `dataSync.js`.** `getChecksum(category)` currently calls the category's `getSnapshot` and discards `data` (`server/services/dataSync.js:451-456`) — every probe materializes the full payload. With pipeline/universe added the wasted work scales with the largest user-creative payload. Define per-category `getChecksum` shortcuts (e.g. hash file size+mtime, or hash raw bytes without parse) and dispatch via `CATEGORIES[cat].getChecksum`. The orchestrator hits the checksum endpoint every cycle — this is the hottest sync-side I/O. Surfaced by /simplify during `extend-syncorchestrator-to-cover-pipeline-universe`.### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsxindex e194ce4801..d34c5529d6 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+ Lock, Globe, Info, Sparkles, Film} from 'lucide-react';import toast from '../components/ui/Toast';import socket from '../services/socket';@@ -411,7 +411,9 @@ const SYNC_CATEGORY_META = [{ key: 'goals', label: 'Goals', icon: Target, description: 'Life goals, milestones, progress tracking' },{ key: 'character', label: 'Character', icon: Sword, description: 'XP, HP, level, events, character sheet' },{ key: 'digitalTwin', label: 'Digital Twin', icon: Fingerprint, description: 'Identity, chronotype, longevity, feedback' },- { key: 'meatspace', label: 'Meatspace', icon: HeartPulse, description: 'Daily logs, blood tests, body metrics, eyes' }+ { key: 'meatspace', label: 'Meatspace', icon: HeartPulse, description: 'Daily logs, blood tests, body metrics, eyes' },+ { key: 'universe', label: 'Universe', icon: Sparkles, description: 'Universe Builder canon: characters, places, objects' },+ { key: 'pipeline', label: 'Pipeline', icon: Film, description: 'Series + issues record state (no image/video blobs)' }];// Snapshot categories (excludes delta-based brain/memory)diff --git a/server/routes/dataSync.js b/server/routes/dataSync.jsindex d844d6b7d5..cc1ef61142 100644--- a/server/routes/dataSync.js+++ b/server/routes/dataSync.js@@ -12,7 +12,7 @@ import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = Router();-const categoryParam = z.enum(['goals', 'character', 'digitalTwin', 'meatspace']);+const categoryParam = z.enum(['goals', 'character', 'digitalTwin', 'meatspace', 'universe', 'pipeline']);// GET /api/sync/:category/checksum — return checksum only (lightweight)router.get('/:category/checksum', asyncHandler(async (req, res) => {diff --git a/server/services/dataSync.js b/server/services/dataSync.jsindex 8ec8041438..a00c831cef 100644--- a/server/services/dataSync.js+++ b/server/services/dataSync.js@@ -10,6 +10,9 @@ import crypto from 'crypto';import { writeFile } from 'fs/promises';import { join } from 'path';import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';+import { mergeUniversesFromSync } from './universeBuilder.js';+import { mergeSeriesFromSync } from './pipeline/series.js';+import { mergeIssuesFromSync } from './pipeline/issues.js';// --- Category Definitions ---@@ -20,6 +23,9 @@ const CHRONOTYPE_FILE = join(PATHS.digitalTwin, 'chronotype.json');const LONGEVITY_FILE = join(PATHS.digitalTwin, 'longevity.json');const FEEDBACK_FILE = join(PATHS.digitalTwin, 'feedback.json');const MEATSPACE_DIR = PATHS.meatspace;+const PIPELINE_SERIES_FILE = join(PATHS.data, 'pipeline-series.json');+const PIPELINE_ISSUES_FILE = join(PATHS.data, 'pipeline-issues.json');+const UNIVERSE_BUILDER_FILE = join(PATHS.data, 'universe-builder.json');const MEATSPACE_FILES = {'daily-log.json': { arrayKey: 'entries', idField: 'date' },@@ -335,13 +341,92 @@ async function applyMeatspaceRemote(remoteData) {return { applied: totalApplied > 0, count: totalApplied };}+// Pipeline + universe sync covers the creative pipeline state (series, issues,+// universes) over Tailscale between same-network peers. Same-content image and+// video blobs continue to flow through the share-bucket system (cloud-synced+// folders) — those are too large for the snapshot-every-cycle pattern this+// service uses. Sync here is record-level only: serialized state for the+// records, no media blobs.++// --- Category: Universe ---++async function getUniverseSnapshot() {+ const data = await readJSONFile(UNIVERSE_BUILDER_FILE, { universes: [] });+ // Skip `runs[]` — that's local LLM run history (transcripts, ephemeral),+ // not user-edited universe state. Each peer keeps its own history.+ const universesOnly = { universes: data.universes || [] };+ return { data: universesOnly, checksum: computeChecksum(universesOnly) };+}++async function applyUniverseRemote(remoteData) {+ if (!remoteData) return { applied: false, count: 0 };+ // Routes through `mergeUniversesFromSync` so the read-modify-write runs+ // INSIDE `queueUniverseWrite` (serialized against every other writer:+ // create / update / promote-variation / handleSave) and each incoming+ // remote record passes through `sanitizeTemplate` for schema-version+ // backfill — older peers landing pre-v4 records get them migrated on the+ // way in instead of polluting disk with un-backfilled state.+ const result = await mergeUniversesFromSync(remoteData.universes || []);+ if (result.applied) {+ console.log(`🔄 Universe sync: merged ${result.count} universe(s)`);+ }+ return result;+}++// --- Category: Pipeline ---++async function getPipelineSnapshot() {+ const [seriesFile, issuesFile] = await Promise.all([+ readJSONFile(PIPELINE_SERIES_FILE, { series: [] }),+ readJSONFile(PIPELINE_ISSUES_FILE, { issues: [] }),+ ]);+ const data = {+ series: seriesFile.series || [],+ issues: issuesFile.issues || [],+ };+ return { data, checksum: computeChecksum(data) };+}++async function applyPipelineRemote(remoteData) {+ if (!remoteData) return { applied: false, count: 0 };+ // Routes through the per-file merge entry points so each side's+ // read-modify-write runs INSIDE its own file-level write queue+ // (`queueSeriesWrite` / `queueIssueWrite`) — serialized against every other+ // local writer (bible edits, season metadata PATCH, season-cover render+ // PATCH, updateStage, etc.). Each incoming record passes through its+ // service's sanitizer for shape enforcement on the way in.+ const [seriesResult, issuesResult] = await Promise.all([+ mergeSeriesFromSync(remoteData.series || []),+ mergeIssuesFromSync(remoteData.issues || []),+ ]);++ const seriesChanged = seriesResult.count;+ const issuesChanged = issuesResult.count;+ if (seriesChanged === 0 && issuesChanged === 0) return { applied: false, count: 0 };++ // `count` is the total number of records actually changed/added by this+ // merge (NOT total post-merge records — that would over-report when callers+ // sum across categories or compare cycle-over-cycle deltas). `seriesChanged`+ // / `issuesChanged` are surfaced separately so per-side telemetry stays+ // distinguishable.+ console.log(`🔄 Pipeline sync: merged ${seriesChanged} series + ${issuesChanged} issue(s)`);+ return {+ applied: true,+ count: seriesChanged + issuesChanged,+ seriesChanged,+ issuesChanged,+ };+}+// --- Public API ---const CATEGORIES = {goals: { getSnapshot: getGoalsSnapshot, applyRemote: applyGoalsRemote },character: { getSnapshot: getCharacterSnapshot, applyRemote: applyCharacterRemote },digitalTwin: { getSnapshot: getDigitalTwinSnapshot, applyRemote: applyDigitalTwinRemote },- meatspace: { getSnapshot: getMeatspaceSnapshot, applyRemote: applyMeatspaceRemote }+ meatspace: { getSnapshot: getMeatspaceSnapshot, applyRemote: applyMeatspaceRemote },+ universe: { getSnapshot: getUniverseSnapshot, applyRemote: applyUniverseRemote },+ pipeline: { getSnapshot: getPipelineSnapshot, applyRemote: applyPipelineRemote }};export function getSupportedCategories() {diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.jsnew file mode 100644index 0000000000..0826e9eb13--- /dev/null+++ b/server/services/dataSync.pipelineUniverse.test.js@@ -0,0 +1,226 @@+/**+ * Tests for the `pipeline` and `universe` sync categories added in PR+ * [extend-syncorchestrator-to-cover-pipeline-universe].+ *+ * Covers: snapshot shape, checksum stability across no-op reads, array-by-id+ * LWW merge for series/issues/universes, no-blob coverage (the sync is+ * record-level only — images and videos flow through the sharing system).+ */++import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';+import { writeFileSync, mkdirSync, readFileSync, rmSync } from 'fs';+import { join } from 'path';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';++const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-datasync-piuni-' });++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makeProxy(actual);+});++afterAll(cleanup);++const dataSync = await import('./dataSync.js');++const SERIES_PATH = join(tempRoot, 'pipeline-series.json');+const ISSUES_PATH = join(tempRoot, 'pipeline-issues.json');+const UNIVERSE_PATH = join(tempRoot, 'universe-builder.json');++function writeJSON(path, obj) {+ mkdirSync(tempRoot, { recursive: true });+ writeFileSync(path, JSON.stringify(obj, null, 2));+}++function readJSON(path) {+ return JSON.parse(readFileSync(path, 'utf-8'));+}++beforeEach(() => {+ rmSync(tempRoot, { recursive: true, force: true });+ mkdirSync(tempRoot, { recursive: true });+});++describe('dataSync — universe category', () => {+ it('is registered alongside the other categories', () => {+ const cats = dataSync.getSupportedCategories();+ expect(cats).toContain('universe');+ expect(cats).toContain('pipeline');+ expect(cats).toContain('goals'); // sanity+ });++ it('snapshot returns just `universes` (not `runs`)', async () => {+ writeJSON(UNIVERSE_PATH, {+ universes: [{ id: 'u1', name: 'Salt', updatedAt: '2026-05-17T10:00:00Z' }],+ runs: [{ id: 'r1', logs: ['ephemeral'] }]+ });+ const snap = await dataSync.getSnapshot('universe');+ expect(snap.data.universes).toHaveLength(1);+ expect(snap.data.universes[0].id).toBe('u1');+ expect(snap.data.runs).toBeUndefined();+ expect(snap.checksum).toBeTruthy();+ });++ it('snapshot checksum is stable across reads when state is unchanged', async () => {+ writeJSON(UNIVERSE_PATH, { 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);+ });++ it('snapshot handles a missing file gracefully', async () => {+ const snap = await dataSync.getSnapshot('universe');+ expect(snap.data.universes).toEqual([]);+ expect(snap.checksum).toBeTruthy();+ });++ it('applyRemote inserts a new universe', async () => {+ writeJSON(UNIVERSE_PATH, { 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);+ expect(persisted.universes).toHaveLength(1);+ expect(persisted.universes[0].id).toBe('u-new');+ // Local-only `runs` must survive the merge.+ expect(persisted.runs).toEqual([]);+ });++ it('applyRemote LWW: newer remote wins, older remote is dropped', async () => {+ writeJSON(UNIVERSE_PATH, {+ 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');++ // 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');+ });++ it('applyRemote preserves local-only `runs[]` when only universes change', async () => {+ // Runs need a valid shape — `sanitizeRun` requires id + universeId since+ // the merge now routes through the service-level entry point that+ // sanitizes every read.+ const localRun = {+ id: 'r1', universeId: 'u-local', collectionId: null,+ jobIds: [], promptCount: 0, createdAt: '2026-05-17T09:00:00Z',+ };+ writeJSON(UNIVERSE_PATH, { universes: [], runs: [localRun] });+ await dataSync.applyRemote('universe', {+ universes: [{ id: 'u1', name: 'X', updatedAt: '2026-05-17T10:00:00Z' }]+ });+ const persisted = readJSON(UNIVERSE_PATH);+ expect(persisted.runs).toHaveLength(1);+ expect(persisted.runs[0].id).toBe('r1');+ expect(persisted.runs[0].universeId).toBe('u-local');+ });+});++describe('dataSync — pipeline category', () => {+ it('snapshot bundles series + issues from their respective files', async () => {+ writeJSON(SERIES_PATH, {+ series: [{ id: 'ser-1', name: 'A', updatedAt: '2026-05-17T10:00:00Z' }]+ });+ writeJSON(ISSUES_PATH, {+ issues: [{ id: 'iss-1', seriesId: 'ser-1', title: 'One', updatedAt: '2026-05-17T10:00:00Z' }]+ });+ const snap = await dataSync.getSnapshot('pipeline');+ expect(snap.data.series).toHaveLength(1);+ expect(snap.data.issues).toHaveLength(1);+ expect(snap.data.issues[0].seriesId).toBe('ser-1');+ });++ it('snapshot tolerates missing files', async () => {+ const snap = await dataSync.getSnapshot('pipeline');+ expect(snap.data.series).toEqual([]);+ expect(snap.data.issues).toEqual([]);+ });++ it('applyRemote merges series + issues; count reports records actually changed', async () => {+ writeJSON(SERIES_PATH, { series: [{ id: 'ser-1', name: 'Old', updatedAt: '2026-05-17T10:00:00Z' }] });+ writeJSON(ISSUES_PATH, { issues: [] });++ const result = await dataSync.applyRemote('pipeline', {+ series: [+ { id: 'ser-1', name: 'New', updatedAt: '2026-05-17T11:00:00Z' },+ { id: 'ser-2', name: 'Foundry', updatedAt: '2026-05-17T10:00:00Z' }+ ],+ issues: [+ { id: 'iss-1', seriesId: 'ser-2', title: 'Pilot', updatedAt: '2026-05-17T10:00:00Z' }+ ]+ });+ expect(result.applied).toBe(true);+ // `count` is records actually changed/added this cycle, NOT total post-+ // merge records (which would over-report when callers sum across cycles+ // or categories). Two series updated/added + one issue added = 3.+ expect(result.count).toBe(3);+ // Per-side breakdown surfaced for telemetry that wants to distinguish them.+ expect(result.seriesChanged).toBe(2);+ expect(result.issuesChanged).toBe(1);++ const persistedSeries = readJSON(SERIES_PATH).series;+ expect(persistedSeries).toHaveLength(2);+ expect(persistedSeries.find(s => s.id === 'ser-1').name).toBe('New'); // LWW+ expect(persistedSeries.find(s => s.id === 'ser-2').name).toBe('Foundry');++ const persistedIssues = readJSON(ISSUES_PATH).issues;+ expect(persistedIssues).toHaveLength(1);+ expect(persistedIssues[0].seriesId).toBe('ser-2');+ });++ it('applyRemote count reports only the changed side when only series differs', async () => {+ writeJSON(SERIES_PATH, { series: [{ id: 'ser-1', name: 'Old', updatedAt: '2026-05-17T10:00:00Z' }] });+ // Local issues exist but won't change — sync must not inflate count to+ // include them (the pre-fix bug counted total post-merge issues).+ writeJSON(ISSUES_PATH, { issues: [{ id: 'iss-1', seriesId: 'ser-1', title: 'Local', updatedAt: '2026-05-17T10:00:00Z' }] });++ const result = await dataSync.applyRemote('pipeline', {+ series: [{ id: 'ser-1', name: 'New', updatedAt: '2026-05-17T11:00:00Z' }],+ issues: [{ id: 'iss-1', seriesId: 'ser-1', title: 'Stale', updatedAt: '2026-05-17T09:00:00Z' }], // older, skipped+ });+ expect(result.applied).toBe(true);+ expect(result.count).toBe(1); // one series change; issues side unchanged+ expect(result.seriesChanged).toBe(1);+ expect(result.issuesChanged).toBe(0);+ });++ it('applyRemote is a no-op when nothing is newer', async () => {+ writeJSON(SERIES_PATH, { series: [{ id: 'ser-1', updatedAt: '2026-05-17T10:00:00Z' }] });+ writeJSON(ISSUES_PATH, { issues: [{ id: 'iss-1', updatedAt: '2026-05-17T10:00:00Z' }] });++ const before = readJSON(SERIES_PATH);+ const result = await dataSync.applyRemote('pipeline', {+ series: [{ id: 'ser-1', updatedAt: '2026-05-17T10:00:00Z' }], // same ts+ issues: [{ id: 'iss-1', updatedAt: '2026-05-17T09:00:00Z' }] // older+ });+ expect(result.applied).toBe(false);+ expect(result.count).toBe(0);+ expect(readJSON(SERIES_PATH)).toEqual(before);+ });++ it('applyRemote skips writes for unchanged sides (writes only what differs)', async () => {+ writeJSON(SERIES_PATH, { series: [{ id: 'ser-1', updatedAt: '2026-05-17T10:00:00Z' }] });+ writeJSON(ISSUES_PATH, { issues: [] });++ // Only issues change. Use a valid issue payload (id + seriesId + title)+ // since the merge now routes through sanitizeIssue.+ await dataSync.applyRemote('pipeline', {+ series: [{ id: 'ser-1', updatedAt: '2026-05-17T09:00:00Z' }], // older → skipped+ issues: [{ id: 'iss-new', seriesId: 'ser-1', title: 'New Issue', updatedAt: '2026-05-17T11:00:00Z' }]+ });++ // Series file untouched (no incidental rewrite that could clobber a+ // concurrent write outside the sync orchestrator).+ expect(readJSON(SERIES_PATH).series[0].updatedAt).toBe('2026-05-17T10:00:00Z');+ expect(readJSON(ISSUES_PATH).issues).toHaveLength(1);+ });+});diff --git a/server/services/instances.js b/server/services/instances.jsindex 19dd828f65..f597c4cc5e 100644--- a/server/services/instances.js+++ b/server/services/instances.js@@ -155,7 +155,9 @@ const DEFAULT_SYNC_CATEGORIES = {goals: false,character: false,digitalTwin: false,- meatspace: false+ meatspace: false,+ universe: false,+ pipeline: false};export { DEFAULT_SYNC_CATEGORIES };diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex fec64c4432..aaba12a4bd 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -649,3 +649,43 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {return { issue: mergedIssue, stage: mergedIssue.stages[stageId] };}); // end queueIssueWrite}++/**+ * Sync-orchestrator entry point. Merges a remote peer's issues array into+ * local state INSIDE `queueIssueWrite`, so the read-modify-write window can't+ * clobber (or be clobbered by) a concurrent updateIssue / updateStage /+ * cover-render PATCH running through the same queue. Each incoming record+ * passes through `sanitizeIssue` for shape enforcement (stage statuses,+ * trimmed fields, valid id format). LWW by `updatedAt`; returns+ * `{ applied, count }` where `count` is the number of issues actually+ * changed/added.+ */+export function mergeIssuesFromSync(remoteIssues) {+ if (!Array.isArray(remoteIssues)) return Promise.resolve({ applied: false, count: 0 });+ return queueIssueWrite(async () => {+ const state = await readState();+ const localById = new Map(state.issues.map((i) => [i.id, i]));+ let changed = 0;+ for (const remote of remoteIssues) {+ if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;+ const sanitized = sanitizeIssue(remote);+ if (!sanitized) continue;+ const local = localById.get(sanitized.id);+ if (!local) {+ localById.set(sanitized.id, sanitized);+ changed++;+ } else {+ const localTs = local.updatedAt || '';+ const remoteTs = sanitized.updatedAt || '';+ if (remoteTs > localTs) {+ localById.set(sanitized.id, sanitized);+ changed++;+ }+ }+ }+ if (changed === 0) return { applied: false, count: 0 };+ state.issues = Array.from(localById.values());+ await writeState(state);+ return { applied: true, count: changed };+ });+}diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex 83a69f8036..0286de9235 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -309,3 +309,42 @@ export async function deleteSeries(id) {return { id };});}++/**+ * Sync-orchestrator entry point. Merges a remote peer's series array into+ * local state INSIDE `queueSeriesWrite`, so the read-modify-write window+ * can't clobber (or be clobbered by) a concurrent bible edit, season-metadata+ * PATCH, season-cover render PATCH, or season-cover filename hook also running+ * through the same queue. Each incoming record passes through `sanitizeSeries`+ * for shape enforcement. LWW by `updatedAt`; returns `{ applied, count }`+ * where `count` is the number of series actually changed/added.+ */+export async function mergeSeriesFromSync(remoteSeries) {+ if (!Array.isArray(remoteSeries)) return { applied: false, count: 0 };+ return queueSeriesWrite(async () => {+ const state = await readState();+ const localById = new Map(state.series.map((s) => [s.id, s]));+ let changed = 0;+ for (const remote of remoteSeries) {+ if (!remote || typeof remote !== 'object' || !isStr(remote.id)) continue;+ const sanitized = sanitizeSeries(remote);+ if (!sanitized) continue;+ const local = localById.get(sanitized.id);+ if (!local) {+ localById.set(sanitized.id, sanitized);+ changed++;+ } else {+ const localTs = local.updatedAt || '';+ const remoteTs = sanitized.updatedAt || '';+ if (remoteTs > localTs) {+ localById.set(sanitized.id, sanitized);+ changed++;+ }+ }+ }+ if (changed === 0) return { applied: false, count: 0 };+ state.series = Array.from(localById.values());+ await writeState(state);+ return { applied: true, count: changed };+ });+}diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 859f9b797b..096fbdf3c3 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -912,6 +912,53 @@ export async function deleteUniverse(id) {return { 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.+ *+ * Each incoming remote record passes through `sanitizeTemplate` so older-+ * schema payloads (pre-v4 universes missing `kind`, prose stylePrompt/+ * negativePrompt, retired `characters` bucket) land on disk already migrated —+ * matching every other entry path into this file (`createUniverse`,+ * `insertUniverseWithId`, `updateUniverse`).+ *+ * LWW semantics by `updatedAt`. Local-only `runs[]` survives the merge+ * (ephemeral, per-peer). Returns `{ applied, count }` where `count` is the+ * number of universes actually changed/added by this merge — NOT the total+ * post-merge count — so callers summing across categories don't over-report.+ */+export async function mergeUniversesFromSync(remoteUniverses) {+ if (!Array.isArray(remoteUniverses)) return { applied: false, count: 0 };+ return 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;+ const local = localById.get(sanitized.id);+ if (!local) {+ localById.set(sanitized.id, sanitized);+ changed++;+ } else {+ const localTs = local.updatedAt || '';+ const remoteTs = sanitized.updatedAt || '';+ if (remoteTs > localTs) {+ localById.set(sanitized.id, sanitized);+ changed++;+ }+ }+ }+ if (changed === 0) return { applied: false, count: 0 };+ state.universes = Array.from(localById.values());+ await writeState(state);+ return { applied: true, count: changed };+ });+}+export async function recordRun(run) {const sanitized = sanitizeRun(run);if (!sanitized) throw makeErr('Invalid run payload', ERR_VALIDATION);