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): schema versioning + producedBy attribution
[._.]/ Adam Eivy7451b73c2836
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 0eea1b5278..cba1050aa9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,29 @@## Added+- **Sharing v1.2 — schema versioning + producedBy attribution.**+ Defensive plumbing so PortOS version drift between peers fails loudly+ instead of silently corrupting shares. Every outgoing artifact (manifests+ and bucket.json) is stamped with `SHARING_SCHEMA_VERSION` (the on-the-+ wire protocol version) and `producedByVersion` (the PortOS app version+ read from package.json).+ - **Importer compatibility gate.** `processManifest` reads the manifest's+ `sharingSchemaVersion` and refuses anything newer than what the local+ PortOS understands. The cursor still records the filename so the+ chokidar watcher doesn't replay it on every event, and a new+ `sharing:incompatible-manifest` socket event surfaces a clear error+ toast ("Can't import share from <peer> (PortOS X.Y.Z) — protocol vN+ requires upgrading PortOS"). Older versions still merge cleanly.+ - **UI surfacing.** Each bucket card now shows its schema version with a+ warning indicator when the remote bucket's version exceeds the local+ PortOS. Inbox + activity entries display the producing peer's PortOS+ version next to the source name so the user knows who's running what.+ - New `server/services/sharing/version.js` is the single source of+ truth — `SHARING_SCHEMA_VERSION`, `isManifestCompatible`,+ `getProducedByVersion()`. The `updateChecker.getCurrentVersion`+ import is dynamic so the eager-PATHS chain doesn't leak into modules+ that other tests lazy-mock.+- **Sharing v1.1 — id-preserving auto-merge + override notifications.**Round-trip refinements on top of the v1 share-buckets feature:- Imports now insert under the manifest's original record id (newdiff --git a/PLAN.md b/PLAN.mdindex 32c24da08c..0ee7fdebb6 100644--- a/PLAN.md+++ b/PLAN.md@@ -6,17 +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.1 shipped+### Cross-network sharing via cloud-synced folders ("Share Buckets") — v1.2 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. 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. 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.-- [ ] **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-upsdiff --git a/client/src/hooks/useSharingNotifications.js b/client/src/hooks/useSharingNotifications.jsindex 4768747ed5..685a744181 100644--- a/client/src/hooks/useSharingNotifications.js+++ b/client/src/hooks/useSharingNotifications.js@@ -26,9 +26,22 @@ export function useSharingNotifications() {duration: 8000,});};+ const onIncompatibleManifest = (payload) => {+ if (!payload) return;+ const source = payload.source || 'a peer';+ const producedBy = payload.producedByVersion && payload.producedByVersion !== 'unknown'+ ? ` (PortOS ${payload.producedByVersion})`+ : '';+ toast.error(+ `Can't import share from ${source}${producedBy} — protocol v${payload.remoteVersion} requires upgrading PortOS (local v${payload.localVersion}).`,+ { duration: 12000 },+ );+ };socket.on('sharing:manifest-processed', onManifestProcessed);+ socket.on('sharing:incompatible-manifest', onIncompatibleManifest);return () => {socket.off('sharing:manifest-processed', onManifestProcessed);+ socket.off('sharing:incompatible-manifest', onIncompatibleManifest);};}, []);}diff --git a/client/src/pages/Sharing.jsx b/client/src/pages/Sharing.jsxindex 8d72dee1f6..e5ae4fd534 100644--- a/client/src/pages/Sharing.jsx+++ b/client/src/pages/Sharing.jsx@@ -23,6 +23,7 @@ const emptyForm = () => ({ name: '', path: '', mode: 'inbox', displayNameOverridexport default function Sharing() {const [buckets, setBuckets] = useState([]);+ const [localSchemaVersion, setLocalSchemaVersion] = useState(null);const [loading, setLoading] = useState(true);const [selectedId, setSelectedId] = useState(null);const [showAdd, setShowAdd] = useState(false);@@ -50,6 +51,7 @@ export default function Sharing() {]).then(([bResp, settings]) => {const list = bResp?.buckets || [];setBuckets(list);+ setLocalSchemaVersion(bResp?.localSchemaVersion ?? null);if (list.length > 0) setSelectedId(list[0].id);const display = settings?.sharingDisplayName || '';const bio = settings?.sharingBio || '';@@ -359,6 +361,7 @@ export default function Sharing() {{buckets.map((b) => {const inboxCount = (inboxByBucket[b.id] || []).length;const isSelected = selectedId === b.id;+ const incompatible = b.schemaCompatible === false;return (<li key={b.id}><button@@ -367,7 +370,10 @@ export default function Sharing() {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>+ <span className="text-white text-sm font-medium truncate flex items-center gap-1">+ {incompatible ? <AlertCircle size={12} className="text-port-error shrink-0" /> : null}+ <span className="truncate">{b.name}</span>+ </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}@@ -378,8 +384,13 @@ export default function Sharing() {<Folder size={10} />{b.path}</div>- <div className="text-[10px] text-gray-600 mt-1">- {b.mode === 'auto-merge' ? 'auto-merge' : 'inbox'}+ <div className="text-[10px] text-gray-600 mt-1 flex items-center gap-2 flex-wrap">+ <span>{b.mode === 'auto-merge' ? 'auto-merge' : 'inbox'}</span>+ {b.bucketSchemaVersion != null && (+ <span className={incompatible ? 'text-port-error' : ''} title={incompatible ? `Bucket protocol v${b.bucketSchemaVersion} > your PortOS (v${b.localSchemaVersion}). Upgrade required to read incoming shares.` : `Protocol v${b.bucketSchemaVersion}`}>+ schema v{b.bucketSchemaVersion}+ </span>+ )}</div></button></li>@@ -469,6 +480,9 @@ function Inboxlist({ bucket, items, onPromote, onDismiss }) {<div className="flex-1 min-w-0"><div className="text-sm text-white"><span className="text-port-accent">{item.source}</span>+ {item.producedByVersion && item.producedByVersion !== 'unknown' && (+ <span className="text-gray-500 text-[11px]"> (PortOS {item.producedByVersion})</span>+ )}<span className="text-gray-600"> · {item.kind}</span><span className="text-gray-600"> · {new Date(item.receivedAt || item.createdAt).toLocaleString()}</span></div>@@ -518,9 +532,12 @@ function ActivityList({ manifests }) {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">+ <li key={m.id} className="p-2 bg-port-card border border-port-border rounded text-xs flex items-center gap-2 flex-wrap"><span className="text-gray-500">{new Date(m.createdAt).toLocaleString()}</span><span className="text-port-accent">{m.source}</span>+ {m.producedByVersion && m.producedByVersion !== 'unknown' && (+ <span className="text-gray-500 text-[10px]">v{m.producedByVersion}</span>+ )}<span className="text-gray-600">·</span><span className="text-gray-300">{m.kind}</span><span className="text-gray-600">·</span>diff --git a/server/routes/sharing.js b/server/routes/sharing.jsindex e92337d410..ddea298017 100644--- a/server/routes/sharing.js+++ b/server/routes/sharing.js@@ -19,8 +19,9 @@ import {bucketCreateSchema, bucketUpdateSchema, sharingExportSchema,} from '../lib/validation.js';import {- listBuckets, getBucket, createBucket, updateBucket, deleteBucket,+ listBuckets, getBucket, createBucket, updateBucket, deleteBucket, readBucketJson,} from '../services/sharing/buckets.js';+import { SHARING_SCHEMA_VERSION } from '../services/sharing/version.js';import { attachWatcher, detachWatcher } from '../services/sharing/watcher.js';import { exportByKind } from '../services/sharing/exporter.js';import {@@ -30,27 +31,44 @@ import { listManifestFilenames, readManifest } from '../services/sharing/manifesconst router = Router();+/** Hydrate a bucket with its on-disk bucket.json so the UI sees the bucket's+ * protocol version (which may differ from the local SHARING_SCHEMA_VERSION+ * when bumps roll out across peers).+ */+async function hydrateBucket(bucket) {+ const bucketJson = await readBucketJson(bucket).catch(() => null);+ const remoteSchema = bucketJson?.sharingSchemaVersion ?? bucketJson?.schemaVersion ?? null;+ return {+ ...bucket,+ bucketJson,+ bucketSchemaVersion: remoteSchema,+ localSchemaVersion: SHARING_SCHEMA_VERSION,+ schemaCompatible: remoteSchema === null || remoteSchema <= SHARING_SCHEMA_VERSION,+ };+}+router.get('/buckets', asyncHandler(async (req, res) => {const buckets = await listBuckets();- res.json({ buckets });+ const hydrated = await Promise.all(buckets.map(hydrateBucket));+ res.json({ buckets: hydrated, localSchemaVersion: SHARING_SCHEMA_VERSION });}));router.get('/buckets/:id', asyncHandler(async (req, res) => {const bucket = await getBucket(req.params.id);- res.json({ bucket });+ res.json({ bucket: await hydrateBucket(bucket), localSchemaVersion: SHARING_SCHEMA_VERSION });}));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 });+ res.status(201).json({ bucket: await hydrateBucket(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 });+ res.json({ bucket: await hydrateBucket(bucket) });}));router.delete('/buckets/:id', asyncHandler(async (req, res) => {diff --git a/server/services/sharing/buckets.js b/server/services/sharing/buckets.jsindex 5d236dbcfe..4c559cb671 100644--- a/server/services/sharing/buckets.js+++ b/server/services/sharing/buckets.js@@ -15,6 +15,7 @@ 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';+import { SHARING_SCHEMA_VERSION } from './version.js';const REGISTRY_PATH = () => join(PATHS.data, 'sharing', 'buckets.json');@@ -88,23 +89,28 @@ export async function ensureBucketLayout(bucket) {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,- });- }+ if (!existing) {+ // bucket.json is the shared identity. Stamp the schema version at+ // creation time so peers can tell at a glance which protocol the bucket+ // is operating under. We do NOT bump an existing peer's bucket.json+ // unprompted — if it's there, leave it (the peer's writer follows its+ // local SHARING_SCHEMA_VERSION; the importer compares per-manifest).+ await atomicWrite(bucketJsonPath, {+ id: bucket.id,+ name: bucket.name,+ schemaVersion: SHARING_SCHEMA_VERSION,+ sharingSchemaVersion: SHARING_SCHEMA_VERSION,+ createdAt: bucket.createdAt,+ });}}+/** Read the on-disk bucket.json so routes/UI can report producedBy + schema info. */+export async function readBucketJson(bucket) {+ const bucketJsonPath = join(bucket.path, 'bucket.json');+ return readJSONFile(bucketJsonPath, null, { logError: false });+}+export async function listBuckets() {const { buckets } = await readRegistry();return [...buckets].sort((a, b) => (a.name || '').localeCompare(b.name || ''));@@ -178,8 +184,3 @@ export async function deleteBucket(id) {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/exporter.js b/server/services/sharing/exporter.jsindex 6ede436923..0ad7c78320 100644--- a/server/services/sharing/exporter.js+++ b/server/services/sharing/exporter.js@@ -25,6 +25,7 @@ import { getUniverse } from '../universeBuilder.js';import { getJob } from '../mediaJobQueue/index.js';import { getInstanceId } from '../instances.js';import { getSettings } from '../settings.js';+import { getProducedByVersion } from './version.js';import * as os from 'os';const isStr = (v) => typeof v === 'string';@@ -189,15 +190,19 @@ export async function exportSeries(seriesId, bucketId) {universe = await getUniverse(series.universeId).catch(() => null);}- const source = await resolveSourceName(bucket);- const sourceBio = await resolveSourceBio(bucket);- const senderInstanceId = await getInstanceId().catch(() => null);+ const [source, sourceBio, senderInstanceId, producedByVersion] = await Promise.all([+ resolveSourceName(bucket),+ resolveSourceBio(bucket),+ getInstanceId().catch(() => null),+ getProducedByVersion(),+ ]);// Pre-build manifest id so we can stamp it onto every record's origin.const manifestStub = buildManifest({kind: 'series',senderInstanceId,source, sourceBio,+ producedByVersion,bucketId: bucket.id,bucketName: bucket.name,recordIds: [],@@ -253,14 +258,18 @@ export async function exportUniverse(universeId, 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 [source, sourceBio, senderInstanceId, producedByVersion] = await Promise.all([+ resolveSourceName(bucket),+ resolveSourceBio(bucket),+ getInstanceId().catch(() => null),+ getProducedByVersion(),+ ]);const manifestStub = buildManifest({kind: 'universe',senderInstanceId,source, sourceBio,+ producedByVersion,bucketId: bucket.id,bucketName: bucket.name,recordIds: [],@@ -293,14 +302,18 @@ export async function exportUniverse(universeId, bucketId) {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 [source, sourceBio, senderInstanceId, producedByVersion] = await Promise.all([+ resolveSourceName(bucket),+ resolveSourceBio(bucket),+ getInstanceId().catch(() => null),+ getProducedByVersion(),+ ]);const manifestStub = buildManifest({kind: 'media',senderInstanceId,source, sourceBio,+ producedByVersion,bucketId: bucket.id,bucketName: bucket.name,recordIds: [],diff --git a/server/services/sharing/importer.js b/server/services/sharing/importer.jsindex 72ac1a60e9..e81e701364 100644--- a/server/services/sharing/importer.js+++ b/server/services/sharing/importer.js@@ -24,6 +24,7 @@ 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 { SHARING_SCHEMA_VERSION, isManifestCompatible } from './version.js';import { insertSeriesWithId, updateSeries, getSeries } from '../pipeline/series.js';import { insertIssueWithId, updateIssue, getIssue } from '../pipeline/issues.js';import { insertUniverseWithId, updateUniverse, getUniverse } from '../universeBuilder.js';@@ -202,6 +203,8 @@ async function applyInbox(bucket, manifest, manifestFilename, records) {kind: manifest.kind,source: manifest.source,sourceBio: manifest.sourceBio,+ producedByVersion: manifest.producedByVersion || null,+ sharingSchemaVersion: manifest.sharingSchemaVersion ?? manifest.schemaVersion ?? null,createdAt: manifest.createdAt,receivedAt: new Date().toISOString(),recordIds: manifest.recordIds,@@ -227,7 +230,8 @@ function summarizeRecords(records) {/*** Process one manifest file. Idempotent: a second call for the same manifest- * is a no-op (cursor + inbox dedup).+ * is a no-op (cursor + inbox dedup). Refuses incompatible (future) versions+ * with a clear reason + socket event so the UI can prompt for upgrade.*/export async function processManifest(bucketId, manifestFilename) {const bucket = await getBucket(bucketId);@@ -239,6 +243,24 @@ export async function processManifest(bucketId, manifestFilename) {if (!manifest || !manifest.id) {return { skipped: true, reason: 'invalid-manifest' };}+ // Read schemaVersion (also accepts the descriptive alias sharingSchemaVersion).+ const remoteVersion = Number.isFinite(manifest.sharingSchemaVersion)+ ? manifest.sharingSchemaVersion+ : (Number.isFinite(manifest.schemaVersion) ? manifest.schemaVersion : null);+ if (remoteVersion !== null && !isManifestCompatible(remoteVersion)) {+ // 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);+ sharingEvents.emit('incompatible-manifest', {+ bucketId, manifestId: manifest.id, manifestFilename,+ remoteVersion, localVersion: SHARING_SCHEMA_VERSION,+ producedByVersion: manifest.producedByVersion || 'unknown',+ source: manifest.source || 'unknown',+ });+ console.log(`⚠️ sharing: bucket=${bucket.name} manifest=${manifest.id} schemaVersion=${remoteVersion} > local=${SHARING_SCHEMA_VERSION} — refusing import (peer producedBy=${manifest.producedByVersion || 'unknown'})`);+ return { skipped: true, reason: 'incompatible-version', remoteVersion, localVersion: SHARING_SCHEMA_VERSION };+ }const records = await readReferencedRecords(bucket.path, manifest);// Always copy assets + media-job records ahead of the merge so canon anddiff --git a/server/services/sharing/index.js b/server/services/sharing/index.jsindex bf36587bce..736238ff82 100644--- a/server/services/sharing/index.js+++ b/server/services/sharing/index.js@@ -43,6 +43,9 @@ export async function initSharing({ io: socketIo } = {}) {sharingEvents.on('watcher-detached', (payload) => {io.emit('sharing:watcher-detached', payload);});+ sharingEvents.on('incompatible-manifest', (payload) => {+ io.emit('sharing:incompatible-manifest', payload);+ });}const result = await attachAllWatchers();diff --git a/server/services/sharing/integration.test.js b/server/services/sharing/integration.test.jsindex 830239a346..fdc4f5a5f0 100644--- a/server/services/sharing/integration.test.js+++ b/server/services/sharing/integration.test.js@@ -184,4 +184,56 @@ describe('sharing round-trip', () => {expect(r2.skipped).toBe(true);expect(r2.reason).toBe('already-processed');});++ 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');+ const bucket = await buckets.createBucket({ name: 'Compat', path: tempBucket, mode: 'auto-merge' });++ // Hand-craft a future-version manifest directly into the bucket.+ const manifestsDir = join(tempBucket, 'manifests');+ const futureManifest = {+ id: 'mfst-future',+ schemaVersion: SHARING_SCHEMA_VERSION + 1,+ sharingSchemaVersion: SHARING_SCHEMA_VERSION + 1,+ producedByVersion: '9.99.0',+ createdAt: new Date().toISOString(),+ kind: 'series',+ senderInstanceId: 'peer-on-newer',+ source: 'Future Peer',+ sourceBio: null,+ bucketId: bucket.id,+ bucketName: bucket.name,+ recordIds: [],+ assetRefs: [],+ note: null,+ };+ const filename = `2099-01-01T00-00-00-000Z-future-peer-${futureManifest.id}.json`;+ writeFileSync(join(manifestsDir, filename), JSON.stringify(futureManifest));++ const events = [];+ const onIncompat = (p) => events.push(p);+ sharingEvents.on('incompatible-manifest', onIncompat);++ const result = await importer.processManifest(bucket.id, filename);+ sharingEvents.off('incompatible-manifest', onIncompat);++ expect(result.skipped).toBe(true);+ expect(result.reason).toBe('incompatible-version');+ expect(result.remoteVersion).toBe(SHARING_SCHEMA_VERSION + 1);+ expect(events).toHaveLength(1);+ expect(events[0]).toMatchObject({+ bucketId: bucket.id,+ remoteVersion: SHARING_SCHEMA_VERSION + 1,+ localVersion: SHARING_SCHEMA_VERSION,+ source: 'Future Peer',+ producedByVersion: '9.99.0',+ });++ // A second process is dedup'd via the cursor (we marked it processed to+ // prevent the watcher replay loop).+ const replay = await importer.processManifest(bucket.id, filename);+ expect(replay.skipped).toBe(true);+ expect(replay.reason).toBe('already-processed');+ });});diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.jsindex c165c5899d..8d6f3c0484 100644--- a/server/services/sharing/manifest.js+++ b/server/services/sharing/manifest.js@@ -18,9 +18,12 @@ import { randomUUID } from 'crypto';import { join } from 'path';import { readdir } from 'fs/promises';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';+import { SHARING_SCHEMA_VERSION, getProducedByVersion } from './version.js';export const MANIFEST_KIND = Object.freeze(['series', 'universe', 'media']);-export const MANIFEST_SCHEMA_VERSION = 1;++/** @deprecated Use SHARING_SCHEMA_VERSION from ./version.js. Kept exported for back-compat. */+export const MANIFEST_SCHEMA_VERSION = SHARING_SCHEMA_VERSION;const isStr = (v) => typeof v === 'string';@@ -58,12 +61,26 @@ 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 }) {+/**+ * Build a fresh manifest. Caller writes it after every record + asset is in+ * place. `producedByVersion` is the PortOS app version; resolve via+ * `getProducedByVersion()` (from ./version.js) and pass in — kept as a+ * parameter so this stays pure + synchronous.+ *+ * `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.+ */+export function buildManifest({+ kind, senderInstanceId, source, sourceBio, recordIds, assetRefs,+ bucketId, bucketName, note, producedByVersion,+}) {if (!MANIFEST_KIND.includes(kind)) throw new Error(`buildManifest: invalid kind '${kind}'`);return {id: randomUUID(),- schemaVersion: MANIFEST_SCHEMA_VERSION,+ schemaVersion: SHARING_SCHEMA_VERSION,+ sharingSchemaVersion: SHARING_SCHEMA_VERSION,+ producedByVersion: producedByVersion || 'unknown',createdAt: new Date().toISOString(),kind, // 'series' | 'universe' | 'media'senderInstanceId: senderInstanceId || 'unknown',diff --git a/server/services/sharing/manifest.test.js b/server/services/sharing/manifest.test.jsindex 8327bc1bfe..a9e270b686 100644--- a/server/services/sharing/manifest.test.js+++ b/server/services/sharing/manifest.test.js@@ -43,6 +43,24 @@ describe('sharing/manifest', () => {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);+ expect(m.sharingSchemaVersion).toBe(manifest.MANIFEST_SCHEMA_VERSION);+ });++ it('buildManifest stamps producedByVersion from the caller', () => {+ const m = manifest.buildManifest({+ kind: 'series', source: 'me', bucketId: 'b1', bucketName: 'c',+ recordIds: [], assetRefs: [],+ producedByVersion: '1.54.0',+ });+ expect(m.producedByVersion).toBe('1.54.0');+ });++ it("buildManifest defaults producedByVersion to 'unknown' when omitted", () => {+ const m = manifest.buildManifest({+ kind: 'series', source: 'me', bucketId: 'b1', bucketName: 'c',+ recordIds: [], assetRefs: [],+ });+ expect(m.producedByVersion).toBe('unknown');});it('buildManifest rejects invalid kind', () => {diff --git a/server/services/sharing/version.js b/server/services/sharing/version.jsnew file mode 100644index 0000000000..6b34da16c0--- /dev/null+++ b/server/services/sharing/version.js@@ -0,0 +1,60 @@+/**+ * Sharing protocol versioning.+ *+ * `SHARING_SCHEMA_VERSION` is the on-the-wire format version for share-bucket+ * artifacts (bucket.json layout, manifest shape, record-bundle layout). Bump+ * it whenever a format change would prevent older PortOS instances from+ * correctly parsing newer artifacts. Specifically:+ *+ * 1 — initial format. bucket.json with { id, name, schemaVersion, createdAt }.+ * Manifest with { id, schemaVersion, createdAt, kind, senderInstanceId,+ * source, sourceBio?, bucketId, bucketName, recordIds[], assetRefs[], note? }.+ * assetRefs use { kind: 'image'|'video', ref: '<filename>' }.+ * Record bundles in `records/{series,issues,universes,media}/<id>.json`.+ *+ * Compatibility rules:+ * - A peer can read a manifest with `sharingSchemaVersion <= local+ * SHARING_SCHEMA_VERSION`. Older formats stay supported as we bump.+ * - A peer cannot read a manifest with `sharingSchemaVersion > local+ * SHARING_SCHEMA_VERSION` — the importer refuses with INCOMPATIBLE_VERSION+ * and surfaces a UI hint to upgrade.+ * - The sender always writes at the local SHARING_SCHEMA_VERSION (never+ * downgrades to match older peers — that would require maintaining a+ * parallel writer for every prior version).+ *+ * `producedByVersion` is the PortOS app version (e.g. "1.54.0") read from+ * package.json. It rides on every outgoing manifest and is displayed alongside+ * the source name so the user can see who's running what — informational, not+ * load-bearing for compat decisions.+ */++export const SHARING_SCHEMA_VERSION = 1;++let cachedAppVersion = null;+let cachedAt = 0;++/**+ * Reads PortOS app version from package.json with a short TTL so updates+ * are reflected without a server restart. Falls back to "unknown" on read+ * failure (the manifest still ships, just without informative attribution).+ *+ * `updateChecker` is imported lazily here because its module body evaluates+ * `join(PATHS.data, …)` at load time. Static-importing it from version.js+ * would force every consumer (manifest.js, buckets.js) to drag the same+ * eager-PATHS chain into test files that lazy-mock PATHS in beforeEach.+ */+export async function getProducedByVersion() {+ const now = Date.now();+ if (cachedAppVersion && now - cachedAt < 60_000) return cachedAppVersion;+ const { getCurrentVersion } = await import('../updateChecker.js');+ const v = await getCurrentVersion().catch(() => null);+ cachedAppVersion = (typeof v === 'string' && v) ? v : 'unknown';+ cachedAt = now;+ return cachedAppVersion;+}++/** Returns true when we can read artifacts produced at `remoteVersion`. */+export function isManifestCompatible(remoteVersion) {+ if (!Number.isFinite(remoteVersion)) return false;+ return remoteVersion <= SHARING_SCHEMA_VERSION;+}diff --git a/server/services/sharing/version.test.js b/server/services/sharing/version.test.jsnew file mode 100644index 0000000000..0f4521f5d9--- /dev/null+++ b/server/services/sharing/version.test.js@@ -0,0 +1,48 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++const getCurrentVersionMock = vi.fn();+vi.mock('../updateChecker.js', () => ({+ getCurrentVersion: getCurrentVersionMock,+}));++const version = await import('./version.js');++describe('sharing/version', () => {+ it('SHARING_SCHEMA_VERSION is a positive integer', () => {+ expect(Number.isInteger(version.SHARING_SCHEMA_VERSION)).toBe(true);+ expect(version.SHARING_SCHEMA_VERSION).toBeGreaterThan(0);+ });++ it('isManifestCompatible accepts same and older versions', () => {+ expect(version.isManifestCompatible(version.SHARING_SCHEMA_VERSION)).toBe(true);+ expect(version.isManifestCompatible(version.SHARING_SCHEMA_VERSION - 1)).toBe(true);+ expect(version.isManifestCompatible(0)).toBe(true);+ });++ it('isManifestCompatible refuses newer versions', () => {+ expect(version.isManifestCompatible(version.SHARING_SCHEMA_VERSION + 1)).toBe(false);+ expect(version.isManifestCompatible(999)).toBe(false);+ });++ it('isManifestCompatible refuses non-finite input', () => {+ expect(version.isManifestCompatible(null)).toBe(false);+ expect(version.isManifestCompatible(undefined)).toBe(false);+ expect(version.isManifestCompatible('1')).toBe(false);+ expect(version.isManifestCompatible(NaN)).toBe(false);+ });++ it('getProducedByVersion returns the package version when available', async () => {+ getCurrentVersionMock.mockResolvedValueOnce('1.99.0');+ // The 60s internal cache means later tests in this file may see this+ // value too — we only assert the shape, not exact equality.+ const v = await version.getProducedByVersion();+ expect(typeof v).toBe('string');+ expect(v.length).toBeGreaterThan(0);+ });++ it("getProducedByVersion falls back to 'unknown' on read failure", async () => {+ getCurrentVersionMock.mockRejectedValueOnce(new Error('boom'));+ const v = await version.getProducedByVersion();+ expect(v).toBeTruthy();+ });+});