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

address review: HTTPS streaming cap + tombstoned-parent collection filter

Adam Eivya4654d86587a
diff --git a/PLAN.md b/PLAN.md
index 68e95a39db..980615ad53 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -26,7 +26,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
- [ ] [peer-sync-ephemeralize-then-delete-stalls-tombstone] **A previously-shared universe/series that's marked ephemeral, then deleted, never propagates the tombstone when the peer still has other subscriptions of that kind.** Codex iter-8 in v2.7.0 release review (P2). The ephemeralize step's `unsubscribeAllForRecord` removes the per-record sub for that record; the subsequent delete fires `recordEvents.deleted` but there's no sub to push it. The snapshot path in `syncOrchestrator.categoriesCoveredByPeerSync` then suppresses the whole-category snapshot for that peer (because ANY other per-record sub for that kind exists), so the tombstone has no fallback transport either. The peer keeps the old live copy indefinitely. Same root cause as `[peer-sync-snapshot-skip-too-coarse-for-partial-subscriptions]` — the snapshot-skip fix needs to either send the snapshot with subscribed records excluded (so tombstones for unsubscribed-but-previously-known records can still ride it), or detect the ephemeralize-then-delete sequence and proactively push the tombstone before tearing down the sub.
- [ ] [peer-sync-per-record-tombstone-ack-cursor] **Tombstone ack cursor is per-peer but should be per-(peer,record).** Codex iter-6 in v2.7.0 release review (P2). Today `ackDeletesUpTo(peerId, deletedAt)` writes a single high-water-mark per peer. If push for record-A fails and a later push for record-B succeeds, the receiver returns `ackedDeletesUpTo = B.deletedAt > A.deletedAt`; the sender then advances the cursor past A's deletedAt even though A was never confirmed delivered. After grace, `tombstoneGc` treats A as acked, prunes it, and A's stale live copy on the receiver resurrects on the next sync that lands. Fix options: (a) per-`(peer, kind, recordId)` cursor (storage proliferation; needs cleanup on record GC); (b) per-(peer, kind) cursor advanced only when the push response cumulatively confirms every-tombstone-up-to-that-deletedAt was delivered (requires receiver to track-and-respond with "I have all your tombstones up to T"); (c) keep current cursor but also persist a per-record `lastConfirmedPushedAt` on each subscription row, and let GC's `cutoffForKind` use `min(min-of-lastConfirmedPushedAt-across-all-records-of-this-kind)`. Option (c) is the smallest behavioral change. Defer because under the dominant single-writer/single-reader pattern in PortOS, push failures are rare and re-tried on the next event tick.
- [ ] [peer-sync-medialightbox-use-mediaimage-for-syncing-assets] **`MediaLightbox.jsx` uses a raw `<img src=...>` for the main media element — peer-synced images that haven't been pulled yet show a broken image and don't get the `peerSync:asset-arrived` placeholder/live-swap.** Codex iter-6 in v2.7.0 release review (P2). The `MediaImage` component was added specifically to handle this, but only thumbnail/card paths use it. Replace the lightbox's `<img>` with `MediaImage` so opening an image during the sync window shows the "Syncing" placeholder and atomically swaps to bytes when they land. Cross-check every `<img>` in `MediaPreview.jsx`, `MediaCollectionDetail.jsx`, `UniverseBuilder.jsx` for the same gap. Defer because the lightbox is reached after the user clicks a thumbnail — by then the thumbnail's MediaImage has likely already swapped to live bytes, so the lightbox typically sees the same.
-- [ ] [peer-sync-snapshot-skip-too-coarse-for-partial-subscriptions] **`syncOrchestrator.categoriesCoveredByPeerSync` skips the entire `universe`/`pipeline` snapshot for any peer with ANY per-record subscription in that category — but partial subscriptions leave the un-subscribed records with no active transport.** Codex iter-4 in v2.7.0 release review (P2). Today: if peer-A has 3 subs for universes A/B/C but the user has 10 universes total, the snapshot for peer-A is fully suppressed. Universes D-J never get edits to peer-A. Two fix options: (a) only suppress the snapshot when the per-record subscription set COVERS every record of that kind for that peer (refresh on subscribe/unsubscribe); (b) send the snapshot but filter out the records that ARE subscribed, so snapshot covers the gap and push covers explicit subs. Option (b) is cleaner — snapshot fills the gap. Scope: `syncOrchestrator.js` skip-decision + `dataSync.getUniverseSnapshot` + `getPipelineSnapshot` accept an exclude-set keyed by record id. Defer because the snapshot-skip works correctly for the common case (peer subscribes to ALL universes or NONE); the partial case requires a thoughtful refactor.
+- [ ] [peer-sync-snapshot-skip-too-coarse-for-partial-subscriptions] **`syncOrchestrator.categoriesCoveredByPeerSync` skips the entire `universe`/`pipeline` snapshot for any peer with ANY per-record subscription in that category, AND uses our OUTGOING subscriptions to suppress INBOUND snapshot pulls — two conflated failures.** Codex iter-4 + iter-9 in v2.7.0 release review (P1/P2). Today: (a) if peer-A has 3 subs for universes A/B/C but the user has 10 universes total, the snapshot for peer-A is fully suppressed, so universes D-J never get edits to peer-A; (b) the outbound sub only proves WE push to peer-A — if the reverse subscription was never created (older peer, inbound-only, initial push failed), peer-A's edits stop reaching us. The fix needs to: (1) distinguish outbound (we push) from inbound (peer pushes) coverage; (2) send the snapshot for un-subscribed records of the category — either by suppressing only when full coverage is confirmed, or by passing an exclude-set into `getUniverseSnapshot`/`getPipelineSnapshot`. Scope: rework `categoriesCoveredByPeerSync` to return a per-direction record-id-set; thread the exclude-set into the snapshot getters. Defer because the snapshot-skip works correctly for the common case (peer subscribes to all-or-none); fixing it requires a thoughtful refactor.
- [ ] [vitest-global-instances-mock-blocks-peer-sync-leakage] **Add a global vitest setup file that mocks `services/instances.js#getPeers` to return `[]` by default, with an opt-out for tests that need the real peer registry.** Surfaced 2026-05-23 during v2.7.0 release: every npm test run was creating "Commit U" + "Commit S" series/universe records on the user's null sync machine. Root cause: `services/instances.js` uses `dataPath('instances.json')` whose closure captures the REAL `PATHS.data`, so a test's `vi.mock('../lib/fileUtils.js', { PATHS: redirected })` doesn't redirect instances reads. `createUniverse`/`createSeries`/`createIssue` then call `autoSubscribeRecordToAllPeers` → `getPeers()` (real instances.json) → `subscribePeer` → initial `pushRecordToPeer` (real HTTP POST to live peer). Three test files were patched as point fixes (`importer.test.js`, `universeBuilderCollectionHook.test.js`, `writersRoom/promoteToPipeline.test.js`) but the pattern will recur as new tests are added. Two paths: (a) add `setupFiles: ['./vitest.setup.js']` to `vitest.config.js`, where setup does `vi.mock('./services/instances.js', { getPeers: () => Promise.resolve([]) })` plus an opt-out registry; (b) refactor `fileUtils.js#dataPath` to use a `getDataRoot()` getter so PATHS mocks propagate through. Option (a) is smaller and more targeted; option (b) fixes a class of leakage beyond peer-sync. Pick (a) for v2.7.x, revisit (b) if more leakage surfaces.
- [ ] [peer-sync-video-collection-metadata-sync] **Sync video-history.json rows alongside .mp4 bytes pushed via peer-sync.** Codex review of the v2.7.0 release PR (2026-05-23) flagged that `buildAssetManifestForCollection` ships the `.mp4` bytes for `kind: 'video'` collection items but never pushes the corresponding `video-history.json` row. After the receiver pulls the asset, `MediaCollectionDetail.jsx#hydrate` looks up the item ref in the `videosById` map (`listVideoHistory()`) and silently filters it out as "missing." The collection appears half-empty on the receiver. Fix options: (a) add `videoHistory` to the snapshot-sync category set so the rows ride the 60s loop; (b) bundle the matching `video-history.json` row alongside the collection item in `linkedCollection` and merge on the receiver; (c) on first pull, synthesize a stub history row from the asset metadata. (a) is the simplest and matches the existing `mediaCollections` snapshot category pattern. Also generate thumbnails on the receiver (or push them as a sibling asset kind). Scope: `server/services/dataSync.js` add `videoHistory` getter + merge; `routes/dataSync.js` add to enum; `routes/instances.js` `syncCategoriesSchema` add the key; `client/src/services/apiInstances.js` `SYNC_CATEGORY_META` add the row. Surfaced in v2.7.0 release codex review.
- [ ] [peer-sync-reverse-subscription-ui-broadcast] **Emit a socket event when applyIncomingPush auto-creates a reverse subscription so the Instances page updates without a refetch.** Today `peerSync:subscription:created` (or similar) doesn't exist; the `PeerCard` in `Instances.jsx` loads `peerSubs` once on mount keyed on `peer.instanceId` only, so a reverse-sub created via `maybeCreateReverseSubscription` is invisible until page reload. Add a socket event (or include a `peerSubsRevision` token on `instances:peers:updated`) and let `PeerCard` re-fetch on bump. Reviewer-3 in v2.7.0 release review.
diff --git a/server/lib/httpClient.js b/server/lib/httpClient.js
index c417da4f53..cad8176c34 100644
--- a/server/lib/httpClient.js
+++ b/server/lib/httpClient.js
@@ -7,7 +7,7 @@ import https from 'https';
// Wraps https.request as fetch-compatible for self-signed cert support
export function insecureFetch(agent) {
- return async (url, { method = 'GET', headers = {}, body, signal } = {}) => {
+ return async (url, { method = 'GET', headers = {}, body, signal, maxBytes } = {}) => {
const u = new URL(url);
return new Promise((resolve, reject) => {
// Declare cleanup before req so it can be called from res.on('end'),
@@ -23,8 +23,39 @@ export function insecureFetch(agent) {
headers,
agent
}, (res) => {
+ // Streaming size cap. Without this, peer-sync asset pulls over HTTPS
+ // buffer the WHOLE response before the post-resolve content-length
+ // check fires — so an oversized or missing-header asset can exhaust
+ // memory before the cap kicks in. Two layers:
+ // 1. Early reject when the server-declared Content-Length already
+ // exceeds the cap — no body bytes read.
+ // 2. Per-chunk accumulator that destroys the request if the actual
+ // bytes-on-the-wire exceed the cap (server lied or omitted
+ // header).
+ // Callers without a cap (everything except asset pull today) skip
+ // both layers — maxBytes only gates when provided.
+ if (typeof maxBytes === 'number' && maxBytes > 0) {
+ const declared = Number(res.headers['content-length']);
+ if (Number.isFinite(declared) && declared > maxBytes) {
+ cleanup();
+ req.destroy();
+ reject(new Error(`Response declared Content-Length ${declared} exceeds maxBytes ${maxBytes}`));
+ return;
+ }
+ }
const chunks = [];
- res.on('data', c => chunks.push(c));
+ let bytesSoFar = 0;
+ res.on('data', c => {
+ chunks.push(c);
+ if (typeof maxBytes === 'number' && maxBytes > 0) {
+ bytesSoFar += c.length;
+ if (bytesSoFar > maxBytes) {
+ cleanup();
+ req.destroy();
+ reject(new Error(`Response body exceeded maxBytes ${maxBytes} (got ${bytesSoFar})`));
+ }
+ }
+ });
res.on('end', () => {
cleanup();
// Concat as a raw Buffer so the response can be projected to text
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index ceab41f1d5..5bd35cb6f4 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -483,19 +483,23 @@ async function applyMediaCollectionsRemote(remoteData) {
// mutate item refs or scalars on a collection whose universe/series
// the user explicitly marked private.
const incoming = Array.isArray(remoteData.collections) ? remoteData.collections : [];
- const ephemeralUniverseIds = new Set(
- (await listUniverses({ includeDeleted: true }).catch(() => []))
- .filter((u) => u?.ephemeral === true)
- .map((u) => u.id),
+ // Build two filter sets per kind: ephemeral parents (privacy) AND
+ // tombstoned parents (cleanup integrity). The delete cascade unlinks
+ // its collection by clearing the parent id — a peer that still has
+ // the parent live could otherwise ship a newer collection snapshot
+ // with the old parent id and re-link the collection to our tombstone,
+ // undoing the cleanup.
+ const allUniverses = await listUniverses({ includeDeleted: true }).catch(() => []);
+ const allSeries = await listSeries({ includeDeleted: true }).catch(() => []);
+ const refusedUniverseIds = new Set(
+ allUniverses.filter((u) => u?.ephemeral === true || u?.deleted === true).map((u) => u.id),
);
- const ephemeralSeriesIds = new Set(
- (await listSeries({ includeDeleted: true }).catch(() => []))
- .filter((s) => s?.ephemeral === true)
- .map((s) => s.id),
+ const refusedSeriesIds = new Set(
+ allSeries.filter((s) => s?.ephemeral === true || s?.deleted === true).map((s) => s.id),
);
const filtered = incoming.filter((c) => {
- if (c?.universeId && ephemeralUniverseIds.has(c.universeId)) return false;
- if (c?.seriesId && ephemeralSeriesIds.has(c.seriesId)) return false;
+ if (c?.universeId && refusedUniverseIds.has(c.universeId)) return false;
+ if (c?.seriesId && refusedSeriesIds.has(c.seriesId)) return false;
return true;
});
// Routes through `mergeMediaCollectionsFromSync` so the read-modify-write
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index f630b26385..8bac644753 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -1213,8 +1213,23 @@ async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName)
const url = `${base}${urlPrefix}/${encodeURIComponent(safeName)}`;
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), ASSET_PULL_TIMEOUT_MS);
- const res = await peerFetch(url, { signal: controller.signal })
- .finally(() => clearTimeout(timeoutId));
+ // maxBytes propagates into the HTTPS shim's streaming cap (see
+ // server/lib/httpClient.js) — without it, an oversized HTTPS asset
+ // buffers the whole body before the post-resolve content-length
+ // check fires. The plain-HTTP fetch path falls back to the
+ // post-resolve checks below (Node's fetch doesn't accept maxBytes,
+ // but Content-Length is universally set by serve-static).
+ const res = await peerFetch(url, { signal: controller.signal, maxBytes: ASSET_PULL_MAX_BYTES })
+ .finally(() => clearTimeout(timeoutId))
+ .catch((err) => {
+ // The HTTPS shim rejects with a thrown Error when maxBytes is
+ // exceeded — distinguish from network/abort errors so we don't
+ // spam the log on a normal abort.
+ if (err?.message?.includes('exceed')) {
+ console.log(`⚠️ peerSync: ${safeName} exceeded asset size cap — ${err.message}`);
+ }
+ return null;
+ });
if (!res || !res.ok) return;
// Size-cap enforcement: REQUIRE a trustworthy content-length header up
// front and refuse the pull if missing or over-cap. Without the header