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): manifest archive pruning per bucket
[._.]/ Adam Eivy7bb6e6b1a48c
diff --git a/DONE.md b/DONE.mdindex b57ba98379..9865693ef0 100644--- a/DONE.md+++ b/DONE.md@@ -6,6 +6,8 @@ Archive of completed work. For active roadmap, see [PLAN.md](./PLAN.md). For pro## 2026-05-16+- **Sharing — manifest archive pruning** — Long-lived buckets no longer accumulate thousands of manifest JSONs under `<bucket>/manifests/`. New `pruneBucketManifests(bucket, { maxManifests = 500, localInstanceId })` in `server/services/sharing/manifest.js` moves owned (this-instance-authored) one-shot manifests in excess of the cap into `<bucket>/.archive/manifests/` (oldest first by ISO-prefixed filename). Subscription manifests (`sub-*.json`) and peer-authored manifests are exempt — only the author of a manifest can confidently say it's superseded, and a cross-peer delete would replicate as an unshare. Wired in via a `pruneAfterExport` helper called from `exportSeries` / `exportUniverse` / `exportMedia`, plus a one-shot prune in `attachAllWatchers` on boot to catch up long-running peers. The watcher's `unlink` handler consults a new `isManifestPruning(bucketId, filename)` marker so our own archive renames don't trip `handleUnshare` (the marker is held ~5s, unref'd from the event loop). Classification reads run in bounded-concurrency batches of 32 to avoid `EMFILE` on multi-thousand-manifest buckets; archive renames run in parallel. 6 new tests in `manifest.test.js` cover under-cap noop, oldest-excess archival, subscription exemption, foreign-peer exemption, unknown-instance noop, and the pruning-in-flight marker.+- **Sharing display-name settings — discoverable from the Settings tab structure** — New `client/src/components/settings/SharingTab.jsx` mirrors the display-name + bio strip from the Sharing page top so users can find the source-attribution fields under `/settings/sharing` as well. Standalone tab uses a vertical card layout with a textarea (not single-line input) for the 2000-char bio. Wired into `client/src/pages/Settings.jsx` TABS + switch, sidebar in `client/src/components/Layout.jsx`, and `server/lib/navManifest.js` (`nav.settings.sharing`) so it's reachable from sidebar, `⌘K`, and voice. The existing Sharing page top strip stays in place — both surfaces hit the same `sharingDisplayName` / `sharingBio` settings keys.## 2026-05-12diff --git a/PLAN.md b/PLAN.mdindex 42ab074633..0846e0c3ab 100644--- a/PLAN.md+++ b/PLAN.md@@ -10,7 +10,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]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). V1.4: collection-aware universe shares — `mediaCollections.universeId` field links a collection to its parent universe, exporter bundles the collection (record + items + assets + media-job records) when a universe is shared, importer find-or-creates the local collection and unions the items in, item-add/remove emits `recordEvents` on the linked universe so subscriptions auto-re-export when peer adds new images. See `~/.claude/plans/new-high-priority-task-valiant-wall.md` for design. Remaining follow-ups:-- [ ] **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 + 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."diff --git a/server/services/sharing/exporter.js b/server/services/sharing/exporter.jsindex 3b6e66a463..84b0dcea32 100644--- a/server/services/sharing/exporter.js+++ b/server/services/sharing/exporter.js@@ -18,7 +18,7 @@ import { copyFile, readFile, writeFile, stat } from 'fs/promises';import { existsSync } from 'fs';import { PATHS, ensureDir, atomicWrite, readJSONFile } from '../../lib/fileUtils.js';import { getBucket, ensureBucketLayout } from './buckets.js';-import { buildManifest, writeManifest } from './manifest.js';+import { buildManifest, writeManifest, pruneBucketManifests } from './manifest.js';import { listSeries, getSeries } from '../pipeline/series.js';import { listIssues } from '../pipeline/issues.js';import { getUniverse } from '../universeBuilder.js';@@ -40,6 +40,18 @@ async function resolveSourceName(bucket) {return os.userInfo().username || 'unknown';}+/**+ * Best-effort cap on the bucket's manifest directory after each export.+ * Subscription manifests + peer-authored manifests are exempt — see+ * `pruneBucketManifests` for the policy. Failures are logged + swallowed+ * so the export response isn't blocked on an archive miss.+ */+async function pruneAfterExport(bucket, senderInstanceId) {+ await pruneBucketManifests(bucket, { localInstanceId: senderInstanceId }).catch((err) => {+ console.log(`⚠️ sharing.exporter: pruneBucketManifests failed for bucket=${bucket.name}: ${err.message}`);+ });+}+async function resolveSourceBio(bucket) {if (bucket.bioOverride) return bucket.bioOverride;const settings = await getSettings().catch(() => ({}));@@ -315,6 +327,7 @@ export async function exportSeries(seriesId, bucketId, opts = {}) {const manifest = { ...manifestStub, recordIds, assetRefs };const filename = await writeManifest(bucket.path, manifest);+ await pruneAfterExport(bucket, senderInstanceId);return { manifestId, filename, recordCount: recordIds.length, assetCount: assetRefs.length };}@@ -372,6 +385,7 @@ export async function exportUniverse(universeId, bucketId, opts = {}) {const manifest = { ...manifestStub, recordIds: [universe.id], assetRefs };const filename = await writeManifest(bucket.path, manifest);+ await pruneAfterExport(bucket, senderInstanceId);return { manifestId, filename, recordCount: 1, assetCount: assetRefs.length };}@@ -424,6 +438,7 @@ export async function exportMedia(items, bucketId) {const manifest = { ...manifestStub, recordIds, assetRefs };const filename = await writeManifest(bucket.path, manifest);+ await pruneAfterExport(bucket, senderInstanceId);return { manifestId, filename, recordCount: recordIds.length, assetCount: assetRefs.length };}diff --git a/server/services/sharing/manifest.js b/server/services/sharing/manifest.jsindex fb28088ed5..8084ff0945 100644--- a/server/services/sharing/manifest.js+++ b/server/services/sharing/manifest.js@@ -16,7 +16,7 @@import { randomUUID } from 'crypto';import { join } from 'path';-import { readdir } from 'fs/promises';+import { readdir, rename } from 'fs/promises';import { PATHS, atomicWrite, readJSONFile, ensureDir } from '../../lib/fileUtils.js';import { SHARING_SCHEMA_VERSION, getProducedByVersion } from './version.js';import { isStr } from '../../lib/storyBible.js';@@ -214,3 +214,123 @@ export async function listManifestFilenames(bucketPath) {const entries = await readdir(dir).catch(() => []);return entries.filter((f) => f.endsWith('.json')).sort().reverse();}++/**+ * Default retention cap per bucket per local instance. A long-lived bucket+ * accumulates one manifest per share action, so capping owned manifests at+ * 500 keeps disk + cloud-sync chatter bounded while preserving enough recent+ * history for "did I share this?" forensics in `/sharing/:id/activity`.+ */+export const DEFAULT_MANIFEST_RETENTION = 500;++/**+ * Filenames currently being moved into `<bucket>/.archive/manifests/` by the+ * pruner. The watcher consults this set so its `unlink` handler can skip+ * `handleUnshare` for our own archive moves — those would otherwise reset+ * cursor entries and emit a misleading "peer unshared" socket event.+ *+ * Held for ~5s after each rename to outlast chokidar's awaitWriteFinish+ * debounce; the entry is unref'd from the event loop so it never blocks+ * shutdown.+ */+const pruningInFlight = new Map();++export function isManifestPruning(bucketId, filename) {+ return pruningInFlight.get(bucketId)?.has(filename) || false;+}++function markPruning(bucketId, filename) {+ let set = pruningInFlight.get(bucketId);+ if (!set) {+ set = new Set();+ pruningInFlight.set(bucketId, set);+ }+ set.add(filename);+}++function scheduleUnmark(bucketId, filename, delayMs = 5000) {+ const t = setTimeout(() => {+ const set = pruningInFlight.get(bucketId);+ if (!set) return;+ set.delete(filename);+ if (set.size === 0) pruningInFlight.delete(bucketId);+ }, delayMs);+ t.unref?.();+}++// Cap concurrent readManifest fd usage during classification — long-lived+// buckets can hold thousands of manifests, and `EMFILE: too many open files`+// is real on macOS defaults if we Promise.all the whole list.+const CLASSIFY_CONCURRENCY = 32;++/**+ * Archive older one-shot manifests authored by `localInstanceId` so a bucket+ * that lives long enough does not accumulate manifests indefinitely.+ *+ * Rules:+ * - Subscription manifests (`sub-*.json`) are never archived — they own a+ * deterministic filename per (recordKind, recordId) so older ones don't+ * accumulate, and removing one would replicate as an unshare to peers.+ * - Manifests authored by other peers are never archived — only the author+ * of a manifest knows whether it's been superseded, and a cross-peer+ * delete would replicate as an unshare on the originating peer.+ * - Owned one-shot manifests in excess of `maxManifests` are moved (oldest+ * first by ISO-prefixed filename) into `<bucket>/.archive/manifests/`.+ *+ * Returns `{ archived, kept, ownedTotal, skippedForeign, skippedReason }`.+ * When `localInstanceId` is missing or 'unknown', returns a noop result with+ * `skippedReason` set — we never blanket-archive without an author check.+ */+export async function pruneBucketManifests(bucket, opts = {}) {+ const maxManifests = Number.isFinite(opts.maxManifests)+ ? Math.max(0, opts.maxManifests)+ : DEFAULT_MANIFEST_RETENTION;+ const localInstanceId = opts.localInstanceId;+ if (!localInstanceId || localInstanceId === 'unknown') {+ return { archived: 0, kept: 0, ownedTotal: 0, skippedForeign: 0, skippedReason: 'no-local-instance-id' };+ }+ const manifestsDir = join(bucket.path, 'manifests');+ const entries = await readdir(manifestsDir).catch(() => []);+ const candidates = entries+ .filter((f) => f.endsWith('.json') && !f.startsWith('sub-'))+ .sort();+ // Fast path: if the total candidate count is at or below the cap, no read+ // of any manifest is necessary — owned count cannot exceed total.+ if (candidates.length <= maxManifests) {+ return { archived: 0, kept: candidates.length, ownedTotal: candidates.length, skippedForeign: 0, skippedReason: null };+ }+ // Classify in bounded-concurrency batches so a bucket with thousands of+ // manifests doesn't exhaust file descriptors.+ const owned = [];+ let skippedForeign = 0;+ for (let i = 0; i < candidates.length; i += CLASSIFY_CONCURRENCY) {+ const batch = candidates.slice(i, i + CLASSIFY_CONCURRENCY);+ const reads = await Promise.all(batch.map((filename) => readManifest(bucket.path, filename).catch(() => null)));+ for (let j = 0; j < batch.length; j++) {+ const m = reads[j];+ if (!m) continue;+ if (m.senderInstanceId === localInstanceId) owned.push(batch[j]);+ else skippedForeign += 1;+ }+ }+ if (owned.length <= maxManifests) {+ return { archived: 0, kept: owned.length, ownedTotal: owned.length, skippedForeign, skippedReason: null };+ }+ const archiveDir = join(bucket.path, '.archive', 'manifests');+ await ensureDir(archiveDir);+ const toArchive = owned.slice(0, owned.length - maxManifests);+ for (const filename of toArchive) markPruning(bucket.id, filename);+ const renames = await Promise.all(toArchive.map(async (filename) => {+ try {+ await rename(join(manifestsDir, filename), join(archiveDir, filename));+ return true;+ } catch (err) {+ console.log(`⚠️ sharing.manifest: archive failed for ${filename}: ${err.message}`);+ return false;+ } finally {+ scheduleUnmark(bucket.id, filename);+ }+ }));+ const archived = renames.filter(Boolean).length;+ return { archived, kept: maxManifests, ownedTotal: owned.length, skippedForeign, skippedReason: null };+}diff --git a/server/services/sharing/manifest.test.js b/server/services/sharing/manifest.test.jsindex 5773e51e84..8997e054d1 100644--- a/server/services/sharing/manifest.test.js+++ b/server/services/sharing/manifest.test.js@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest';-import { mkdtempSync, rmSync } from 'fs';+import { mkdtempSync, rmSync, existsSync, writeFileSync, readdirSync, mkdirSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';import { vi } from 'vitest';@@ -118,6 +118,128 @@ describe('sharing/manifest', () => {expect(manifest.hasBeenProcessed(c, 'sub-universe-abc.json', 'mfst-1')).toBe(false);});+ describe('pruneBucketManifests', () => {+ let bucketRoot;++ function makeBucket(id = 'bkt-1') {+ bucketRoot = mkdtempSync(join(tmpdir(), 'portos-prune-bucket-'));+ // pruneBucketManifests does not create the manifests/ dir —+ // ensureBucketLayout already does. Mirror that here.+ mkdirSync(join(bucketRoot, 'manifests'), { recursive: true });+ return { id, name: 'Test', path: bucketRoot };+ }++ function writeOwnedManifest(bucketPath, name, { sender = 'me', createdAt }) {+ const stub = manifest.buildManifest({+ kind: 'series',+ senderInstanceId: sender,+ source: 'me',+ bucketId: 'bkt-1',+ bucketName: 'T',+ recordIds: [],+ assetRefs: [],+ producedByVersion: '1.0.0',+ });+ if (createdAt) stub.createdAt = createdAt;+ writeFileSync(join(bucketPath, 'manifests', name), JSON.stringify(stub));+ }++ afterEach(() => {+ if (bucketRoot) {+ rmSync(bucketRoot, { recursive: true, force: true });+ bucketRoot = null;+ }+ });++ it('noops when total candidates are under the cap', async () => {+ const bucket = makeBucket();+ writeOwnedManifest(bucket.path, '2024-01-01T00-00-00-000Z-me-a.json', { sender: 'me' });+ writeOwnedManifest(bucket.path, '2024-01-02T00-00-00-000Z-me-b.json', { sender: 'me' });+ const r = await manifest.pruneBucketManifests(bucket, { maxManifests: 10, localInstanceId: 'me' });+ expect(r.archived).toBe(0);+ expect(readdirSync(join(bucket.path, 'manifests'))).toHaveLength(2);+ expect(existsSync(join(bucket.path, '.archive'))).toBe(false);+ });++ it('archives only the oldest owned excess into .archive/manifests/', async () => {+ const bucket = makeBucket();+ // 5 owned manifests, cap at 2 → archive 3 oldest.+ for (let i = 0; i < 5; i++) {+ writeOwnedManifest(bucket.path, `2024-01-0${i + 1}T00-00-00-000Z-me-${i}.json`, { sender: 'me' });+ }+ const r = await manifest.pruneBucketManifests(bucket, { maxManifests: 2, localInstanceId: 'me' });+ expect(r.archived).toBe(3);+ expect(r.kept).toBe(2);+ expect(r.ownedTotal).toBe(5);+ const active = readdirSync(join(bucket.path, 'manifests'));+ expect(active.sort()).toEqual([+ '2024-01-04T00-00-00-000Z-me-3.json',+ '2024-01-05T00-00-00-000Z-me-4.json',+ ]);+ const archived = readdirSync(join(bucket.path, '.archive', 'manifests'));+ expect(archived.sort()).toEqual([+ '2024-01-01T00-00-00-000Z-me-0.json',+ '2024-01-02T00-00-00-000Z-me-1.json',+ '2024-01-03T00-00-00-000Z-me-2.json',+ ]);+ });++ it('never archives subscription manifests (sub-* filename) even when over cap', async () => {+ const bucket = makeBucket();+ writeOwnedManifest(bucket.path, 'sub-universe-uni-1.json', { sender: 'me' });+ writeOwnedManifest(bucket.path, 'sub-universe-uni-2.json', { sender: 'me' });+ writeOwnedManifest(bucket.path, '2024-01-01T00-00-00-000Z-me-old.json', { sender: 'me' });+ const r = await manifest.pruneBucketManifests(bucket, { maxManifests: 0, localInstanceId: 'me' });+ // 1 owned non-subscription manifest exceeds the cap → archived.+ expect(r.archived).toBe(1);+ const active = readdirSync(join(bucket.path, 'manifests')).sort();+ // Subscription manifests preserved.+ expect(active).toContain('sub-universe-uni-1.json');+ expect(active).toContain('sub-universe-uni-2.json');+ expect(active).not.toContain('2024-01-01T00-00-00-000Z-me-old.json');+ });++ it('never archives manifests authored by other peers', async () => {+ const bucket = makeBucket();+ writeOwnedManifest(bucket.path, '2024-01-01T00-00-00-000Z-other-old.json', { sender: 'peer-A' });+ writeOwnedManifest(bucket.path, '2024-01-02T00-00-00-000Z-me-a.json', { sender: 'me' });+ writeOwnedManifest(bucket.path, '2024-01-03T00-00-00-000Z-me-b.json', { sender: 'me' });+ const r = await manifest.pruneBucketManifests(bucket, { maxManifests: 1, localInstanceId: 'me' });+ expect(r.archived).toBe(1);+ expect(r.skippedForeign).toBe(1);+ const active = readdirSync(join(bucket.path, 'manifests')).sort();+ // Foreign manifest stays put; oldest owned moves to archive.+ expect(active).toContain('2024-01-01T00-00-00-000Z-other-old.json');+ expect(active).toContain('2024-01-03T00-00-00-000Z-me-b.json');+ expect(active).not.toContain('2024-01-02T00-00-00-000Z-me-a.json');+ });++ it('is a noop when localInstanceId is missing or unknown', async () => {+ const bucket = makeBucket();+ for (let i = 0; i < 3; i++) {+ writeOwnedManifest(bucket.path, `2024-01-0${i + 1}T00-00-00-000Z-me-${i}.json`, { sender: 'me' });+ }+ const r1 = await manifest.pruneBucketManifests(bucket, { maxManifests: 0 });+ const r2 = await manifest.pruneBucketManifests(bucket, { maxManifests: 0, localInstanceId: 'unknown' });+ expect(r1.archived).toBe(0);+ expect(r2.archived).toBe(0);+ expect(r1.skippedReason).toBe('no-local-instance-id');+ expect(readdirSync(join(bucket.path, 'manifests'))).toHaveLength(3);+ });++ it('marks archived filenames as pruning-in-flight to suppress watcher unshare events', async () => {+ const bucket = makeBucket();+ writeOwnedManifest(bucket.path, '2024-01-01T00-00-00-000Z-me-a.json', { sender: 'me' });+ writeOwnedManifest(bucket.path, '2024-01-02T00-00-00-000Z-me-b.json', { sender: 'me' });+ // Run prune but don't await the 5s unmark timer — check the marker+ // exists immediately after the rename.+ await manifest.pruneBucketManifests(bucket, { maxManifests: 1, localInstanceId: 'me' });+ expect(manifest.isManifestPruning(bucket.id, '2024-01-01T00-00-00-000Z-me-a.json')).toBe(true);+ // Filenames not archived are not marked.+ expect(manifest.isManifestPruning(bucket.id, '2024-01-02T00-00-00-000Z-me-b.json')).toBe(false);+ });+ });+it('manifestFilename is deterministic when subscription is set', () => {const m = manifest.buildManifest({kind: 'universe', source: 'me', bucketId: 'b1', bucketName: 'c',diff --git a/server/services/sharing/watcher.js b/server/services/sharing/watcher.jsindex cf2255efee..5d33bb30e6 100644--- a/server/services/sharing/watcher.js+++ b/server/services/sharing/watcher.js@@ -18,6 +18,8 @@ import { watch } from 'chokidar';import { join, basename } from 'path';import { processManifest, processBacklog, handleUnshare, sharingEvents } from './importer.js';import { getBucket, listBuckets, ensureBucketLayout } from './buckets.js';+import { isManifestPruning, pruneBucketManifests } from './manifest.js';+import { getInstanceId } from '../instances.js';const watchers = new Map(); // bucketId → chokidar instanceconst backlogQueues = new Map(); // bucketId → { running: Promise, queued: Promise|null }@@ -106,6 +108,10 @@ export async function attachWatcher(bucketId) {if (!path.includes(`${manifestsDir}/`)) return;const file = basename(path);if (!file.endsWith('.json')) return;+ // Our own pruner moves stale manifests into `<bucket>/.archive/manifests/`;+ // skip the resulting unlink so we don't reset our cursor or emit a+ // misleading "peer unshared" socket event for an archive we initiated.+ if (isManifestPruning(bucketId, file)) return;try {await handleUnshare(bucketId, file);} catch (err) {@@ -131,6 +137,7 @@ export async function detachWatcher(bucketId) {export async function attachAllWatchers() {const buckets = await listBuckets();+ const localInstanceId = await getInstanceId().catch(() => null);for (const b of buckets) {await attachWatcher(b.id).catch((err) => {console.error(`❌ sharing.watcher: failed to attach bucket=${b.name}: ${err.message}`);@@ -139,6 +146,13 @@ export async function attachAllWatchers() {await processBacklog(b.id).catch((err) => {console.error(`❌ sharing.watcher: backlog process failed bucket=${b.name}: ${err.message}`);});+ // One-shot prune on boot: handles long-lived buckets where this instance+ // rarely exports (post-export prune wouldn't fire often enough).+ if (localInstanceId) {+ await pruneBucketManifests(b, { localInstanceId }).catch((err) => {+ console.error(`❌ sharing.watcher: prune failed bucket=${b.name}: ${err.message}`);+ });+ }}return { attached: watchers.size };}