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(sharing): cross-network share buckets via cloud-synced folders
[._.]/ Adam Eivye610d1a50d1d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 289590f7be..6f627a95fb 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,53 @@## Added+- **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+ networks** by exporting into a cloud-synced folder (Google Drive, Dropbox,+ iCloud Drive, Syncthing, USB stick). PortOS reads/writes a stable layout+ inside the folder; the cloud-sync app handles cross-network transport, so+ no PortOS-side broker is required.+ - New **Sharing** page at `/sharing` (under Create in the sidebar ++ `⌘K`-reachable) registers each synced folder as a "bucket" with a+ per-bucket import mode: `inbox` (incoming shares queue for explicit+ review) or `auto-merge` (LWW into the local working set on arrival).+ - **ShareToButton** on the Pipeline series list, UniverseBuilder toolbar,+ and Media Collection detail bulk-action bar exports the selected record+ into any registered bucket. **OriginBadge** chips render on every+ imported record with the sharer's display name + bucket name + import+ timestamp.+ - **Full-fidelity gen metadata.** Exports walk each record's+ `imageJobId` / `sceneVideoJobId` / `imageRefs` / `videoPath` references,+ copy the underlying asset (+ sidecar metadata JSON) into the bucket's+ `assets/{images,videos}/`, and write the full `media-jobs.json` entry+ (prompt, negative prompt, model, seed, sampler, dimensions, ref images,+ audio inputs, LoRA selections, etc.) into `records/media/<jobId>.json`+ so recipients can Regenerate / Iterate with identical parameters.+ - **Source attribution.** A user-configurable `sharingDisplayName` ++ optional `sharingBio` (in PortOS settings, with per-bucket overrides)+ is stamped onto every outgoing manifest and every record's+ `origin.{ bucketId, bucketName, source, sourceBio, manifestId,+ importedAt }`. Recipients see attribution via `<OriginBadge>` on+ imported records.+ - **chokidar** watcher attaches to each bucket's `manifests/` directory+ on boot and on bucket registration; backlog processing catches any+ manifests that arrived while the server was offline. Per-bucket cursor+ dedup (`data/sharing/cursors/<bucketId>.json`) ensures the same manifest+ is never imported twice.+ - **Privacy note:** the cloud-sync provider sees bucket contents in+ plaintext; this is no different from any Google Drive folder share and+ is surfaced inline on the Sharing page.++ **Files:** new `server/services/sharing/{index,buckets,manifest,exporter,+ importer,watcher}.js`, `server/routes/sharing.js`,+ `server/lib/sharingOrigin.js`, `client/src/pages/Sharing.jsx`,+ `client/src/components/sharing/{ShareToButton,OriginBadge}.jsx`,+ `client/src/services/apiSharing.js`. `series` / `issues` / `universes` /+ `media-collections` sanitizers gained an optional `origin` field. Tests:+ `server/lib/sharingOrigin.test.js`, `server/services/sharing/{buckets,+ manifest}.test.js`.+- **Pipeline — per-issue length profile, per-stage gen config, comic front cover.**Three additive pipeline-UX features rescued from a pre-crash recovery branchand cherry-picked into main:diff --git a/PLAN.md b/PLAN.mdindex a0e8711e85..f0c2ba2617 100644--- a/PLAN.md+++ b/PLAN.md@@ -6,6 +6,21 @@ 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++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:++- [ ] **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).+- [ ] **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.+- [ ] **End-to-end encryption inside the bucket.** Plaintext today (privacy note in the UI). Add age/PGP-based encryption per-bucket so the cloud provider can't read shared content.+- [ ] **Multi-hop provenance chains.** Re-share authors a fresh `origin` block; chain[] would preserve full attribution. Defer until users ask.+### Universe-as-Canon refactor — Phase B.4 cleanup + follow-upsThe world model is now a Marvel-style **universe** carrying canonical entities (characters, places, objects) that multiple series can share for crossovers + cameos. Shipped 2026-05-14 across Phase 0 (world→universe rename), Phase A (canon arrays + Universe Canon page + cast-wide differentiate + image-delete purge sync), Phase B (render paths read via `getSeriesCanon`), Phase B.2 (Nouns page reads/writes universe canon), Phase B.3a (legacy series-side canon helpers redirect to universe when linked), Phase B.3b (Nouns page drops the orphan series fallback), and the "Appears in" cross-reference footer on every Canon card. Migration scripts: `server/scripts/migrateAll.js` (chains `migrateWorldToUniverse.js` + `migrateSeriesCanon.js`).diff --git a/client/src/App.jsx b/client/src/App.jsxindex b4469da5c7..a188a5d7f7 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -83,6 +83,7 @@ const Wiki = lazyWithReload(() => import('./pages/Wiki'));const RapidReaderPage = lazyWithReload(() => import('./pages/RapidReader'));const WritersRoom = lazyWithReload(() => import('./pages/WritersRoom'));const Pipeline = lazyWithReload(() => import('./pages/Pipeline'));+const Sharing = lazyWithReload(() => import('./pages/Sharing'));const PipelineSeries = lazyWithReload(() => import('./pages/PipelineSeries'));const PipelineIssue = lazyWithReload(() => import('./pages/PipelineIssue'));@@ -223,6 +224,7 @@ export default function App() {<Route path="universe-builder/:universeId" element={<UniverseBuilder />} /><Route path="universe-builder/:universeId/canon" element={<UniverseCanon />} /><Route path="writers-room" element={<WritersRoom />} />+ <Route path="sharing" element={<Sharing />} /><Route path="pipeline" element={<Pipeline />} /><Route path="pipeline/series/:seriesId" element={<PipelineSeries />} /><Route path="pipeline/issues/:issueId" element={<Navigate to="idea" replace />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 8cdf67716c..e977b2f57a 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -79,6 +79,7 @@ import {Eraser,Sun,Moon,+ Share2,Workflow as WorkflowIcon} from 'lucide-react';/* global __APP_VERSION__ */@@ -194,6 +195,7 @@ const navItems = [children: [{ to: '/media', label: 'Media Gen', icon: Layers },{ to: '/pipeline', label: 'Pipeline', icon: WorkflowIcon, dynamic: 'pipelineSeries' },+ { to: '/sharing', label: 'Sharing', icon: Share2 },{ to: '/universe-builder', label: 'Universe Builder', icon: Globe },{ to: '/writers-room', label: 'Writers Room', icon: NotebookPen }]diff --git a/client/src/components/sharing/OriginBadge.jsx b/client/src/components/sharing/OriginBadge.jsxnew file mode 100644index 0000000000..25c2f4060a--- /dev/null+++ b/client/src/components/sharing/OriginBadge.jsx@@ -0,0 +1,40 @@+/**+ * OriginBadge — small chip on records imported from a share bucket. Shows+ * the source display name and the bucket alias; hover/tap reveals full+ * provenance metadata.+ *+ * Props:+ * origin: { bucketId, bucketName, source, sourceBio?, manifestId, importedAt }+ * compact?: boolean // icon-only chip+ */++import { Users } from 'lucide-react';++export default function OriginBadge({ origin, compact = false, className = '' }) {+ if (!origin || typeof origin !== 'object') return null;+ const { source, bucketName, sourceBio, importedAt } = origin;+ if (!source) return null;++ const importedDate = importedAt ? new Date(importedAt).toLocaleDateString() : null;+ const title = [+ `From ${source}`,+ bucketName ? `via ${bucketName}` : null,+ importedDate ? `imported ${importedDate}` : null,+ sourceBio ? `\n\n${sourceBio}` : null,+ ].filter(Boolean).join(' · ');++ return (+ <span+ className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded bg-port-bg border border-port-border text-[10px] text-gray-400 ${className}`}+ title={title}+ >+ <Users size={10} />+ {!compact && (+ <>+ <span className="text-port-accent">{source}</span>+ {bucketName ? <span className="text-gray-600">· {bucketName}</span> : null}+ </>+ )}+ </span>+ );+}diff --git a/client/src/components/sharing/ShareToButton.jsx b/client/src/components/sharing/ShareToButton.jsxnew file mode 100644index 0000000000..18d51ad08a--- /dev/null+++ b/client/src/components/sharing/ShareToButton.jsx@@ -0,0 +1,124 @@+/**+ * ShareToButton — small dropdown that lists registered share buckets and+ * exports the given record (series / universe / media items) to the chosen+ * bucket. Used on Pipeline.jsx, UniverseBuilder.jsx, and the media gallery.+ *+ * Props:+ * kind: 'series' | 'universe' | 'media'+ * ids?: string[] // for series / universe+ * items?: [{ kind, ref }] // for media (mediaCollections item shape)+ * label?: string // button label override+ * compact?: boolean // icon-only when true+ */++import { useEffect, useRef, useState } from 'react';+import { Share2, Check, Loader2 } from 'lucide-react';+import toast from '../ui/Toast';+import {+ listShareBuckets,+ exportToShareBucket,+} from '../../services/api';++export default function ShareToButton({ kind, ids, items, label = 'Share', compact = false, className = '' }) {+ const [open, setOpen] = useState(false);+ const [buckets, setBuckets] = useState([]);+ const [loading, setLoading] = useState(false);+ const [sharingTo, setSharingTo] = useState(null);+ const wrapperRef = useRef(null);++ useEffect(() => {+ if (!open) return;+ setLoading(true);+ listShareBuckets({ silent: true })+ .then((r) => setBuckets(r?.buckets || []))+ .catch(() => setBuckets([]))+ .finally(() => setLoading(false));+ }, [open]);++ // Close on click-outside.+ useEffect(() => {+ if (!open) return;+ const handler = (e) => {+ if (wrapperRef.current && !wrapperRef.current.contains(e.target)) setOpen(false);+ };+ window.addEventListener('mousedown', handler);+ return () => window.removeEventListener('mousedown', handler);+ }, [open]);++ const handleShare = async (bucket) => {+ setSharingTo(bucket.id);+ const body = { kind };+ if (kind === 'media') body.items = items || [];+ else body.ids = ids || [];+ const result = await exportToShareBucket(bucket.id, body).catch((err) => {+ toast.error(err.message || `Share to ${bucket.name} failed`);+ return null;+ });+ setSharingTo(null);+ if (!result) return;+ const totals = (result.exports || []).reduce(+ (acc, e) => ({ records: acc.records + (e.recordCount || 0), assets: acc.assets + (e.assetCount || 0) }),+ { records: 0, assets: 0 },+ );+ toast.success(`Shared to ${bucket.name} — ${totals.records} record${totals.records === 1 ? '' : 's'}, ${totals.assets} asset${totals.assets === 1 ? '' : 's'}`);+ setOpen(false);+ };++ // Disabled when there's nothing to share.+ const nothingToShare = kind === 'media'+ ? !(Array.isArray(items) && items.length > 0)+ : !(Array.isArray(ids) && ids.length > 0);++ return (+ <div ref={wrapperRef} className={`relative inline-block ${className}`}>+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ disabled={nothingToShare}+ className={`inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded text-xs border border-port-border hover:border-port-accent/40 text-gray-300 hover:text-white disabled:opacity-40 disabled:cursor-not-allowed transition-colors ${compact ? 'p-1.5' : ''}`}+ title={nothingToShare ? 'Nothing selected to share' : 'Share to a bucket'}+ >+ <Share2 size={12} />+ {!compact && <span>{label}</span>}+ </button>++ {open && (+ <div className="absolute right-0 z-30 mt-1 w-64 bg-port-card border border-port-border rounded-lg shadow-lg overflow-hidden">+ <div className="px-3 py-2 text-[10px] uppercase tracking-wider text-gray-500 border-b border-port-border">+ Share to bucket+ </div>+ {loading ? (+ <div className="px-3 py-3 text-xs text-gray-500 flex items-center gap-2">+ <Loader2 size={12} className="animate-spin" /> Loading buckets…+ </div>+ ) : buckets.length === 0 ? (+ <div className="px-3 py-3 text-xs text-gray-500">+ No buckets yet. <a href="/sharing" className="text-port-accent hover:underline">Add one</a>.+ </div>+ ) : (+ <ul className="max-h-72 overflow-y-auto">+ {buckets.map((b) => (+ <li key={b.id}>+ <button+ type="button"+ onClick={() => handleShare(b)}+ disabled={sharingTo === b.id}+ className="w-full text-left px-3 py-2 hover:bg-port-bg disabled:opacity-50 flex items-start gap-2"+ >+ <div className="flex-1 min-w-0">+ <div className="text-sm text-white truncate">{b.name}</div>+ <div className="text-[10px] text-gray-500 truncate">+ {b.mode === 'auto-merge' ? 'auto-merge' : 'inbox'} · {b.path}+ </div>+ </div>+ {sharingTo === b.id ? <Loader2 size={12} className="animate-spin mt-1 text-port-accent" /> : <Check size={12} className="mt-1 text-gray-600" />}+ </button>+ </li>+ ))}+ </ul>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/pages/MediaCollectionDetail.jsx b/client/src/pages/MediaCollectionDetail.jsxindex bbee51aca5..9e6400d27c 100644--- a/client/src/pages/MediaCollectionDetail.jsx+++ b/client/src/pages/MediaCollectionDetail.jsx@@ -1,6 +1,7 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useParams, Link, useNavigate } from 'react-router-dom';import { ArrowLeft, CheckSquare, Copy, FolderInput, Inbox, Pencil, Star, StarOff, Trash2, X } from 'lucide-react';+import ShareToButton from '../components/sharing/ShareToButton';import toast from '../components/ui/Toast';import MediaCard from '../components/media/MediaCard';import MediaPreview from '../components/media/MediaPreview';@@ -374,6 +375,11 @@ export default function MediaCollectionDetail() {><StarOff className="w-3 h-3" /> Unstar</button>+ <ShareToButton+ kind="media"+ items={selectedItems.map((it) => ({ kind: it.kind, ref: it.ref }))}+ label="Share…"+ /><buttonref={moveBtnRef}type="button"diff --git a/client/src/pages/Pipeline.jsx b/client/src/pages/Pipeline.jsxindex 1e4ef5d151..599155c13f 100644--- a/client/src/pages/Pipeline.jsx+++ b/client/src/pages/Pipeline.jsx@@ -11,6 +11,8 @@ import { useEffect, useState } from 'react';import { Link } from 'react-router-dom';import { Plus, Workflow as WorkflowIcon, Trash2, Loader2, Globe2 } from 'lucide-react';import toast from '../components/ui/Toast';+import ShareToButton from '../components/sharing/ShareToButton';+import OriginBadge from '../components/sharing/OriginBadge';import {listPipelineSeries,createPipelineSeries,@@ -259,7 +261,10 @@ export default function Pipeline() {{series.map((s) => (<li key={s.id} className="flex items-center justify-between gap-3 p-3 bg-port-card border border-port-border rounded-lg hover:border-port-accent/40 transition-colors"><Link to={`/pipeline/series/${s.id}`} className="flex-1 min-w-0">- <div className="text-white font-medium truncate">{s.name}</div>+ <div className="text-white font-medium truncate flex items-center gap-2">+ <span className="truncate">{s.name}</span>+ {s.origin ? <OriginBadge origin={s.origin} compact /> : null}+ </div>{s.logline ? (<div className="text-xs text-gray-500 truncate">{s.logline}</div>) : (@@ -271,6 +276,7 @@ export default function Pipeline() {</div>) : null}</Link>+ <ShareToButton kind="series" ids={[s.id]} compact /><buttontype="button"onClick={() => handleDelete(s)}diff --git a/client/src/pages/Sharing.jsx b/client/src/pages/Sharing.jsxnew file mode 100644index 0000000000..8d72dee1f6--- /dev/null+++ b/client/src/pages/Sharing.jsx@@ -0,0 +1,578 @@+/**+ * Sharing page — cross-network share buckets via cloud-synced folders.+ *+ * Lists registered buckets, lets the user add/remove buckets and toggle each+ * one's import mode (auto-merge vs inbox), and surfaces the per-bucket inbox+ * + activity log. Top strip lets the user configure the display name + bio+ * that get stamped as the source on every outgoing share.+ */++import { useEffect, useRef, useState } from 'react';+import {+ Share2, Plus, Trash2, Folder, Inbox, History, Save, Loader2, Check, X, Users, AlertCircle,+} from 'lucide-react';+import toast from '../components/ui/Toast';+import socket from '../services/socket';+import {+ listShareBuckets, createShareBucket, updateShareBucket, deleteShareBucket,+ listShareInbox, promoteShareInboxItem, dismissShareInboxItem,+ listShareActivity, getSettings, updateSettings,+} from '../services/api';++const emptyForm = () => ({ name: '', path: '', mode: 'inbox', displayNameOverride: '', bioOverride: '' });++export default function Sharing() {+ const [buckets, setBuckets] = useState([]);+ const [loading, setLoading] = useState(true);+ const [selectedId, setSelectedId] = useState(null);+ const [showAdd, setShowAdd] = useState(false);+ const [form, setForm] = useState(emptyForm);+ const [creating, setCreating] = useState(false);+ const [activeTab, setActiveTab] = useState('inbox'); // inbox | activity | settings++ // Display name + bio settings — used as the source attribution on outgoing shares.+ const [sharingDisplayName, setSharingDisplayName] = useState('');+ const [sharingBio, setSharingBio] = useState('');+ const [savedDisplayName, setSavedDisplayName] = useState('');+ const [savedBio, setSavedBio] = useState('');+ const [savingDisplayName, setSavingDisplayName] = useState(false);++ const [inboxByBucket, setInboxByBucket] = useState({}); // bucketId → items[]+ const [activityByBucket, setActivityByBucket] = useState({});++ const [armedRemove, setArmedRemove] = useState(null);++ // Load buckets + settings on mount.+ useEffect(() => {+ Promise.all([+ listShareBuckets({ silent: true }).catch(() => ({ buckets: [] })),+ getSettings().catch(() => ({})),+ ]).then(([bResp, settings]) => {+ const list = bResp?.buckets || [];+ setBuckets(list);+ if (list.length > 0) setSelectedId(list[0].id);+ const display = settings?.sharingDisplayName || '';+ const bio = settings?.sharingBio || '';+ setSharingDisplayName(display);+ setSharingBio(bio);+ setSavedDisplayName(display);+ setSavedBio(bio);+ setLoading(false);+ });+ }, []);++ // Lazy-load inbox + activity when a bucket is selected.+ const loadInbox = (bucketId) => {+ listShareInbox(bucketId, { silent: true })+ .then((r) => setInboxByBucket((m) => ({ ...m, [bucketId]: r?.items || [] })))+ .catch(() => setInboxByBucket((m) => ({ ...m, [bucketId]: [] })));+ };+ const loadActivity = (bucketId) => {+ listShareActivity(bucketId, { silent: true })+ .then((r) => setActivityByBucket((m) => ({ ...m, [bucketId]: r?.manifests || [] })))+ .catch(() => setActivityByBucket((m) => ({ ...m, [bucketId]: [] })));+ };+ useEffect(() => {+ if (!selectedId) return;+ loadInbox(selectedId);+ loadActivity(selectedId);+ }, [selectedId]);++ // Live socket updates: inbox changes + new manifests.+ useEffect(() => {+ const onInboxUpdated = ({ bucketId }) => {+ if (bucketId) loadInbox(bucketId);+ };+ const onManifestProcessed = ({ bucketId }) => {+ if (bucketId) {+ loadInbox(bucketId);+ loadActivity(bucketId);+ }+ };+ socket.on('sharing:inbox-updated', onInboxUpdated);+ socket.on('sharing:manifest-processed', onManifestProcessed);+ return () => {+ socket.off('sharing:inbox-updated', onInboxUpdated);+ socket.off('sharing:manifest-processed', onManifestProcessed);+ };+ }, []);++ const handleCreate = async (e) => {+ e?.preventDefault();+ const name = form.name.trim();+ const path = form.path.trim();+ if (!name) {+ toast.error('Bucket name is required');+ return;+ }+ if (!path) {+ toast.error('Bucket path is required');+ return;+ }+ setCreating(true);+ const result = await createShareBucket({+ name,+ path,+ mode: form.mode,+ displayNameOverride: form.displayNameOverride.trim() || null,+ bioOverride: form.bioOverride.trim() || null,+ }).catch((err) => {+ toast.error(err.message || 'Failed to register bucket');+ return null;+ });+ setCreating(false);+ if (!result?.bucket) return;+ setBuckets((prev) => [...prev, result.bucket].sort((a, b) => a.name.localeCompare(b.name)));+ setSelectedId(result.bucket.id);+ setForm(emptyForm());+ setShowAdd(false);+ toast.success(`Registered bucket "${result.bucket.name}"`);+ };++ const handleDelete = async (bucket) => {+ if (armedRemove !== bucket.id) {+ setArmedRemove(bucket.id);+ return;+ }+ setArmedRemove(null);+ const prior = buckets;+ setBuckets((prev) => prev.filter((b) => b.id !== bucket.id));+ if (selectedId === bucket.id) setSelectedId(prior[0]?.id !== bucket.id ? prior[0]?.id : (prior[1]?.id || null));+ await deleteShareBucket(bucket.id).catch((err) => {+ toast.error(err.message || 'Failed to remove bucket');+ setBuckets(prior);+ });+ };++ const handleModeToggle = async (bucket) => {+ const nextMode = bucket.mode === 'auto-merge' ? 'inbox' : 'auto-merge';+ const result = await updateShareBucket(bucket.id, { mode: nextMode }).catch((err) => {+ toast.error(err.message || 'Failed to update mode');+ return null;+ });+ if (!result?.bucket) return;+ setBuckets((prev) => prev.map((b) => (b.id === bucket.id ? result.bucket : b)));+ toast.success(`Bucket "${result.bucket.name}" now ${nextMode}`);+ };++ const handleSaveDisplayName = async () => {+ setSavingDisplayName(true);+ const patch = {+ sharingDisplayName: sharingDisplayName.trim(),+ sharingBio: sharingBio.trim(),+ };+ const merged = await updateSettings(patch).catch((err) => {+ toast.error(err.message || 'Failed to save');+ return null;+ });+ setSavingDisplayName(false);+ if (!merged) return;+ setSavedDisplayName(patch.sharingDisplayName);+ setSavedBio(patch.sharingBio);+ toast.success('Saved');+ };++ const handlePromote = async (bucketId, manifestId) => {+ const result = await promoteShareInboxItem(bucketId, manifestId).catch((err) => {+ toast.error(err.message || 'Promote failed');+ return null;+ });+ if (!result) return;+ setInboxByBucket((m) => ({ ...m, [bucketId]: (m[bucketId] || []).filter((it) => it.manifestId !== manifestId) }));+ const applied = result.outcome?.applied ?? 0;+ toast.success(`Imported — ${applied} record${applied === 1 ? '' : 's'}`);+ };++ const handleDismiss = async (bucketId, manifestId) => {+ const result = await dismissShareInboxItem(bucketId, manifestId).catch((err) => {+ toast.error(err.message || 'Dismiss failed');+ return null;+ });+ if (!result) return;+ setInboxByBucket((m) => ({ ...m, [bucketId]: (m[bucketId] || []).filter((it) => it.manifestId !== manifestId) }));+ };++ const selected = buckets.find((b) => b.id === selectedId) || null;+ const displayNameDirty = sharingDisplayName !== savedDisplayName || sharingBio !== savedBio;++ return (+ <div>+ <div className="flex items-center justify-between mb-6 flex-wrap gap-3">+ <div className="flex items-center gap-3">+ <Share2 className="w-6 h-6 text-port-accent" />+ <h1 className="text-2xl font-bold text-white">Sharing</h1>+ </div>+ <button+ type="button"+ onClick={() => setShowAdd((v) => !v)}+ className="inline-flex items-center gap-2 px-3 py-2 rounded-lg bg-port-accent hover:bg-port-accent/90 text-white text-sm font-medium"+ >+ <Plus size={16} />+ Add bucket+ </button>+ </div>++ <p className="text-sm text-gray-400 mb-6">+ Share pipeline series, universes, and individual media with peers on different networks by exporting into a+ cloud-synced folder (Google Drive, Dropbox, iCloud, Syncthing, USB stick). PortOS reads/writes the folder; the+ cloud-sync app handles the cross-network transport.+ <span className="block mt-1 text-[11px] text-gray-500">+ ⚠️ The cloud provider sees the bucket contents as plaintext. Treat sharing trust like you would a Google Drive folder share.+ </span>+ </p>++ {/* Display name + bio strip */}+ <div className="mb-6 p-4 bg-port-card border border-port-border rounded-lg">+ <div className="flex items-center gap-2 mb-2">+ <Users size={14} className="text-gray-500" />+ <h2 className="text-sm font-medium text-white">Your display name</h2>+ </div>+ <p className="text-xs text-gray-500 mb-3">+ This name is stamped as the <em>source</em> on every share you send. Recipients see it as attribution. Each bucket can override this with its own name.+ </p>+ <div className="grid grid-cols-1 md:grid-cols-[1fr_2fr_auto] gap-3 items-start">+ <input+ type="text"+ value={sharingDisplayName}+ onChange={(e) => setSharingDisplayName(e.target.value)}+ placeholder="Display name (e.g. atomantic)"+ maxLength={120}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ <input+ type="text"+ value={sharingBio}+ onChange={(e) => setSharingBio(e.target.value)}+ placeholder="Optional bio / contact note (visible to recipients)"+ maxLength={2000}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ <button+ type="button"+ onClick={handleSaveDisplayName}+ disabled={!displayNameDirty || savingDisplayName}+ className="inline-flex items-center gap-2 px-3 py-2 rounded bg-port-accent text-white text-sm disabled:opacity-40 disabled:cursor-not-allowed"+ >+ {savingDisplayName ? <Loader2 size={14} className="animate-spin" /> : <Save size={14} />}+ Save+ </button>+ </div>+ </div>++ {showAdd && (+ <form onSubmit={handleCreate} className="mb-6 p-4 bg-port-card border border-port-border rounded-lg space-y-3">+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">+ <div>+ <label className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Bucket name</label>+ <input+ type="text"+ value={form.name}+ onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}+ placeholder="Creative circle"+ maxLength={120}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ autoFocus+ />+ </div>+ <div>+ <label className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Import mode</label>+ <select+ value={form.mode}+ onChange={(e) => setForm((f) => ({ ...f, mode: e.target.value }))}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ >+ <option value="inbox">Inbox — review before importing</option>+ <option value="auto-merge">Auto-merge — apply immediately (trusted)</option>+ </select>+ </div>+ </div>+ <div>+ <label className="block text-xs uppercase tracking-wider text-gray-500 mb-1">+ Folder path+ </label>+ <input+ type="text"+ value={form.path}+ onChange={(e) => setForm((f) => ({ ...f, path: e.target.value }))}+ placeholder="/Users/you/Library/CloudStorage/GoogleDrive-…/PortOS Shares/creative-circle"+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm font-mono"+ />+ <p className="text-[11px] text-gray-500 mt-1">+ Pick a folder that's synced by your cloud-storage app. PortOS will create <code>manifests/</code>, <code>records/</code>, and <code>assets/</code> inside it.+ </p>+ </div>+ <div className="grid grid-cols-1 md:grid-cols-2 gap-3">+ <div>+ <label className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Display name override (optional)</label>+ <input+ type="text"+ value={form.displayNameOverride}+ onChange={(e) => setForm((f) => ({ ...f, displayNameOverride: e.target.value }))}+ placeholder="Use a different name in this bucket"+ maxLength={120}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </div>+ <div>+ <label className="block text-xs uppercase tracking-wider text-gray-500 mb-1">Bio override (optional)</label>+ <input+ type="text"+ value={form.bioOverride}+ onChange={(e) => setForm((f) => ({ ...f, bioOverride: e.target.value }))}+ placeholder="Different bio for this bucket"+ maxLength={2000}+ className="w-full px-3 py-2 bg-port-bg border border-port-border rounded text-white text-sm"+ />+ </div>+ </div>+ <div className="flex gap-2">+ <button+ type="submit"+ disabled={creating}+ className="inline-flex items-center gap-2 px-3 py-2 rounded bg-port-accent text-white text-sm font-medium disabled:opacity-50"+ >+ {creating ? <Loader2 size={14} className="animate-spin" /> : null}+ Register bucket+ </button>+ <button+ type="button"+ onClick={() => setShowAdd(false)}+ className="px-3 py-2 rounded text-gray-400 hover:text-white text-sm"+ >+ Cancel+ </button>+ </div>+ </form>+ )}++ <div className="grid grid-cols-1 md:grid-cols-[280px_1fr] gap-4">+ {/* Bucket list */}+ <aside>+ {loading ? (+ <div className="text-gray-500 text-sm">Loading…</div>+ ) : buckets.length === 0 ? (+ <div className="p-4 bg-port-card border border-port-border rounded-lg text-sm text-gray-500">+ No buckets yet. Click <span className="text-port-accent">Add bucket</span> to register a synced folder.+ </div>+ ) : (+ <ul className="space-y-2">+ {buckets.map((b) => {+ const inboxCount = (inboxByBucket[b.id] || []).length;+ const isSelected = selectedId === b.id;+ return (+ <li key={b.id}>+ <button+ type="button"+ onClick={() => setSelectedId(b.id)}+ className={`w-full text-left p-3 rounded-lg border ${isSelected ? 'bg-port-card border-port-accent/40' : 'bg-port-card border-port-border'} hover:border-port-accent/30 transition-colors`}+ >+ <div className="flex items-center justify-between gap-2">+ <span className="text-white text-sm font-medium truncate">{b.name}</span>+ {inboxCount > 0 && (+ <span className="inline-flex items-center justify-center min-w-[18px] px-1.5 py-0.5 rounded-full bg-port-accent text-[10px] text-white">+ {inboxCount}+ </span>+ )}+ </div>+ <div className="text-[11px] text-gray-500 truncate mt-1 flex items-center gap-1">+ <Folder size={10} />+ {b.path}+ </div>+ <div className="text-[10px] text-gray-600 mt-1">+ {b.mode === 'auto-merge' ? 'auto-merge' : 'inbox'}+ </div>+ </button>+ </li>+ );+ })}+ </ul>+ )}+ </aside>++ {/* Detail panel */}+ <section>+ {!selected ? (+ <div className="p-6 bg-port-card border border-port-border rounded-lg text-sm text-gray-500">+ Pick a bucket on the left to see its inbox + activity.+ </div>+ ) : (+ <div>+ {/* Tabs */}+ <div className="flex gap-1 mb-3 border-b border-port-border">+ <TabButton active={activeTab === 'inbox'} onClick={() => setActiveTab('inbox')} icon={Inbox} label="Inbox" count={(inboxByBucket[selected.id] || []).length} />+ <TabButton active={activeTab === 'activity'} onClick={() => setActiveTab('activity')} icon={History} label="Activity" />+ <TabButton active={activeTab === 'settings'} onClick={() => setActiveTab('settings')} icon={Save} label="Settings" />+ </div>++ {activeTab === 'inbox' && (+ <Inboxlist+ bucket={selected}+ items={inboxByBucket[selected.id] || []}+ onPromote={(id) => handlePromote(selected.id, id)}+ onDismiss={(id) => handleDismiss(selected.id, id)}+ />+ )}+ {activeTab === 'activity' && (+ <ActivityList manifests={activityByBucket[selected.id] || []} />+ )}+ {activeTab === 'settings' && (+ <SettingsPanel+ bucket={selected}+ onToggleMode={() => handleModeToggle(selected)}+ onDelete={() => handleDelete(selected)}+ armed={armedRemove === selected.id}+ />+ )}+ </div>+ )}+ </section>+ </div>+ </div>+ );+}++function TabButton({ active, onClick, icon: Icon, label, count }) {+ return (+ <button+ type="button"+ onClick={onClick}+ className={`inline-flex items-center gap-1.5 px-3 py-1.5 text-xs ${active ? 'border-b-2 border-port-accent text-white' : 'border-b-2 border-transparent text-gray-400 hover:text-white'}`}+ >+ <Icon size={12} />+ {label}+ {typeof count === 'number' && count > 0 ? (+ <span className="inline-flex items-center justify-center min-w-[16px] px-1 py-0 rounded-full bg-port-accent text-[10px] text-white">{count}</span>+ ) : null}+ </button>+ );+}++function Inboxlist({ bucket, items, onPromote, onDismiss }) {+ if (bucket.mode === 'auto-merge') {+ return (+ <div className="p-4 bg-port-card border border-port-border rounded-lg text-sm text-gray-500 flex items-start gap-2">+ <AlertCircle size={14} className="mt-0.5 text-port-accent" />+ <div>+ This bucket is in <strong className="text-white">auto-merge</strong> mode — incoming shares are applied immediately. Switch to <strong className="text-white">inbox</strong> in the Settings tab to require manual review.+ </div>+ </div>+ );+ }+ if (items.length === 0) {+ return <div className="p-4 bg-port-card border border-port-border rounded-lg text-sm text-gray-500">No pending imports.</div>;+ }+ return (+ <ul className="space-y-2">+ {items.map((item) => (+ <li key={item.manifestId} className="p-3 bg-port-card border border-port-border rounded-lg">+ <div className="flex items-start justify-between gap-3">+ <div className="flex-1 min-w-0">+ <div className="text-sm text-white">+ <span className="text-port-accent">{item.source}</span>+ <span className="text-gray-600"> · {item.kind}</span>+ <span className="text-gray-600"> · {new Date(item.receivedAt || item.createdAt).toLocaleString()}</span>+ </div>+ {item.sourceBio ? (+ <div className="text-[11px] text-gray-500 mt-0.5 italic">{item.sourceBio}</div>+ ) : null}+ {Array.isArray(item.summary) && item.summary.length > 0 ? (+ <ul className="mt-1 text-[12px] text-gray-400 list-disc pl-4">+ {item.summary.map((s, i) => (+ <li key={i}><span className="text-gray-600">{s.kind}:</span> {s.label}</li>+ ))}+ </ul>+ ) : null}+ {item.assetCount ? <div className="text-[11px] text-gray-500 mt-1">{item.assetCount} asset{item.assetCount === 1 ? '' : 's'}</div> : null}+ </div>+ <div className="flex flex-col gap-1">+ <button+ type="button"+ onClick={() => onPromote(item.manifestId)}+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs bg-port-success/20 text-port-success hover:bg-port-success/30 border border-port-success/30"+ title="Apply to local state"+ >+ <Check size={12} />+ Import+ </button>+ <button+ type="button"+ onClick={() => onDismiss(item.manifestId)}+ className="inline-flex items-center gap-1 px-2 py-1 rounded text-xs text-gray-400 hover:text-port-error border border-port-border"+ title="Discard this share"+ >+ <X size={12} />+ Dismiss+ </button>+ </div>+ </div>+ </li>+ ))}+ </ul>+ );+}++function ActivityList({ manifests }) {+ if (manifests.length === 0) {+ return <div className="p-4 bg-port-card border border-port-border rounded-lg text-sm text-gray-500">No share activity yet.</div>;+ }+ return (+ <ul className="space-y-1.5">+ {manifests.map((m) => (+ <li key={m.id} className="p-2 bg-port-card border border-port-border rounded text-xs flex items-center gap-2">+ <span className="text-gray-500">{new Date(m.createdAt).toLocaleString()}</span>+ <span className="text-port-accent">{m.source}</span>+ <span className="text-gray-600">·</span>+ <span className="text-gray-300">{m.kind}</span>+ <span className="text-gray-600">·</span>+ <span className="text-gray-500">{(m.recordIds || []).length} record{(m.recordIds || []).length === 1 ? '' : 's'}, {(m.assetRefs || []).length} asset{(m.assetRefs || []).length === 1 ? '' : 's'}</span>+ </li>+ ))}+ </ul>+ );+}++function SettingsPanel({ bucket, onToggleMode, onDelete, armed }) {+ return (+ <div className="space-y-4">+ <div className="p-4 bg-port-card border border-port-border rounded-lg">+ <h3 className="text-sm font-medium text-white mb-2">Import mode</h3>+ <div className="flex items-center gap-3">+ <span className={`text-sm ${bucket.mode === 'inbox' ? 'text-white' : 'text-gray-500'}`}>Inbox (review)</span>+ <button+ type="button"+ onClick={onToggleMode}+ className={`relative inline-flex h-5 w-9 items-center rounded-full transition-colors ${bucket.mode === 'auto-merge' ? 'bg-port-accent' : 'bg-port-border'}`}+ aria-label="Toggle mode"+ >+ <span className={`inline-block h-3 w-3 transform rounded-full bg-white transition-transform ${bucket.mode === 'auto-merge' ? 'translate-x-5' : 'translate-x-1'}`} />+ </button>+ <span className={`text-sm ${bucket.mode === 'auto-merge' ? 'text-white' : 'text-gray-500'}`}>Auto-merge</span>+ </div>+ <p className="text-[11px] text-gray-500 mt-2">+ Auto-merge applies incoming records directly (LWW by updatedAt). Inbox queues them for explicit review.+ </p>+ </div>+ <div className="p-4 bg-port-card border border-port-border rounded-lg">+ <h3 className="text-sm font-medium text-white mb-1">Folder</h3>+ <div className="text-xs font-mono text-gray-400 break-all">{bucket.path}</div>+ <p className="text-[11px] text-gray-500 mt-2">+ To move a bucket to a different folder, remove this bucket and register a new one at the target path.+ </p>+ </div>+ <div className="p-4 bg-port-card border border-port-error/30 rounded-lg">+ <h3 className="text-sm font-medium text-port-error mb-2">Remove bucket</h3>+ <p className="text-[11px] text-gray-500 mb-3">+ Stops watching the folder for new shares and drops the bucket from PortOS. Files inside the folder are not deleted — your cloud-sync app keeps the data.+ </p>+ <button+ type="button"+ onClick={onDelete}+ className={`inline-flex items-center gap-2 px-3 py-2 rounded text-xs ${armed ? 'bg-port-error text-white' : 'bg-port-bg text-port-error border border-port-error/40 hover:bg-port-error/10'}`}+ >+ <Trash2 size={12} />+ {armed ? 'Click again to confirm' : 'Remove bucket'}+ </button>+ </div>+ </div>+ );+}diff --git a/client/src/pages/UniverseBuilder.jsx b/client/src/pages/UniverseBuilder.jsxindex 6476be9766..57db9097d5 100644--- a/client/src/pages/UniverseBuilder.jsx+++ b/client/src/pages/UniverseBuilder.jsx@@ -27,6 +27,8 @@ import {import InfluenceChipsInput from '../components/universeBuilder/InfluenceChipsInput';import BackendChipStrip from '../components/media/BackendChipStrip';import ImageGenControls from '../components/imageGen/ImageGenControls';+import ShareToButton from '../components/sharing/ShareToButton';+import OriginBadge from '../components/sharing/OriginBadge';import { deriveAvailableBackends, IMAGE_GEN_MODE } from '../lib/imageGenBackends';const CATEGORY_LABELS = {@@ -866,6 +868,8 @@ export default function UniverseBuilder() {><Library size={16} /> Canon</Link>+ <ShareToButton kind="universe" ids={[selectedId]} label="Share" />+ {draft.origin ? <OriginBadge origin={draft.origin} /> : null}<buttononClick={handleDelete}className={`px-3 py-2 rounded flex items-center gap-2 min-h-[40px] ${diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 7de60f1cfd..825aa7f35b 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -41,6 +41,7 @@ export * from './apiMediaJobs.js';export * from './apiWritersRoom.js';export * from './apiUniverseBuilder.js';export * from './apiPipeline.js';+export * from './apiSharing.js';// Default export for simplified imports (get/post/put/delete helpers)export { default } from './apiCore.js';diff --git a/client/src/services/apiSharing.js b/client/src/services/apiSharing.jsnew file mode 100644index 0000000000..a7046d46d7--- /dev/null+++ b/client/src/services/apiSharing.js@@ -0,0 +1,47 @@+import { request } from './apiCore.js';++export const BUCKET_MODES = Object.freeze(['auto-merge', 'inbox']);++// ---- Buckets ----+export const listShareBuckets = (options) => request('/sharing/buckets', options);++export const createShareBucket = (data, options) => request('/sharing/buckets', {+ method: 'POST',+ body: JSON.stringify(data),+ ...options,+});++export const updateShareBucket = (id, patch, options) => request(`/sharing/buckets/${encodeURIComponent(id)}`, {+ method: 'PUT',+ body: JSON.stringify(patch),+ ...options,+});++export const deleteShareBucket = (id, options) => request(`/sharing/buckets/${encodeURIComponent(id)}`, {+ method: 'DELETE',+ ...options,+});++// ---- Export ----+// body: { kind: 'series'|'universe'|'media', ids?: string[], items?: [{kind,ref}] }+export const exportToShareBucket = (bucketId, body, options) => request(`/sharing/buckets/${encodeURIComponent(bucketId)}/export`, {+ method: 'POST',+ body: JSON.stringify(body),+ ...options,+});++// ---- Inbox ----+export const listShareInbox = (bucketId, options) => request(`/sharing/buckets/${encodeURIComponent(bucketId)}/inbox`, options);++export const promoteShareInboxItem = (bucketId, manifestId, options) => request(+ `/sharing/buckets/${encodeURIComponent(bucketId)}/inbox/${encodeURIComponent(manifestId)}/promote`,+ { method: 'POST', ...options },+);++export const dismissShareInboxItem = (bucketId, manifestId, options) => request(+ `/sharing/buckets/${encodeURIComponent(bucketId)}/inbox/${encodeURIComponent(manifestId)}/dismiss`,+ { method: 'POST', ...options },+);++// ---- Activity ----+export const listShareActivity = (bucketId, options) => request(`/sharing/buckets/${encodeURIComponent(bucketId)}/activity`, options);diff --git a/server/index.js b/server/index.jsindex 737382658f..63bc47f724 100644--- a/server/index.js+++ b/server/index.js@@ -96,6 +96,8 @@ import imageVideoModelsRoutes from './routes/imageVideoModels.js';import lorasRoutes from './routes/loras.js';import sdapiRoutes from './routes/sdapi.js';import openclawRoutes from './routes/openclaw.js';+import sharingRoutes from './routes/sharing.js';+import { initSharing } from './services/sharing/index.js';import askRoutes from './routes/ask.js';import { ensureSelf, startPolling } from './services/instances.js';import { initSyncLog } from './services/brainSyncLog.js';@@ -374,6 +376,7 @@ app.use('/api/loras', lorasRoutes);// settings.imageGen.expose.a1111 so it returns 403 unless the user opted in.app.use('/sdapi/v1', sdapiRoutes);app.use('/api/openclaw', openclawRoutes);+app.use('/api/sharing', sharingRoutes);app.use('/api/ask', askRoutes);// initMediaJobQueue is awaited as part of the startup chain below so that@@ -506,6 +509,15 @@ ensureSelf()// for `completed` events — so initialize the hook here.initUniverseBuilderCollectionHook();})+ .then(() => {+ // Sharing: attach chokidar watchers to every registered share bucket so+ // incoming manifests from peers are picked up live. Backlog processing+ // (manifests that arrived while the server was offline) runs as part of+ // initSharing. Fire-and-forget — a failed bucket shouldn't block boot.+ initSharing({ io }).catch((err) => {+ console.error(`❌ Sharing init failed: ${err.message}`);+ });+ }).then(() => {// Fire-and-forget — resume any Creative Director projects that were mid-// flight when the server died. The queue reload above just reclassifieddiff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex b69314de56..22598a9da0 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -20,6 +20,7 @@ export const NAV_COMMANDS = [{ id: 'nav.media.models', path: '/media/models', label: 'Media Models', section: 'Create', aliases: ['media-models', 'image-models', 'video-models', 'huggingface'], keywords: ['hf cache', 'model storage', 'disk'] },{ id: 'nav.create.universe-builder', path: '/universe-builder', label: 'Universe Builder', section: 'Create', aliases: ['universe-builder', 'worldbuilder', 'worldbuild', 'world', 'universe', 'lore'], keywords: ['style template', 'sci-fi', 'fantasy', 'concept art', 'batch render', 'variations'] },{ id: 'nav.create.pipeline', path: '/pipeline', label: 'Pipeline', section: 'Create', aliases: ['pipeline', 'production', 'series-pipeline', 'production-pipeline'], keywords: ['series', 'issue', 'episode', 'comic', 'script', 'prose', 'storyboard', 'narrative', 'workflow'] },+ { id: 'nav.create.sharing', path: '/sharing', label: 'Sharing', section: 'Create', aliases: ['sharing', 'share', 'buckets', 'share-buckets'], keywords: ['google drive', 'dropbox', 'icloud', 'syncthing', 'export', 'import', 'collaborate', 'federation', 'peer', 'cross-network'] },{ id: 'nav.media.loras', path: '/media/loras', label: 'LoRAs', section: 'Create', aliases: ['loras', 'lora', 'lora-manager', 'civitai'], keywords: ['lora', 'civitai', 'fine-tune', 'style adapter', 'realstagram', 'photoreal', 'flux lora'] },{ id: 'nav.media.settings', path: '/media/image?settings=1', label: 'Media Gen Settings', section: 'Create', aliases: ['media-settings', 'image-gen-settings', 'sd-settings', 'video-gen-settings'] },{ id: 'nav.writers-room', path: '/writers-room', label: 'Writers Room', section: 'Create', aliases: ['writers-room', 'writersroom', 'writer', 'write', 'studio', 'novel'], keywords: ['prose', 'screenplay', 'story', 'draft', 'manuscript', 'literary', 'novel', 'short story'] },diff --git a/server/lib/sharingOrigin.js b/server/lib/sharingOrigin.jsnew file mode 100644index 0000000000..0eb6333260--- /dev/null+++ b/server/lib/sharingOrigin.js@@ -0,0 +1,35 @@+/**+ * Origin metadata for records imported from share buckets.+ *+ * When a pipeline series / issue / universe / media collection item is imported+ * from another PortOS instance via a share bucket, the importer stamps the+ * record with `origin: { ... }`. Locally-authored records have no `origin`.+ *+ * Single level of provenance only — re-sharing authors a fresh origin on the+ * recipient; we do not maintain a chain[]. Keep it simple; if attribution+ * chains become important, the manifest archive in the bucket still has the+ * full history.+ */++import { isStr, trimTo } from './storyBible.js';++export const ORIGIN_BUCKET_ID_MAX = 64;+export const ORIGIN_BUCKET_NAME_MAX = 120;+export const ORIGIN_SOURCE_MAX = 120;+export const ORIGIN_SOURCE_BIO_MAX = 2000;+export const ORIGIN_MANIFEST_ID_MAX = 64;++export function sanitizeOrigin(raw) {+ if (!raw || typeof raw !== 'object') return null;+ const bucketId = trimTo(raw.bucketId, ORIGIN_BUCKET_ID_MAX);+ const bucketName = trimTo(raw.bucketName, ORIGIN_BUCKET_NAME_MAX);+ const source = trimTo(raw.source, ORIGIN_SOURCE_MAX);+ const manifestId = trimTo(raw.manifestId, ORIGIN_MANIFEST_ID_MAX);+ // bucketId + source + manifestId are the load-bearing identifiers. If any+ // is missing the origin metadata is degenerate — drop the whole field+ // rather than persist a half-record that the UI can't render.+ if (!bucketId || !source || !manifestId) return null;+ const sourceBio = trimTo(raw.sourceBio, ORIGIN_SOURCE_BIO_MAX) || null;+ const importedAt = isStr(raw.importedAt) ? raw.importedAt : new Date().toISOString();+ return { bucketId, bucketName: bucketName || bucketId, source, sourceBio, manifestId, importedAt };+}diff --git a/server/lib/sharingOrigin.test.js b/server/lib/sharingOrigin.test.jsnew file mode 100644index 0000000000..9a0a04f666--- /dev/null+++ b/server/lib/sharingOrigin.test.js@@ -0,0 +1,59 @@+import { describe, it, expect } from 'vitest';+import { sanitizeOrigin } from './sharingOrigin.js';++describe('sharingOrigin.sanitizeOrigin', () => {+ it('returns null for non-objects', () => {+ expect(sanitizeOrigin(null)).toBeNull();+ expect(sanitizeOrigin(undefined)).toBeNull();+ expect(sanitizeOrigin('foo')).toBeNull();+ expect(sanitizeOrigin(42)).toBeNull();+ });++ it('returns null when load-bearing fields are missing', () => {+ expect(sanitizeOrigin({ bucketName: 'X' })).toBeNull(); // no bucketId/source/manifestId+ expect(sanitizeOrigin({ bucketId: 'b1', source: 'me' })).toBeNull(); // no manifestId+ expect(sanitizeOrigin({ bucketId: 'b1', manifestId: 'm1' })).toBeNull(); // no source+ });++ it('round-trips a well-formed origin', () => {+ const out = sanitizeOrigin({+ bucketId: 'b1',+ bucketName: 'Creative Circle',+ source: 'atomantic',+ sourceBio: 'Maker, dreamer',+ manifestId: 'm1',+ importedAt: '2026-05-15T12:00:00Z',+ });+ expect(out).toEqual({+ bucketId: 'b1',+ bucketName: 'Creative Circle',+ source: 'atomantic',+ sourceBio: 'Maker, dreamer',+ manifestId: 'm1',+ importedAt: '2026-05-15T12:00:00Z',+ });+ });++ it('defaults bucketName to bucketId when missing', () => {+ const out = sanitizeOrigin({ bucketId: 'b1', source: 'me', manifestId: 'm1' });+ expect(out.bucketName).toBe('b1');+ });++ it('coerces sourceBio absence to null', () => {+ const out = sanitizeOrigin({ bucketId: 'b1', source: 'me', manifestId: 'm1' });+ expect(out.sourceBio).toBeNull();+ });++ it('stamps importedAt when missing', () => {+ const before = Date.now();+ const out = sanitizeOrigin({ bucketId: 'b1', source: 'me', manifestId: 'm1' });+ const ts = Date.parse(out.importedAt);+ expect(ts).toBeGreaterThanOrEqual(before);+ });++ it('trims strings to their limits', () => {+ const longSource = 'x'.repeat(500);+ const out = sanitizeOrigin({ bucketId: 'b1', source: longSource, manifestId: 'm1' });+ expect(out.source.length).toBeLessThanOrEqual(120);+ });+});diff --git a/server/lib/validation.js b/server/lib/validation.jsindex fe3b917ba0..c201b52be8 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -821,6 +821,52 @@ export function sanitizeTaskMetadata(raw) {}+// =============================================================================+// SHARING (cross-network share buckets via cloud-synced folders)+// =============================================================================++export const bucketModeSchema = z.enum(['auto-merge', 'inbox']);++export const bucketCreateSchema = z.object({+ name: z.string().trim().min(1).max(120),+ path: z.string().trim().min(1).max(2000),+ mode: bucketModeSchema.optional().default('inbox'),+ displayNameOverride: z.string().trim().max(120).optional().nullable(),+ bioOverride: z.string().trim().max(2000).optional().nullable(),+}).strict();++export const bucketUpdateSchema = z.object({+ name: z.string().trim().min(1).max(120).optional(),+ mode: bucketModeSchema.optional(),+ displayNameOverride: z.string().trim().max(120).nullable().optional(),+ bioOverride: z.string().trim().max(2000).nullable().optional(),+}).strict();++// Items shape for kind:'media'. Mirrors mediaCollections item key+// — { kind: 'image'|'video', ref: '<filename>' }.+const sharingMediaItemSchema = z.object({+ kind: z.enum(['image', 'video']),+ ref: z.string().min(1).max(500),+}).strict();++export const sharingExportSchema = z.object({+ kind: z.enum(['series', 'universe', 'media']),+ ids: z.array(z.string().min(1).max(120)).max(50).optional(),+ items: z.array(sharingMediaItemSchema).max(200).optional(),+}).strict().refine(+ (data) => {+ if (data.kind === 'media') return Array.isArray(data.items) && data.items.length > 0;+ return Array.isArray(data.ids) && data.ids.length > 0;+ },+ { message: "Provide 'ids' for kind=series|universe, or 'items' for kind=media" },+);++// User-level sharing config — extends settings.json.+export const sharingSettingsPatchSchema = z.object({+ sharingDisplayName: z.string().trim().max(120).optional(),+ sharingBio: z.string().trim().max(2000).optional(),+}).strict();+// =============================================================================// CREATIVE DIRECTOR SCHEMAS// =============================================================================diff --git a/server/routes/sharing.js b/server/routes/sharing.jsnew file mode 100644index 0000000000..e92337d410--- /dev/null+++ b/server/routes/sharing.js@@ -0,0 +1,94 @@+/**+ * Sharing routes — cross-network share buckets via cloud-synced folders.+ *+ * GET /api/sharing/buckets → list registered buckets+ * POST /api/sharing/buckets → register a new bucket+ * PUT /api/sharing/buckets/:id → patch bucket (name/mode/overrides)+ * DELETE /api/sharing/buckets/:id → unregister + detach watcher+ * POST /api/sharing/buckets/:id/export → export series/universe/media+ * GET /api/sharing/buckets/:id/inbox → list pending imports+ * POST /api/sharing/buckets/:id/inbox/:manifestId/promote → adopt into local state+ * POST /api/sharing/buckets/:id/inbox/:manifestId/dismiss → drop from inbox+ * GET /api/sharing/buckets/:id/activity → recent manifests (in/out)+ */++import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest } from '../lib/validation.js';+import {+ bucketCreateSchema, bucketUpdateSchema, sharingExportSchema,+} from '../lib/validation.js';+import {+ listBuckets, getBucket, createBucket, updateBucket, deleteBucket,+} from '../services/sharing/buckets.js';+import { attachWatcher, detachWatcher } from '../services/sharing/watcher.js';+import { exportByKind } from '../services/sharing/exporter.js';+import {+ listInbox, promoteInboxItem, dismissInboxItem,+} from '../services/sharing/importer.js';+import { listManifestFilenames, readManifest } from '../services/sharing/manifest.js';++const router = Router();++router.get('/buckets', asyncHandler(async (req, res) => {+ const buckets = await listBuckets();+ res.json({ buckets });+}));++router.get('/buckets/:id', asyncHandler(async (req, res) => {+ const bucket = await getBucket(req.params.id);+ res.json({ bucket });+}));++router.post('/buckets', asyncHandler(async (req, res) => {+ const input = validateRequest(bucketCreateSchema, req.body || {});+ const bucket = await createBucket(input);+ await attachWatcher(bucket.id);+ res.status(201).json({ bucket });+}));++router.put('/buckets/:id', asyncHandler(async (req, res) => {+ const patch = validateRequest(bucketUpdateSchema, req.body || {});+ const bucket = await updateBucket(req.params.id, patch);+ res.json({ bucket });+}));++router.delete('/buckets/:id', asyncHandler(async (req, res) => {+ await detachWatcher(req.params.id);+ const result = await deleteBucket(req.params.id);+ res.json(result);+}));++router.post('/buckets/:id/export', asyncHandler(async (req, res) => {+ const body = validateRequest(sharingExportSchema, req.body || {});+ const result = await exportByKind({ ...body, bucketId: req.params.id });+ res.json(result);+}));++router.get('/buckets/:id/inbox', asyncHandler(async (req, res) => {+ const items = await listInbox(req.params.id);+ res.json({ items });+}));++router.post('/buckets/:id/inbox/:manifestId/promote', asyncHandler(async (req, res) => {+ const result = await promoteInboxItem(req.params.id, req.params.manifestId);+ res.json(result);+}));++router.post('/buckets/:id/inbox/:manifestId/dismiss', asyncHandler(async (req, res) => {+ const result = await dismissInboxItem(req.params.id, req.params.manifestId);+ res.json(result);+}));++/** Recent manifests (max 50, newest first) — both incoming and outgoing land here. */+router.get('/buckets/:id/activity', asyncHandler(async (req, res) => {+ const bucket = await getBucket(req.params.id);+ const filenames = (await listManifestFilenames(bucket.path)).slice(0, 50);+ const reads = await Promise.all(filenames.map(async (f) => {+ const m = await readManifest(bucket.path, f);+ return m ? { filename: f, ...m } : null;+ }));+ res.json({ manifests: reads.filter(Boolean) });+}));++export default router;diff --git a/server/services/mediaCollections.js b/server/services/mediaCollections.jsindex 6fa7371a37..16eff5712e 100644--- a/server/services/mediaCollections.js+++ b/server/services/mediaCollections.js@@ -14,6 +14,7 @@ import { join } from 'path';import { randomUUID } from 'crypto';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../lib/fileUtils.js';import { ITEM_KIND, REF_MAX_LENGTH, itemKey } from '../lib/mediaItemKey.js';+import { sanitizeOrigin } from '../lib/sharingOrigin.js';const STATE_PATH = join(PATHS.data, 'media-collections.json');@@ -45,7 +46,10 @@ const sanitizeItem = (raw) => {// resolver's Date sort — replace anything unparseable with now().const parsed = typeof raw.addedAt === 'string' ? Date.parse(raw.addedAt) : NaN;const addedAt = Number.isFinite(parsed) ? raw.addedAt : new Date().toISOString();- return { kind: raw.kind, ref, addedAt };+ const out = { kind: raw.kind, ref, addedAt };+ const origin = sanitizeOrigin(raw.origin);+ if (origin) out.origin = origin;+ return out;};const sanitizeCollection = (raw) => {diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.jsindex bd36527177..bae260114d 100644--- a/server/services/pipeline/issues.js+++ b/server/services/pipeline/issues.js@@ -25,6 +25,7 @@ import {LENGTH_PROFILE_NAMES, DEFAULT_LENGTH_PROFILE,CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,} from '../../lib/issueLength.js';+import { sanitizeOrigin } from '../../lib/sharingOrigin.js';// Lazy resolution — see series.js for context.const statePath = () => join(PATHS.data, 'pipeline-issues.json');@@ -223,6 +224,8 @@ const sanitizeIssue = (raw) => {pageTarget,minutesTarget,stages: sanitizeStages(raw.stages || {}),+ // Share-bucket provenance — present on imported records, absent on locally-authored ones.+ origin: sanitizeOrigin(raw.origin),createdAt,updatedAt,};@@ -380,6 +383,7 @@ export function updateIssue(id, patch = {}) {...('lengthProfile' in patch ? { lengthProfile: patch.lengthProfile } : {}),...('pageTarget' in patch ? { pageTarget: patch.pageTarget } : {}),...('minutesTarget' in patch ? { minutesTarget: patch.minutesTarget } : {}),+ ...('origin' in patch ? { origin: patch.origin } : {}),stages: mergedStages,updatedAt: new Date().toISOString(),});diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.jsindex a8e9404f59..98307845ba 100644--- a/server/services/pipeline/series.js+++ b/server/services/pipeline/series.js@@ -20,6 +20,7 @@ import {} from '../../lib/storyBible.js';import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';import { extractBible } from '../../lib/bibleExtractor.js';+import { sanitizeOrigin } from '../../lib/sharingOrigin.js';// Lazy resolution — PATHS.data may not be available at module-load time// (e.g. tests that swap it through a Proxy mock).@@ -84,6 +85,8 @@ const sanitizeSeries = (raw) => {targetFormat,issueCountTarget,llm,+ // Share-bucket provenance — present on imported records, absent on locally-authored ones.+ origin: sanitizeOrigin(raw.origin),createdAt,updatedAt,};@@ -165,6 +168,7 @@ export async function updateSeries(id, patch = {}) {...('styleNotes' in patch ? { styleNotes: patch.styleNotes } : {}),...('targetFormat' in patch ? { targetFormat: patch.targetFormat } : {}),...('issueCountTarget' in patch ? { issueCountTarget: patch.issueCountTarget } : {}),+ ...('origin' in patch ? { origin: patch.origin } : {}),llm: mergedLlm,updatedAt: new Date().toISOString(),});diff --git a/server/services/sharing/buckets.js b/server/services/sharing/buckets.jsnew file mode 100644index 0000000000..5d236dbcfe--- /dev/null+++ b/server/services/sharing/buckets.js@@ -0,0 +1,185 @@+/**+ * Share Buckets — registry CRUD.+ *+ * A "bucket" is a local directory the user registers; PortOS reads/writes a+ * stable layout inside it (bucket.json + manifests/ + records/ + assets/),+ * while an external cloud-sync app (Google Drive, Dropbox, iCloud, Syncthing,+ * USB stick…) handles cross-network replication. PortOS is transport-agnostic.+ *+ * The registry itself lives in PortOS's local data/, NOT in the shared bucket —+ * otherwise every peer's settings would overwrite each other.+ */++import { randomUUID } from 'crypto';+import { join } from 'path';+import { access, constants, stat } from 'fs/promises';+import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';+import { isStr, trimTo } from '../../lib/storyBible.js';++const REGISTRY_PATH = () => join(PATHS.data, 'sharing', 'buckets.json');++export const BUCKET_MODES = Object.freeze(['auto-merge', 'inbox']);++export const NAME_MAX = 120;+export const PATH_MAX = 2000;+export const DISPLAY_NAME_MAX = 120;+export const BIO_MAX = 2000;++export const ERR_NOT_FOUND = 'SHARING_BUCKET_NOT_FOUND';+export const ERR_VALIDATION = 'SHARING_BUCKET_VALIDATION';+export const ERR_PATH_UNUSABLE = 'SHARING_BUCKET_PATH_UNUSABLE';++const makeErr = (message, code) => Object.assign(new Error(message), { code });++const sanitizeBucket = (raw) => {+ if (!raw || typeof raw !== 'object') return null;+ if (!isStr(raw.id) || !raw.id) return null;+ const name = trimTo(raw.name, NAME_MAX);+ const path = trimTo(raw.path, PATH_MAX);+ if (!name || !path) return null;+ const mode = BUCKET_MODES.includes(raw.mode) ? raw.mode : 'inbox';+ const displayNameOverride = trimTo(raw.displayNameOverride, DISPLAY_NAME_MAX) || null;+ const bioOverride = trimTo(raw.bioOverride, BIO_MAX) || null;+ const createdAt = isStr(raw.createdAt) ? raw.createdAt : new Date().toISOString();+ const updatedAt = isStr(raw.updatedAt) ? raw.updatedAt : createdAt;+ return { id: raw.id, name, path, mode, displayNameOverride, bioOverride, createdAt, updatedAt };+};++async function readRegistry() {+ await ensureDir(join(PATHS.data, 'sharing'));+ const raw = await readJSONFile(REGISTRY_PATH(), { buckets: [] }, { logError: false });+ const buckets = Array.isArray(raw.buckets) ? raw.buckets.map(sanitizeBucket).filter(Boolean) : [];+ return { buckets };+}++async function writeRegistry(state) {+ await ensureDir(join(PATHS.data, 'sharing'));+ await atomicWrite(REGISTRY_PATH(), state);+}++/** Validate that the bucket path is a readable+writable directory. */+async function assertPathUsable(path) {+ let st;+ try {+ st = await stat(path);+ } catch (err) {+ throw makeErr(`Bucket path does not exist or is unreadable: ${path}`, ERR_PATH_UNUSABLE);+ }+ if (!st.isDirectory()) {+ throw makeErr(`Bucket path is not a directory: ${path}`, ERR_PATH_UNUSABLE);+ }+ try {+ await access(path, constants.R_OK | constants.W_OK);+ } catch (err) {+ throw makeErr(`Bucket path is not writable: ${path}`, ERR_PATH_UNUSABLE);+ }+}++/** Lay out the canonical bucket structure (idempotent). */+export async function ensureBucketLayout(bucket) {+ const base = bucket.path;+ await ensureDir(base);+ await ensureDir(join(base, 'manifests'));+ await ensureDir(join(base, 'records', 'series'));+ await ensureDir(join(base, 'records', 'issues'));+ await ensureDir(join(base, 'records', 'universes'));+ await ensureDir(join(base, 'records', 'media'));+ await ensureDir(join(base, 'assets', 'images'));+ await ensureDir(join(base, 'assets', 'videos'));+ const bucketJsonPath = join(base, 'bucket.json');+ const existing = await readJSONFile(bucketJsonPath, null, { logError: false });+ if (!existing || existing.id !== bucket.id) {+ // Bucket.json carries the *shared* identity. If a peer registered the+ // same folder first, keep their id — otherwise stamp ours. A mismatched+ // id with the registry happens when two peers initially register the+ // same folder; we still operate on whatever the on-disk bucket.json says+ // is the canonical id (importer keys on that).+ if (!existing) {+ await atomicWrite(bucketJsonPath, {+ id: bucket.id,+ name: bucket.name,+ schemaVersion: 1,+ createdAt: bucket.createdAt,+ });+ }+ }+}++export async function listBuckets() {+ const { buckets } = await readRegistry();+ return [...buckets].sort((a, b) => (a.name || '').localeCompare(b.name || ''));+}++export async function getBucket(id) {+ const { buckets } = await readRegistry();+ const found = buckets.find((b) => b.id === id);+ if (!found) throw makeErr(`Bucket not found: ${id}`, ERR_NOT_FOUND);+ return found;+}++export async function createBucket(input = {}) {+ const name = trimTo(input.name, NAME_MAX);+ if (!name) throw makeErr(`Bucket name is required (1..${NAME_MAX} chars)`, ERR_VALIDATION);+ const path = trimTo(input.path, PATH_MAX);+ if (!path) throw makeErr('Bucket path is required', ERR_VALIDATION);+ await assertPathUsable(path);+ const state = await readRegistry();+ // Reject duplicate paths so two registry entries can't both attempt to+ // claim the same on-disk folder (they would fight over bucket.json + the+ // watcher would double-fire on every manifest).+ if (state.buckets.some((b) => b.path === path)) {+ throw makeErr(`A bucket is already registered at: ${path}`, ERR_VALIDATION);+ }+ const now = new Date().toISOString();+ const bucket = sanitizeBucket({+ id: `bkt-${randomUUID()}`,+ name,+ path,+ mode: input.mode || 'inbox',+ displayNameOverride: input.displayNameOverride || null,+ bioOverride: input.bioOverride || null,+ createdAt: now,+ updatedAt: now,+ });+ state.buckets.push(bucket);+ await writeRegistry(state);+ await ensureBucketLayout(bucket);+ return bucket;+}++export async function updateBucket(id, patch = {}) {+ const state = await readRegistry();+ const idx = state.buckets.findIndex((b) => b.id === id);+ if (idx < 0) throw makeErr(`Bucket not found: ${id}`, ERR_NOT_FOUND);+ const cur = state.buckets[idx];+ const merged = sanitizeBucket({+ ...cur,+ ...('name' in patch ? { name: patch.name } : {}),+ ...('mode' in patch ? { mode: patch.mode } : {}),+ ...('displayNameOverride' in patch ? { displayNameOverride: patch.displayNameOverride } : {}),+ ...('bioOverride' in patch ? { bioOverride: patch.bioOverride } : {}),+ updatedAt: new Date().toISOString(),+ });+ if (!merged) throw makeErr('Invalid bucket payload', ERR_VALIDATION);+ // `path` is intentionally NOT patchable — if the user wants to move a+ // bucket, they delete and re-register so the registry can re-validate and+ // re-layout the new path.+ state.buckets[idx] = merged;+ await writeRegistry(state);+ return merged;+}++export async function deleteBucket(id) {+ const state = await readRegistry();+ const before = state.buckets.length;+ state.buckets = state.buckets.filter((b) => b.id !== id);+ if (state.buckets.length === before) throw makeErr(`Bucket not found: ${id}`, ERR_NOT_FOUND);+ await writeRegistry(state);+ return { id };+}++/** Convenience: read bucket.json from disk if present. */+export async function readBucketManifestRoot(bucket) {+ const bucketJsonPath = join(bucket.path, 'bucket.json');+ return readJSONFile(bucketJsonPath, null, { logError: false });+}diff --git a/server/services/sharing/buckets.test.js b/server/services/sharing/buckets.test.jsnew file mode 100644index 0000000000..50693afb63--- /dev/null+++ b/server/services/sharing/buckets.test.js@@ -0,0 +1,103 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { vi } from 'vitest';++let tempRoot;+let bucketTargetDir;++// Mock PATHS so the registry writes into a temp dir per test.+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: tempRoot };+ return target[prop];+ },+ });+});++const buckets = await import('./buckets.js');++describe('sharing/buckets', () => {+ beforeEach(() => {+ tempRoot = mkdtempSync(join(tmpdir(), 'portos-sharing-test-'));+ bucketTargetDir = mkdtempSync(join(tmpdir(), 'portos-sharing-bucket-'));+ });+ afterEach(() => {+ if (tempRoot) rmSync(tempRoot, { recursive: true, force: true });+ if (bucketTargetDir) rmSync(bucketTargetDir, { recursive: true, force: true });+ });++ it('listBuckets returns [] for fresh state', async () => {+ expect(await buckets.listBuckets()).toEqual([]);+ });++ it('createBucket lays out the canonical structure inside the target path', async () => {+ const b = await buckets.createBucket({ name: 'Test', path: bucketTargetDir });+ expect(b.id).toMatch(/^bkt-/);+ expect(b.name).toBe('Test');+ expect(b.path).toBe(bucketTargetDir);+ expect(b.mode).toBe('inbox');++ const fs = await import('fs');+ expect(fs.existsSync(join(bucketTargetDir, 'manifests'))).toBe(true);+ expect(fs.existsSync(join(bucketTargetDir, 'records', 'series'))).toBe(true);+ expect(fs.existsSync(join(bucketTargetDir, 'records', 'issues'))).toBe(true);+ expect(fs.existsSync(join(bucketTargetDir, 'records', 'universes'))).toBe(true);+ expect(fs.existsSync(join(bucketTargetDir, 'records', 'media'))).toBe(true);+ expect(fs.existsSync(join(bucketTargetDir, 'assets', 'images'))).toBe(true);+ expect(fs.existsSync(join(bucketTargetDir, 'assets', 'videos'))).toBe(true);+ expect(fs.existsSync(join(bucketTargetDir, 'bucket.json'))).toBe(true);+ });++ it('createBucket rejects an unusable path', async () => {+ await expect(buckets.createBucket({ name: 'X', path: '/nonexistent/path/here' }))+ .rejects.toMatchObject({ code: buckets.ERR_PATH_UNUSABLE });+ });++ it('createBucket rejects duplicate paths', async () => {+ await buckets.createBucket({ name: 'A', path: bucketTargetDir });+ await expect(buckets.createBucket({ name: 'B', path: bucketTargetDir }))+ .rejects.toMatchObject({ code: buckets.ERR_VALIDATION });+ });++ it('createBucket accepts mode override', async () => {+ const b = await buckets.createBucket({ name: 'T', path: bucketTargetDir, mode: 'auto-merge' });+ expect(b.mode).toBe('auto-merge');+ });++ it('updateBucket patches name + mode but NOT path', async () => {+ const created = await buckets.createBucket({ name: 'A', path: bucketTargetDir });+ const updated = await buckets.updateBucket(created.id, { name: 'B', mode: 'auto-merge', path: '/other/path' });+ expect(updated.name).toBe('B');+ expect(updated.mode).toBe('auto-merge');+ expect(updated.path).toBe(bucketTargetDir); // path is immutable+ });++ it('deleteBucket removes from registry', async () => {+ const created = await buckets.createBucket({ name: 'A', path: bucketTargetDir });+ await buckets.deleteBucket(created.id);+ expect(await buckets.listBuckets()).toEqual([]);+ });++ it('getBucket throws for missing id', async () => {+ await expect(buckets.getBucket('does-not-exist'))+ .rejects.toMatchObject({ code: buckets.ERR_NOT_FOUND });+ });++ it('list is sorted alphabetically', async () => {+ const a = mkdtempSync(join(tmpdir(), 'b1-'));+ const b = mkdtempSync(join(tmpdir(), 'b2-'));+ try {+ await buckets.createBucket({ name: 'Zeta', path: a });+ await buckets.createBucket({ name: 'Alpha', path: b });+ const list = await buckets.listBuckets();+ expect(list.map((x) => x.name)).toEqual(['Alpha', 'Zeta']);+ } finally {+ rmSync(a, { recursive: true, force: true });+ rmSync(b, { recursive: true, force: true });+ }+ });+});diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.jsnew file mode 100644index 0000000000..6ede436923--- /dev/null+++ b/server/services/sharing/exporter.js@@ -0,0 +1,355 @@+/**+ * Share Bucket — exporter.+ *+ * Gathers a pipeline series / universe / media item from local state, copies+ * the referenced asset blobs (image/video files + per-asset media-job records+ * for full-fidelity re-render metadata) into the bucket, then writes a manifest+ * pointing at the bundled records.+ *+ * Asset filenames are already UUIDs (data/images/<uuid>.png), so collisions+ * between peers' exports are extremely unlikely. We skip-if-present rather than+ * overwrite — a re-share that includes the same asset is a no-op for the blob+ * copy, but the manifest still references it so the recipient knows the asset+ * belongs to the latest share.+ */++import { join, basename } from 'path';+import { copyFile, readFile, writeFile, stat } from 'fs/promises';+import { existsSync } from 'fs';+import { PATHS, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';+import { getBucket, ensureBucketLayout } from './buckets.js';+import { buildManifest, writeManifest } from './manifest.js';+import { listSeries, getSeries } from '../pipeline/series.js';+import { listIssues } from '../pipeline/issues.js';+import { getUniverse } from '../universeBuilder.js';+import { getJob } from '../mediaJobQueue/index.js';+import { getInstanceId } from '../instances.js';+import { getSettings } from '../settings.js';+import * as os from 'os';++const isStr = (v) => typeof v === 'string';++/** Resolve the bucket-effective display name (per-bucket override → instance setting → OS user). */+async function resolveSourceName(bucket) {+ if (bucket.displayNameOverride) return bucket.displayNameOverride;+ const settings = await getSettings().catch(() => ({}));+ if (isStr(settings?.sharingDisplayName) && settings.sharingDisplayName.trim()) {+ return settings.sharingDisplayName.trim();+ }+ return os.userInfo().username || 'unknown';+}++async function resolveSourceBio(bucket) {+ if (bucket.bioOverride) return bucket.bioOverride;+ const settings = await getSettings().catch(() => ({}));+ if (isStr(settings?.sharingBio) && settings.sharingBio.trim()) {+ return settings.sharingBio.trim();+ }+ return null;+}++/** Copy an asset file from `data/images` or `data/videos` into the bucket. Returns ref entry. */+async function copyAssetIfPresent(filename, kind, bucketPath) {+ if (!filename || typeof filename !== 'string') return null;+ const base = basename(filename);+ if (!base || base !== filename) return null; // refuse path traversal+ const sourceDir = kind === 'video' ? PATHS.videos : PATHS.images;+ const targetDir = join(bucketPath, 'assets', kind === 'video' ? 'videos' : 'images');+ await ensureDir(targetDir);+ const sourcePath = join(sourceDir, base);+ if (!existsSync(sourcePath)) {+ console.log(`⚠️ sharing.exporter: asset not found locally, skipping: ${sourcePath}`);+ return null;+ }+ const targetPath = join(targetDir, base);+ if (!existsSync(targetPath)) {+ await copyFile(sourcePath, targetPath);+ }+ // Also copy the sidecar metadata.json (image-gen path stamps prompts there).+ if (kind === 'image') {+ const sidecarBase = base.replace(/\.(png|jpe?g|webp)$/i, '') + '.metadata.json';+ const sidecarSource = join(sourceDir, sidecarBase);+ if (existsSync(sidecarSource)) {+ const sidecarTarget = join(targetDir, sidecarBase);+ if (!existsSync(sidecarTarget)) await copyFile(sidecarSource, sidecarTarget);+ }+ }+ return { kind, ref: base };+}++/**+ * For each `imageJobId`, fetch the live media-job (or look it up in the persisted+ * archive) and write a sanitized copy into the bucket records/media/ so the+ * recipient can re-render with identical prompt/seed/params. Returns the asset+ * refs (image filenames) discovered.+ */+async function exportMediaJobAndAsset(jobId, bucketPath, mediaRecordsDir) {+ if (!jobId || !isStr(jobId)) return [];+ const job = getJob(jobId);+ if (!job) {+ console.log(`⚠️ sharing.exporter: imageJobId ${jobId} not found in live queue or archive`);+ return [];+ }+ // Trim transient/runtime fields — keep enough to re-render with full fidelity.+ const exported = {+ id: job.id,+ kind: job.kind,+ owner: job.owner,+ status: job.status,+ completedAt: job.completedAt,+ params: job.params,+ result: job.result,+ };+ await ensureDir(mediaRecordsDir);+ await atomicWrite(join(mediaRecordsDir, `${job.id}.json`), exported);+ // Copy the produced asset(s).+ const assetKind = job.kind === 'video' ? 'video' : 'image';+ const refs = [];+ // result.filename is the canonical single-output shape; some video paths use+ // result.videoPath / result.thumbnail; handle both defensively.+ if (job.result?.filename) {+ const ref = await copyAssetIfPresent(job.result.filename, assetKind, bucketPath);+ if (ref) refs.push(ref);+ }+ if (job.result?.videoPath) {+ // videoPath is a filesystem path; we only need its basename here since+ // copyAssetIfPresent rebuilds the source dir.+ const ref = await copyAssetIfPresent(basename(job.result.videoPath), 'video', bucketPath);+ if (ref) refs.push(ref);+ }+ if (Array.isArray(job.result?.images)) {+ for (const im of job.result.images) {+ const fname = im?.filename || im?.path;+ if (!fname) continue;+ const ref = await copyAssetIfPresent(basename(fname), assetKind, bucketPath);+ if (ref) refs.push(ref);+ }+ }+ return refs;+}++/**+ * Walk a record and collect every (imageJobId, imageRefs, videoPath, sceneVideoJobId)+ * it references. Used by the series exporter to enumerate what to copy. The+ * caller decides whether to fetch + write the media-job records.+ */+function collectAssetReferences(record) {+ const jobIds = new Set();+ const directImageFilenames = new Set();+ const directVideoFilenames = new Set();++ const walk = (node) => {+ if (!node) return;+ if (Array.isArray(node)) { node.forEach(walk); return; }+ if (typeof node !== 'object') return;+ // Known shape carriers+ if (isStr(node.imageJobId)) jobIds.add(node.imageJobId);+ if (isStr(node.sceneVideoJobId)) jobIds.add(node.sceneVideoJobId);+ if (Array.isArray(node.imageRefs)) {+ for (const r of node.imageRefs) if (isStr(r)) directImageFilenames.add(r);+ }+ if (isStr(node.videoPath)) directVideoFilenames.add(basename(node.videoPath));+ for (const k of Object.keys(node)) {+ const v = node[k];+ if (v && (Array.isArray(v) || typeof v === 'object')) walk(v);+ }+ };+ walk(record);++ return {+ jobIds: [...jobIds],+ directImageFilenames: [...directImageFilenames],+ directVideoFilenames: [...directVideoFilenames],+ };+}++/** Stamp the outgoing record with origin metadata. */+function stampOrigin(record, { bucket, source, sourceBio, manifestId }) {+ return {+ ...record,+ origin: {+ bucketId: bucket.id,+ bucketName: bucket.name,+ source,+ sourceBio,+ manifestId,+ importedAt: new Date().toISOString(),+ },+ };+}++/** Export a full series (with its issues + linked universe + every asset). */+export async function exportSeries(seriesId, bucketId) {+ const bucket = await getBucket(bucketId);+ await ensureBucketLayout(bucket);+ const series = await getSeries(seriesId);+ const issues = await listIssues({ seriesId });+ let universe = null;+ if (series.universeId) {+ universe = await getUniverse(series.universeId).catch(() => null);+ }++ const source = await resolveSourceName(bucket);+ const sourceBio = await resolveSourceBio(bucket);+ const senderInstanceId = await getInstanceId().catch(() => null);++ // Pre-build manifest id so we can stamp it onto every record's origin.+ const manifestStub = buildManifest({+ kind: 'series',+ senderInstanceId,+ source, sourceBio,+ bucketId: bucket.id,+ bucketName: bucket.name,+ recordIds: [],+ assetRefs: [],+ });+ const manifestId = manifestStub.id;++ // Write records.+ const recordIds = [series.id];+ const stampedSeries = stampOrigin(series, { bucket, source, sourceBio, manifestId });+ await atomicWrite(join(bucket.path, 'records', 'series', `${series.id}.json`), stampedSeries);++ for (const issue of issues) {+ recordIds.push(issue.id);+ const stamped = stampOrigin(issue, { bucket, source, sourceBio, manifestId });+ await atomicWrite(join(bucket.path, 'records', 'issues', `${issue.id}.json`), stamped);+ }++ if (universe) {+ recordIds.push(universe.id);+ const stampedUni = stampOrigin(universe, { bucket, source, sourceBio, manifestId });+ await atomicWrite(join(bucket.path, 'records', 'universes', `${universe.id}.json`), stampedUni);+ }++ // Gather asset refs across every record.+ const allJobIds = new Set();+ const allImageFiles = new Set();+ const allVideoFiles = new Set();+ for (const rec of [series, ...issues, universe].filter(Boolean)) {+ const refs = collectAssetReferences(rec);+ refs.jobIds.forEach((j) => allJobIds.add(j));+ refs.directImageFilenames.forEach((f) => allImageFiles.add(f));+ refs.directVideoFilenames.forEach((f) => allVideoFiles.add(f));+ }++ // Copy media-job records + their assets — run all three groups in parallel.+ const mediaRecordsDir = join(bucket.path, 'records', 'media');+ const [jobRefGroups, imageRefs, videoRefs] = await Promise.all([+ Promise.all([...allJobIds].map((jobId) => exportMediaJobAndAsset(jobId, bucket.path, mediaRecordsDir))),+ Promise.all([...allImageFiles].map((f) => copyAssetIfPresent(f, 'image', bucket.path))),+ Promise.all([...allVideoFiles].map((f) => copyAssetIfPresent(f, 'video', bucket.path))),+ ]);+ const assetRefs = [...jobRefGroups.flat(), ...imageRefs.filter(Boolean), ...videoRefs.filter(Boolean)];++ const manifest = { ...manifestStub, recordIds, assetRefs };+ const filename = await writeManifest(bucket.path, manifest);+ return { manifestId, filename, recordCount: recordIds.length, assetCount: assetRefs.length };+}++/** Export a universe on its own (no series attached). */+export async function exportUniverse(universeId, bucketId) {+ const bucket = await getBucket(bucketId);+ await ensureBucketLayout(bucket);+ const universe = await getUniverse(universeId);++ const source = await resolveSourceName(bucket);+ const sourceBio = await resolveSourceBio(bucket);+ const senderInstanceId = await getInstanceId().catch(() => null);++ const manifestStub = buildManifest({+ kind: 'universe',+ senderInstanceId,+ source, sourceBio,+ bucketId: bucket.id,+ bucketName: bucket.name,+ recordIds: [],+ assetRefs: [],+ });+ const manifestId = manifestStub.id;++ const stamped = stampOrigin(universe, { bucket, source, sourceBio, manifestId });+ await atomicWrite(join(bucket.path, 'records', 'universes', `${universe.id}.json`), stamped);++ const refs = collectAssetReferences(universe);+ const mediaRecordsDir = join(bucket.path, 'records', 'media');+ const [jobRefGroups, imageRefs] = await Promise.all([+ Promise.all(refs.jobIds.map((jobId) => exportMediaJobAndAsset(jobId, bucket.path, mediaRecordsDir))),+ Promise.all(refs.directImageFilenames.map((f) => copyAssetIfPresent(f, 'image', bucket.path))),+ ]);+ const assetRefs = [...jobRefGroups.flat(), ...imageRefs.filter(Boolean)];++ const manifest = { ...manifestStub, recordIds: [universe.id], assetRefs };+ const filename = await writeManifest(bucket.path, manifest);+ return { manifestId, filename, recordCount: 1, assetCount: assetRefs.length };+}++/**+ * Export individual media items (images / videos identified by `{ kind, ref }`).+ * Looks up each ref's media-job (best effort) to bundle prompt/params alongside+ * the blob. If no job is found (manually uploaded image), the blob still ships+ * but without re-render metadata — recipient sees the file with no params.+ */+export async function exportMedia(items, bucketId) {+ const bucket = await getBucket(bucketId);+ await ensureBucketLayout(bucket);+ const source = await resolveSourceName(bucket);+ const sourceBio = await resolveSourceBio(bucket);+ const senderInstanceId = await getInstanceId().catch(() => null);++ const manifestStub = buildManifest({+ kind: 'media',+ senderInstanceId,+ source, sourceBio,+ bucketId: bucket.id,+ bucketName: bucket.name,+ recordIds: [],+ assetRefs: [],+ });+ const manifestId = manifestStub.id;++ const mediaRecordsDir = join(bucket.path, 'records', 'media');+ // Pre-resolve each item to a job (or null) so we know what to parallelize+ // and what record ids to collect for the manifest.+ const resolved = (items || []).flatMap((item) => {+ if (!item || typeof item !== 'object') return [];+ const ref = isStr(item.ref) ? item.ref.trim() : '';+ if (!ref) return [];+ const kind = item.kind === 'video' ? 'video' : 'image';+ const baseId = ref.replace(/\.[a-z0-9]+$/i, '');+ return [{ ref, kind, job: getJob(baseId) }];+ });+ const recordIds = resolved.filter((r) => r.job).map((r) => r.job.id);+ const results = await Promise.all(resolved.map(async (r) => {+ if (r.job) return exportMediaJobAndAsset(r.job.id, bucket.path, mediaRecordsDir);+ const copied = await copyAssetIfPresent(r.ref, r.kind, bucket.path);+ return copied ? [copied] : [];+ }));+ const assetRefs = results.flat();++ const manifest = { ...manifestStub, recordIds, assetRefs };+ const filename = await writeManifest(bucket.path, manifest);+ return { manifestId, filename, recordCount: recordIds.length, assetCount: assetRefs.length };+}++/** Dispatch by kind. */+export async function exportByKind({ kind, ids, items, bucketId }) {+ if (kind === 'series') {+ if (!Array.isArray(ids) || ids.length === 0) throw new Error('exportByKind: ids required for series');+ // For v1 we export one series per request; loop if multiple are passed.+ const results = [];+ for (const id of ids) results.push(await exportSeries(id, bucketId));+ return { exports: results };+ }+ if (kind === 'universe') {+ if (!Array.isArray(ids) || ids.length === 0) throw new Error('exportByKind: ids required for universe');+ const results = [];+ for (const id of ids) results.push(await exportUniverse(id, bucketId));+ return { exports: results };+ }+ if (kind === 'media') {+ if (!Array.isArray(items) || items.length === 0) throw new Error('exportByKind: items required for media');+ return { exports: [await exportMedia(items, bucketId)] };+ }+ throw new Error(`exportByKind: unknown kind '${kind}'`);+}diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsnew file mode 100644index 0000000000..d32e930f24--- /dev/null+++ b/server/services/sharing/importer.js@@ -0,0 +1,335 @@+/**+ * Share Bucket — importer.+ *+ * Reads a manifest dropped into `<bucket>/manifests/` and either:+ * - bucket.mode === 'auto-merge' → apply records into local pipeline /+ * universe / media state directly, using LWW by updatedAt against any+ * existing local record of the same id.+ * - bucket.mode === 'inbox' → write a pending-import entry into+ * `data/sharing/inbox/<bucketId>.json` for the user to review + promote.+ *+ * Either way the cursor records the manifest filename so the watcher doesn't+ * replay it on restart.+ *+ * Asset blobs referenced by the manifest are copied from the bucket's+ * `assets/{images,videos}/` into the local `data/{images,videos}/` directories+ * (skip-if-present). Media-job records bundled in `records/media/` are merged+ * into `data/media-jobs.json` so re-render workflows have the prompt + params.+ */++import { join, basename } from 'path';+import { copyFile, readdir } from 'fs/promises';+import { existsSync } from 'fs';+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';++const isStr = (v) => typeof v === 'string';++export const sharingEvents = new EventEmitter();++const inboxPath = (bucketId) => join(PATHS.data, 'sharing', 'inbox', `${bucketId}.json`);++async function readInbox(bucketId) {+ await ensureDir(join(PATHS.data, 'sharing', 'inbox'));+ return readJSONFile(inboxPath(bucketId), { items: [] }, { logError: false });+}++async function writeInbox(bucketId, inbox) {+ await ensureDir(join(PATHS.data, 'sharing', 'inbox'));+ await atomicWrite(inboxPath(bucketId), inbox);+}++/** Newer of two ISO timestamps wins (LWW). Equal → keep local. */+function remoteWins(localTs, remoteTs) {+ return (remoteTs || '') > (localTs || '');+}++/** Copy bundled assets from the bucket into local data dirs. Runs in parallel. */+async function copyAssetsLocally(bucketPath, assetRefs) {+ await ensureDir(PATHS.images);+ await ensureDir(PATHS.videos);+ await Promise.all((assetRefs || []).map(async (ref) => {+ if (!ref || !isStr(ref.ref)) return;+ const filename = basename(ref.ref);+ const isVideo = ref.kind === 'video';+ const sourceDir = join(bucketPath, 'assets', isVideo ? 'videos' : 'images');+ const targetDir = isVideo ? PATHS.videos : PATHS.images;+ const sourcePath = join(sourceDir, filename);+ const targetPath = join(targetDir, filename);+ if (!existsSync(sourcePath)) {+ console.log(`⚠️ sharing.importer: asset ${filename} listed in manifest but missing in bucket`);+ return;+ }+ if (!existsSync(targetPath)) {+ await copyFile(sourcePath, targetPath);+ }+ if (!isVideo) {+ const sidecarBase = filename.replace(/\.(png|jpe?g|webp)$/i, '') + '.metadata.json';+ const sidecarSource = join(sourceDir, sidecarBase);+ if (existsSync(sidecarSource)) {+ const sidecarTarget = join(targetDir, sidecarBase);+ if (!existsSync(sidecarTarget)) await copyFile(sidecarSource, sidecarTarget);+ }+ }+ }));+}++/** Merge bucket-bundled media-job records into local data/media-jobs.json. */+async function mergeMediaJobRecords(bucketPath, recordIds) {+ const mediaDir = join(bucketPath, 'records', 'media');+ if (!existsSync(mediaDir)) return;+ const persistedPath = join(PATHS.data, 'media-jobs.json');+ const [persisted, incoming] = await Promise.all([+ readJSONFile(persistedPath, { jobs: [] }, { logError: false }),+ Promise.all((recordIds || []).map(async (id) => {+ const recordPath = join(mediaDir, `${id}.json`);+ if (!existsSync(recordPath)) return null;+ return readJSONFile(recordPath, null, { logError: false });+ })),+ ]);+ const byId = new Map((persisted.jobs || []).map((j) => [j.id, j]));+ let changed = false;+ for (const job of incoming) {+ if (!job?.id || byId.has(job.id)) continue;+ byId.set(job.id, job);+ changed = true;+ }+ if (changed) {+ await atomicWrite(persistedPath, { jobs: Array.from(byId.values()) });+ }+}++/** Read the records referenced by a manifest. */+async function readReferencedRecords(bucketPath, manifest) {+ const records = { series: [], issues: [], universes: [], media: [] };+ for (const id of manifest.recordIds || []) {+ if (id.startsWith('ser-')) {+ const r = await readJSONFile(join(bucketPath, 'records', 'series', `${id}.json`), null, { logError: false });+ if (r) records.series.push(r);+ } else if (id.startsWith('iss-')) {+ const r = await readJSONFile(join(bucketPath, 'records', 'issues', `${id}.json`), null, { logError: false });+ if (r) records.issues.push(r);+ } else if (id.startsWith('chr-') || id.startsWith('set-') || id.startsWith('obj-')) {+ // Bible entries — never standalone, just skip.+ continue;+ } else {+ // Could be a universe (uuid only) or media job (uuid only). Try both.+ const uni = await readJSONFile(join(bucketPath, 'records', 'universes', `${id}.json`), null, { logError: false });+ if (uni) { records.universes.push(uni); continue; }+ const med = await readJSONFile(join(bucketPath, 'records', 'media', `${id}.json`), null, { logError: false });+ if (med) records.media.push(med);+ }+ }+ return records;+}++/**+ * 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).+ */+async function applyAutoMerge(bucket, manifest, records) {+ let applied = 0;++ // Universes first — series may reference them via universeId.+ for (const uni of records.universes) {+ const existing = await getUniverse(uni.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;+ }+ if (remoteWins(existing.updatedAt, uni.updatedAt)) {+ await updateUniverse(existing.id, uni);+ applied++;+ }+ }++ // Series.+ 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++;+ }+ }++ // 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++;+ }+ }++ return { applied };+}++const INBOX_MAX = 1000;++/** Inbox mode: write the manifest + record refs to the bucket's inbox for review. */+async function applyInbox(bucket, manifest, manifestFilename, records) {+ const inbox = await readInbox(bucket.id);+ inbox.items = Array.isArray(inbox.items) ? inbox.items : [];+ // Dedup by manifest id.+ if (inbox.items.some((it) => it.manifestId === manifest.id)) {+ return { queued: false, reason: 'already-in-inbox' };+ }+ inbox.items.push({+ manifestId: manifest.id,+ manifestFilename,+ kind: manifest.kind,+ source: manifest.source,+ sourceBio: manifest.sourceBio,+ createdAt: manifest.createdAt,+ receivedAt: new Date().toISOString(),+ recordIds: manifest.recordIds,+ assetCount: (manifest.assetRefs || []).length,+ note: manifest.note,+ summary: summarizeRecords(records),+ });+ // Cap to prevent unbounded growth — a peer dropping thousands of manifests+ // shouldn't blow up the inbox file. Drop the oldest entries.+ if (inbox.items.length > INBOX_MAX) inbox.items = inbox.items.slice(-INBOX_MAX);+ await writeInbox(bucket.id, inbox);+ return { queued: true };+}++function summarizeRecords(records) {+ const out = [];+ for (const s of records.series) out.push({ kind: 'series', id: s.id, label: s.name || s.id });+ for (const i of records.issues) out.push({ kind: 'issue', id: i.id, label: i.title || i.id });+ for (const u of records.universes) out.push({ kind: 'universe', id: u.id, label: u.name || u.id });+ for (const m of records.media) out.push({ kind: 'media', id: m.id, label: m.params?.prompt?.slice?.(0, 80) || m.id });+ return out;+}++/**+ * Process one manifest file. Idempotent: a second call for the same manifest+ * is a no-op (cursor + inbox dedup).+ */+export async function processManifest(bucketId, manifestFilename) {+ const bucket = await getBucket(bucketId);+ const cursor = await readCursor(bucketId);+ if (hasBeenProcessed(cursor, manifestFilename)) {+ return { skipped: true, reason: 'already-processed' };+ }+ const manifest = await readManifest(bucket.path, manifestFilename);+ if (!manifest || !manifest.id) {+ return { skipped: true, reason: 'invalid-manifest' };+ }+ const records = await readReferencedRecords(bucket.path, manifest);++ // Always copy assets + media-job records ahead of the merge so canon and+ // pipeline records that reference them point at present files.+ await copyAssetsLocally(bucket.path, manifest.assetRefs);+ await mergeMediaJobRecords(bucket.path, manifest.recordIds);++ let outcome;+ if (bucket.mode === 'auto-merge') {+ outcome = { mode: 'auto-merge', ...(await applyAutoMerge(bucket, manifest, records)) };+ } else {+ outcome = { mode: 'inbox', ...(await applyInbox(bucket, manifest, manifestFilename, records)) };+ }+ await markProcessed(bucketId, manifestFilename);++ sharingEvents.emit('manifest-processed', { bucketId, manifestId: manifest.id, manifestFilename, outcome });+ console.log(`📥 sharing: bucket=${bucket.name} manifest=${manifest.id} kind=${manifest.kind} mode=${bucket.mode} ${outcome.applied !== undefined ? `applied=${outcome.applied}` : `queued=${outcome.queued}`}`);+ return { processed: true, manifest, outcome };+}++/** On startup or registration, scan the manifests dir for unprocessed entries. */+export async function processBacklog(bucketId) {+ const bucket = await getBucket(bucketId);+ const manifestsDir = join(bucket.path, 'manifests');+ if (!existsSync(manifestsDir)) return { processed: 0 };+ const cursor = await readCursor(bucketId);+ const filenames = (await readdir(manifestsDir).catch(() => []))+ .filter((f) => f.endsWith('.json'))+ .sort();+ let processed = 0;+ for (const f of filenames) {+ if (hasBeenProcessed(cursor, f)) continue;+ const res = await processManifest(bucketId, f).catch((err) => {+ console.log(`⚠️ sharing.importer: processManifest failed for ${f}: ${err.message}`);+ return null;+ });+ if (res?.processed) processed++;+ }+ return { processed };+}++/** Promote a pending inbox item: re-process it via the auto-merge path. */+export async function promoteInboxItem(bucketId, manifestId) {+ const inbox = await readInbox(bucketId);+ const idx = (inbox.items || []).findIndex((it) => it.manifestId === manifestId);+ if (idx < 0) throw Object.assign(new Error(`Inbox item not found: ${manifestId}`), { code: 'SHARING_INBOX_NOT_FOUND' });+ const item = inbox.items[idx];+ const bucket = await getBucket(bucketId);+ const manifest = await readManifest(bucket.path, item.manifestFilename);+ if (!manifest) throw new Error(`Manifest no longer exists in bucket: ${item.manifestFilename}`);+ const records = await readReferencedRecords(bucket.path, manifest);+ await copyAssetsLocally(bucket.path, manifest.assetRefs);+ await mergeMediaJobRecords(bucket.path, manifest.recordIds);+ const outcome = await applyAutoMerge(bucket, manifest, records);+ // Drop from inbox.+ inbox.items.splice(idx, 1);+ await writeInbox(bucketId, inbox);+ sharingEvents.emit('inbox-updated', { bucketId });+ return { promoted: true, outcome };+}++export async function dismissInboxItem(bucketId, manifestId) {+ const inbox = await readInbox(bucketId);+ const before = (inbox.items || []).length;+ inbox.items = (inbox.items || []).filter((it) => it.manifestId !== manifestId);+ if (inbox.items.length === before) throw Object.assign(new Error(`Inbox item not found: ${manifestId}`), { code: 'SHARING_INBOX_NOT_FOUND' });+ await writeInbox(bucketId, inbox);+ sharingEvents.emit('inbox-updated', { bucketId });+ return { dismissed: true };+}++export async function listInbox(bucketId) {+ const inbox = await readInbox(bucketId);+ return Array.isArray(inbox.items) ? inbox.items : [];+}diff --git a/server/services/sharing/index.js b/server/services/sharing/index.jsnew file mode 100644index 0000000000..bf36587bce--- /dev/null+++ b/server/services/sharing/index.js@@ -0,0 +1,58 @@+/**+ * Share Bucket — lifecycle entry point.+ *+ * Called from server/index.js once on boot. Attaches a chokidar watcher to+ * each registered bucket's `manifests/` directory, processes any backlog from+ * while the server was offline, and wires Socket.IO so the UI can react to+ * inbox updates / watcher errors live.+ */++import { ensureDir, PATHS } from '../../lib/fileUtils.js';+import { join } from 'path';+import { attachAllWatchers, attachWatcher, detachWatcher, shutdownAllWatchers, listAttachedWatchers } from './watcher.js';+import { sharingEvents } from './importer.js';++export { sharingEvents } from './importer.js';+export { attachWatcher, detachWatcher, listAttachedWatchers };++let initialized = false;+let io = null;++export async function initSharing({ io: socketIo } = {}) {+ if (initialized) return;+ initialized = true;+ io = socketIo || null;+ await ensureDir(join(PATHS.data, 'sharing'));+ await ensureDir(join(PATHS.data, 'sharing', 'cursors'));+ await ensureDir(join(PATHS.data, 'sharing', 'inbox'));++ // Wire socket events for the client UI.+ if (io) {+ sharingEvents.on('manifest-processed', (payload) => {+ io.emit('sharing:manifest-processed', payload);+ if (payload.outcome?.mode === 'inbox') {+ io.emit('sharing:inbox-updated', { bucketId: payload.bucketId });+ }+ });+ sharingEvents.on('inbox-updated', (payload) => {+ io.emit('sharing:inbox-updated', payload);+ });+ sharingEvents.on('watcher-attached', (payload) => {+ io.emit('sharing:watcher-attached', payload);+ });+ sharingEvents.on('watcher-detached', (payload) => {+ io.emit('sharing:watcher-detached', payload);+ });+ }++ const result = await attachAllWatchers();+ console.log(`📡 sharing: initialized, watchers attached for ${result.attached} bucket(s)`);+ return result;+}++export async function shutdownSharing() {+ await shutdownAllWatchers();+ sharingEvents.removeAllListeners();+ initialized = false;+ io = null;+}diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.jsnew file mode 100644index 0000000000..c165c5899d--- /dev/null+++ b/server/services/sharing/manifest.js@@ -0,0 +1,104 @@+/**+ * Share Bucket — manifest & cursor helpers.+ *+ * A manifest is one JSON file in `<bucket>/manifests/` per share action. It+ * names the records + assets bundled in that share, plus identifying+ * metadata (sender, source display name, timestamp). The cursor tracks which+ * manifest filenames the local PortOS has already processed so the watcher+ * doesn't replay them on restart.+ *+ * Manifest filename convention:+ * <iso-ts>-<sender-id>-<manifest-id>.json+ *+ * Using an ISO-prefixed timestamp gives chokidar's lexicographic event order a+ * stable replay order if multiple manifests land in the same poll cycle.+ */++import { randomUUID } from 'crypto';+import { join } from 'path';+import { readdir } from 'fs/promises';+import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';++export const MANIFEST_KIND = Object.freeze(['series', 'universe', 'media']);+export const MANIFEST_SCHEMA_VERSION = 1;++const isStr = (v) => typeof v === 'string';++const cursorPath = (bucketId) => join(PATHS.data, 'sharing', 'cursors', `${bucketId}.json`);++export async function readCursor(bucketId) {+ await ensureDir(join(PATHS.data, 'sharing', 'cursors'));+ return readJSONFile(cursorPath(bucketId), { processed: [] }, { logError: false });+}++export async function writeCursor(bucketId, cursor) {+ await ensureDir(join(PATHS.data, 'sharing', 'cursors'));+ await atomicWrite(cursorPath(bucketId), cursor);+}++/**+ * Mark a manifest filename as processed. Keeps the last 5000 entries — the+ * cursor file would otherwise grow unbounded if a single bucket lives for+ * years. 5000 is well past any sensible "is this duplicate?" lookback window+ * for a single user's collaborator group.+ */+export async function markProcessed(bucketId, manifestFilename) {+ const cursor = await readCursor(bucketId);+ if (cursor.processed.includes(manifestFilename)) return cursor;+ cursor.processed.push(manifestFilename);+ if (cursor.processed.length > 5000) {+ cursor.processed = cursor.processed.slice(-5000);+ }+ cursor.lastProcessedAt = new Date().toISOString();+ await writeCursor(bucketId, cursor);+ return cursor;+}++export function hasBeenProcessed(cursor, manifestFilename) {+ return Array.isArray(cursor?.processed) && cursor.processed.includes(manifestFilename);+}++/** Build a fresh manifest. Caller writes it after every record + asset is in place. */+export function buildManifest({ kind, senderInstanceId, source, sourceBio, recordIds, assetRefs, bucketId, bucketName, note }) {+ if (!MANIFEST_KIND.includes(kind)) throw new Error(`buildManifest: invalid kind '${kind}'`);+ return {+ id: randomUUID(),+ schemaVersion: MANIFEST_SCHEMA_VERSION,+ createdAt: new Date().toISOString(),+ kind, // 'series' | 'universe' | 'media'+ senderInstanceId: senderInstanceId || 'unknown',+ source: source || 'unknown', // human display name+ sourceBio: sourceBio || null,+ bucketId,+ bucketName: bucketName || bucketId,+ recordIds: Array.isArray(recordIds) ? recordIds : [],+ assetRefs: Array.isArray(assetRefs) ? assetRefs : [],+ note: isStr(note) ? note.slice(0, 1000) : null,+ };+}++export function manifestFilename(manifest) {+ const ts = manifest.createdAt.replace(/[:.]/g, '-');+ const senderSlug = (manifest.source || manifest.senderInstanceId || 'unknown')+ .toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40)+ || 'unknown';+ return `${ts}-${senderSlug}-${manifest.id}.json`;+}++export async function writeManifest(bucketPath, manifest) {+ await ensureDir(join(bucketPath, 'manifests'));+ const filename = manifestFilename(manifest);+ await atomicWrite(join(bucketPath, 'manifests', filename), manifest);+ return filename;+}++export async function readManifest(bucketPath, filename) {+ return readJSONFile(join(bucketPath, 'manifests', filename), null, { logError: false });+}++/** List every manifest filename in a bucket, newest first by ISO-prefixed name. */+export async function listManifestFilenames(bucketPath) {+ const dir = join(bucketPath, 'manifests');+ const entries = await readdir(dir).catch(() => []);+ return entries.filter((f) => f.endsWith('.json')).sort().reverse();+}diff --git a/server/services/sharing/manifest.test.js b/server/services/sharing/manifest.test.jsnew file mode 100644index 0000000000..8327bc1bfe--- /dev/null+++ b/server/services/sharing/manifest.test.js@@ -0,0 +1,83 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { vi } from 'vitest';++let tempRoot;++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: tempRoot };+ return target[prop];+ },+ });+});++const manifest = await import('./manifest.js');++describe('sharing/manifest', () => {+ beforeEach(() => {+ tempRoot = mkdtempSync(join(tmpdir(), 'portos-manifest-test-'));+ });+ afterEach(() => {+ if (tempRoot) rmSync(tempRoot, { recursive: true, force: true });+ });++ it('buildManifest produces a valid shape', () => {+ const m = manifest.buildManifest({+ kind: 'series',+ senderInstanceId: 'inst-123',+ source: 'me',+ sourceBio: null,+ bucketId: 'b1',+ bucketName: 'creative',+ recordIds: ['ser-1', 'iss-2'],+ assetRefs: [{ kind: 'image', ref: 'abc.png' }],+ });+ expect(m.id).toBeTruthy();+ expect(m.kind).toBe('series');+ expect(m.source).toBe('me');+ expect(m.recordIds).toEqual(['ser-1', 'iss-2']);+ expect(m.assetRefs).toEqual([{ kind: 'image', ref: 'abc.png' }]);+ expect(m.schemaVersion).toBe(manifest.MANIFEST_SCHEMA_VERSION);+ });++ it('buildManifest rejects invalid kind', () => {+ expect(() => manifest.buildManifest({ kind: 'bogus' })).toThrow(/invalid kind/);+ });++ it('manifestFilename is sortable + slug-safe', () => {+ const m = manifest.buildManifest({+ kind: 'series',+ source: 'Bob & Co!',+ bucketId: 'b1',+ bucketName: 'b',+ recordIds: [],+ assetRefs: [],+ });+ const name = manifest.manifestFilename(m);+ expect(name).toMatch(/^\d{4}-\d{2}-\d{2}T/);+ // `Bob & Co!` slugifies to `bob-co-` (each run of non-alphanumeric → single dash).+ expect(name).toContain('bob-co-');+ expect(name).toMatch(/\.json$/);+ expect(name).not.toMatch(/[^a-zA-Z0-9._-]/);+ });++ it('hasBeenProcessed reports cursor state correctly', async () => {+ const cursor = await manifest.readCursor('bucket-1');+ expect(manifest.hasBeenProcessed(cursor, 'foo.json')).toBe(false);+ await manifest.markProcessed('bucket-1', 'foo.json');+ const next = await manifest.readCursor('bucket-1');+ expect(manifest.hasBeenProcessed(next, 'foo.json')).toBe(true);+ });++ it('markProcessed is idempotent', async () => {+ await manifest.markProcessed('b1', 'a.json');+ await manifest.markProcessed('b1', 'a.json');+ const c = await manifest.readCursor('b1');+ expect(c.processed.filter((x) => x === 'a.json')).toHaveLength(1);+ });+});diff --git a/server/services/sharing/watcher.js b/server/services/sharing/watcher.jsnew file mode 100644index 0000000000..010df82134--- /dev/null+++ b/server/services/sharing/watcher.js@@ -0,0 +1,99 @@+/**+ * Share Bucket — chokidar watcher on each bucket's `manifests/` directory.+ *+ * When a peer's cloud-sync app drops a new manifest into the shared folder,+ * chokidar fires `add` and we ingest it via importer.processManifest. Mirrors+ * the pattern in server/services/taskWatcher.js — persistent + ignoreInitial+ * + awaitWriteFinish so we don't pick up the file mid-write.+ *+ * Per-bucket watchers are kept in a map keyed by bucket id so a bucket+ * registration / removal can attach / detach individually without restarting+ * everything.+ */++import { watch } from 'chokidar';+import { join, basename } from 'path';+import { processManifest, processBacklog, sharingEvents } from './importer.js';+import { getBucket, listBuckets, ensureBucketLayout } from './buckets.js';++const watchers = new Map(); // bucketId → chokidar instance++export async function attachWatcher(bucketId) {+ const existing = watchers.get(bucketId);+ if (existing) {+ await existing.close().catch(() => {});+ }+ const bucket = await getBucket(bucketId);+ await ensureBucketLayout(bucket);+ const manifestsDir = join(bucket.path, 'manifests');+ const w = watch(manifestsDir, {+ persistent: true,+ ignoreInitial: true,+ awaitWriteFinish: { stabilityThreshold: 300, pollInterval: 100 },+ });++ // try/catch around async event handlers — see CLAUDE.md "PTY/child-process+ // /setTimeout/setInterval callbacks" rule (chokidar events fire outside the+ // request lifecycle, no Express middleware to bubble the throw to).+ w.on('add', async (path) => {+ const file = basename(path);+ if (!file.endsWith('.json')) return;+ try {+ await processManifest(bucketId, file);+ } catch (err) {+ console.error(`❌ sharing.watcher: processManifest threw for ${file}: ${err?.message || err}`);+ }+ });+ w.on('change', async (path) => {+ // A manifest *changing* after first write is unusual (atomicWrite+ // produces a stable file), but it can happen if a peer's sync app+ // does a delete-then-write. Re-process — cursor will dedup.+ const file = basename(path);+ if (!file.endsWith('.json')) return;+ try {+ await processManifest(bucketId, file);+ } catch (err) {+ console.error(`❌ sharing.watcher: processManifest threw on change ${file}: ${err?.message || err}`);+ }+ });+ w.on('error', (err) => {+ console.error(`❌ sharing.watcher: bucket=${bucket.name} ${err?.message || err}`);+ });+ watchers.set(bucketId, w);+ sharingEvents.emit('watcher-attached', { bucketId, manifestsDir });+ console.log(`👁️ sharing.watcher: attached bucket=${bucket.name} path=${manifestsDir}`);+ return w;+}++export async function detachWatcher(bucketId) {+ const w = watchers.get(bucketId);+ if (!w) return;+ await w.close().catch(() => {});+ watchers.delete(bucketId);+ sharingEvents.emit('watcher-detached', { bucketId });+}++export async function attachAllWatchers() {+ const buckets = await listBuckets();+ for (const b of buckets) {+ await attachWatcher(b.id).catch((err) => {+ console.error(`❌ sharing.watcher: failed to attach bucket=${b.name}: ${err.message}`);+ });+ // Catch up on any manifests that arrived while we were offline.+ await processBacklog(b.id).catch((err) => {+ console.error(`❌ sharing.watcher: backlog process failed bucket=${b.name}: ${err.message}`);+ });+ }+ return { attached: watchers.size };+}++export async function shutdownAllWatchers() {+ const ids = [...watchers.keys()];+ for (const id of ids) {+ await detachWatcher(id).catch(() => {});+ }+}++export function listAttachedWatchers() {+ return [...watchers.keys()];+}diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.jsindex 4507a9d865..d1f20fba66 100644--- a/server/services/universeBuilder.js+++ b/server/services/universeBuilder.js@@ -30,6 +30,7 @@ import {sanitizeBibleList, BIBLE_KIND, BIBLE_FIELD, BIBLE_LIMITS, BIBLE_SOURCE,normalizeBibleName,} from '../lib/storyBible.js';+import { sanitizeOrigin } from '../lib/sharingOrigin.js';// Bumped when a sanitizer-time backfill changes how on-disk universes are// shaped, so future migrations can gate on the prior version.@@ -455,6 +456,8 @@ const sanitizeTemplate = (raw) => {objects,schemaVersion,llm,+ // Share-bucket provenance — present on imported records, absent on locally-authored ones.+ origin: sanitizeOrigin(raw.origin),createdAt,updatedAt,};@@ -573,6 +576,8 @@ export async function updateUniverse(id, patch = {}) {// Canon entity arrays — patched wholesale (the sanitizer reruns// sanitizeBibleList so per-entry shape is enforced on every save).'characters', 'settings', 'objects',+ // Share-bucket origin metadata (importer sets it; user clears via wholesale null).+ 'origin',];const scalarPatch = Object.fromEntries(PATCHABLE_SCALARS.filter((k) => k in patch).map((k) => [k, patch[k]]),