Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat(sharing): subscription model — toggle on/off + updates auto-flow

[._.]/ Adam Eivyeb104e3a0ccd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ae83b7f5be..1df2f8993c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,53 @@
## Added
+- **Sharing v1.3 — subscriptions: toggle on/off, updates auto-flow.**
+ Rewrote the share-bucket model from one-shot manifests to persistent
+ subscriptions, addressing two real UX gaps:
+ 1. The ShareToButton's always-on gray check icon made every bucket look
+ "already checked" with no way to tell what was actually shared. The
+ icon is now a real state indicator — filled CheckCircle on subscribed
+ buckets, empty Circle otherwise.
+ 2. Every click previously wrote a fresh timestamped manifest, so picking
+ the same bucket twice produced two manifests. Now each (bucket,
+ record) pair is a single subscription whose manifest lives at a
+ deterministic filename in the bucket; re-exports overwrite in place.
+ - **Subscription model.** A subscription is a `(bucketId, recordKind,
+ recordId)` tuple persisted in `data/sharing/subscriptions.json`. The
+ subscribable kinds are `series` and `universe` (records that mutate
+ over time). Media stays one-shot — items don't change after creation.
+ - **Auto-re-export on edit.** A small `recordEvents` EventEmitter is
+ fired by `updateSeries`, `updateIssue` (re-emits its parent series),
+ and `updateUniverse` after each successful persist. The subscriptions
+ service listens with a per-subscription 3-second debounce and re-exports
+ the affected record into every bucket it's subscribed to. Recipients
+ see the change via chokidar's `change` event.
+ - **Content-aware cursor.** The bucket cursor now stores `{filename:
+ manifestId}` so a re-import of the same subscription filename with a
+ fresh manifestId processes the update, while legacy `processed[]`
+ entries from v1.0–v1.2 still suppress re-imports of one-shot manifests.
+ - **Unshare propagation.** Clicking a subscribed bucket again unsubscribes:
+ the registry row is removed and the bucket-side file is deleted.
+ Recipients' watchers fire `unlink`, which clears the cursor entry,
+ drops any pending inbox row for that subscription, and emits a
+ `sharing:unshared` socket event. The recipient's already-imported
+ local record is NOT reverted — they keep what they have, just stop
+ receiving updates.
+ - **Inbox collapse.** Subscription manifests in inbox mode replace any
+ prior inbox entry for the same `(recordKind, recordId)` so the user
+ always sees the latest snapshot, not a pile of revisions.
+
+ **Endpoints:** new `GET /api/sharing/subscriptions[?filter]`,
+ `POST /api/sharing/subscriptions`, `DELETE /api/sharing/subscriptions/:id`.
+ **Files:** new `server/services/sharing/{recordEvents,subscriptions}.js`,
+ changes to `manifest.js` (cursor + filename), `exporter.js` (subscription
+ opt-in), `importer.js` (content-aware dedup + `handleUnshare`),
+ `watcher.js` (`unlink` handler), `pipeline/{series,issues}.js` +
+ `universeBuilder.js` (emit on update), `routes/sharing.js`, and
+ `client/src/components/sharing/ShareToButton.jsx`. Tests: 11 new (7 unit
+ for the subscriptions service, 4 covering the new cursor and
+ deterministic-filename behavior, plus an integration round-trip).
+
- **Universal folder-picker UX — Sharing + Backup + Templates.**
Three places that ask the user for a server-side folder path now all
use the same `FolderPicker` component (a folder-icon button that opens
diff --git a/PLAN.md b/PLAN.md
index 0ee7fdebb6..c4e252d518 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -6,13 +6,15 @@ 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.2 shipped
+### Cross-network sharing via cloud-synced folders ("Share Buckets") — v1.3 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. V1.1: id-preserving inserts (`insertSeriesWithId` / `insertIssueWithId` / `insertUniverseWithId`) so re-shares LWW-merge instead of duplicating; `overridden[]` outcome surfaced via socket → global `useSharingNotifications` toast; round-trip integration tests. V1.2: schema versioning — `SHARING_SCHEMA_VERSION` stamped on every manifest + bucket.json, `producedByVersion` (PortOS app version) on every manifest, importer refuses future-version manifests with a clear toast + cursor-mark, bucket cards warn when remote schema > local. See `~/.claude/plans/new-high-priority-task-valiant-wall.md` for design. Remaining follow-ups:
+V1 landed: buckets, ShareToButton on Pipeline + UniverseBuilder + MediaCollection, OriginBadge, exporter with full gen-metadata fidelity, importer with `auto-merge` + `inbox` modes, chokidar watcher, configurable `sharingDisplayName` source attribution, nav-manifest registration. V1.1: id-preserving inserts (`insertSeriesWithId` / `insertIssueWithId` / `insertUniverseWithId`) so re-shares LWW-merge instead of duplicating; `overridden[]` outcome surfaced via socket → global `useSharingNotifications` toast; round-trip integration tests. V1.2: schema versioning — `SHARING_SCHEMA_VERSION` stamped on every manifest + bucket.json, `producedByVersion` (PortOS app version) on every manifest, importer refuses future-version manifests with a clear toast + cursor-mark, bucket cards warn when remote schema > local. V1.3: subscription model for series + universe — toggle on/off in ShareToButton with real state indicators, persistent (bucket, record) tuples in `data/sharing/subscriptions.json`, deterministic-filename manifests that overwrite on re-export, auto-re-export on edit via `recordEvents` (debounced 3s), `unlink` → `handleUnshare` flow that propagates "stop sharing" to recipients without reverting their local copies, content-aware cursor (`processedById` map). See `~/.claude/plans/new-high-priority-task-valiant-wall.md` for design. Remaining follow-ups:
- [ ] **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.
- [ ] **Manifest archive pruning.** A bucket lived long enough accumulates thousands of manifests under `<bucket>/manifests/`. Add a per-bucket retention policy (e.g. keep last 500 manifests, archive the rest into `manifests/.archive/` or drop entirely once cursor advances past them).
-- [ ] **Route-level tests for `server/routes/sharing.js`.** Bucket CRUD + export + inbox actions are exercised through the service layer in integration.test.js, but the HTTP surface (Zod rejection, error mapping) is uncovered. Add a `server/routes/sharing.test.js` to lock the JSON contract.
+- [ ] **Route-level tests for `server/routes/sharing.js`.** Bucket CRUD + export + inbox actions + subscriptions are exercised through the service layer in integration.test.js + subscriptions.test.js, but the HTTP surface (Zod rejection, error mapping) is uncovered. Add a `server/routes/sharing.test.js` to lock the JSON contract.
+- [ ] **Auto-unsubscribe on local record delete.** Today if the user deletes a subscribed series/universe, the subscription in `data/sharing/subscriptions.json` becomes an orphan — next re-export attempt logs an error but the entry persists. Hook `deleteSeries` / `deleteUniverse` to call `unsubscribe()` for every subscription where `recordId === id`. Surface the unshare in the UI so the user sees "Removed from N bucket(s)" alongside the deletion toast.
+- [ ] **Inbox UI: visually mark subscription items.** New inbox entries already carry `subscription: { recordKind, recordId }` when applicable, but the Sharing page renders them identically to one-shot manifest items. Add a small "🔄 live" badge to subscription rows so the user sees "this is the latest snapshot of a live share" vs "this is a one-time snapshot."
- [ ] **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.
- [ ] **Multi-hop provenance chains.** Re-share authors a fresh `origin` block; chain[] would preserve full attribution. Defer until users ask.
diff --git a/client/src/components/sharing/ShareToButton.jsx b/client/src/components/sharing/ShareToButton.jsx
index 18d51ad08a..4bc514e757 100644
--- a/client/src/components/sharing/ShareToButton.jsx
+++ b/client/src/components/sharing/ShareToButton.jsx
@@ -1,41 +1,79 @@
/**
- * 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.
+ * ShareToButton — dropdown of registered buckets that toggles subscriptions
+ * for series + universes, and does one-shot sharing for media items.
+ *
+ * Subscription kinds (series, universe):
+ * Each bucket row shows a filled CheckCircle when the (recordKind, recordId)
+ * is currently subscribed to that bucket, or an empty Circle otherwise.
+ * Clicking a checked row UNSUBSCRIBES; clicking an unchecked row SUBSCRIBES
+ * (which kicks off the initial export and then auto-re-exports on every
+ * subsequent local edit, debounced).
+ *
+ * Media kind:
+ * One-shot — clicking a bucket exports the selected items into that bucket
+ * as a manifest. No checked-state tracking because media doesn't mutate
+ * after creation; repeated clicks are repeated shares.
*
* 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
+ * ids?: string[] // for series / universe (uses ids[0] as the subject)
+ * items?: [{ kind, ref }] // for media
+ * label?: string
+ * compact?: boolean
*/
import { useEffect, useRef, useState } from 'react';
-import { Share2, Check, Loader2 } from 'lucide-react';
+import { Share2, Check, Circle, CheckCircle2, Loader2 } from 'lucide-react';
import toast from '../ui/Toast';
import {
listShareBuckets,
exportToShareBucket,
+ listShareSubscriptions,
+ subscribeToShareBucket,
+ unsubscribeFromShareBucket,
} from '../../services/api';
+const SUBSCRIBABLE_KINDS = new Set(['series', 'universe']);
+
export default function ShareToButton({ kind, ids, items, label = 'Share', compact = false, className = '' }) {
const [open, setOpen] = useState(false);
const [buckets, setBuckets] = useState([]);
+ const [subscriptions, setSubscriptions] = useState([]); // [{id, bucketId, ...}]
const [loading, setLoading] = useState(false);
- const [sharingTo, setSharingTo] = useState(null);
+ const [busyBucketId, setBusyBucketId] = useState(null);
const wrapperRef = useRef(null);
- useEffect(() => {
- if (!open) return;
+ const isSubscribable = SUBSCRIBABLE_KINDS.has(kind);
+ const recordId = isSubscribable && Array.isArray(ids) && ids.length > 0 ? ids[0] : null;
+
+ // Refresh buckets + subscriptions on open. Subscriptions are scoped to the
+ // (kind, recordId) being viewed so the "checked" indicator reflects this
+ // record specifically, not the bucket's universe of subscriptions.
+ const refresh = async () => {
setLoading(true);
- listShareBuckets({ silent: true })
- .then((r) => setBuckets(r?.buckets || []))
- .catch(() => setBuckets([]))
- .finally(() => setLoading(false));
+ const tasks = [
+ listShareBuckets({ silent: true }).then((r) => r?.buckets || []).catch(() => []),
+ ];
+ if (isSubscribable && recordId) {
+ tasks.push(
+ listShareSubscriptions({ recordKind: kind, recordId }, { silent: true })
+ .then((r) => r?.subscriptions || [])
+ .catch(() => []),
+ );
+ } else {
+ tasks.push(Promise.resolve([]));
+ }
+ const [b, s] = await Promise.all(tasks);
+ setBuckets(b);
+ setSubscriptions(s);
+ setLoading(false);
+ };
+
+ useEffect(() => {
+ if (open) refresh();
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [open]);
- // Close on click-outside.
useEffect(() => {
if (!open) return;
const handler = (e) => {
@@ -45,16 +83,48 @@ export default function ShareToButton({ kind, ids, items, label = 'Share', compa
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) => {
+ const subscriptionForBucket = (bucketId) =>
+ subscriptions.find((s) => s.bucketId === bucketId) || null;
+
+ // Subscribable path — toggle on click.
+ const handleToggleSubscription = async (bucket) => {
+ if (!recordId) return;
+ setBusyBucketId(bucket.id);
+ const existing = subscriptionForBucket(bucket.id);
+ if (existing) {
+ const ok = await unsubscribeFromShareBucket(existing.id).catch((err) => {
+ toast.error(err.message || `Unshare from ${bucket.name} failed`);
+ return null;
+ });
+ if (ok) {
+ setSubscriptions((prev) => prev.filter((s) => s.id !== existing.id));
+ toast.success(`Unshared from ${bucket.name}`);
+ }
+ } else {
+ const result = await subscribeToShareBucket({
+ bucketId: bucket.id,
+ recordKind: kind,
+ recordId,
+ }).catch((err) => {
+ toast.error(err.message || `Share to ${bucket.name} failed`);
+ return null;
+ });
+ if (result?.subscription) {
+ setSubscriptions((prev) => [...prev, result.subscription]);
+ toast.success(`Sharing to ${bucket.name} — updates will sync automatically`);
+ }
+ }
+ setBusyBucketId(null);
+ };
+
+ // Media one-shot path — click to send a fresh manifest.
+ const handleOneShotShare = async (bucket) => {
+ setBusyBucketId(bucket.id);
+ const result = await exportToShareBucket(bucket.id, { kind, items: items || [] }).catch((err) => {
toast.error(err.message || `Share to ${bucket.name} failed`);
return null;
});
- setSharingTo(null);
+ setBusyBucketId(null);
if (!result) return;
const totals = (result.exports || []).reduce(
(acc, e) => ({ records: acc.records + (e.recordCount || 0), assets: acc.assets + (e.assetCount || 0) }),
@@ -64,10 +134,9 @@ export default function ShareToButton({ kind, ids, items, label = 'Share', compa
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);
+ const nothingToShare = isSubscribable
+ ? !recordId
+ : !(Array.isArray(items) && items.length > 0);
return (
<div ref={wrapperRef} className={`relative inline-block ${className}`}>
@@ -83,9 +152,9 @@ export default function ShareToButton({ kind, ids, items, label = 'Share', compa
</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="absolute right-0 z-30 mt-1 w-72 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
+ {isSubscribable ? 'Subscribe to bucket' : 'Share to bucket'}
</div>
{loading ? (
<div className="px-3 py-3 text-xs text-gray-500 flex items-center gap-2">
@@ -97,26 +166,46 @@ export default function ShareToButton({ kind, ids, items, label = 'Share', compa
</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}
+ {buckets.map((b) => {
+ const subscribed = isSubscribable && !!subscriptionForBucket(b.id);
+ const busy = busyBucketId === b.id;
+ const click = isSubscribable ? () => handleToggleSubscription(b) : () => handleOneShotShare(b);
+ return (
+ <li key={b.id}>
+ <button
+ type="button"
+ onClick={click}
+ disabled={busy}
+ className="w-full text-left px-3 py-2 hover:bg-port-bg disabled:opacity-50 flex items-start gap-2"
+ >
+ <span className="mt-0.5 shrink-0">
+ {busy ? (
+ <Loader2 size={14} className="animate-spin text-port-accent" />
+ ) : isSubscribable ? (
+ subscribed
+ ? <CheckCircle2 size={14} className="text-port-success" />
+ : <Circle size={14} className="text-gray-600" />
+ ) : (
+ <Check size={14} className="text-gray-600" />
+ )}
+ </span>
+ <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>
- </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>
- ))}
+ </button>
+ </li>
+ );
+ })}
</ul>
)}
+ {isSubscribable && subscriptions.length > 0 && (
+ <div className="px-3 py-2 text-[10px] text-gray-500 border-t border-port-border">
+ Subscribed buckets receive your edits automatically as you save.
+ </div>
+ )}
</div>
)}
</div>
diff --git a/client/src/services/apiSharing.js b/client/src/services/apiSharing.js
index a7046d46d7..a8bc314796 100644
--- a/client/src/services/apiSharing.js
+++ b/client/src/services/apiSharing.js
@@ -45,3 +45,26 @@ export const dismissShareInboxItem = (bucketId, manifestId, options) => request(
// ---- Activity ----
export const listShareActivity = (bucketId, options) => request(`/sharing/buckets/${encodeURIComponent(bucketId)}/activity`, options);
+
+// ---- Subscriptions (persistent, kind=series|universe) ----
+export const listShareSubscriptions = (filter = {}, options) => {
+ const qs = new URLSearchParams();
+ if (filter.bucketId) qs.set('bucketId', filter.bucketId);
+ if (filter.recordKind) qs.set('recordKind', filter.recordKind);
+ if (filter.recordId) qs.set('recordId', filter.recordId);
+ const query = qs.toString();
+ return request(`/sharing/subscriptions${query ? `?${query}` : ''}`, options);
+};
+
+export const subscribeToShareBucket = ({ bucketId, recordKind, recordId }, options) =>
+ request('/sharing/subscriptions', {
+ method: 'POST',
+ body: JSON.stringify({ bucketId, recordKind, recordId }),
+ ...options,
+ });
+
+export const unsubscribeFromShareBucket = (subscriptionId, options) =>
+ request(`/sharing/subscriptions/${encodeURIComponent(subscriptionId)}`, {
+ method: 'DELETE',
+ ...options,
+ });
diff --git a/server/lib/validation.js b/server/lib/validation.js
index efa26569c6..8ef7a56909 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -873,6 +873,15 @@ export const sharingSettingsPatchSchema = z.object({
sharingBio: z.string().trim().max(2000).optional(),
}).strict();
+// Subscription creation: persistent (bucket, record) tuple. Series + universe
+// are the subscribable kinds (records that change over time and benefit from
+// auto-re-export). Media is one-shot via /buckets/:id/export.
+export const subscriptionCreateSchema = z.object({
+ bucketId: z.string().trim().min(1).max(120),
+ recordKind: z.enum(['series', 'universe']),
+ recordId: z.string().trim().min(1).max(120),
+}).strict();
+
// =============================================================================
// CREATIVE DIRECTOR SCHEMAS
// =============================================================================
diff --git a/server/routes/sharing.js b/server/routes/sharing.js
index ddea298017..93ea25cb83 100644
--- a/server/routes/sharing.js
+++ b/server/routes/sharing.js
@@ -16,7 +16,7 @@ import { Router } from 'express';
import { asyncHandler } from '../lib/errorHandler.js';
import { validateRequest } from '../lib/validation.js';
import {
- bucketCreateSchema, bucketUpdateSchema, sharingExportSchema,
+ bucketCreateSchema, bucketUpdateSchema, sharingExportSchema, subscriptionCreateSchema,
} from '../lib/validation.js';
import {
listBuckets, getBucket, createBucket, updateBucket, deleteBucket, readBucketJson,
@@ -27,6 +27,9 @@ import { exportByKind } from '../services/sharing/exporter.js';
import {
listInbox, promoteInboxItem, dismissInboxItem,
} from '../services/sharing/importer.js';
+import {
+ listSubscriptions, subscribe, unsubscribe,
+} from '../services/sharing/subscriptions.js';
import { listManifestFilenames, readManifest } from '../services/sharing/manifest.js';
const router = Router();
@@ -98,6 +101,31 @@ router.post('/buckets/:id/inbox/:manifestId/dismiss', asyncHandler(async (req, r
res.json(result);
}));
+/**
+ * Subscriptions — persistent (bucket, record) tuples for series + universe.
+ * Subscribing kicks off the initial export; updates auto-re-export on
+ * record change (debounced ~3s); unsubscribing removes the bucket-side file.
+ */
+router.get('/subscriptions', asyncHandler(async (req, res) => {
+ const filter = {};
+ if (req.query.bucketId) filter.bucketId = String(req.query.bucketId);
+ if (req.query.recordKind) filter.recordKind = String(req.query.recordKind);
+ if (req.query.recordId) filter.recordId = String(req.query.recordId);
+ const subscriptions = await listSubscriptions(filter);
+ res.json({ subscriptions });
+}));
+
+router.post('/subscriptions', asyncHandler(async (req, res) => {
+ const input = validateRequest(subscriptionCreateSchema, req.body || {});
+ const sub = await subscribe(input);
+ res.status(201).json({ subscription: sub });
+}));
+
+router.delete('/subscriptions/:id', asyncHandler(async (req, res) => {
+ const result = await unsubscribe(req.params.id);
+ 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);
diff --git a/server/services/pipeline/issues.js b/server/services/pipeline/issues.js
index 3459988343..31b81d79f2 100644
--- a/server/services/pipeline/issues.js
+++ b/server/services/pipeline/issues.js
@@ -26,6 +26,7 @@ import {
CUSTOM_PAGE_MIN, CUSTOM_PAGE_MAX, CUSTOM_MINUTE_MIN, CUSTOM_MINUTE_MAX,
} from '../../lib/issueLength.js';
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
+import { emitRecordUpdated } from '../sharing/recordEvents.js';
// Lazy resolution — see series.js for context.
const statePath = () => join(PATHS.data, 'pipeline-issues.json');
@@ -419,6 +420,9 @@ export function updateIssue(id, patch = {}) {
if (!merged) throw makeErr('Invalid issue payload', ERR_VALIDATION);
state.issues[idx] = merged;
await writeState(state);
+ // Issues are exported as part of their parent series — re-export the
+ // series so any active subscription picks up the issue change.
+ emitRecordUpdated('series', merged.seriesId);
return merged;
}); // end queueIssueWrite
}
@@ -486,6 +490,7 @@ export function updateStageWithLatest(issueId, stageId, computeFn) {
});
state.issues[idx] = mergedIssue;
await writeState(state);
+ emitRecordUpdated('series', mergedIssue.seriesId);
return { issue: mergedIssue, stage: mergedIssue.stages[stageId] };
}); // end queueIssueWrite
}
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index c83aeffb29..012626c239 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -21,6 +21,7 @@ import {
import { sanitizeArc, sanitizeSeasonList } from '../../lib/storyArc.js';
import { extractBible } from '../../lib/bibleExtractor.js';
import { sanitizeOrigin } from '../../lib/sharingOrigin.js';
+import { emitRecordUpdated } from '../sharing/recordEvents.js';
// Lazy resolution — PATHS.data may not be available at module-load time
// (e.g. tests that swap it through a Proxy mock).
@@ -202,6 +203,7 @@ export async function updateSeries(id, patch = {}) {
if (!merged) throw makeErr('Invalid series payload', ERR_VALIDATION);
state.series[idx] = merged;
await writeState(state);
+ emitRecordUpdated('series', merged.id);
return merged;
}
diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.js
index 0ad7c78320..30f48ac6d1 100644
--- a/server/services/sharing/exporter.js
+++ b/server/services/sharing/exporter.js
@@ -179,8 +179,15 @@ function stampOrigin(record, { bucket, source, sourceBio, manifestId }) {
};
}
-/** Export a full series (with its issues + linked universe + every asset). */
-export async function exportSeries(seriesId, bucketId) {
+/**
+ * Export a full series (with its issues + linked universe + every asset).
+ *
+ * `opts.subscription` (optional): when set to `{ recordKind, recordId }` the
+ * manifest is marked as a subscription — bucket-side filename becomes
+ * deterministic (`sub-series-<id>.json`) so re-exports overwrite in place
+ * instead of accumulating. Omit for one-shot legacy shares.
+ */
+export async function exportSeries(seriesId, bucketId, opts = {}) {
const bucket = await getBucket(bucketId);
await ensureBucketLayout(bucket);
const series = await getSeries(seriesId);
@@ -203,6 +210,7 @@ export async function exportSeries(seriesId, bucketId) {
senderInstanceId,
source, sourceBio,
producedByVersion,
+ subscription: opts.subscription || null,
bucketId: bucket.id,
bucketName: bucket.name,
recordIds: [],
@@ -252,8 +260,8 @@ export async function exportSeries(seriesId, bucketId) {
return { manifestId, filename, recordCount: recordIds.length, assetCount: assetRefs.length };
}
-/** Export a universe on its own (no series attached). */
-export async function exportUniverse(universeId, bucketId) {
+/** Export a universe on its own (no series attached). See exportSeries for opts. */
+export async function exportUniverse(universeId, bucketId, opts = {}) {
const bucket = await getBucket(bucketId);
await ensureBucketLayout(bucket);
const universe = await getUniverse(universeId);
@@ -270,6 +278,7 @@ export async function exportUniverse(universeId, bucketId) {
senderInstanceId,
source, sourceBio,
producedByVersion,
+ subscription: opts.subscription || null,
bucketId: bucket.id,
bucketName: bucket.name,
recordIds: [],
diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.js
index e81e701364..d323873bbd 100644
--- a/server/services/sharing/importer.js
+++ b/server/services/sharing/importer.js
@@ -23,7 +23,7 @@ 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 { readManifest, markProcessed, readCursor, hasBeenProcessed, forgetProcessed } from './manifest.js';
import { SHARING_SCHEMA_VERSION, isManifestCompatible } from './version.js';
import { insertSeriesWithId, updateSeries, getSeries } from '../pipeline/series.js';
import { insertIssueWithId, updateIssue, getIssue } from '../pipeline/issues.js';
@@ -189,18 +189,30 @@ async function applyAutoMerge(bucket, manifest, records) {
const INBOX_MAX = 1000;
-/** Inbox mode: write the manifest + record refs to the bucket's inbox for review. */
+/**
+ * Inbox mode: write the manifest + record refs to the bucket's inbox for review.
+ *
+ * For subscription manifests we replace any prior inbox entry for the same
+ * (recordKind, recordId) so a sender's repeated edits don't pile up as N
+ * inbox items — the user always sees the latest snapshot. One-shot manifests
+ * dedup by manifest id.
+ */
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)) {
+ const sub = manifest.subscription;
+ if (sub?.recordKind && sub?.recordId) {
+ inbox.items = inbox.items.filter((it) => !(it.subscription
+ && it.subscription.recordKind === sub.recordKind
+ && it.subscription.recordId === sub.recordId));
+ } else 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,
+ subscription: sub || null,
source: manifest.source,
sourceBio: manifest.sourceBio,
producedByVersion: manifest.producedByVersion || null,
@@ -212,8 +224,6 @@ async function applyInbox(bucket, manifest, manifestFilename, records) {
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 };
@@ -235,14 +245,16 @@ function summarizeRecords(records) {
*/
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 cursor = await readCursor(bucketId);
+ // Content-aware dedup: subscription manifests reuse the same filename
+ // across updates and a fresh manifestId means the contents changed.
+ if (hasBeenProcessed(cursor, manifestFilename, manifest.id)) {
+ return { skipped: true, reason: 'already-processed' };
+ }
// Read schemaVersion (also accepts the descriptive alias sharingSchemaVersion).
const remoteVersion = Number.isFinite(manifest.sharingSchemaVersion)
? manifest.sharingSchemaVersion
@@ -251,7 +263,7 @@ export async function processManifest(bucketId, manifestFilename) {
// Mark processed so the watcher doesn't replay it on every file event,
// but emit a clear signal to the UI so the user knows a peer is on a
// newer protocol and they should upgrade PortOS to consume their shares.
- await markProcessed(bucketId, manifestFilename);
+ await markProcessed(bucketId, manifestFilename, manifest.id);
sharingEvents.emit('incompatible-manifest', {
bucketId, manifestId: manifest.id, manifestFilename,
remoteVersion, localVersion: SHARING_SCHEMA_VERSION,
@@ -274,7 +286,7 @@ export async function processManifest(bucketId, manifestFilename) {
} else {
outcome = { mode: 'inbox', ...(await applyInbox(bucket, manifest, manifestFilename, records)) };
}
- await markProcessed(bucketId, manifestFilename);
+ await markProcessed(bucketId, manifestFilename, manifest.id);
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}`}`);
@@ -322,6 +334,33 @@ export async function promoteInboxItem(bucketId, manifestId) {
return { promoted: true, outcome };
}
+/**
+ * A subscription file disappeared from the bucket — the upstream peer
+ * unsubscribed. We clear the cursor entry so a future re-share of the same
+ * record imports cleanly, drop any pending inbox entry for that subscription,
+ * and emit a socket signal. We DO NOT delete the local imported record:
+ * the recipient keeps whatever they already received.
+ */
+export async function handleUnshare(bucketId, manifestFilename) {
+ const cursor = await readCursor(bucketId);
+ const wasTracked = manifestFilename in (cursor.processedById || {})
+ || (Array.isArray(cursor.processed) && cursor.processed.includes(manifestFilename));
+ await forgetProcessed(bucketId, manifestFilename);
+
+ // Drop matching inbox entry by manifest filename (subscriptions have stable
+ // filenames; one-shot manifests do too, just timestamped — both work).
+ const inbox = await readInbox(bucketId);
+ const before = (inbox.items || []).length;
+ inbox.items = (inbox.items || []).filter((it) => it.manifestFilename !== manifestFilename);
+ if (inbox.items.length !== before) await writeInbox(bucketId, inbox);
+
+ sharingEvents.emit('unshared', { bucketId, manifestFilename });
+ if (wasTracked) {
+ console.log(`📤 sharing: bucket=${bucketId} manifest=${manifestFilename} unshared by peer`);
+ }
+ return { handled: true, wasTracked };
+}
+
export async function dismissInboxItem(bucketId, manifestId) {
const inbox = await readInbox(bucketId);
const before = (inbox.items || []).length;
diff --git a/server/services/sharing/index.js b/server/services/sharing/index.js
index 736238ff82..beaeb90de6 100644
--- a/server/services/sharing/index.js
+++ b/server/services/sharing/index.js
@@ -11,6 +11,7 @@ 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';
+import { installSubscriptionListener } from './subscriptions.js';
export { sharingEvents } from './importer.js';
export { attachWatcher, detachWatcher, listAttachedWatchers };
@@ -46,8 +47,12 @@ export async function initSharing({ io: socketIo } = {}) {
sharingEvents.on('incompatible-manifest', (payload) => {
io.emit('sharing:incompatible-manifest', payload);
});
+ sharingEvents.on('unshared', (payload) => {
+ io.emit('sharing:unshared', payload);
+ });
}
+ installSubscriptionListener();
const result = await attachAllWatchers();
console.log(`📡 sharing: initialized, watchers attached for ${result.attached} bucket(s)`);
return result;
diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.js
index fdc4f5a5f0..4b97d5259f 100644
--- a/server/services/sharing/integration.test.js
+++ b/server/services/sharing/integration.test.js
@@ -185,6 +185,56 @@ describe('sharing round-trip', () => {
expect(r2.reason).toBe('already-processed');
});
+ it('subscription round-trip: subscribe → mutate → re-export onto same filename → unsubscribe → unshared event', async () => {
+ const { subscribe, unsubscribe, subscriptionFilename, __resetForTests } = await import('./subscriptions.js');
+ const { sharingEvents } = await import('./importer.js');
+ __resetForTests();
+ const bucket = await buckets.createBucket({ name: 'SubBucket', path: tempBucket, mode: 'auto-merge' });
+ const universeBuilder = await import('../universeBuilder.js');
+ const u = await universeBuilder.createUniverse({ name: 'Sub Universe' });
+
+ // Subscribe — first export writes a deterministic-named file.
+ const sub = await subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: u.id });
+ const filename = subscriptionFilename(sub);
+ const filePath = join(tempBucket, 'manifests', filename);
+ const fs = await import('fs');
+ expect(fs.existsSync(filePath)).toBe(true);
+ const first = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ expect(first.subscription).toMatchObject({ recordKind: 'universe', recordId: u.id });
+ const firstManifestId = first.id;
+
+ // Mutate the universe — emit fires recordEvents which schedules a re-export.
+ // For the test, bypass the 3s debounce by calling subscribe again (idempotent).
+ await universeBuilder.updateUniverse(u.id, { starterPrompt: 'updated prompt' });
+ await subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: u.id }); // forces immediate re-export
+ const second = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
+ expect(second.id).not.toBe(firstManifestId);
+ // Importer's cursor logic dedups by manifest id, so a re-import of the
+ // updated file is recognized as new content.
+ const r1 = await importer.processManifest(bucket.id, filename);
+ expect(r1.processed || r1.skipped).toBeTruthy();
+
+ // Unsubscribe — deletes the file. Watcher's `unlink` calls handleUnshare
+ // (here we invoke it directly since chokidar is not running in tests).
+ const events = [];
+ const onUnshared = (p) => events.push(p);
+ sharingEvents.on('unshared', onUnshared);
+
+ await unsubscribe(sub.id);
+ expect(fs.existsSync(filePath)).toBe(false);
+
+ await importer.handleUnshare(bucket.id, filename);
+ sharingEvents.off('unshared', onUnshared);
+
+ expect(events).toHaveLength(1);
+ expect(events[0]).toMatchObject({ bucketId: bucket.id, manifestFilename: filename });
+
+ // Local imported universe should NOT have been removed — unshare doesn't
+ // reverse the import on the recipient. The universe still exists locally.
+ const stillThere = await universeBuilder.getUniverse(u.id);
+ expect(stillThere.id).toBe(u.id);
+ });
+
it('refuses a manifest with a sharingSchemaVersion newer than local + emits incompatible event', async () => {
const { SHARING_SCHEMA_VERSION } = await import('./version.js');
const { sharingEvents } = await import('./importer.js');
diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.js
index 8d6f3c0484..783e14829c 100644
--- a/server/services/sharing/manifest.js
+++ b/server/services/sharing/manifest.js
@@ -29,9 +29,29 @@ const isStr = (v) => typeof v === 'string';
const cursorPath = (bucketId) => join(PATHS.data, 'sharing', 'cursors', `${bucketId}.json`);
+/**
+ * Cursor shape:
+ * {
+ * processedById: { '<filename>': '<lastSeenManifestId>' },
+ * processed: ['<filename>', ...], // legacy: pre-content-aware cursor entries
+ * lastProcessedAt: ISO
+ * }
+ *
+ * The `processedById` map is the content-aware path used for subscription
+ * manifests: a fresh `manifestId` inside the same filename means the file's
+ * contents changed (the subscription re-exported) and we need to re-import.
+ * Legacy `processed[]` entries from buckets created on v1.0..v1.2 still
+ * suppress re-import — those were one-shot manifests with random filenames,
+ * so they're never going to be re-processed by content anyway.
+ */
export async function readCursor(bucketId) {
await ensureDir(join(PATHS.data, 'sharing', 'cursors'));
- return readJSONFile(cursorPath(bucketId), { processed: [] }, { logError: false });
+ const raw = await readJSONFile(cursorPath(bucketId), { processedById: {}, processed: [] }, { logError: false });
+ return {
+ processedById: (raw.processedById && typeof raw.processedById === 'object') ? raw.processedById : {},
+ processed: Array.isArray(raw.processed) ? raw.processed : [],
+ lastProcessedAt: raw.lastProcessedAt || null,
+ };
}
export async function writeCursor(bucketId, cursor) {
@@ -40,24 +60,56 @@ export async function writeCursor(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.
+ * Mark a manifest filename as processed at the given manifestId. Caps the
+ * cursor at 5000 entries so a runaway peer can't grow the file unbounded.
*/
-export async function markProcessed(bucketId, manifestFilename) {
+export async function markProcessed(bucketId, manifestFilename, manifestId = null) {
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.processedById[manifestFilename] = manifestId || cursor.processedById[manifestFilename] || '';
+ // Drop legacy entry if it was tracked there; the map is now authoritative.
+ if (cursor.processed.includes(manifestFilename)) {
+ cursor.processed = cursor.processed.filter((f) => f !== manifestFilename);
+ }
+ const keys = Object.keys(cursor.processedById);
+ if (keys.length > 5000) {
+ // Drop the lexicographically-smallest 1000 — for timestamp-prefixed
+ // one-shot manifests this is the oldest entries. Subscription filenames
+ // (sub-…) sort after timestamp-prefixed ones, so they survive a prune
+ // even when the cursor is full of legacy one-shot history.
+ const drop = new Set(keys.sort().slice(0, keys.length - 5000));
+ for (const k of drop) delete cursor.processedById[k];
}
cursor.lastProcessedAt = new Date().toISOString();
await writeCursor(bucketId, cursor);
return cursor;
}
-export function hasBeenProcessed(cursor, manifestFilename) {
+/**
+ * Remove a filename from the cursor entirely (used on `unlink` so a future
+ * re-share of the same record under the same filename re-imports cleanly).
+ */
+export async function forgetProcessed(bucketId, manifestFilename) {
+ const cursor = await readCursor(bucketId);
+ if (cursor.processedById[manifestFilename] !== undefined) {
+ delete cursor.processedById[manifestFilename];
+ }
+ cursor.processed = cursor.processed.filter((f) => f !== manifestFilename);
+ await writeCursor(bucketId, cursor);
+ return cursor;
+}
+
+/**
+ * Returns true when we've already imported THIS specific version of the
+ * manifest. For subscription manifests, content-aware: a new manifestId on
+ * the same filename re-processes. For legacy entries (processed[] array),
+ * any subsequent reference to that filename is suppressed.
+ */
+export function hasBeenProcessed(cursor, manifestFilename, manifestId = null) {
+ if (cursor?.processedById && manifestFilename in cursor.processedById) {
+ const stored = cursor.processedById[manifestFilename];
+ if (!stored) return true; // unknown id → trust filename match (idempotent)
+ return manifestId ? stored === manifestId : true;
+ }
return Array.isArray(cursor?.processed) && cursor.processed.includes(manifestFilename);
}
@@ -70,10 +122,17 @@ export function hasBeenProcessed(cursor, manifestFilename) {
* `schemaVersion` is the wire-protocol version (the only one importer compat
* is gated on). `sharingSchemaVersion` is its more descriptive alias kept for
* forward-compat readability — both carry the same value.
+ *
+ * `subscription`, when provided as `{ recordKind, recordId }`, marks this
+ * manifest as a persistent subscription rather than a one-shot share. The
+ * filename is then deterministic per (recordKind, recordId), so re-exports
+ * overwrite in place and recipients see updates via chokidar `change`
+ * events. Importer cursor keys on the manifest id (fresh per export) so
+ * content-changes re-process correctly.
*/
export function buildManifest({
kind, senderInstanceId, source, sourceBio, recordIds, assetRefs,
- bucketId, bucketName, note, producedByVersion,
+ bucketId, bucketName, note, producedByVersion, subscription,
}) {
if (!MANIFEST_KIND.includes(kind)) throw new Error(`buildManifest: invalid kind '${kind}'`);
return {
@@ -83,6 +142,9 @@ export function buildManifest({
producedByVersion: producedByVersion || 'unknown',
createdAt: new Date().toISOString(),
kind, // 'series' | 'universe' | 'media'
+ subscription: subscription && subscription.recordKind && subscription.recordId
+ ? { recordKind: subscription.recordKind, recordId: subscription.recordId }
+ : null,
senderInstanceId: senderInstanceId || 'unknown',
source: source || 'unknown', // human display name
sourceBio: sourceBio || null,
@@ -94,7 +156,20 @@ export function buildManifest({
};
}
+/**
+ * Filename a manifest lives under inside `<bucket>/manifests/`.
+ *
+ * For subscription manifests we use a deterministic name keyed on the
+ * (recordKind, recordId, bucketId) tuple so re-exports overwrite the same
+ * file — bucket recipients see updates via chokidar `change` events, not as
+ * accumulating new files. For one-shot manifests we use the legacy
+ * `<iso-ts>-<source>-<uuid>.json` naming so the watcher's add-order remains
+ * lexicographically deterministic.
+ */
export function manifestFilename(manifest) {
+ if (manifest.subscription?.recordKind && manifest.subscription?.recordId) {
+ return `sub-${manifest.subscription.recordKind}-${manifest.subscription.recordId}.json`;
+ }
const ts = manifest.createdAt.replace(/[:.]/g, '-');
const senderSlug = (manifest.source || manifest.senderInstanceId || 'unknown')
.toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40)
diff --git a/server/services/sharing/manifest.test.js b/server/services/sharing/manifest.test.js
index a9e270b686..5773e51e84 100644
--- a/server/services/sharing/manifest.test.js
+++ b/server/services/sharing/manifest.test.js
@@ -92,10 +92,45 @@ describe('sharing/manifest', () => {
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');
+ it('markProcessed records the manifest id and is idempotent on re-mark', async () => {
+ await manifest.markProcessed('b1', 'a.json', 'mfst-1');
+ await manifest.markProcessed('b1', 'a.json', 'mfst-1');
const c = await manifest.readCursor('b1');
- expect(c.processed.filter((x) => x === 'a.json')).toHaveLength(1);
+ expect(c.processedById['a.json']).toBe('mfst-1');
+ expect(manifest.hasBeenProcessed(c, 'a.json', 'mfst-1')).toBe(true);
+ });
+
+ it('hasBeenProcessed re-processes a known filename when manifest id changes (subscription update)', async () => {
+ await manifest.markProcessed('b1', 'sub-universe-abc.json', 'mfst-v1');
+ let c = await manifest.readCursor('b1');
+ expect(manifest.hasBeenProcessed(c, 'sub-universe-abc.json', 'mfst-v1')).toBe(true);
+ expect(manifest.hasBeenProcessed(c, 'sub-universe-abc.json', 'mfst-v2')).toBe(false);
+ await manifest.markProcessed('b1', 'sub-universe-abc.json', 'mfst-v2');
+ c = await manifest.readCursor('b1');
+ expect(c.processedById['sub-universe-abc.json']).toBe('mfst-v2');
+ });
+
+ it('forgetProcessed removes the entry so a future re-share imports cleanly', async () => {
+ await manifest.markProcessed('b1', 'sub-universe-abc.json', 'mfst-1');
+ await manifest.forgetProcessed('b1', 'sub-universe-abc.json');
+ const c = await manifest.readCursor('b1');
+ expect(c.processedById['sub-universe-abc.json']).toBeUndefined();
+ expect(manifest.hasBeenProcessed(c, 'sub-universe-abc.json', 'mfst-1')).toBe(false);
+ });
+
+ it('manifestFilename is deterministic when subscription is set', () => {
+ const m = manifest.buildManifest({
+ kind: 'universe', source: 'me', bucketId: 'b1', bucketName: 'c',
+ recordIds: [], assetRefs: [],
+ subscription: { recordKind: 'universe', recordId: 'uni-abc-123' },
+ });
+ expect(manifest.manifestFilename(m)).toBe('sub-universe-uni-abc-123.json');
+ // Same record → same filename regardless of timestamp.
+ const m2 = manifest.buildManifest({
+ kind: 'universe', source: 'me', bucketId: 'b1', bucketName: 'c',
+ recordIds: [], assetRefs: [],
+ subscription: { recordKind: 'universe', recordId: 'uni-abc-123' },
+ });
+ expect(manifest.manifestFilename(m2)).toBe(manifest.manifestFilename(m));
});
});
diff --git a/server/services/sharing/recordEvents.js b/server/services/sharing/recordEvents.js
new file mode 100644
index 0000000000..9d7b5b0813
--- /dev/null
+++ b/server/services/sharing/recordEvents.js
@@ -0,0 +1,23 @@
+/**
+ * Cross-service event bus for record mutations the sharing subsystem
+ * cares about. Each pipeline / universe write path emits `updated` with
+ * `{ recordKind, recordId }` after a successful persist; subscriptions.js
+ * listens and re-exports the record into any bucket it's currently
+ * subscribed to.
+ *
+ * Kept separate from the service modules so importing this bus doesn't
+ * drag in the heavyweight pipeline graph.
+ */
+
+import { EventEmitter } from 'events';
+
+export const recordEvents = new EventEmitter();
+// Many subscriptions per record + the subscriptions listener itself can
+// add up past the default 10-listener warning threshold under load.
+recordEvents.setMaxListeners(100);
+
+/** Fire-and-forget — listeners' failures shouldn't poison the caller. */
+export function emitRecordUpdated(recordKind, recordId) {
+ if (!recordKind || !recordId) return;
+ recordEvents.emit('updated', { recordKind, recordId });
+}
diff --git a/server/services/sharing/subscriptions.js b/server/services/sharing/subscriptions.js
new file mode 100644
index 0000000000..0f337232ef
--- /dev/null
+++ b/server/services/sharing/subscriptions.js
@@ -0,0 +1,206 @@
+/**
+ * Share-bucket subscriptions.
+ *
+ * A subscription is a persistent (bucketId, recordKind, recordId) tuple. It
+ * says "as long as this exists, I am continuously sharing this record into
+ * that bucket — every local edit auto-re-exports onto a deterministic file
+ * in the bucket, replacing the previous snapshot."
+ *
+ * Per the user mental model: clicking a bucket in ShareToButton creates a
+ * subscription + does the initial export. Clicking again removes it (and
+ * deletes the bucket-side file so recipients see the share go away). Local
+ * mutations to the subscribed record fire `recordEvents` which this service
+ * listens to and re-exports via the same deterministic filename.
+ *
+ * Subscriptions are local-only state (data/sharing/subscriptions.json) — the
+ * bucket itself only holds the deterministic manifest file. Multiple peers
+ * may both be subscribing the same bucket; each writes their own
+ * sub-<kind>-<recordId>.json with their own source attribution.
+ */
+
+import { join } from 'path';
+import { unlink } from 'fs/promises';
+import { existsSync } from 'fs';
+import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';
+import { isStr } from '../../lib/storyBible.js';
+import { getBucket } from './buckets.js';
+import { exportSeries, exportUniverse } from './exporter.js';
+import { recordEvents } from './recordEvents.js';
+
+export const SUBSCRIBABLE_KINDS = Object.freeze(['series', 'universe']);
+
+export const ERR_NOT_FOUND = 'SHARING_SUBSCRIPTION_NOT_FOUND';
+export const ERR_VALIDATION = 'SHARING_SUBSCRIPTION_VALIDATION';
+export const ERR_DUPLICATE = 'SHARING_SUBSCRIPTION_DUPLICATE';
+const makeErr = (message, code) => Object.assign(new Error(message), { code });
+
+const STATE_PATH = () => join(PATHS.data, 'sharing', 'subscriptions.json');
+
+function subId({ bucketId, recordKind, recordId }) {
+ return `sub-${recordKind}-${recordId}-${bucketId}`;
+}
+
+/** Deterministic file name in `<bucket>/manifests/` for a subscription. */
+export function subscriptionFilename({ recordKind, recordId }) {
+ return `sub-${recordKind}-${recordId}.json`;
+}
+
+async function readState() {
+ await ensureDir(join(PATHS.data, 'sharing'));
+ const raw = await readJSONFile(STATE_PATH(), { subscriptions: [] }, { logError: false });
+ const subs = Array.isArray(raw.subscriptions) ? raw.subscriptions : [];
+ return { subscriptions: subs };
+}
+
+async function writeState(state) {
+ await ensureDir(join(PATHS.data, 'sharing'));
+ await atomicWrite(STATE_PATH(), state);
+}
+
+export async function listSubscriptions(filter = {}) {
+ const { subscriptions } = await readState();
+ return subscriptions.filter((s) => {
+ if (filter.bucketId && s.bucketId !== filter.bucketId) return false;
+ if (filter.recordKind && s.recordKind !== filter.recordKind) return false;
+ if (filter.recordId && s.recordId !== filter.recordId) return false;
+ return true;
+ });
+}
+
+export async function findSubscription(bucketId, recordKind, recordId) {
+ if (!bucketId || !recordKind || !recordId) return null;
+ const { subscriptions } = await readState();
+ return subscriptions.find(
+ (s) => s.bucketId === bucketId && s.recordKind === recordKind && s.recordId === recordId,
+ ) || null;
+}
+
+/**
+ * Create a subscription and trigger the first export. If a subscription
+ * already exists for the same (bucket, kind, id), idempotently re-export
+ * rather than throwing — clicking "subscribe" on an already-subscribed
+ * bucket should be a no-op refresh, not an error.
+ */
+export async function subscribe({ bucketId, recordKind, recordId }) {
+ if (!SUBSCRIBABLE_KINDS.includes(recordKind)) {
+ throw makeErr(`subscribable kinds are ${SUBSCRIBABLE_KINDS.join(', ')} (got "${recordKind}")`, ERR_VALIDATION);
+ }
+ if (!isStr(bucketId) || !isStr(recordId)) {
+ throw makeErr('bucketId and recordId are required', ERR_VALIDATION);
+ }
+ // Validate the bucket exists (throws ERR_NOT_FOUND otherwise).
+ await getBucket(bucketId);
+
+ const state = await readState();
+ const id = subId({ bucketId, recordKind, recordId });
+ let sub = state.subscriptions.find((s) => s.id === id);
+ const now = new Date().toISOString();
+ if (!sub) {
+ sub = { id, bucketId, recordKind, recordId, createdAt: now, updatedAt: now, lastManifestId: null, lastExportedAt: null };
+ state.subscriptions.push(sub);
+ await writeState(state);
+ }
+
+ const exp = await runExport({ bucketId, recordKind, recordId });
+ if (exp) {
+ sub.lastManifestId = exp.manifestId;
+ sub.lastExportedAt = now;
+ sub.updatedAt = now;
+ await writeState(state);
+ }
+ return sub;
+}
+
+/** Internal: dispatch to the right exporter based on recordKind. */
+async function runExport({ bucketId, recordKind, recordId }) {
+ const opts = { subscription: { recordKind, recordId } };
+ if (recordKind === 'series') return exportSeries(recordId, bucketId, opts);
+ if (recordKind === 'universe') return exportUniverse(recordId, bucketId, opts);
+ return null;
+}
+
+export async function unsubscribe(id) {
+ if (!isStr(id)) throw makeErr('subscription id required', ERR_VALIDATION);
+ const state = await readState();
+ const idx = state.subscriptions.findIndex((s) => s.id === id);
+ if (idx < 0) throw makeErr(`Subscription not found: ${id}`, ERR_NOT_FOUND);
+ const sub = state.subscriptions[idx];
+
+ // Delete the deterministic file from the bucket. Best-effort: the bucket
+ // path may be unmounted; the subscription record removal still wins so the
+ // user's "I want to stop sharing" intent is honored regardless. Importers
+ // on other peers see the file vanish via chokidar `unlink`.
+ const bucket = await getBucket(sub.bucketId).catch(() => null);
+ if (bucket) {
+ const filename = subscriptionFilename(sub);
+ const filePath = join(bucket.path, 'manifests', filename);
+ if (existsSync(filePath)) {
+ await unlink(filePath).catch((err) => {
+ console.log(`⚠️ sharing.subscriptions: failed to remove ${filePath}: ${err.message}`);
+ });
+ }
+ }
+
+ state.subscriptions.splice(idx, 1);
+ await writeState(state);
+ return { id, removed: true };
+}
+
+/**
+ * Re-export every subscription for a given (recordKind, recordId). Called by
+ * the recordEvents listener. Debounced per subscription so a flurry of edits
+ * coalesces into one export per ~3s window.
+ */
+const DEBOUNCE_MS = 3000;
+const pendingTimers = new Map(); // subId → Timeout
+
+async function reexportNow(sub) {
+ const exp = await runExport(sub).catch((err) => {
+ console.log(`⚠️ sharing.subscriptions: re-export failed for ${sub.id}: ${err.message}`);
+ return null;
+ });
+ if (!exp) return;
+ const state = await readState();
+ const live = state.subscriptions.find((s) => s.id === sub.id);
+ if (!live) return; // unsubscribed between the trigger and the write
+ live.lastManifestId = exp.manifestId;
+ live.lastExportedAt = new Date().toISOString();
+ live.updatedAt = live.lastExportedAt;
+ await writeState(state);
+}
+
+export async function reexportSubscribedRecord(recordKind, recordId) {
+ const subs = await listSubscriptions({ recordKind, recordId });
+ for (const sub of subs) {
+ const existing = pendingTimers.get(sub.id);
+ if (existing) clearTimeout(existing);
+ const t = setTimeout(() => {
+ pendingTimers.delete(sub.id);
+ reexportNow(sub).catch(() => {});
+ }, DEBOUNCE_MS);
+ // unref so a pending debounce can't keep the process alive past shutdown.
+ if (typeof t.unref === 'function') t.unref();
+ pendingTimers.set(sub.id, t);
+ }
+}
+
+let listenerInstalled = false;
+
+/** Attach the recordEvents listener — call once during sharing init. */
+export function installSubscriptionListener() {
+ if (listenerInstalled) return;
+ listenerInstalled = true;
+ recordEvents.on('updated', ({ recordKind, recordId }) => {
+ reexportSubscribedRecord(recordKind, recordId).catch((err) => {
+ console.log(`⚠️ sharing.subscriptions: listener error for ${recordKind}/${recordId}: ${err.message}`);
+ });
+ });
+}
+
+/** Test-only: clear pending debounces and detach the listener so suites can isolate. */
+export function __resetForTests() {
+ for (const t of pendingTimers.values()) clearTimeout(t);
+ pendingTimers.clear();
+ recordEvents.removeAllListeners('updated');
+ listenerInstalled = false;
+}
diff --git a/server/services/sharing/subscriptions.test.js b/server/services/sharing/subscriptions.test.js
new file mode 100644
index 0000000000..d068fd086e
--- /dev/null
+++ b/server/services/sharing/subscriptions.test.js
@@ -0,0 +1,121 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { mkdtempSync, rmSync, mkdirSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+// Universe builder evaluates PATHS.data at module top, so allocate a stable
+// temp dir before any service imports. beforeEach wipes + reseeds inside.
+const tempData = mkdtempSync(join(tmpdir(), 'portos-subs-test-data-'));
+let tempBucket;
+
+vi.mock('../../lib/fileUtils.js', async () => {
+ const actual = await vi.importActual('../../lib/fileUtils.js');
+ return new Proxy(actual, {
+ get(target, prop) {
+ if (prop === 'PATHS') return {
+ ...actual.PATHS,
+ data: tempData,
+ images: join(tempData, 'images'),
+ videos: join(tempData, 'videos'),
+ };
+ return target[prop];
+ },
+ });
+});
+vi.mock('../instances.js', () => ({ getInstanceId: () => Promise.resolve('inst-test') }));
+vi.mock('../mediaJobQueue/index.js', () => ({ getJob: () => null }));
+
+const buckets = await import('./buckets.js');
+const subs = await import('./subscriptions.js');
+const universeBuilder = await import('../universeBuilder.js');
+const series = await import('../pipeline/series.js');
+
+describe('sharing/subscriptions', () => {
+ beforeEach(() => {
+ rmSync(tempData, { recursive: true, force: true });
+ mkdirSync(tempData, { recursive: true });
+ mkdirSync(join(tempData, 'images'), { recursive: true });
+ tempBucket = mkdtempSync(join(tmpdir(), 'portos-subs-test-bucket-'));
+ subs.__resetForTests();
+ });
+ afterEach(() => {
+ if (tempBucket) rmSync(tempBucket, { recursive: true, force: true });
+ });
+
+ it('subscribe creates a subscription and writes a deterministic-named manifest', async () => {
+ const bucket = await buckets.createBucket({ name: 'B', path: tempBucket, mode: 'inbox' });
+ const u = await universeBuilder.createUniverse({ name: 'U1' });
+
+ const sub = await subs.subscribe({
+ bucketId: bucket.id, recordKind: 'universe', recordId: u.id,
+ });
+ expect(sub.id).toMatch(/^sub-universe-/);
+ expect(sub.bucketId).toBe(bucket.id);
+ expect(sub.lastManifestId).toBeTruthy();
+
+ const fs = await import('fs');
+ const filename = subs.subscriptionFilename({ recordKind: 'universe', recordId: u.id });
+ expect(filename).toBe(`sub-universe-${u.id}.json`);
+ expect(fs.existsSync(join(tempBucket, 'manifests', filename))).toBe(true);
+ });
+
+ it('subscribe is idempotent — second call re-exports onto the same file with a new manifestId', async () => {
+ const bucket = await buckets.createBucket({ name: 'B', path: tempBucket });
+ const u = await universeBuilder.createUniverse({ name: 'U2' });
+ const first = await subs.subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: u.id });
+ const second = await subs.subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: u.id });
+ expect(first.id).toBe(second.id);
+ expect(second.lastManifestId).not.toBe(first.lastManifestId);
+
+ const all = await subs.listSubscriptions();
+ expect(all.filter((s) => s.recordId === u.id)).toHaveLength(1);
+ });
+
+ it('unsubscribe removes the subscription and deletes the bucket file', async () => {
+ const bucket = await buckets.createBucket({ name: 'B', path: tempBucket });
+ const u = await universeBuilder.createUniverse({ name: 'U3' });
+ const sub = await subs.subscribe({ bucketId: bucket.id, recordKind: 'universe', recordId: u.id });
+ const filename = subs.subscriptionFilename(sub);
+ const filePath = join(tempBucket, 'manifests', filename);
+ const fs = await import('fs');
+ expect(fs.existsSync(filePath)).toBe(true);
+
+ await subs.unsubscribe(sub.id);
+ expect(fs.existsSync(filePath)).toBe(false);
+ expect(await subs.listSubscriptions()).toEqual([]);
+ });
+
+ it('listSubscriptions filters by bucketId / recordKind / recordId', async () => {
+ const bucket1 = await buckets.createBucket({ name: 'A', path: tempBucket });
+ const bucket2Path = mkdtempSync(join(tmpdir(), 'portos-subs-b2-'));
+ const bucket2 = await buckets.createBucket({ name: 'B', path: bucket2Path });
+ const u = await universeBuilder.createUniverse({ name: 'U4' });
+ const s = await series.createSeries({ name: 'S1' });
+
+ await subs.subscribe({ bucketId: bucket1.id, recordKind: 'universe', recordId: u.id });
+ await subs.subscribe({ bucketId: bucket2.id, recordKind: 'universe', recordId: u.id });
+ await subs.subscribe({ bucketId: bucket1.id, recordKind: 'series', recordId: s.id });
+
+ expect((await subs.listSubscriptions({ bucketId: bucket1.id }))).toHaveLength(2);
+ expect((await subs.listSubscriptions({ recordKind: 'universe' }))).toHaveLength(2);
+ expect((await subs.listSubscriptions({ recordKind: 'series', recordId: s.id }))).toHaveLength(1);
+
+ rmSync(bucket2Path, { recursive: true, force: true });
+ });
+
+ it('subscribe rejects unsubscribable kinds', async () => {
+ const bucket = await buckets.createBucket({ name: 'B', path: tempBucket });
+ await expect(subs.subscribe({ bucketId: bucket.id, recordKind: 'media', recordId: 'x' }))
+ .rejects.toMatchObject({ code: subs.ERR_VALIDATION });
+ });
+
+ it('unsubscribe throws ERR_NOT_FOUND for unknown id', async () => {
+ await expect(subs.unsubscribe('does-not-exist'))
+ .rejects.toMatchObject({ code: subs.ERR_NOT_FOUND });
+ });
+
+ it('findSubscription returns null when none exists', async () => {
+ const bucket = await buckets.createBucket({ name: 'B', path: tempBucket });
+ expect(await subs.findSubscription(bucket.id, 'universe', 'no-such-id')).toBeNull();
+ });
+});
diff --git a/server/services/sharing/watcher.js b/server/services/sharing/watcher.js
index 010df82134..e5f68f662d 100644
--- a/server/services/sharing/watcher.js
+++ b/server/services/sharing/watcher.js
@@ -13,7 +13,7 @@
import { watch } from 'chokidar';
import { join, basename } from 'path';
-import { processManifest, processBacklog, sharingEvents } from './importer.js';
+import { processManifest, processBacklog, handleUnshare, sharingEvents } from './importer.js';
import { getBucket, listBuckets, ensureBucketLayout } from './buckets.js';
const watchers = new Map(); // bucketId → chokidar instance
@@ -56,6 +56,15 @@ export async function attachWatcher(bucketId) {
console.error(`❌ sharing.watcher: processManifest threw on change ${file}: ${err?.message || err}`);
}
});
+ w.on('unlink', async (path) => {
+ const file = basename(path);
+ if (!file.endsWith('.json')) return;
+ try {
+ await handleUnshare(bucketId, file);
+ } catch (err) {
+ console.error(`❌ sharing.watcher: handleUnshare threw for ${file}: ${err?.message || err}`);
+ }
+ });
w.on('error', (err) => {
console.error(`❌ sharing.watcher: bucket=${bucket.name} ${err?.message || err}`);
});
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index d612568a92..9b622ec769 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -31,6 +31,7 @@ import {
normalizeBibleName,
} from '../lib/storyBible.js';
import { sanitizeOrigin } from '../lib/sharingOrigin.js';
+import { emitRecordUpdated } from './sharing/recordEvents.js';
// Bumped when a sanitizer-time backfill changes how on-disk universes are
// shaped, so future migrations can gate on the prior version.
@@ -623,6 +624,7 @@ export async function updateUniverse(id, patch = {}) {
if (!merged) throw makeErr('Invalid universe payload', ERR_VALIDATION);
state.universes[idx] = merged;
await writeState(state);
+ emitRecordUpdated('universe', merged.id);
return merged;
}