Skip to content

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

feat(sharing): id-preserving auto-merge + override notifications + integration tests

[._.]/ Adam Eivy9182bbe96ed5
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 6f627a95fb..0eea1b5278 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,23 @@
## Added
+- **Sharing v1.1 — id-preserving auto-merge + override notifications.**
+ Round-trip refinements on top of the v1 share-buckets feature:
+ - Imports now insert under the manifest's original record id (new
+ `insertSeriesWithId` / `insertIssueWithId` / `insertUniverseWithId`
+ helpers). A subsequent re-share of the same series LWW-merges onto
+ the same local row instead of accumulating a duplicate. Issue
+ `seriesId` references stay valid across peers without rewiring.
+ - `applyAutoMerge` now returns an `overridden[]` list naming the local
+ records LWW-overwrote by an incoming share. A new global
+ `useSharingNotifications` hook (mounted in `Layout.jsx`) listens to
+ the `sharing:manifest-processed` socket event and toasts the user —
+ suppressed when they're already viewing `/sharing`. Suffices for
+ "your work just got changed by peer X" awareness without modal noise.
+ - Integration tests at `server/services/sharing/integration.test.js`
+ exercise the full export → manifest → import round-trip in both
+ `inbox` and `auto-merge` modes, plus cursor-dedup on replay.
+
- **Cross-network sharing via cloud-synced folders (share buckets).**
Pipeline series (with all issues + linked universe), universes, and
individual media can now be shared with peers on **different Tailscale
diff --git a/PLAN.md b/PLAN.md
index f0c2ba2617..32c24da08c 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -6,15 +6,13 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
## Next Up
-### Cross-network sharing via cloud-synced folders ("Share Buckets") — v1 shipped
+### Cross-network sharing via cloud-synced folders ("Share Buckets") — v1.1 shipped
-V1 landed: buckets, ShareToButton on Pipeline + UniverseBuilder + MediaCollection, OriginBadge, exporter with full gen-metadata fidelity, importer with `auto-merge` + `inbox` modes, chokidar watcher, configurable `sharingDisplayName` source attribution, nav-manifest registration, unit tests for buckets/manifest/origin. See `~/.claude/plans/new-high-priority-task-valiant-wall.md` for design. Remaining follow-ups:
+V1 landed: buckets, ShareToButton on Pipeline + UniverseBuilder + MediaCollection, OriginBadge, exporter with full gen-metadata fidelity, importer with `auto-merge` + `inbox` modes, chokidar watcher, configurable `sharingDisplayName` source attribution, nav-manifest registration. V1.1: id-preserving inserts (`insertSeriesWithId` / `insertIssueWithId` / `insertUniverseWithId`) so re-shares LWW-merge instead of duplicating; `overridden[]` outcome surfaced via socket → global `useSharingNotifications` toast; round-trip integration tests. See `~/.claude/plans/new-high-priority-task-valiant-wall.md` for design. Remaining follow-ups:
-- [ ] **Inbox-route + exporter integration tests.** Unit tests cover bucket validation, manifest helpers, origin sanitizer. End-to-end exporter+importer flow (export series → simulate peer pickup → promote) is only verified by manual smoke at v1; add `server/routes/sharing.test.js` + `server/services/sharing/exporter.test.js` + `importer.test.js` with mocked PATHS to cover the round-trip + asset copy + LWW merge paths.
-- [ ] **Preserve series id on auto-merge insert.** Today `applyAutoMerge` falls back to `createSeries` for new arrivals, which assigns a fresh local id (re-shares of the same series would land as duplicates). Either expose an `insertSeriesWithId` helper from `services/pipeline/series.js` for the importer, or normalize via the manifest's bucketId+originalId pair so subsequent updates LWW-merge into the right local record. Same applies to `universeBuilder.createUniverse`.
- [ ] **Per-instance display-name fallback inside the Sharing page.** Settings save flow currently lives on the Sharing page top strip; mirror it into the existing Settings tab structure (`client/src/components/settings/`) so the field is discoverable from both surfaces.
-- [ ] **Conflict UI for auto-merge.** Today incoming records LWW silently. When a remote record overwrites a local one with a newer `updatedAt`, surface a notification ("auto-merged 'My Series' — local changes overridden") so the user knows. Could piggyback on the existing toast + `sharing:manifest-processed` socket event.
- [ ] **Manifest archive pruning.** A bucket lived long enough accumulates thousands of manifests under `<bucket>/manifests/`. Add a per-bucket retention policy (e.g. keep last 500 manifests, archive the rest into `manifests/.archive/` or drop entirely once cursor advances past them).
+- [ ] **Route-level tests for `server/routes/sharing.js`.** Bucket CRUD + export + inbox actions are exercised through the service layer in integration.test.js, but the HTTP surface (Zod rejection, error mapping) is uncovered. Add a `server/routes/sharing.test.js` to lock the JSON contract.
- [ ] **Native Google Drive / Dropbox API integration.** Mount-the-folder transport ships v1; a future iteration could integrate Drive API directly so users don't have to mount the drive themselves.
- [ ] **Content-addressed asset dedup.** Today asset copies skip-if-filename-exists. Hash-based dedup would let multiple manifests share the same blob even when filenames differ.
- [ ] **Extend `syncOrchestrator` to cover pipeline/universe over Tailscale.** Separate ticket from buckets — same-network peers on Tailscale should be able to sync these categories without going through a bucket.
diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsx
index e977b2f57a..da3191de2f 100644
--- a/client/src/components/Layout.jsx
+++ b/client/src/components/Layout.jsx
@@ -87,6 +87,7 @@ import Logo from './Logo';
import { useErrorNotifications } from '../hooks/useErrorNotifications';
import { useNotifications } from '../hooks/useNotifications';
import { useAgentFeedbackToast } from '../hooks/useAgentFeedbackToast';
+import { useSharingNotifications } from '../hooks/useSharingNotifications';
import { useUpdateChecker } from '../hooks/useUpdateChecker';
import { useAIStatusNotifications } from '../hooks/useAIStatusNotifications';
import { useThemeContext } from './ThemeContext';
@@ -352,6 +353,8 @@ export default function Layout() {
// Subscribe to server error notifications
useErrorNotifications();
+ // Toast when an auto-merge bucket overwrites a local record
+ useSharingNotifications();
// Subscribe to agent completion feedback toasts
useAgentFeedbackToast();
diff --git a/client/src/hooks/useSharingNotifications.js b/client/src/hooks/useSharingNotifications.js
new file mode 100644
index 0000000000..4768747ed5
--- /dev/null
+++ b/client/src/hooks/useSharingNotifications.js
@@ -0,0 +1,34 @@
+import { useEffect } from 'react';
+import socket from '../services/socket';
+import toast from '../components/ui/Toast';
+
+/**
+ * Global subscriber for share-bucket notifications. Mirrors useErrorNotifications:
+ * mounts once in Layout.jsx so any open page hears about auto-merge updates
+ * regardless of where the user is in the app.
+ *
+ * The Sharing page itself does NOT need to toast — it already lists incoming
+ * activity in its own UI. We suppress the toast when the user is on /sharing
+ * to avoid the duplicate.
+ */
+export function useSharingNotifications() {
+ useEffect(() => {
+ const onManifestProcessed = (payload) => {
+ const overridden = payload?.outcome?.overridden;
+ if (!Array.isArray(overridden) || overridden.length === 0) return;
+ if (typeof window !== 'undefined' && window.location?.pathname?.startsWith('/sharing')) return;
+ const labels = overridden
+ .slice(0, 3)
+ .map((o) => `${o.kind === 'issue' ? 'Issue' : o.kind === 'universe' ? 'Universe' : 'Series'} "${o.label || o.id}"`);
+ const more = overridden.length > 3 ? ` (+${overridden.length - 3} more)` : '';
+ toast(`Auto-merged: ${labels.join(', ')}${more}`, {
+ icon: '🔄',
+ duration: 8000,
+ });
+ };
+ socket.on('sharing:manifest-processed', onManifestProcessed);
+ return () => {
+ socket.off('sharing:manifest-processed', onManifestProcessed);
+ };
+ }, []);
+}
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index bae260114d..3459988343 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -56,8 +56,11 @@ function queueIssueWrite(_issueId, fn) {
export const ERR_NOT_FOUND = 'PIPELINE_ISSUE_NOT_FOUND';
export const ERR_VALIDATION = 'PIPELINE_ISSUE_VALIDATION';
+export const ERR_DUPLICATE = 'PIPELINE_ISSUE_DUPLICATE';
const makeErr = (message, code) => Object.assign(new Error(message), { code });
+const ISSUE_ID_RE = /^iss-[A-Za-z0-9-]+$/;
+
export const TITLE_MAX = 300;
export const SERIES_ID_MAX = 64;
export const SEASON_ID_MAX = 64;
@@ -318,6 +321,32 @@ function nextIssueNumber(issues, seriesId) {
return Math.max(...peers.map((i) => i.number || 0)) + 1;
}
+/**
+ * Insert an issue with a caller-supplied id (used by the share-bucket importer
+ * so re-imports of the same issue LWW-merge onto the same local row).
+ * Throws ERR_DUPLICATE / ERR_VALIDATION on contract violations.
+ */
+export function insertIssueWithId(input = {}) {
+ if (!isStr(input.id) || !ISSUE_ID_RE.test(input.id)) {
+ return Promise.reject(makeErr(`insertIssueWithId: invalid id "${input.id}" (expected iss-<uuid>)`, ERR_VALIDATION));
+ }
+ const seriesId = trimTo(input.seriesId, SERIES_ID_MAX);
+ if (!seriesId) return Promise.reject(makeErr('seriesId is required', ERR_VALIDATION));
+ const title = trimTo(input.title, TITLE_MAX);
+ if (!title) return Promise.reject(makeErr(`title is required (1..${TITLE_MAX} chars)`, ERR_VALIDATION));
+ return queueIssueWrite(input.id, async () => {
+ const state = await readState();
+ if (state.issues.some((i) => i.id === input.id)) {
+ throw makeErr(`Issue id already exists: ${input.id}`, ERR_DUPLICATE);
+ }
+ const next = sanitizeIssue({ ...input, seriesId, title });
+ if (!next) throw makeErr('Invalid issue payload', ERR_VALIDATION);
+ state.issues.push(next);
+ await writeState(state);
+ return next;
+ });
+}
+
export function updateIssue(id, patch = {}) {
return queueIssueWrite(id, async () => {
const state = await readState();
diff --git a/server/services/pipeline/issues.test.js b/server/services/pipeline/issues.test.js
index f61ef37320..d5b04be2ce 100644
--- a/server/services/pipeline/issues.test.js
+++ b/server/services/pipeline/issues.test.js
@@ -305,4 +305,30 @@ describe('pipeline issues service', () => {
await svc.deleteIssue(i.id);
await expect(svc.deleteIssue(i.id)).rejects.toMatchObject({ code: svc.ERR_NOT_FOUND });
});
+
+ describe('insertIssueWithId', () => {
+ it('preserves the caller-supplied id', async () => {
+ const i = await svc.insertIssueWithId({ id: 'iss-fixed-xyz', seriesId: 'ser-1', title: 'Imported' });
+ expect(i.id).toBe('iss-fixed-xyz');
+ expect(i.seriesId).toBe('ser-1');
+ });
+
+ it('rejects malformed id', async () => {
+ await expect(svc.insertIssueWithId({ id: 'wrong-prefix', seriesId: 'ser-1', title: 'X' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('rejects duplicate id', async () => {
+ await svc.insertIssueWithId({ id: 'iss-dup', seriesId: 'ser-1', title: 'First' });
+ await expect(svc.insertIssueWithId({ id: 'iss-dup', seriesId: 'ser-1', title: 'Second' }))
+ .rejects.toMatchObject({ code: svc.ERR_DUPLICATE });
+ });
+
+ it('requires seriesId and title', async () => {
+ await expect(svc.insertIssueWithId({ id: 'iss-no-series', title: 'X' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ await expect(svc.insertIssueWithId({ id: 'iss-no-title', seriesId: 'ser-1' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+ });
});
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index 98307845ba..c83aeffb29 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -28,8 +28,11 @@ const statePath = () => join(PATHS.data, 'pipeline-series.json');
export const ERR_NOT_FOUND = 'PIPELINE_SERIES_NOT_FOUND';
export const ERR_VALIDATION = 'PIPELINE_SERIES_VALIDATION';
+export const ERR_DUPLICATE = 'PIPELINE_SERIES_DUPLICATE';
const makeErr = (message, code) => Object.assign(new Error(message), { code });
+const SERIES_ID_RE = /^ser-[A-Za-z0-9-]+$/;
+
export const NAME_MAX = 200;
export const LOGLINE_MAX = 500;
export const PREMISE_MAX = 8000;
@@ -144,6 +147,30 @@ export async function createSeries(input = {}) {
return next;
}
+/**
+ * Insert a series with a caller-supplied id (used by the share-bucket importer
+ * so re-imports of the same series LWW-merge onto the same local row instead
+ * of accumulating duplicates). Throws ERR_DUPLICATE if the id is already
+ * present, ERR_VALIDATION if the id is malformed. Preserves createdAt /
+ * updatedAt verbatim so LWW comparisons against subsequent re-shares work.
+ */
+export async function insertSeriesWithId(input = {}) {
+ if (!isStr(input.id) || !SERIES_ID_RE.test(input.id)) {
+ throw makeErr(`insertSeriesWithId: invalid id "${input.id}" (expected ser-<uuid>)`, ERR_VALIDATION);
+ }
+ const name = trimTo(input.name, NAME_MAX);
+ if (!name) throw makeErr(`Series name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);
+ const state = await readState();
+ if (state.series.some((s) => s.id === input.id)) {
+ throw makeErr(`Series id already exists: ${input.id}`, ERR_DUPLICATE);
+ }
+ const next = sanitizeSeries({ ...input, name });
+ if (!next) throw makeErr('Invalid series payload', ERR_VALIDATION);
+ state.series.push(next);
+ await writeState(state);
+ return next;
+}
+
export async function updateSeries(id, patch = {}) {
const state = await readState();
const idx = state.series.findIndex((s) => s.id === id);
diff --git a/server/services/pipeline/series.test.js b/server/services/pipeline/series.test.js
index d085e22734..18d4df30f1 100644
--- a/server/services/pipeline/series.test.js
+++ b/server/services/pipeline/series.test.js
@@ -98,4 +98,37 @@ describe('pipeline series service', () => {
const s = await svc.createSeries({ name: 'X', characters: many });
expect(s.characters).toHaveLength(svc.CHARACTERS_PER_SERIES_MAX);
});
+
+ describe('insertSeriesWithId', () => {
+ it('preserves the caller-supplied id', async () => {
+ const s = await svc.insertSeriesWithId({ id: 'ser-fixed-abc', name: 'Imported' });
+ expect(s.id).toBe('ser-fixed-abc');
+ expect(s.name).toBe('Imported');
+ });
+
+ it('preserves createdAt/updatedAt when provided', async () => {
+ const ts = '2026-01-01T00:00:00.000Z';
+ const s = await svc.insertSeriesWithId({ id: 'ser-stamped', name: 'X', createdAt: ts, updatedAt: ts });
+ expect(s.createdAt).toBe(ts);
+ expect(s.updatedAt).toBe(ts);
+ });
+
+ it('rejects malformed id', async () => {
+ await expect(svc.insertSeriesWithId({ id: 'not-a-series-id', name: 'X' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ await expect(svc.insertSeriesWithId({ name: 'X' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it('rejects duplicate id', async () => {
+ await svc.insertSeriesWithId({ id: 'ser-dup', name: 'First' });
+ await expect(svc.insertSeriesWithId({ id: 'ser-dup', name: 'Second' }))
+ .rejects.toMatchObject({ code: svc.ERR_DUPLICATE });
+ });
+
+ it('requires a name', async () => {
+ await expect(svc.insertSeriesWithId({ id: 'ser-noname' }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+ });
});
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index d32e930f24..72ac1a60e9 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -24,9 +24,9 @@ import { EventEmitter } from 'events';
import { PATHS, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';
import { getBucket } from './buckets.js';
import { readManifest, markProcessed, readCursor, hasBeenProcessed } from './manifest.js';
-import { listSeries, createSeries, updateSeries, getSeries } from '../pipeline/series.js';
-import { listIssues, createIssue, updateIssue, getIssue } from '../pipeline/issues.js';
-import { listUniverses, createUniverse, updateUniverse, getUniverse } from '../universeBuilder.js';
+import { insertSeriesWithId, updateSeries, getSeries } from '../pipeline/series.js';
+import { insertIssueWithId, updateIssue, getIssue } from '../pipeline/issues.js';
+import { insertUniverseWithId, updateUniverse, getUniverse } from '../universeBuilder.js';
const isStr = (v) => typeof v === 'string';
@@ -130,79 +130,60 @@ async function readReferencedRecords(bucketPath, manifest) {
/**
* Auto-merge mode: apply records into live state.
- * LWW: if a record already exists locally with a newer updatedAt, skip;
- * otherwise insert (via createSeries) or patch (via updateSeries).
+ *
+ * Each record either inserts under its manifest id (via insertWithId) on
+ * first arrival, or LWW-overwrites the existing local record when the
+ * remote updatedAt is newer. Ids are preserved across peers so a subsequent
+ * re-share of the same record merges onto the same local row instead of
+ * accumulating duplicates.
+ *
+ * `overridden` counts records whose local copy was newer-than-zero-but-older
+ * than remote and got replaced — surfaced via the socket event so the user
+ * is notified when auto-merge clobbers local edits.
*/
async function applyAutoMerge(bucket, manifest, records) {
let applied = 0;
+ const overridden = [];
- // Universes first — series may reference them via universeId.
- for (const uni of records.universes) {
- const existing = await getUniverse(uni.id).catch(() => null);
+ const mergeOne = async ({ kind, record, getFn, insertFn, updateFn, label }) => {
+ const existing = await getFn(record.id).catch(() => null);
if (!existing) {
- // No createUniverseWithId() — universeBuilder.createUniverse assigns a
- // fresh UUID. Workaround: write directly through updateUniverse paired
- // with a seed insert via the readState/writeState pair would require
- // exporting an internal helper. For now, fall back to the merge being
- // additive: if we can't recreate, we put it in inbox-equivalent state.
- // The pragmatic v1 path: write the universe with createUniverse and
- // accept that the id changes. We then keep the bucket-id mapping for
- // series.universeId rewiring below.
- const created = await createUniverse(uni).catch(() => null);
- if (created) {
- // Remap series.universeId references in this same manifest.
- for (const s of records.series) {
- if (s.universeId === uni.id) s.universeId = created.id;
- }
- applied++;
- }
- continue;
+ await insertFn(record).catch((err) => {
+ // Duplicate id is benign — a parallel manifest already inserted it.
+ if (err?.code?.endsWith('_DUPLICATE')) return null;
+ console.log(`⚠️ sharing.importer: insertWithId(${kind}=${record.id}) failed: ${err.message}`);
+ });
+ applied++;
+ return;
}
- if (remoteWins(existing.updatedAt, uni.updatedAt)) {
- await updateUniverse(existing.id, uni);
+ if (remoteWins(existing.updatedAt, record.updatedAt)) {
+ await updateFn(existing.id, record);
+ overridden.push({ kind, id: record.id, label });
applied++;
}
- }
+ };
- // Series.
+ // Universes first — series may reference them via universeId.
+ for (const uni of records.universes) {
+ await mergeOne({
+ kind: 'universe', record: uni, label: uni.name,
+ getFn: getUniverse, insertFn: insertUniverseWithId, updateFn: updateUniverse,
+ });
+ }
for (const s of records.series) {
- const existing = await getSeries(s.id).catch(() => null);
- if (!existing) {
- // createSeries assigns a fresh id — to preserve the manifest's series.id
- // (so subsequent imports of the same series LWW-merge correctly), we
- // need to insert directly. For v1, accept that auto-merge new arrivals
- // get a fresh local id; the origin field still attributes the record.
- const created = await createSeries(s).catch(() => null);
- if (created) {
- // Rewrite issue.seriesId references for this manifest's issues.
- for (const iss of records.issues) {
- if (iss.seriesId === s.id) iss.seriesId = created.id;
- }
- applied++;
- }
- continue;
- }
- if (remoteWins(existing.updatedAt, s.updatedAt)) {
- await updateSeries(existing.id, s);
- applied++;
- }
+ await mergeOne({
+ kind: 'series', record: s, label: s.name,
+ getFn: getSeries, insertFn: insertSeriesWithId, updateFn: updateSeries,
+ });
}
-
- // Issues.
for (const iss of records.issues) {
- const existing = await getIssue(iss.id).catch(() => null);
- if (!existing) {
- await createIssue(iss).catch(() => null);
- applied++;
- continue;
- }
- if (remoteWins(existing.updatedAt, iss.updatedAt)) {
- await updateIssue(existing.id, iss);
- applied++;
- }
+ await mergeOne({
+ kind: 'issue', record: iss, label: iss.title,
+ getFn: getIssue, insertFn: insertIssueWithId, updateFn: updateIssue,
+ });
}
- return { applied };
+ return { applied, overridden };
}
const INBOX_MAX = 1000;
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
new file mode 100644
index 0000000000..830239a346
--- /dev/null
+++ b/server/services/sharing/integration.test.js
@@ -0,0 +1,187 @@
+/**
+ * End-to-end sharing round-trip test.
+ *
+ * Exercises: register bucket → export series (records + assets + manifest) →
+ * delete locally → processManifest (auto-merge) → verify the series reappears
+ * with its original id, origin metadata, and asset blobs intact. Also verifies
+ * the LWW re-merge path: re-export with newer updatedAt, re-process, confirm
+ * local record updated and `overridden` populated.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, existsSync, mkdirSync, readFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+// Universe builder evaluates `join(PATHS.data, …)` at module-top, so PATHS
+// must point at a real dir from the very first import. Allocate a single
+// root up-front; per-test setup wipes + reseeds inside it.
+const tempData = mkdtempSync(join(tmpdir(), 'portos-sharing-roundtrip-data-'));
+let tempBucket;
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return new Proxy(actual, {
+ get(target, prop) {
+ if (prop === 'PATHS') return {
+ ...actual.PATHS,
+ data: tempData,
+ images: join(tempData, 'images'),
+ videos: join(tempData, 'videos'),
+ };
+ return target[prop];
+ },
+ });
+});
+
+// Stub instances.getInstanceId so the exporter doesn't try to read the
+// real identity.json. Returns a fixed id for assertions.
+vi.mock('../instances.js', () => ({
+ getInstanceId: () => Promise.resolve('test-instance-id'),
+}));
+
+// Stub mediaJobQueue.getJob — exporter uses it for full-fidelity gen
+// metadata on each shared imageJobId. Returns null so the exporter falls
+// through to direct asset copy via imageRefs.
+vi.mock('../mediaJobQueue/index.js', () => ({
+ getJob: () => null,
+}));
+
+const buckets = await import('./buckets.js');
+const exporter = await import('./exporter.js');
+const importer = await import('./importer.js');
+const series = await import('../pipeline/series.js');
+const issues = await import('../pipeline/issues.js');
+
+describe('sharing round-trip', () => {
+ beforeEach(() => {
+ // Wipe and re-seed the temp data dir + a fake asset for each test.
+ rmSync(tempData, { recursive: true, force: true });
+ mkdirSync(tempData, { recursive: true });
+ mkdirSync(join(tempData, 'images'), { recursive: true });
+ mkdirSync(join(tempData, 'videos'), { recursive: true });
+ writeFileSync(join(tempData, 'images', 'fakeasset.png'), 'PNGSTUB');
+ tempBucket = mkdtempSync(join(tmpdir(), 'portos-sharing-roundtrip-bucket-'));
+ });
+ afterEach(() => {
+ if (tempBucket) rmSync(tempBucket, { recursive: true, force: true });
+ });
+
+ it('exports a series, processes the manifest as inbox, then promotes — id + origin preserved', async () => {
+ const bucket = await buckets.createBucket({ name: 'Test', path: tempBucket, mode: 'inbox' });
+
+ // Author a series + an issue locally.
+ const s = await series.createSeries({
+ name: 'Salt Run', logline: 'A foundry city goes silent.', premise: 'The only survivor is a child.',
+ // Add an imageRef on a character so the exporter has an asset to copy.
+ characters: [{ name: 'Vex', imageRefs: ['fakeasset.png'] }],
+ });
+ const iss = await issues.createIssue({ seriesId: s.id, title: 'Issue 1' });
+
+ // Export.
+ const exp = await exporter.exportSeries(s.id, bucket.id);
+ expect(exp.manifestId).toBeTruthy();
+ expect(exp.recordCount).toBe(2); // series + issue
+ expect(exp.assetCount).toBeGreaterThanOrEqual(1);
+
+ // Verify the bucket layout.
+ expect(existsSync(join(tempBucket, 'manifests', exp.filename))).toBe(true);
+ expect(existsSync(join(tempBucket, 'records', 'series', `${s.id}.json`))).toBe(true);
+ expect(existsSync(join(tempBucket, 'records', 'issues', `${iss.id}.json`))).toBe(true);
+ expect(existsSync(join(tempBucket, 'assets', 'images', 'fakeasset.png'))).toBe(true);
+
+ // Process as inbox (the bucket mode is 'inbox'). The manifest should
+ // queue, not auto-apply.
+ const result = await importer.processManifest(bucket.id, exp.filename);
+ expect(result.processed).toBe(true);
+ expect(result.outcome.mode).toBe('inbox');
+ expect(result.outcome.queued).toBe(true);
+
+ // Inbox should have one item.
+ const inbox = await importer.listInbox(bucket.id);
+ expect(inbox).toHaveLength(1);
+ expect(inbox[0].source).toBeTruthy();
+
+ // Delete the local series + issue, then promote — the promote path runs
+ // the auto-merge logic with insertWithId, so ids round-trip.
+ await series.deleteSeries(s.id);
+ await issues.deleteIssue(iss.id);
+ await importer.promoteInboxItem(bucket.id, exp.manifestId);
+
+ const restored = await series.getSeries(s.id);
+ expect(restored.id).toBe(s.id);
+ expect(restored.name).toBe('Salt Run');
+ expect(restored.origin).toMatchObject({
+ bucketId: bucket.id,
+ manifestId: exp.manifestId,
+ });
+ expect(restored.origin.source).toBeTruthy();
+
+ const restoredIssue = await issues.getIssue(iss.id);
+ expect(restoredIssue.id).toBe(iss.id);
+ expect(restoredIssue.seriesId).toBe(s.id);
+ expect(restoredIssue.origin).toBeTruthy();
+
+ // Asset blob should be back in data/images.
+ expect(existsSync(join(tempData, 'images', 'fakeasset.png'))).toBe(true);
+
+ // Inbox should be empty after promotion.
+ expect(await importer.listInbox(bucket.id)).toEqual([]);
+ });
+
+ it('auto-merge mode applies records immediately and reports overridden on re-export', async () => {
+ const bucket = await buckets.createBucket({ name: 'AutoBucket', path: tempBucket, mode: 'auto-merge' });
+
+ const s = await series.createSeries({ name: 'Test Series', logline: 'A' });
+ const exp = await exporter.exportSeries(s.id, bucket.id);
+
+ // Drop the local series, then process — auto-merge inserts under preserved id.
+ await series.deleteSeries(s.id);
+ const r1 = await importer.processManifest(bucket.id, exp.filename);
+ expect(r1.outcome.mode).toBe('auto-merge');
+ expect(r1.outcome.applied).toBeGreaterThan(0);
+ expect(r1.outcome.overridden).toEqual([]);
+ const restored = await series.getSeries(s.id);
+ expect(restored.id).toBe(s.id);
+
+ // Modify the local series so the next export carries a NEWER updatedAt.
+ await new Promise((r) => setTimeout(r, 5));
+ await series.updateSeries(s.id, { name: 'Test Series (renamed)' });
+
+ // Re-export — manifest carries the newer record.
+ const exp2 = await exporter.exportSeries(s.id, bucket.id);
+
+ // Roll the local copy backwards by a millisecond so the *remote* is newer.
+ await new Promise((r) => setTimeout(r, 5));
+ await series.updateSeries(s.id, { name: 'Test Series (renamed)' });
+ // Force the local updatedAt to be older than the manifest so LWW triggers override.
+ // (Easiest: mutate the on-disk JSON directly to set an old updatedAt.)
+ const statePath = join(tempData, 'pipeline-series.json');
+ const state = JSON.parse(readFileSync(statePath, 'utf-8'));
+ state.series[0].updatedAt = '2020-01-01T00:00:00.000Z';
+ writeFileSync(statePath, JSON.stringify(state, null, 2));
+
+ // Process the new manifest — should LWW-override.
+ const r2 = await importer.processManifest(bucket.id, exp2.filename);
+ expect(r2.outcome.mode).toBe('auto-merge');
+ expect(r2.outcome.overridden).toHaveLength(1);
+ expect(r2.outcome.overridden[0]).toMatchObject({ kind: 'series', id: s.id });
+
+ const afterOverride = await series.getSeries(s.id);
+ expect(afterOverride.name).toBe('Test Series (renamed)');
+ });
+
+ it('re-importing the same manifest is a no-op (cursor dedup)', async () => {
+ const bucket = await buckets.createBucket({ name: 'D', path: tempBucket, mode: 'auto-merge' });
+ const s = await series.createSeries({ name: 'X' });
+ const exp = await exporter.exportSeries(s.id, bucket.id);
+ await series.deleteSeries(s.id);
+
+ const r1 = await importer.processManifest(bucket.id, exp.filename);
+ expect(r1.processed).toBe(true);
+
+ const r2 = await importer.processManifest(bucket.id, exp.filename);
+ expect(r2.skipped).toBe(true);
+ expect(r2.reason).toBe('already-processed');
+ });
+});
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index d1f20fba66..d612568a92 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -40,8 +40,14 @@ const STATE_PATH = join(PATHS.data, 'universe-builder.json');
export const ERR_NOT_FOUND = 'NOT_FOUND';
export const ERR_VALIDATION = 'VALIDATION_ERROR';
+export const ERR_DUPLICATE = 'DUPLICATE';
const makeErr = (message, code) => Object.assign(new Error(message), { code });
+// Universe ids are bare UUIDs (no prefix). Accept any reasonable alphanumeric
+// id 8–80 chars so future id-scheme changes upstream still round-trip; the
+// importer is the only caller, and it gets ids from manifests it controls.
+const UNIVERSE_ID_RE = /^[A-Za-z0-9-]{8,80}$/;
+
export const NAME_MAX_LENGTH = 100;
// A render can enqueue up to 5 categories × 50 variations × 20 batchPerVariation
// = 5000 jobs. Cap at 10k to leave headroom against future bumps to those caps.
@@ -538,6 +544,28 @@ export async function createUniverse(input = {}) {
return next;
}
+/**
+ * Insert a universe with a caller-supplied id (used by the share-bucket
+ * importer so re-imports of the same universe LWW-merge onto the same local
+ * row). Throws ERR_DUPLICATE / ERR_VALIDATION on contract violations.
+ */
+export async function insertUniverseWithId(input = {}) {
+ if (!isStr(input.id) || !UNIVERSE_ID_RE.test(input.id)) {
+ throw makeErr(`insertUniverseWithId: invalid id "${input.id}"`, ERR_VALIDATION);
+ }
+ const name = trimTo(input.name, NAME_MAX_LENGTH);
+ if (!name) throw makeErr(`Universe name is required (1..${NAME_MAX_LENGTH} chars)`, ERR_VALIDATION);
+ const state = await readState();
+ if (state.universes.some((u) => u.id === input.id)) {
+ throw makeErr(`Universe id already exists: ${input.id}`, ERR_DUPLICATE);
+ }
+ const next = sanitizeTemplate({ ...input, name });
+ if (!next) throw makeErr('Invalid universe payload', ERR_VALIDATION);
+ state.universes.push(next);
+ await writeState(state);
+ return next;
+}
+
export async function updateUniverse(id, patch = {}) {
const state = await readState();
const idx = state.universes.findIndex((w) => w.id === id);
diff --git a/server/services/universeBuilder.test.js b/server/services/universeBuilder.test.js
index 53565f6577..69bc2a14f7 100644
--- a/server/services/universeBuilder.test.js
+++ b/server/services/universeBuilder.test.js
@@ -715,4 +715,34 @@ describe("universeBuilder service", () => {
expect(list[0].categories.landscapes.variations[0].label).toBe("Good");
});
});
+
+ describe("insertUniverseWithId", () => {
+ it("preserves the caller-supplied id", async () => {
+ const u = await svc.insertUniverseWithId({
+ id: "550e8400-e29b-41d4-a716-446655440000",
+ name: "Imported Universe",
+ });
+ expect(u.id).toBe("550e8400-e29b-41d4-a716-446655440000");
+ expect(u.name).toBe("Imported Universe");
+ });
+
+ it("rejects malformed id", async () => {
+ await expect(svc.insertUniverseWithId({ id: "bad id with spaces", name: "X" }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ await expect(svc.insertUniverseWithId({ name: "X" }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+
+ it("rejects duplicate id", async () => {
+ const id = "550e8400-e29b-41d4-a716-446655440001";
+ await svc.insertUniverseWithId({ id, name: "First" });
+ await expect(svc.insertUniverseWithId({ id, name: "Second" }))
+ .rejects.toMatchObject({ code: svc.ERR_DUPLICATE });
+ });
+
+ it("requires a name", async () => {
+ await expect(svc.insertUniverseWithId({ id: "550e8400-e29b-41d4-a716-446655440002" }))
+ .rejects.toMatchObject({ code: svc.ERR_VALIDATION });
+ });
+ });
});