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 (codex): snapshot-gate coverage, self-heal re-diff, manifest cap

[._.]/ Adam Eivyb90fbb76b54f
diff --git a/server/services/dataSync.pipelineUniverse.test.js b/server/services/dataSync.pipelineUniverse.test.js
index 6ff61b4a80..ce60df74fa 100644
--- a/server/services/dataSync.pipelineUniverse.test.js
+++ b/server/services/dataSync.pipelineUniverse.test.js
@@ -1107,6 +1107,11 @@ describe('dataSync — per-category schema gate (cross-key isolation)', () => {
// manifest). Gated at applyIncomingPush via compareSchemaVersions /
// RECORD_KIND_SCHEMA_CATEGORIES.writersRoomWork.
'writersRoomWorks',
+ // Standalone media library (#1566) → its own receiver-pull endpoint
+ // (GET /api/peer-sync/library-manifest), NOT the file-snapshot transfer.
+ // Versioned for the manifest envelope and gated by syncMediaLibraryFromPeer's
+ // gentle skip-if-ahead; declared non-record in NON_RECORD_SCHEMA_CATEGORIES.
+ 'mediaLibrary',
]);
const covered = new Set(Object.values(dataSync.getSnapshotCategorySchemaKeys()).flat());
for (const key of Object.keys(PORTOS_SCHEMA_VERSIONS)) {
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 0554bece9f..14653a07bb 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -2832,6 +2832,11 @@ export async function buildMediaLibraryManifest() {
// post-boot sweep just re-confirms disk, cheap because the diff finds everything
// present and pulls nothing).
const lastLibraryManifestHash = new Map(); // peerInstanceId → manifestHash
+// Consecutive unchanged-manifest ticks per peer; after FORCE_REVALIDATE_EVERY we
+// force a full re-diff even though the remote manifest is unchanged, so a local
+// file loss self-heals without waiting for a restart or a remote library change.
+const libraryUnchangedSkips = new Map(); // peerInstanceId → count
+const FORCE_REVALIDATE_EVERY = 10; // ~10 min at the 60s sweep cadence
// Per-peer re-entrancy guard so a slow sweep (large pull) can't overlap itself
// when the periodic tick fires again before it finishes.
const librarySweepInFlight = new Set(); // peerInstanceId
@@ -2874,6 +2879,18 @@ export async function syncMediaLibraryFromPeer(peer) {
.finally(() => clearTimeout(timeoutId))
.catch(() => null);
if (!res || !res.ok) return { pulled: 0, skipped: 'unreachable' };
+ // Enforce the manifest cap before buffering the body. peerFetch's `maxBytes`
+ // only streams-caps the HTTPS (host) shim; for a plain-HTTP (address) peer it
+ // delegates to native fetch, which ignores `maxBytes`, so `res.json()` would
+ // otherwise buffer an unbounded body. Express on the sender sets Content-Length
+ // for the JSON response, so a content-length check here is the real cap (mirrors
+ // the record-pull path's RECORD_PAYLOAD_MAX_BYTES guard). A peer that omits it
+ // is a trusted tailnet peer per the threat model.
+ const declaredLen = Number(res.headers?.get?.('content-length'));
+ if (Number.isFinite(declaredLen) && declaredLen > MEDIA_LIBRARY_MANIFEST_MAX_BYTES) {
+ console.log(`⚠️ peerSync: media-library manifest from ${peer.name || peer.instanceId} too large (${declaredLen} > ${MEDIA_LIBRARY_MANIFEST_MAX_BYTES}) — skipping`);
+ return { pulled: 0, skipped: 'too-large' };
+ }
const body = await res.json().catch(() => null);
const parsed = peerLibraryManifestSchema.safeParse(body);
if (!parsed.success) {
@@ -2889,9 +2906,18 @@ export async function syncMediaLibraryFromPeer(peer) {
console.log(`⏸️ peerSync: ${peer.name || peer.instanceId} media-library manifest is schema v${manifest.schemaVersion} > local v${PORTOS_SCHEMA_VERSIONS.mediaLibrary} — skipping until this instance updates`);
return { pulled: 0, skipped: 'schema-ahead' };
}
- // Unchanged-library short-circuit.
+ // Unchanged-library short-circuit — but force a full re-diff every
+ // FORCE_REVALIDATE_EVERY consecutive unchanged ticks so a LOCAL file loss /
+ // corruption self-heals even while the REMOTE manifest stays put. (The
+ // recorded hash is in-memory, so a process restart also re-diffs; this covers
+ // the mid-session window between restarts.)
if (lastLibraryManifestHash.get(peer.instanceId) === manifest.manifestHash) {
- return { pulled: 0, skipped: 'unchanged' };
+ const skips = (libraryUnchangedSkips.get(peer.instanceId) || 0) + 1;
+ if (skips < FORCE_REVALIDATE_EVERY) {
+ libraryUnchangedSkips.set(peer.instanceId, skips);
+ return { pulled: 0, skipped: 'unchanged' };
+ }
+ libraryUnchangedSkips.set(peer.instanceId, 0); // periodic forced re-diff — fall through
}
const missing = await diffAssetManifestAgainstLocal(manifest.assets);
if (missing.length === 0) {
diff --git a/server/services/sharing/peerSync.test.js b/server/services/sharing/peerSync.test.js
index 0d421764e4..19a868fcd5 100644
--- a/server/services/sharing/peerSync.test.js
+++ b/server/services/sharing/peerSync.test.js
@@ -3863,6 +3863,47 @@ describe('media-library federation (#1566)', () => {
expect(res2.skipped).not.toBe('unchanged');
});
+ it('skips a manifest whose Content-Length exceeds the cap (unbounded-body guard for HTTP peers)', async () => {
+ vi.mocked(peerFetch).mockResolvedValue({
+ ok: true,
+ headers: new Headers({ 'content-length': String(64 * 1024 * 1024) }), // > 32MB cap
+ json: async () => ({ schemaVersion: PORTOS_SCHEMA_VERSIONS.mediaLibrary, manifestHash: 'a'.repeat(64), assets: [] }),
+ });
+ const res = await syncMediaLibraryFromPeer(mkPeer('fs-huge'));
+ expect(res.skipped).toBe('too-large');
+ });
+
+ it('forces a re-diff after repeated unchanged ticks so a local file loss self-heals', async () => {
+ const peer = mkPeer('fs-selfheal');
+ vi.mocked(getPeers).mockResolvedValue([peer]);
+ const bytes = Buffer.from('heal-bytes');
+ const manifest = {
+ schemaVersion: PORTOS_SCHEMA_VERSIONS.mediaLibrary,
+ manifestHash: 'f0'.repeat(32),
+ assets: [{ filename: 'heal.wav', kind: 'audio' }], // existence-only diff
+ };
+ vi.mocked(peerFetch).mockImplementation(async (url) => {
+ if (String(url).endsWith('/library-manifest')) return { ok: true, json: async () => manifest };
+ return {
+ ok: true,
+ headers: new Headers({ 'content-length': String(bytes.length) }),
+ arrayBuffer: async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),
+ };
+ });
+ // First sweep lands the file and records the manifestHash.
+ expect((await syncMediaLibraryFromPeer(peer)).pulled).toBe(1);
+ // Simulate local loss after the hash was recorded.
+ await rm(join(PATHS.audio, 'heal.wav'), { force: true });
+ // Unchanged ticks short-circuit until the periodic forced re-diff fires and
+ // re-pulls the lost file (proves self-heal without a restart).
+ let healed = false;
+ for (let i = 0; i < 12; i++) {
+ const r = await syncMediaLibraryFromPeer(peer);
+ if (r.skipped !== 'unchanged') { healed = true; break; }
+ }
+ expect(healed).toBe(true);
+ });
+
it('records the manifestHash + reconciles once missing bytes actually land', async () => {
const peer = mkPeer('fs-success');
vi.mocked(getPeers).mockResolvedValue([peer]);