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 CRITICAL linkedCollection schema gap + 5 HIGH issues

Adam Eivy09a210f5e357
diff --git a/client/src/components/sharing/SyncToPeerButton.jsx b/client/src/components/sharing/SyncToPeerButton.jsx
index 28f5fb71d3..f4a170d8e2 100644
--- a/client/src/components/sharing/SyncToPeerButton.jsx
+++ b/client/src/components/sharing/SyncToPeerButton.jsx
@@ -84,7 +84,10 @@ export default function SyncToPeerButton({
setBusyPeerId(peer.instanceId);
const existing = subscriptionForPeer(peer.instanceId);
if (existing) {
- const ok = await unsubscribeFromPeer(existing.id).catch((err) => {
+ // silent:true — the catch below already owns the error toast, so the
+ // apiCore helper must not fire its own (per CLAUDE.md "Custom catch ⇒
+ // silent: true" rule). Otherwise the user sees two toasts on failure.
+ const ok = await unsubscribeFromPeer(existing.id, { silent: true }).catch((err) => {
toast.error(err.message || `Unsync from ${peer.name} failed`);
return null;
});
@@ -97,7 +100,7 @@ export default function SyncToPeerButton({
peerId: peer.instanceId,
recordKind,
recordId,
- }).catch((err) => {
+ }, { silent: true }).catch((err) => {
toast.error(err.message || `Sync to ${peer.name} failed`);
return null;
});
diff --git a/client/src/components/sharing/SyncToPeerButton.test.jsx b/client/src/components/sharing/SyncToPeerButton.test.jsx
index 2722b1aa48..269c67c01c 100644
--- a/client/src/components/sharing/SyncToPeerButton.test.jsx
+++ b/client/src/components/sharing/SyncToPeerButton.test.jsx
@@ -82,11 +82,10 @@ describe('SyncToPeerButton', () => {
await user.click(screen.getByRole('button', { name: /Sync/i }));
await screen.findByText('Peer A');
await user.click(screen.getByText('Peer A'));
- expect(api.subscribeToPeer).toHaveBeenCalledWith({
- peerId: 'peer-a',
- recordKind: 'universe',
- recordId: 'u1',
- });
+ expect(api.subscribeToPeer).toHaveBeenCalledWith(
+ { peerId: 'peer-a', recordKind: 'universe', recordId: 'u1' },
+ { silent: true },
+ );
});
it('unsubscribes when a checked peer row is clicked', async () => {
@@ -104,6 +103,6 @@ describe('SyncToPeerButton', () => {
await user.click(screen.getByRole('button', { name: /Sync/i }));
await screen.findByText('Peer A');
await user.click(screen.getByText('Peer A'));
- expect(api.unsubscribeFromPeer).toHaveBeenCalledWith('peer-universe-u1-peer-a');
+ expect(api.unsubscribeFromPeer).toHaveBeenCalledWith('peer-universe-u1-peer-a', { silent: true });
});
});
diff --git a/client/src/pages/Instances.jsx b/client/src/pages/Instances.jsx
index 2178b77bde..d630baaa35 100644
--- a/client/src/pages/Instances.jsx
+++ b/client/src/pages/Instances.jsx
@@ -570,7 +570,8 @@ function PeerSyncSubscriptionsSection({ peer, peerSubs, peerSubsLoaded, setPeerS
const handleUnsubscribe = async (sub) => {
setBusyId(sub.id);
- const ok = await unsubscribeFromPeer(sub.id).catch((err) => {
+ // silent:true — own toast in the catch, so suppress the apiCore default.
+ const ok = await unsubscribeFromPeer(sub.id, { silent: true }).catch((err) => {
toast.error(err.message || 'Unsubscribe failed');
return null;
});
diff --git a/server/lib/validation.js b/server/lib/validation.js
index d89c094aed..bbab162d12 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -1222,6 +1222,14 @@ const peerSyncPushBase = {
record: peerWireRecordSchema,
assetManifest: z.array(peerAssetManifestEntrySchema).max(2000),
sourceInstanceId: z.string().trim().min(1).max(120),
+ // Optional bundled media collection — Stage 5 media-collections sync
+ // attaches the universe / series's linked collection so collection-only
+ // edits propagate via the per-record push pipeline. Same shape as a
+ // record on the wire (id required, sanitizer handles the rest); without
+ // this field on both push branches the strict() rejection drops every
+ // production push from a universe / series with images. See
+ // peerSync.js buildPushPayload and applyIncomingPush.
+ linkedCollection: peerWireRecordSchema.optional(),
};
const universePushSchema = z.object({
kind: z.literal('universe'),
diff --git a/server/routes/peerSync.test.js b/server/routes/peerSync.test.js
index 9d89edcc0f..4cf0d1b75b 100644
--- a/server/routes/peerSync.test.js
+++ b/server/routes/peerSync.test.js
@@ -53,6 +53,27 @@ describe('peer-sync routes', () => {
}));
});
+ it('accepts a universe push that bundles a linkedCollection (Stage 5 media-collections sync)', async () => {
+ // Regression: peerSyncPushSchema's strict() branches must include
+ // `linkedCollection` — without it, every production push from a
+ // universe/series with images 400s because peerSync.js's
+ // buildPushPayload spreads `linkedCollection` into the payload.
+ svc.applyIncomingPush.mockResolvedValue({ missingAssets: [], reverseSubscriptionCreated: false, ackedDeletesUpTo: 0 });
+ const res = await request(buildApp())
+ .post('/api/peer-sync/push')
+ .send({
+ kind: 'universe',
+ record: { id: 'u1', name: 'Foo' },
+ assetManifest: [],
+ sourceInstanceId: 'peer-a',
+ linkedCollection: { id: 'col-1', name: 'Universe: Foo', items: [] },
+ });
+ expect(res.status).toBe(200);
+ expect(svc.applyIncomingPush).toHaveBeenCalledWith(expect.objectContaining({
+ linkedCollection: expect.objectContaining({ id: 'col-1' }),
+ }));
+ });
+
it('accepts a series push with bundled issues', async () => {
svc.applyIncomingPush.mockResolvedValue({ missingAssets: [], reverseSubscriptionCreated: false, ackedDeletesUpTo: 0 });
const res = await request(buildApp())
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 559c9520dc..c980abe993 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -266,8 +266,20 @@ export async function spawnTuiAgent({
// Safety valve: rewrite the file with just this batch instead of
// appending. The tail-read at finalize wants the MOST RECENT bytes,
// not the oldest, so truncating preserves what analyzeAgentFailure
- // actually uses while bounding disk usage at ~RAW_SPOOL_MAX_BYTES
- // plus one debounce window.
+ // actually uses while bounding disk usage at ~RAW_SPOOL_MAX_BYTES.
+ // If a single debounce-window batch exceeds the cap (runaway producer
+ // emitting MB/sec), slice to the trailing RAW_SPOOL_MAX_BYTES bytes
+ // first — Buffer-slice to keep UTF-8 byte semantics correct (a
+ // string.slice would index by UTF-16 code units and produce torn
+ // multi-byte sequences at the boundary).
+ let writeBuf;
+ if (batchBytes > RAW_SPOOL_MAX_BYTES) {
+ const buf = Buffer.from(batch, 'utf8');
+ writeBuf = buf.subarray(buf.length - RAW_SPOOL_MAX_BYTES);
+ } else {
+ writeBuf = batch;
+ }
+ const writeBytes = typeof writeBuf === 'string' ? batchBytes : writeBuf.length;
if (!rawSpoolTruncationWarned) {
rawSpoolTruncationWarned = true;
console.warn(`⚠️ TUI agent ${agentId} raw PTY spool reached ${Math.round(RAW_SPOOL_MAX_BYTES / 1024 / 1024)}MB — truncating spool (oldest bytes dropped; tail-read still reflects most recent)`);
@@ -277,8 +289,8 @@ export async function spawnTuiAgent({
// Only update the byte counter on successful write — a failed write
// would otherwise inflate rawBytesWritten and make subsequent flush
// decisions race the actual on-disk state.
- const wrote = await writeFile(rawFile, batch).then(() => true).catch(() => false);
- if (wrote) rawBytesWritten = batchBytes;
+ const wrote = await writeFile(rawFile, writeBuf).then(() => true).catch(() => false);
+ if (wrote) rawBytesWritten = writeBytes;
return;
}
const wrote = await appendFile(rawFile, batch).then(() => true).catch(() => false);
@@ -432,46 +444,55 @@ export async function spawnTuiAgent({
};
const handleData = async (data) => {
- // node-pty can deliver chunks between finalize starting and the shell
- // session being killed in finalize's finally block. Once finalized, drop
- // them — appending to the spool, growing the post-paste accumulator, or
- // mutating timing state is all pointless after finish has settled.
- if (finalized) return;
- // node-pty surfaces output as already-decoded UTF-8 strings via
- // shellService's onData hook (StringDecoder handles multi-byte
- // boundaries internally), so `data` is a string here in normal use.
- // The String(...) coerces defensively in case a future caller wires
- // a Buffer-emitting encoding.
- const text = typeof data === 'string' ? data : String(data);
- pendingRawChunks.push(text);
- scheduleRawFlush();
- if (postPasteBuffer !== null) postPasteBuffer += text;
- lastOutputAt = Date.now();
- if (firstOutputAt === null) firstOutputAt = lastOutputAt;
-
- if (!hasStartedWorking) {
- hasStartedWorking = true;
- await updateAgent(agentId, { metadata: { phase: 'working' } });
- emitLog('info', `TUI agent ${agentId} working...`, { agentId, phase: 'working' });
- }
+ // EventEmitter listeners run outside the request lifecycle — a rejection
+ // here on Node ≥15 will kill the process unless we catch locally. The
+ // outer try/catch routes failures through emitLog (best-effort log, no
+ // re-throw) and leaves the agent run intact.
+ // See skill: nodejs-async-event-listener-unhandled-rejection.
+ try {
+ // node-pty can deliver chunks between finalize starting and the shell
+ // session being killed in finalize's finally block. Once finalized, drop
+ // them — appending to the spool, growing the post-paste accumulator, or
+ // mutating timing state is all pointless after finish has settled.
+ if (finalized) return;
+ // node-pty surfaces output as already-decoded UTF-8 strings via
+ // shellService's onData hook (StringDecoder handles multi-byte
+ // boundaries internally), so `data` is a string here in normal use.
+ // The String(...) coerces defensively in case a future caller wires
+ // a Buffer-emitting encoding.
+ const text = typeof data === 'string' ? data : String(data);
+ pendingRawChunks.push(text);
+ scheduleRawFlush();
+ if (postPasteBuffer !== null) postPasteBuffer += text;
+ lastOutputAt = Date.now();
+ if (firstOutputAt === null) firstOutputAt = lastOutputAt;
+
+ if (!hasStartedWorking) {
+ hasStartedWorking = true;
+ await updateAgent(agentId, { metadata: { phase: 'working' } });
+ emitLog('info', `TUI agent ${agentId} working...`, { agentId, phase: 'working' });
+ }
- // The TUI is a *screen*, not a log: every progress tick repaints the
- // status line (`thinking with…`, token counters, footer) and gets
- // re-captured if we parse it line-by-line. The attached shell session
- // shows the live TUI faithfully — see-the-shell is the user-facing
- // path. We still spool the raw stream to raw.txt for error analysis
- // on failure, and we detect early "command not found" so a missing
- // binary fails fast instead of idling.
- if (!promptSentAt) {
- const lowerStripped = streamingStrip(text).toLowerCase();
- if (lowerStripped.includes('command not found') && lowerStripped.includes(commandName.toLowerCase())) {
- await finish({
- success: false,
- exitCode: 127,
- error: `TUI command not found: ${tuiConfig.command}`,
- reason: 'command-not-found'
- });
+ // The TUI is a *screen*, not a log: every progress tick repaints the
+ // status line (`thinking with…`, token counters, footer) and gets
+ // re-captured if we parse it line-by-line. The attached shell session
+ // shows the live TUI faithfully — see-the-shell is the user-facing
+ // path. We still spool the raw stream to raw.txt for error analysis
+ // on failure, and we detect early "command not found" so a missing
+ // binary fails fast instead of idling.
+ if (!promptSentAt) {
+ const lowerStripped = streamingStrip(text).toLowerCase();
+ if (lowerStripped.includes('command not found') && lowerStripped.includes(commandName.toLowerCase())) {
+ await finish({
+ success: false,
+ exitCode: 127,
+ error: `TUI command not found: ${tuiConfig.command}`,
+ reason: 'command-not-found'
+ });
+ }
}
+ } catch (err) {
+ emitLog('error', `TUI agent ${agentId} handleData failed: ${err?.message || err}`, { agentId });
}
};
diff --git a/server/services/mortalLoomStore.js b/server/services/mortalLoomStore.js
index 50a43efb4f..55bd8806c0 100644
--- a/server/services/mortalLoomStore.js
+++ b/server/services/mortalLoomStore.js
@@ -217,6 +217,23 @@ export async function isMortalLoomEnabled() {
return Boolean(s?.mortalloom?.enabled);
}
+/**
+ * Single-read snapshot of {enabled, path} from settings — collapses the prior
+ * isMortalLoomEnabled() + readStore() → resolvePath() → getSettings() double-
+ * read in every runtime helper into one settings I/O. Without this, the half-
+ * fail window the boot-pin fix guards against (settings rejects transiently
+ * between the two calls) is still live in the read path — first call says
+ * "enabled", second call fails and the helper returns null even though sync
+ * is on. Returns `null` when sync is disabled OR the read fails.
+ */
+async function readEnabledStore() {
+ const s = await getSettings();
+ if (!s?.mortalloom?.enabled) return null;
+ const path = normalizePath(s.mortalloom.path);
+ if (!path) return null;
+ return readStoreAtPath(path);
+}
+
/**
* Read + parse the store at `path`. Returns `null` for:
* - file absent (ENOENT or `existsSync` false) — silently
@@ -329,8 +346,7 @@ export async function mlReplace(key, array) {
/** Returns `store.profile` when MortalLoom sync is enabled, else null. */
export async function mlGetProfileIfEnabled() {
- if (!(await isMortalLoomEnabled())) return null;
- const store = await readStore();
+ const store = await readEnabledStore();
return (store && typeof store.profile === 'object') ? store.profile : null;
}
@@ -381,7 +397,7 @@ export async function mlUpsertHealthMetricByDate(date, patch) {
* Return the id of the N-th record in store[key] with the given date (in stored order).
*/
export async function mlIdAtDateIndex(key, date, index) {
- const store = await readStore();
+ const store = await readEnabledStore();
if (!store || !Array.isArray(store[key])) return null;
const sameDate = store[key].filter(r => r.date === date);
return sameDate[index]?.id ?? null;
@@ -391,8 +407,7 @@ export async function mlIdAtDateIndex(key, date, index) {
/** Returns an array for `key` from the store when enabled, else null (fall through to local). */
export async function mlArrayIfEnabled(key) {
- if (!(await isMortalLoomEnabled())) return null;
- const store = await readStore();
+ const store = await readEnabledStore();
if (!store || !Array.isArray(store[key])) return null;
return store[key];
}
@@ -429,8 +444,7 @@ export function buildDailyLogFromMortalLoom(store) {
}
export async function readDailyLogIfEnabled() {
- if (!(await isMortalLoomEnabled())) return null;
- const store = await readStore();
+ const store = await readEnabledStore();
return store ? buildDailyLogFromMortalLoom(store) : null;
}
diff --git a/server/services/pipeline/series.js b/server/services/pipeline/series.js
index ed9334afc5..996aab4ca5 100644
--- a/server/services/pipeline/series.js
+++ b/server/services/pipeline/series.js
@@ -324,18 +324,22 @@ export async function updateSeries(id, patch = {}) {
// shareable series reaches every peer with the pipeline category enabled.
// Must run BEFORE emitRecordUpdated so the peerSync 'updated' listener
// doesn't schedule pushes against subs that are about to be torn down.
+ // The dynamic import is awaited (NOT fire-and-forget .then) — otherwise
+ // the unsubscribe resolves on a microtask after emitRecordUpdated has
+ // already fired the listener and pushes get scheduled against the
+ // about-to-be-deleted subs.
if (prevEphemeral && !nextEphemeral) {
- import('../sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>
- autoSubscribeRecordToAllPeers('series', merged.id)
- ).catch((err) => {
- console.log(`⚠️ series: re-subscribe after un-ephemeralizing failed: ${err.message}`);
- });
+ await import('../sharing/peerSync.js')
+ .then(({ autoSubscribeRecordToAllPeers }) => autoSubscribeRecordToAllPeers('series', merged.id))
+ .catch((err) => {
+ console.log(`⚠️ series: re-subscribe after un-ephemeralizing failed: ${err.message}`);
+ });
} else if (!prevEphemeral && nextEphemeral) {
- import('../sharing/peerSync.js').then(({ unsubscribeAllForRecord }) =>
- unsubscribeAllForRecord('series', merged.id)
- ).catch((err) => {
- console.log(`⚠️ series: unsubscribe after ephemeralizing failed: ${err.message}`);
- });
+ await import('../sharing/peerSync.js')
+ .then(({ unsubscribeAllForRecord }) => unsubscribeAllForRecord('series', merged.id))
+ .catch((err) => {
+ console.log(`⚠️ series: unsubscribe after ephemeralizing failed: ${err.message}`);
+ });
}
// Cascade rename onto the linked per-series media collection (if any) —
// log but don't fail the save. Runs OUTSIDE the queue so the media-
diff --git a/server/services/sharing/peerSync.js b/server/services/sharing/peerSync.js
index 3ffc48fefe..fc6f6beda0 100644
--- a/server/services/sharing/peerSync.js
+++ b/server/services/sharing/peerSync.js
@@ -1169,11 +1169,20 @@ async function doPullOneAsset(peer, base, entry, urlPrefix, localDir, safeName)
// `serve-static` always sets content-length for static files (verified
// by the `acceptRanges: true` mount config in server/index.js), so this
// is enforceable in the real deployment path.
- const contentLength = Number(res.headers.get('content-length'));
- if (!Number.isFinite(contentLength) || contentLength < 0) {
+ // Use has() to distinguish "header missing" from "header is '0'" — without
+ // the explicit check, `Number(null)` is 0 and slips past the finite-non-negative
+ // guard, letting a peer that omits the header buffer an unbounded body before
+ // the size cap runs (the cap on .arrayBuffer() length only kicks in AFTER the
+ // body lands in memory).
+ if (!res.headers.has('content-length')) {
console.log(`⚠️ peerSync: asset ${safeName} has no content-length — refusing pull`);
return;
}
+ const contentLength = Number(res.headers.get('content-length'));
+ if (!Number.isFinite(contentLength) || contentLength <= 0) {
+ console.log(`⚠️ peerSync: asset ${safeName} has invalid content-length (${res.headers.get('content-length')}) — refusing pull`);
+ return;
+ }
if (contentLength > ASSET_PULL_MAX_BYTES) {
console.log(`⚠️ peerSync: asset ${safeName} too large (${contentLength}) — refusing pull`);
return;
diff --git a/server/services/sharing/tombstoneGc.js b/server/services/sharing/tombstoneGc.js
index dfd895a629..d64a07c5b5 100644
--- a/server/services/sharing/tombstoneGc.js
+++ b/server/services/sharing/tombstoneGc.js
@@ -85,6 +85,12 @@ async function snapshotPeerIdsForKind(recordKind) {
return peers
.filter((p) => {
if (!p?.enabled) return false;
+ // Mirror syncOrchestrator's syncAllPeers gate — a globally-silenced
+ // peer (syncEnabled === false) never receives snapshots, so it can't
+ // resurrect a pruned tombstone. Without this filter, a silenced peer's
+ // stale syncCategories map permanently stalls GC by reporting "snapshot
+ // peer not covered by per-record sub" → cutoff = null → refuse to prune.
+ if (p.syncEnabled === false) return false;
const cats = p.syncCategories;
return !!cats && typeof cats === 'object' && cats[category] === true;
})
diff --git a/server/services/universeBuilder.js b/server/services/universeBuilder.js
index 0246cba76b..668519c608 100644
--- a/server/services/universeBuilder.js
+++ b/server/services/universeBuilder.js
@@ -1179,18 +1179,23 @@ export async function updateUniverse(id, patchOrMutator = {}) {
// by per-record subs (see syncOrchestrator.categoriesCoveredByPeerSync),
// so without this re-subscribe the record would be silently
// invisible to those peers.
+ // Await the dynamic import — fire-and-forget .then() resolves on a
+ // microtask AFTER the synchronous emitRecordUpdated below, so the
+ // peerSync 'updated' listener would schedule pushes against subs the
+ // user just disabled. The await keeps the documented "BEFORE
+ // emitRecordUpdated" contract honest.
if (prevEphemeral && !nextEphemeral) {
- import('./sharing/peerSync.js').then(({ autoSubscribeRecordToAllPeers }) =>
- autoSubscribeRecordToAllPeers('universe', merged.id)
- ).catch((err) => {
- console.log(`⚠️ universe: re-subscribe after un-ephemeralizing failed: ${err.message}`);
- });
+ await import('./sharing/peerSync.js')
+ .then(({ autoSubscribeRecordToAllPeers }) => autoSubscribeRecordToAllPeers('universe', merged.id))
+ .catch((err) => {
+ console.log(`⚠️ universe: re-subscribe after un-ephemeralizing failed: ${err.message}`);
+ });
} else if (!prevEphemeral && nextEphemeral) {
- import('./sharing/peerSync.js').then(({ unsubscribeAllForRecord }) =>
- unsubscribeAllForRecord('universe', merged.id)
- ).catch((err) => {
- console.log(`⚠️ universe: unsubscribe after ephemeralizing failed: ${err.message}`);
- });
+ await import('./sharing/peerSync.js')
+ .then(({ unsubscribeAllForRecord }) => unsubscribeAllForRecord('universe', merged.id))
+ .catch((err) => {
+ console.log(`⚠️ universe: unsubscribe after ephemeralizing failed: ${err.message}`);
+ });
}
emitRecordUpdated('universe', merged.id);
return merged;