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 (self): pre-release fixes for v2.18.0

Adam Eivy7386ddc09b64
diff --git a/.changelog/v2.18.0.md b/.changelog/v2.18.0.md
index b2c96501a6..e31cdbe9c1 100644
--- a/.changelog/v2.18.0.md
+++ b/.changelog/v2.18.0.md
@@ -16,7 +16,6 @@ Released: 2026-06-09
- **[issue-1070] Federation sync is now bidirectional from one switch** — turning on a sync category for a peer (Brain, Goals, Universe, etc.) now automatically asks that peer to sync the same category back, so you no longer have to set the toggle on both machines by hand. Since you typically own every federated machine, enabling once establishes two-way sync. The Sync Categories panel explains this inline, and a new **Make mutual** button pushes the current set to a peer that was offline during an earlier change (or was configured one-directionally before this existed). Peers on older versions that don't understand the request simply stay one-directional until you toggle again — nothing breaks.
- **Songs: built-in alert stacks cleanly on mobile** — the "Built-in default" banner on the song page now stacks its label, description, and Refresh action vertically on narrow screens instead of cramming them onto one row, with full-width touch targets for the refresh/confirm buttons.
-- **[issue-1027] Songs: vocal takes remember their pitch analysis** — a recorded take now saves its tuner trace and color-match score so your accuracy isn't recomputed every time you reopen the song.
- **[issue-1060] Cleaner test runs** — browser-dependent tests now run only under their own test environment, so the server test run no longer reports spurious failures from double-running them.
- **[issue-1050] More reliable database exports** — manual database exports now pick a PostgreSQL dump tool that matches the database being exported, so an export no longer fails on machines with several Postgres versions installed.
- **[issue-909] CyberCity theme colors** — internal refactor of how the 3D city picks up your theme accent, replacing a fragile shared-state mechanism with a cleaner one; no change to how the city looks.
diff --git a/client/src/components/city/Building.jsx b/client/src/components/city/Building.jsx
index 45121ab6ad..65bbcd4612 100644
--- a/client/src/components/city/Building.jsx
+++ b/client/src/components/city/Building.jsx
@@ -1,4 +1,4 @@
-import { useRef, useState, useMemo } from 'react';
+import { useRef, useState, useMemo, useEffect } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { getBuildingHeight, BUILDING_PARAMS, PIXEL_FONT_URL, mixHex, seededRand } from './cityConstants';
@@ -408,6 +408,12 @@ export default function Building({ app, position, agentCount, onClick, playSfx,
[accentColor, width, height, seed, tintStructure]
);
+ // R3F does NOT dispose a CanvasTexture handed in via `map`/`emissiveMap` — it
+ // only frees objects it owns on unmount. Since the city no longer remounts on
+ // theme switch (issue-1064), each recolor recreates this texture and would
+ // strand the previous one in VRAM per building. Dispose it on replace + unmount.
+ useEffect(() => () => windowTexture.dispose(), [windowTexture]);
+
// Format name for building face
const displayName = useMemo(() => {
return (app.name || '').replace(/[-_.]/g, ' ').toUpperCase();
diff --git a/client/src/components/city/CityLandscape.jsx b/client/src/components/city/CityLandscape.jsx
index 0d7ee49615..09895d48bc 100644
--- a/client/src/components/city/CityLandscape.jsx
+++ b/client/src/components/city/CityLandscape.jsx
@@ -74,7 +74,13 @@ function TerrainPlane({ dayMix, accent }) {
},
side: THREE.DoubleSide,
depthWrite: true,
- }), [dayMix, accent]);
+ // accent intentionally NOT a dep — a theme switch updates the uniform in
+ // place (effect below) rather than recompiling the GLSL program. Matches the
+ // imperative-uniform pattern in CitySky / CityBillboards / CityVolumetricLights.
+ }), [dayMix]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // Push the accent into the existing material on theme change — no rebuild.
+ useEffect(() => { material.uniforms.uAccent.value.set(accent); }, [material, accent]);
// R3F doesn't dispose a material handed in via the `material` prop, so free the
// prior one when dayMix flips (Day/Night toggle) and on unmount.
diff --git a/client/src/components/songs/PitchTuner.jsx b/client/src/components/songs/PitchTuner.jsx
index 4dd2a9c639..b5a063e80c 100644
--- a/client/src/components/songs/PitchTuner.jsx
+++ b/client/src/components/songs/PitchTuner.jsx
@@ -129,6 +129,10 @@ export default function PitchTuner({ stream = null, a4 = 440 }) {
}, []);
const startStandalone = useCallback(async () => {
+ // Guard against a double-activation opening two mics (only the last lands in
+ // ownStreamRef, leaking the first). The button hides once standaloneOn flips,
+ // but a fast double event can re-enter before the re-render.
+ if (standaloneOn || trackerRef.current) return;
const src = await navigator.mediaDevices.getUserMedia({ audio: true }).catch((err) => {
toast.error(err?.message || 'Microphone access denied');
return null;
@@ -138,7 +142,7 @@ export default function PitchTuner({ stream = null, a4 = 440 }) {
ownStreamRef.current = src;
setStandaloneOn(true);
attach(src);
- }, [attach]);
+ }, [attach, standaloneOn]);
const active = Boolean(stream) || standaloneOn;
const quality = tuningQuality(reading.cents);
diff --git a/client/src/hooks/useColorMatch.js b/client/src/hooks/useColorMatch.js
index 530b901cd0..d5296c2b3e 100644
--- a/client/src/hooks/useColorMatch.js
+++ b/client/src/hooks/useColorMatch.js
@@ -61,6 +61,7 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =
const pitchRef = useRef({ hz: null }); // latest tracked pitch, read each rAF frame
const gradesRef = useRef({}); // mutable accumulator; flushed to state
const cursorRef = useRef(0); // lower-bound index hint for noteAtTime
+ const maxReachedRef = useRef(-1); // furthest note.index the timeline walked
const rafRef = useRef(null);
// Tear down the audio graph, tracker, metronome, and rAF loop. Idempotent.
@@ -83,6 +84,22 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =
const stop = useCallback(() => {
teardown();
if (!mountedRef.current) return;
+ // Fill MISSED for every note the timeline WALKED PAST (index <= maxReached)
+ // that never received a usable grade — so a note the singer skipped counts
+ // against the take. Notes never reached on an early stop stay absent, so
+ // they're correctly excluded from the denominator (summarizeAccuracy's
+ // contract). Iterate the timeline so we only seed real (non-rest) notes.
+ const timeline = timelineRef.current;
+ if (timeline && maxReachedRef.current >= 0) {
+ const filled = { ...gradesRef.current };
+ for (const n of timeline.notes) {
+ if (n.index <= maxReachedRef.current && !(n.index in filled)) {
+ filled[n.index] = GRADE.MISSED;
+ }
+ }
+ gradesRef.current = filled;
+ setNoteColors(filled);
+ }
setSummary(summarizeAccuracy(gradesRef.current));
setRunning(false);
setCountingIn(false);
@@ -104,6 +121,10 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =
const hit = noteAtTime(timeline, elapsedMs, cursorRef.current);
if (hit) {
cursorRef.current = hit.idx;
+ // Track the furthest note the timeline actually reached, so finalize() can
+ // fill MISSED for notes WALKED PAST but never sung (they count against the
+ // take) while still EXCLUDING notes never reached on an early stop.
+ if (hit.note.index > maxReachedRef.current) maxReachedRef.current = hit.note.index;
const g = gradeNote(pitchRef.current.hz, hit.note.targetHz);
const prev = gradesRef.current[hit.note.index] ?? GRADE.MISSED;
const next = bestGrade(prev, g);
@@ -127,6 +148,7 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =
teardown();
gradesRef.current = {};
cursorRef.current = 0;
+ maxReachedRef.current = -1;
timelineRef.current = timeline;
setNoteColors({});
setSummary(null);
diff --git a/client/src/lib/colorMatch.test.js b/client/src/lib/colorMatch.test.js
index b51731403c..19a3e857f9 100644
--- a/client/src/lib/colorMatch.test.js
+++ b/client/src/lib/colorMatch.test.js
@@ -154,4 +154,23 @@ describe('summarizeAccuracy', () => {
expect(summarizeAccuracy({}).percentInTune).toBe(0);
expect(summarizeAccuracy([]).percentInTune).toBe(0);
});
+
+ // Release review finding: a note the singer WALKED PAST but never produced a
+ // usable pitch for must be recorded as MISSED (not absent) so it counts
+ // against the take. useColorMatch.stop() fills these before summarizing; here
+ // we pin the lib contract that MISSED is in the denominator (unlike PENDING).
+ it('counts MISSED notes in the denominator (a skipped note lowers the score)', () => {
+ const grades = { 0: GRADE.IN_TUNE, 1: GRADE.MISSED, 2: GRADE.MISSED, 3: GRADE.IN_TUNE };
+ const s = summarizeAccuracy(grades);
+ expect(s.graded).toBe(4);
+ expect(s.counts.missed).toBe(2);
+ expect(s.percentInTune).toBe(50);
+ });
+
+ it('an all-MISSED take scores 0% over every walked note', () => {
+ const grades = { 0: GRADE.MISSED, 1: GRADE.MISSED, 2: GRADE.MISSED };
+ const s = summarizeAccuracy(grades);
+ expect(s.graded).toBe(3);
+ expect(s.percentInTune).toBe(0);
+ });
});
diff --git a/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.js b/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.js
index 514d447351..610f58f46d 100644
--- a/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.js
+++ b/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.js
@@ -80,7 +80,7 @@ function replayTerminal(entries) {
* Returns { stores, compactedLines, ghostsTombstoned } with mutated stores and
* the compacted JSONL line array (seq numbers preserved).
*/
-export function computeBrainCleanup(logEntries, stores, { nowIso }) {
+export function computeBrainCleanup(logEntries, stores) {
// Newest delete updatedAt per (type/id), for ghost detection.
const newestDelete = new Map();
for (const e of logEntries) {
@@ -105,7 +105,12 @@ export function computeBrainCleanup(logEntries, stores, { nowIso }) {
_deleted: true,
updatedAt: del.updatedAt,
originInstanceId: record.originInstanceId ?? del.originInstanceId ?? 'unknown',
- deletedAt: nowIso,
+ // Match the runtime tombstone invariant (makeTombstone: deletedAt ===
+ // updatedAt at birth) rather than this migration's own run time, so
+ // two peers that run the cleanup independently produce identical
+ // tombstones. (The reconcile checksum also excludes deletedAt, so this
+ // is belt-and-suspenders for any code that DOES compare the field.)
+ deletedAt: del.updatedAt,
};
ghostsTombstoned++;
}
@@ -190,8 +195,7 @@ export async function up({ rootDir }) {
}
}
- const nowIso = new Date().toISOString();
- const { compactedLines, ghostsTombstoned } = computeBrainCleanup(logEntries, stores, { nowIso });
+ const { compactedLines, ghostsTombstoned } = computeBrainCleanup(logEntries, stores);
// Persist tombstoned stores (only those we loaded; only when changed is fine
// to skip — rewriting an unchanged store is harmless and keeps the code simple).
diff --git a/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.test.js b/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.test.js
index 84d3727a3b..96e9a7c7c7 100644
--- a/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.test.js
+++ b/scripts/migrations/080-brain-tombstone-and-synclog-cleanup.test.js
@@ -53,6 +53,10 @@ describe('migration 080 — brain tombstone + sync-log cleanup', () => {
const rec = readStore('links').records['ghost-1'];
expect(rec._deleted).toBe(true);
expect(rec.updatedAt).toBe('2026-01-02T00:00:00.000Z');
+ // deletedAt must equal updatedAt (the delete instant), matching the runtime
+ // makeTombstone invariant — NOT the migration's own run time. Otherwise two
+ // peers running the cleanup independently stamp different deletedAt values.
+ expect(rec.deletedAt).toBe('2026-01-02T00:00:00.000Z');
});
it('leaves a live record whose delete is OLDER than the record (legit re-create) alone', async () => {
@@ -153,7 +157,7 @@ describe('migration 080 — brain tombstone + sync-log cleanup', () => {
{ seq: 10, op: 'create', type: 'links', id: 'a', record: { updatedAt: '2026-01-01T00:00:00.000Z' } },
{ seq: 99, op: 'delete', type: 'links', id: 'a', record: { updatedAt: '2026-01-02T00:00:00.000Z' } },
];
- const { compactedLines } = computeBrainCleanup(log, {}, { nowIso: '2026-06-08T00:00:00.000Z' });
+ const { compactedLines } = computeBrainCleanup(log, {});
const seqs = compactedLines.map((l) => JSON.parse(l).seq);
expect(Math.max(...seqs)).toBe(99);
});
@@ -163,7 +167,7 @@ describe('migration 080 — brain tombstone + sync-log cleanup', () => {
{ seq: 10, op: 'create', type: 'links', id: 'a', record: { updatedAt: '2026-01-01T00:00:00.000Z' } },
{ seq: 200 }, // a malformed/typeless high-seq entry — must still anchor the cursor
];
- const { compactedLines } = computeBrainCleanup(log, {}, { nowIso: '2026-06-08T00:00:00.000Z' });
+ const { compactedLines } = computeBrainCleanup(log, {});
const seqs = compactedLines.map((l) => JSON.parse(l).seq);
expect(Math.max(...seqs)).toBe(200);
});
diff --git a/server/services/brainReconcile.js b/server/services/brainReconcile.js
index 582768a443..b542f52aa8 100644
--- a/server/services/brainReconcile.js
+++ b/server/services/brainReconcile.js
@@ -69,15 +69,45 @@ function stableStringify(value) {
return `{${keys.map(k => `${JSON.stringify(k)}:${stableStringify(value[k])}`).join(',')}}`;
}
+/**
+ * Strip machine-local fields that are NOT part of converged LWW state before
+ * hashing. `deletedAt` is a tombstone's GC clock (when this machine first saw
+ * the delete) — two peers stamp it at different wall-clock instants (and the
+ * #080 cleanup migration sets it to its own run time), so it differs even when
+ * both peers agree on the record's logical state (`_deleted` + `updatedAt`).
+ * Hashing it would make the reconcile checksum permanently mismatch and force a
+ * full snapshot exchange every cycle until GC prunes the tombstones. The delete
+ * instant that actually matters for convergence is `updatedAt` (the LWW clock),
+ * which IS hashed; `deletedAt` is still SENT in snapshots so the receiver can GC.
+ */
+function checksumView(rawMap) {
+ const view = {};
+ for (const type of Object.keys(rawMap)) {
+ const records = {};
+ for (const id of Object.keys(rawMap[type])) {
+ const rec = rawMap[type][id];
+ if (rec && typeof rec === 'object' && !Array.isArray(rec) && 'deletedAt' in rec) {
+ const { deletedAt, ...rest } = rec;
+ records[id] = rest;
+ } else {
+ records[id] = rec;
+ }
+ }
+ view[type] = records;
+ }
+ return view;
+}
+
/**
* Deterministic md5 over the canonical brain record map. Matches `dataSync`'s
* `computeChecksum` shape (md5 of a JSON string) but uses a key-sorted
* serialization so two installs with identical brain state hash identically
* regardless of per-record field order. `buildRawMap` sorts the type + id
- * levels; `stableStringify` extends order-independence into each record's fields.
+ * levels; `stableStringify` extends order-independence into each record's fields;
+ * `checksumView` drops the machine-local `deletedAt` GC clock from convergence.
*/
function computeChecksum(rawMap) {
- return createHash('md5').update(stableStringify(rawMap)).digest('hex');
+ return createHash('md5').update(stableStringify(checksumView(rawMap))).digest('hex');
}
/**
diff --git a/server/services/brainReconcile.test.js b/server/services/brainReconcile.test.js
index cb59589730..4516e6cbbc 100644
--- a/server/services/brainReconcile.test.js
+++ b/server/services/brainReconcile.test.js
@@ -62,6 +62,28 @@ describe('brainReconcile checksum', () => {
expect(live).not.toBe(tomb);
});
+ // Release review finding: `deletedAt` is a machine-local GC clock — two peers
+ // stamp it at different instants for the same logical delete (and migration 080
+ // sets it to its own run time). Hashing it would make two converged peers
+ // mismatch forever and re-pull the snapshot every cycle. It must be EXCLUDED
+ // from the checksum; `updatedAt` (the LWW clock) still distinguishes deletes.
+ it('ignores deletedAt (the local GC clock) so two peers converge on a delete', async () => {
+ emptyStores({ links: { a: { _deleted: true, updatedAt: '2026-01-05T00:00:00.000Z', deletedAt: '2026-01-05T00:00:00.000Z', originInstanceId: 'x' } } });
+ const peerA = await getBrainChecksum();
+ // Same logical tombstone, different deletedAt (saw the delete a day later).
+ emptyStores({ links: { a: { _deleted: true, updatedAt: '2026-01-05T00:00:00.000Z', deletedAt: '2026-01-06T12:34:56.000Z', originInstanceId: 'x' } } });
+ const peerB = await getBrainChecksum();
+ expect(peerA).toBe(peerB);
+ });
+
+ it('still distinguishes two tombstones with different updatedAt (LWW clock)', async () => {
+ emptyStores({ links: { a: { _deleted: true, updatedAt: '2026-01-05T00:00:00.000Z', deletedAt: '2026-01-05T00:00:00.000Z', originInstanceId: 'x' } } });
+ const older = await getBrainChecksum();
+ emptyStores({ links: { a: { _deleted: true, updatedAt: '2026-01-09T00:00:00.000Z', deletedAt: '2026-01-05T00:00:00.000Z', originInstanceId: 'x' } } });
+ const newer = await getBrainChecksum();
+ expect(older).not.toBe(newer);
+ });
+
// #1077 review finding: plain JSON.stringify preserves field-insertion order,
// so two installs holding the SAME logical record (e.g. one migrated by
// backfillOriginInstanceId, which appends originInstanceId LAST) would hash
diff --git a/server/services/brainStorage.js b/server/services/brainStorage.js
index 4dcdd9f1d8..2cb2ad322b 100644
--- a/server/services/brainStorage.js
+++ b/server/services/brainStorage.js
@@ -737,6 +737,14 @@ export const deleteBucket = (id) => remove('buckets', id);
* Apply a remote record to a JSON store (last-writer-wins by updatedAt)
*/
export async function applyRemoteRecord(type, id, record, op) {
+ // Reject prototype-polluting ids before they reach `data.records[id]`. JSON
+ // serialization drops a `__proto__` key so there's no live data corruption,
+ // but accepting it would return `applied:true` and append a phantom relay
+ // entry that can never converge (the reconcile snapshot path guards this too;
+ // centralizing it here covers BOTH the delta-sync and snapshot callers).
+ if (id === '__proto__' || id === 'constructor' || id === 'prototype') {
+ return { applied: false, reason: 'invalid_id' };
+ }
return withStoreWriteLock(async () => {
const data = await loadJsonStore(type);