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: fix HTTPS asset-pull regression + 2 P2 + test-isolation leak

Adam Eivycf3b26a0d761
diff --git a/PLAN.md b/PLAN.md
index 69b1ad0e71..686373691f 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -23,6 +23,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
- [ ] [ref-watch-phosphene-mlx-post-decode-os-exit] **Bypass MLX post-decode deallocator hang via `os._exit(0)`.** From `reference-watch` review of phosphene (commits `adc1cd25` + `94bd6965`, 2026-05-22). At PortOS's current `LTX2_PIN=f8f20c83` the bug isn't reachable, but the moment a user updates `ltx-2-mlx` or PortOS bumps the pin past the May 9 refactor, every Distilled / Extend / two-stage render stalls 5–15 min after the upstream "Decoding done in X.Xs" log while Metal command-buffer completion handlers hold the GIL through frame teardown. Fix: in `scripts/generate_ltx2.py` `main()`, after `print(json.dumps(...))`, call `os._exit(0)` instead of returning normally — mp4 is on disk, stdout was flushed, skipping deallocator teardown saves up to 15 min. Document why in the file's docstring. Subsumes any in-helper watchdog approach.
- [ ] [ref-watch-phosphene-broaden-negative-prompt-override] **Broaden `DEFAULT_NEGATIVE_PROMPT` override to every module that defines it.** From `reference-watch` review of phosphene (commit `4e6129b7`, 2026-05-22). `scripts/generate_ltx2.py:55-70` `configure_negative_prompt()` only patches `ti2vid_one_stage.DEFAULT_NEGATIVE_PROMPT`. At PortOS's current pin this happens to cover every pipeline (the constant resolves against `ti2vid_one_stage` for the base class), but post-May-9 the constant moves to `ltx_pipelines_mlx._base` and `utils.constants` — and the PortOS override silently no-ops on Q8 / two-stage / HQ paths with no error for the user to chase. Fix: rewrite `configure_negative_prompt()` to probe `ti2vid_one_stage`, `_base`, and `utils.constants`, monkey-patch every module that has the constant. Keep PortOS's *replace* semantics (don't switch to phosphene's append-with-comma). No contextmanager needed — the helper is short-lived.
- [ ] [tombstone-gc-manual-trigger-ui] **Wire a manual "GC tombstones now" button on the Instances page.** Today `sharing/tombstoneGc.js#sweepTombstones` only fires from the 60s `syncOrchestrator` interval and uses a hard-coded `GRACE_MS = 24 * 60 * 60 * 1000`, so a user who just mass-deleted records has to wait 24h for them to disappear from `data/universe-builder.json` / `data/pipeline-series.json` / `data/pipeline-issues.json` (even when every subscribed peer has already acked them). Wiring goals: (1) parameterize `sweepTombstones({ now, graceMs })` so callers can override the 24h buffer — keep the 24h default so the orchestrator path is unchanged. (2) Expose `POST /api/sync/tombstones/sweep` with optional `{ graceMs }` body (Zod-validated; clamp to `[0, 24*60*60*1000]` so the button can only shrink the grace, never bypass the ack horizon). The route still calls `cutoffForKind` for each kind so the existing safety checks (peer-ack horizon, refuse-when-snapshot-peer-uncovered) keep firing. (3) Add a "GC tombstones now" button under the Instances page's Sync Status section that POSTs with `graceMs: 0`. Disabled when any enabled peer has snapshot-mode coverage for a kind it isn't subscribed to (mirror the route's null-cutoff refusal). Surfaces the per-kind prune count in a toast (`pruned N universes / M series / K issues` — quiet when zero). (4) One-shot CLI script in `scripts/gc-tombstones-now.js` for headless cleanups (the inline-Node prune we ran 2026-05-23 for the post-Echoes-cleanup batch is the seed). Use `scripts/cleanup-test-data.js`'s pm2-stop-required wording in the header — the prune helpers serialize through per-file write tails that don't cross processes. Surfaced 2026-05-23 during the media-collections sync PR: peer null had acked 82 universe + 192 series tombstones from a same-day mass-delete and the user wanted them off-disk early.
+- [ ] [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.
- [ ] [peer-sync-disambiguate-two-health-rows-in-palette] **Disambiguate the two `Health` rows the ⌘K palette now renders.** Moving the CoS Health page from `meatspace.health` semantics also added `aliases: ['cos-health', 'health']` to `nav.cos.health` while keeping `nav.meatspace.health` with the label "Health". The palette renders two rows labeled "Health" under different sections; bare "health" voice routes to CoS. Pick one: rename the MeatSpace label to "Body Health" / "Health Metrics" in both `Layout.jsx` and `navManifest.js`, or document the bare-word disambiguation as final. Reviewer-6 in v2.7.0 release review.
diff --git a/server/lib/httpClient.js b/server/lib/httpClient.js
index 7b9aef0c2e..c417da4f53 100644
--- a/server/lib/httpClient.js
+++ b/server/lib/httpClient.js
@@ -37,7 +37,15 @@ export function insecureFetch(agent) {
resolve({
ok: res.statusCode >= 200 && res.statusCode < 300,
status: res.statusCode,
- headers: { get: n => res.headers[n.toLowerCase()] ?? null },
+ headers: {
+ get: n => res.headers[n.toLowerCase()] ?? null,
+ // has() mirrors Fetch's Headers API so consumers (peerSync's
+ // asset-pull cap check) can distinguish "header missing" from
+ // "header is '0'" without branching on transport. Without this
+ // the asset-pull `res.headers.has('content-length')` throws
+ // TypeError on every HTTPS pull.
+ has: n => Object.prototype.hasOwnProperty.call(res.headers, n.toLowerCase()),
+ },
text: () => Promise.resolve(buffer.toString('utf-8')),
json: () => Promise.resolve(JSON.parse(buffer.toString('utf-8'))),
// ArrayBuffer view matching Fetch's Response so call sites can
diff --git a/server/services/dataSync.js b/server/services/dataSync.js
index f8db4019f2..1d20ef944f 100644
--- a/server/services/dataSync.js
+++ b/server/services/dataSync.js
@@ -11,8 +11,8 @@ import { stat } from 'fs/promises';
import { join } from 'path';
import { atomicWrite, readJSONFile, PATHS } from '../lib/fileUtils.js';
import { isPlainObject } from '../lib/objects.js';
-import { mergeUniversesFromSync } from './universeBuilder.js';
-import { mergeSeriesFromSync } from './pipeline/series.js';
+import { mergeUniversesFromSync, listUniverses } from './universeBuilder.js';
+import { mergeSeriesFromSync, listSeries } from './pipeline/series.js';
import { mergeIssuesFromSync } from './pipeline/issues.js';
import { mergeMediaCollectionsFromSync, listCollections, itemKey } from './mediaCollections.js';
import { sanitizeStateForWire } from '../lib/syncWire.js';
@@ -434,6 +434,28 @@ async function getMediaCollectionsSnapshot() {
// the checksum cache (`CHECKSUM_PATHS` fingerprint check) already short-
// circuits the I/O when the file hasn't moved.
const collections = await listCollections();
+ // Filter out collections whose linked record (universe or series) is marked
+ // ephemeral. Mirrors the per-record push pipeline's local-ephemeral guard
+ // (see peerSync.js applyIncomingPush) — without this filter, the
+ // mediaCollections snapshot category would still leak the collection name +
+ // item refs for records the user explicitly opted out of sync. Tombstoned
+ // ephemeral parents also drop their collection (sender wouldn't bundle them
+ // anyway, but the snapshot path is independent).
+ const ephemeralUniverseIds = new Set(
+ (await listUniverses({ includeDeleted: true }).catch(() => []))
+ .filter((u) => u?.ephemeral === true)
+ .map((u) => u.id),
+ );
+ const ephemeralSeriesIds = new Set(
+ (await listSeries({ includeDeleted: true }).catch(() => []))
+ .filter((s) => s?.ephemeral === true)
+ .map((s) => s.id),
+ );
+ const filtered = collections.filter((c) => {
+ if (c.universeId && ephemeralUniverseIds.has(c.universeId)) return false;
+ if (c.seriesId && ephemeralSeriesIds.has(c.seriesId)) return false;
+ return true;
+ });
// Canonicalize ordering for the wire so two peers holding identical sets
// produce identical checksums regardless of write history. Without this
// sort, on-disk order is insertion-order — peer A and peer B can land the
@@ -442,7 +464,7 @@ async function getMediaCollectionsSnapshot() {
// forever. Sort collections by id (stable, unique) and each collection's
// items by `<kind>:<ref>` (the same key used for set membership in
// `mergeCollectionItems`).
- const canonical = collections
+ const canonical = filtered
.map((c) => ({
...c,
items: [...(c.items || [])].sort((a, b) => itemKey(a).localeCompare(itemKey(b))),
@@ -483,7 +505,12 @@ const CHECKSUM_PATHS = {
meatspace: Object.keys(MEATSPACE_FILES).map((f) => join(MEATSPACE_DIR, f)),
universe: [UNIVERSE_BUILDER_FILE],
pipeline: [PIPELINE_SERIES_FILE, PIPELINE_ISSUES_FILE],
- mediaCollections: [MEDIA_COLLECTIONS_FILE],
+ // mediaCollections invalidates on its own file AND on the parent record
+ // files — `getMediaCollectionsSnapshot` filters collections whose linked
+ // universe/series is ephemeral, so a "mark ephemeral" PATCH on a universe
+ // must re-checksum the collections snapshot even though
+ // media-collections.json itself didn't move. Same goes for un-ephemeral.
+ mediaCollections: [MEDIA_COLLECTIONS_FILE, UNIVERSE_BUILDER_FILE, PIPELINE_SERIES_FILE],
};
const CATEGORIES = {
diff --git a/server/services/importer.test.js b/server/services/importer.test.js
index 24c8bf7ade..f1c30bae35 100644
--- a/server/services/importer.test.js
+++ b/server/services/importer.test.js
@@ -44,6 +44,17 @@ vi.mock('../lib/fileUtils.js', async () => {
};
});
+// Stub instances.js so non-ephemeral createSeries/createUniverse paths
+// don't fan out to real peers via peerSync's autoSubscribeRecordToAllPeers
+// (instances.js uses `dataPath` whose closure points at the REAL PATHS,
+// bypassing our PATHS mock above). Defense-in-depth: even with explicit
+// ephemeral:true on the direct fixtures, downstream production code may
+// still create non-ephemeral records.
+vi.mock('./instances.js', async () => {
+ const actual = await vi.importActual('./instances.js');
+ return { ...actual, getPeers: () => Promise.resolve([]) };
+});
+
// Mock runStagedLLM so tests never hit a real provider — every importer
// LLM call resolves to a canned JSON shape we control per-test.
const mockRunStagedLLM = vi.fn();
@@ -499,8 +510,15 @@ describe('classifyImportContent', () => {
async function setupForCommit() {
// Create the universe + series the analyze phase would have created, then
// exercise commitImport directly with a hand-shaped payload.
- const uni = await universeSvc.createUniverse({ name: 'Commit U' });
- const ser = await seriesSvc.createSeries({ name: 'Commit S', universeId: uni.id });
+ //
+ // ephemeral:true keeps the fixtures out of peer-sync. Without it, the
+ // create*-time `autoSubscribeRecordToAllPeers` reads the LIVE peer
+ // registry (instances.json is NOT mocked by PATHS — only fileUtils.js
+ // PATHS is, and instances.js resolves its own file paths) and fans the
+ // fixture out to every actual peer, leaving "Commit U" / "Commit S"
+ // records on the user's null sync machine after every test run.
+ const uni = await universeSvc.createUniverse({ name: 'Commit U', ephemeral: true });
+ const ser = await seriesSvc.createSeries({ name: 'Commit S', universeId: uni.id, ephemeral: true });
return { uni, ser };
}
diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.js
index d64a07c5b5..660930d0a8 100644
--- a/server/services/sharing/tombstoneGc.js
+++ b/server/services/sharing/tombstoneGc.js
@@ -47,7 +47,17 @@ const GRACE_MS = 24 * 60 * 60 * 1000; // 24h grace
*/
async function peerIdsSubscribedToKind(recordKind) {
const subs = await listPeerSubscriptions({ recordKind });
- return [...new Set(subs.map((s) => s.peerId).filter(Boolean))];
+ // Filter against the live peer registry — peer_subscriptions.json rows
+ // outlive peer removal (no cleanup hook on instance delete), so a
+ // long-gone peer would otherwise be treated as an active subscriber.
+ // getMinAckAcrossPeers would then include it with its frozen-at-removal
+ // ack (often 0) and refuse to prune any tombstone for this kind. Bound
+ // to the peers we can actually reach so a removed peer doesn't
+ // permanently stall GC.
+ const livePeerIds = new Set(
+ (await getPeers().catch(() => [])).map((p) => p?.instanceId).filter(Boolean),
+ );
+ return [...new Set(subs.map((s) => s.peerId).filter((id) => id && livePeerIds.has(id)))];
}
/**
diff --git a/server/services/sharing/tombstoneGc.test.js b/server/services/sharing/tombstoneGc.test.js
index 25d3d488bb..daf2284c2b 100644
--- a/server/services/sharing/tombstoneGc.test.js
+++ b/server/services/sharing/tombstoneGc.test.js
@@ -74,6 +74,10 @@ describe('sweepTombstones — peers behind', () => {
if (recordKind === 'universe') return [{ peerId: 'peer-a' }];
return [];
});
+ // peerIdsSubscribedToKind now filters against live peers (removed-peer
+ // subscriptions otherwise stall GC forever). Register peer-a so the
+ // sub passes the registry filter.
+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);
getMinAckAcrossPeers.mockImplementation(async (peerIds) => {
if (peerIds.includes('peer-a')) return minAck;
return Infinity;
@@ -95,6 +99,7 @@ describe('sweepTombstones — peers behind', () => {
if (recordKind === 'series') return [{ peerId: 'peer-a' }];
return [];
});
+ getPeers.mockResolvedValue([{ instanceId: 'peer-a', enabled: true }]);
getMinAckAcrossPeers.mockImplementation(async (peerIds) => {
if (peerIds.includes('peer-a')) return seriesAck;
return Infinity;
@@ -135,6 +140,10 @@ describe('sweepTombstones — peers behind', () => {
}
return [];
});
+ getPeers.mockResolvedValue([
+ { instanceId: 'peer-a', enabled: true },
+ { instanceId: 'peer-b', enabled: true },
+ ]);
getMinAckAcrossPeers.mockResolvedValue(NOW - 1000);
await sweepTombstones({ now: NOW });
expect(getMinAckAcrossPeers).toHaveBeenCalledWith(
@@ -144,6 +153,26 @@ describe('sweepTombstones — peers behind', () => {
// De-dup invariant.
expect(new Set(firstCallArgs).size).toBe(firstCallArgs.length);
});
+
+ it('ignores subscriptions for peers no longer in the registry (removed-peer GC stall)', async () => {
+ // Regression: peer_subscriptions.json rows outlive peer removal — no
+ // cleanup hook on instance delete. Without the live-registry filter,
+ // getMinAckAcrossPeers would receive a removed peer-id, return its
+ // frozen-at-removal ack (often 0), and the cutoff would clamp to
+ // `0 - GRACE` — refusing to prune any tombstone for this kind
+ // indefinitely.
+ listPeerSubscriptions.mockImplementation(async ({ recordKind }) => {
+ if (recordKind === 'universe') return [{ peerId: 'peer-ghost' }, { peerId: 'peer-live' }];
+ return [];
+ });
+ // peer-ghost was removed; only peer-live is still in the registry.
+ getPeers.mockResolvedValue([{ instanceId: 'peer-live', enabled: true }]);
+ getMinAckAcrossPeers.mockResolvedValue(NOW - 1000);
+ await sweepTombstones({ now: NOW });
+ const firstCallArgs = getMinAckAcrossPeers.mock.calls[0][0];
+ expect(firstCallArgs).toEqual(['peer-live']);
+ expect(firstCallArgs).not.toContain('peer-ghost');
+ });
});
describe('sweepTombstones — return shape', () => {
diff --git a/server/services/universeBuilderCollectionHook.test.js b/server/services/universeBuilderCollectionHook.test.js
index ecb6853539..648b82b99d 100644
--- a/server/services/universeBuilderCollectionHook.test.js
+++ b/server/services/universeBuilderCollectionHook.test.js
@@ -20,6 +20,15 @@ vi.mock('../lib/fileUtils.js', async () => {
});
});
+// Stub instances.js so non-ephemeral createUniverse paths don't fan out
+// to real peers via peerSync's autoSubscribeRecordToAllPeers (instances.js
+// uses dataPath whose closure points at REAL PATHS, bypassing the mock
+// above).
+vi.mock('./instances.js', async () => {
+ const actual = await vi.importActual('./instances.js');
+ return { ...actual, getPeers: () => Promise.resolve([]) };
+});
+
const { mediaJobEvents } = await import('./mediaJobQueue/index.js');
const collections = await import('./mediaCollections.js');
const recordEvents = await import('./sharing/recordEvents.js');
@@ -150,6 +159,11 @@ describe('universeBuilderCollectionHook', () => {
name,
characters,
categories: { [categoryKey]: { variations } },
+ // Test uses a real tempdir but doesn't mock instances.js, so a
+ // non-ephemeral create would fire autoSubscribeRecordToAllPeers and
+ // initial-push a fixture universe to every real peer in
+ // data/instances.json — see series.js#createSeries auto-subscribe.
+ ephemeral: true,
});
return created;
}
diff --git a/server/services/writersRoom/promoteToPipeline.test.js b/server/services/writersRoom/promoteToPipeline.test.js
index c1d5946796..e183fa5b4a 100644
--- a/server/services/writersRoom/promoteToPipeline.test.js
+++ b/server/services/writersRoom/promoteToPipeline.test.js
@@ -11,6 +11,15 @@ vi.mock('../../lib/fileUtils.js', async () => {
return makePathsProxy(actual, { dataRoot: () => tempRoot });
});
+// Stub instances.js so promoteWorkToPipeline's non-ephemeral
+// createSeries/createIssue calls don't fan out to real peers via
+// peerSync's autoSubscribeRecordToAllPeers (which reads the live peer
+// registry through dataPath closure to the real PATHS).
+vi.mock('../instances.js', async () => {
+ const actual = await vi.importActual('../instances.js');
+ return { ...actual, getPeers: () => Promise.resolve([]) };
+});
+
const wrLocal = await import('./local.js');
const { promoteWorkToPipeline, ERR_NO_DRAFT_BODY } = await import('./promoteToPipeline.js');
const { createCharacter } = await import('./characters.js');
@@ -142,8 +151,12 @@ describe('promoteWorkToPipeline', () => {
// Simulate a corrupted link: rewrite the work manifest to point at the
// first series but a DIFFERENT (unrelated) series' issue. Mirrors a
// manual edit, partial delete, or migration bug.
- const strayerSeries = await seriesSvc.createSeries({ name: 'Strayer' });
- const strayerIssue = await issuesSvc.createIssue({ seriesId: strayerSeries.id, title: 'Stray' });
+ // ephemeral:true keeps the fixture out of peer-sync. Test uses a real
+ // tempdir but doesn't mock instances.js; without this, autosubscribe-
+ // on-create initial-pushes the 'Strayer' record to every real peer in
+ // data/instances.json.
+ const strayerSeries = await seriesSvc.createSeries({ name: 'Strayer', ephemeral: true });
+ const strayerIssue = await issuesSvc.createIssue({ seriesId: strayerSeries.id, title: 'Stray', ephemeral: true });
await wrLocal.linkToPipeline(work.id, { seriesId: first.series.id, issueId: strayerIssue.id });
const second = await promoteWorkToPipeline(work.id);