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): version the brain reconcile checksum cache, fix StrictMode autoscroll guard, refresh stale import auto-fill

[._.]/ Adam Eivy6ca56a7aebea
diff --git a/client/src/hooks/useAutoscroll.js b/client/src/hooks/useAutoscroll.js
index 959230566e..b8f87c597e 100644
--- a/client/src/hooks/useAutoscroll.js
+++ b/client/src/hooks/useAutoscroll.js
@@ -21,8 +21,16 @@ export default function useAutoscroll(containerRef, { initialPxPerSec = 30 } = {
const pxPerSecRef = useRef(pxPerSec);
pxPerSecRef.current = pxPerSec;
+ // Reset to true in setup, not just initialized: StrictMode dev runs effects
+ // setup→cleanup→setup on the same instance (refs persist), so a cleanup-only
+ // guard would stay false forever and wheel-pause / bottom-stop would no-op.
+ // (The CLAUDE.md "never reset to true" rule is for deferred network emits,
+ // where staying false is the safe direction — here it gates live UI.)
const mountedRef = useRef(true);
- useEffect(() => () => { mountedRef.current = false; }, []);
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => { mountedRef.current = false; };
+ }, []);
useEffect(() => {
if (!playing) return undefined;
diff --git a/client/src/pages/SongBookImport.jsx b/client/src/pages/SongBookImport.jsx
index 11794eeb5c..71f254e6fd 100644
--- a/client/src/pages/SongBookImport.jsx
+++ b/client/src/pages/SongBookImport.jsx
@@ -14,7 +14,7 @@
* createSong → navigate to the new song's viewer.
*/
-import { useMemo, useState, useCallback } from 'react';
+import { useMemo, useRef, useState, useCallback } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import { ListMusic, ArrowLeft, ClipboardPaste, Eraser, Wand2, Globe, FileText, Save } from 'lucide-react';
import toast from '../components/ui/Toast';
@@ -81,10 +81,22 @@ export default function SongBookImport() {
const [stage, setStage] = useState('new');
const [tags, setTags] = useState('');
+ // Last values WE auto-filled — so a second import can replace a stale
+ // auto-fill (still equal to what we set) without clobbering user edits.
+ const autoFilledRef = useRef({ title: '', artist: '' });
+
const applyMetaDefaults = useCallback((meta) => {
- // Prefill only untouched fields — never clobber what the user typed.
- if (meta?.title) setTitle((cur) => cur || meta.title);
- if (meta?.artist) setArtist((cur) => cur || meta.artist);
+ // Prefill untouched fields; a field still holding the PREVIOUS auto-fill
+ // counts as untouched, so importing song B after song A refreshes it.
+ const prev = { ...autoFilledRef.current };
+ if (meta?.title) {
+ autoFilledRef.current.title = meta.title;
+ setTitle((cur) => (!cur || cur === prev.title ? meta.title : cur));
+ }
+ if (meta?.artist) {
+ autoFilledRef.current.artist = meta.artist;
+ setArtist((cur) => (!cur || cur === prev.artist ? meta.artist : cur));
+ }
}, []);
const onPasteButton = useCallback(async () => {
diff --git a/server/services/syncOrchestrator.js b/server/services/syncOrchestrator.js
index dad6f75e52..5c6f2dcf1a 100644
--- a/server/services/syncOrchestrator.js
+++ b/server/services/syncOrchestrator.js
@@ -15,6 +15,7 @@ import { getPeers, DEFAULT_SYNC_CATEGORIES, allSyncCategoriesOn, updatePeer, get
import { peerBaseUrl } from '../lib/peerUrl.js';
import { peerAuthHeaders } from '../lib/peerHttpClient.js';
import * as brainSync from './brainSync.js';
+import { BRAIN_ENTITY_TYPES } from './brainStorage.js';
import * as brainSyncLog from './brainSyncLog.js';
import * as brainReconcile from './brainReconcile.js';
import * as memorySync from './memorySync.js';
@@ -194,10 +195,22 @@ async function syncBrainFromPeer(peer, cursor) {
// cache the peer checksum so step 2 short-circuits next cycle.
// Returns `brainChecksum` so the caller caches the converged value on the
// cursor (cache key is the peer checksum we reconciled against).
- let brainChecksum = cursor.brainChecksum ?? null;
+ //
+ // The cached checksum is VERSIONED by this install's entity-type list
+ // (`brainChecksumTypes`): a peer running older code silently skips unknown
+ // types when applying a snapshot, yet still caches the remote checksum. If
+ // that cache survived an upgrade, step 2 would short-circuit against an
+ // unchanged remote and the skipped records (e.g. `songs`) would stay absent
+ // until an unrelated remote mutation happened to change the checksum. A
+ // signature mismatch (or a legacy cursor with no signature) treats the cache
+ // as cold, forcing one full reconcile after any enrollment change.
+ const typesSignature = [...BRAIN_ENTITY_TYPES].sort().join(',');
+ const cachedChecksum =
+ cursor.brainChecksumTypes === typesSignature ? (cursor.brainChecksum ?? null) : null;
+ let brainChecksum = cachedChecksum;
const remote = await fetchPeer(peer, '/api/brain/reconcile/checksum');
const remoteChecksum = isNonEmptyStr(remote?.checksum) ? remote.checksum : null;
- if (remoteChecksum && remoteChecksum !== cursor.brainChecksum) {
+ if (remoteChecksum && remoteChecksum !== cachedChecksum) {
const localChecksum = await brainReconcile.getBrainChecksum().catch(() => null);
if (remoteChecksum === localChecksum) {
// Already converged — record the peer checksum so we skip next cycle.
@@ -216,7 +229,7 @@ async function syncBrainFromPeer(peer, cursor) {
}
}
- return { brainSeq, totalApplied, brainChecksum };
+ return { brainSeq, totalApplied, brainChecksum, brainChecksumTypes: typesSignature };
}
/**
@@ -753,6 +766,11 @@ export async function syncWithPeer(peer) {
// the prior value so we don't lose the skip-optimization on a blip.
if (isNonEmptyStr(brainResult.brainChecksum)) {
cursors[peerId].brainChecksum = brainResult.brainChecksum;
+ // Stamp the entity-type signature the cache is valid for — an
+ // enrollment change (new brain type) invalidates the cached checksum
+ // so the first post-upgrade cycle re-reconciles records that older
+ // code skipped as unknown types.
+ cursors[peerId].brainChecksumTypes = brainResult.brainChecksumTypes;
}
}
if (memoryResult.memorySeq !== (cursor.memorySeq ?? '0')) cursors[peerId].memorySeq = memoryResult.memorySeq;
diff --git a/server/services/syncOrchestrator.test.js b/server/services/syncOrchestrator.test.js
index ad67c9b457..3cce6b4c14 100644
--- a/server/services/syncOrchestrator.test.js
+++ b/server/services/syncOrchestrator.test.js
@@ -22,6 +22,15 @@ vi.mock('./brainSyncLog.js', () => ({
vi.mock('./brainSync.js', () => ({
applyRemoteChanges: vi.fn()
}));
+// Real brainStorage builds data paths at module load, which the fileUtils mock
+// breaks — the orchestrator only needs the type list for the checksum-cache
+// signature. Keep it a stable literal here; the real list is pinned elsewhere.
+vi.mock('./brainStorage.js', () => ({
+ BRAIN_ENTITY_TYPES: Object.freeze([
+ 'people', 'projects', 'ideas', 'admin', 'memories',
+ 'links', 'buckets', 'journals', 'inbox', 'songs',
+ ]),
+}));
vi.mock('./brainReconcile.js', () => ({
getBrainChecksum: vi.fn().mockResolvedValue('local-cksum'),
getBrainSnapshot: vi.fn(),
@@ -88,6 +97,7 @@ vi.mock('fs/promises', () => ({
import { readJSONFile } from '../lib/fileUtils.js';
import { getPeers } from './instances.js';
import { applyRemoteChanges as applyBrainChanges } from './brainSync.js';
+import { BRAIN_ENTITY_TYPES } from './brainStorage.js';
import { applyRemoteChanges as applyMemoryChanges } from './memorySync.js';
import { applyRemoteChanges as applyCatalogChanges } from './catalogSync.js';
import { instanceEvents } from './instanceEvents.js';
@@ -719,7 +729,10 @@ describe('syncOrchestrator', () => {
});
it('SKIPS reconcile entirely when peer checksum matches the cached cursor checksum', async () => {
- readJSONFile.mockImplementation(async () => ({ [mockPeer.instanceId]: { brainSeq: 0, brainChecksum: 'cached-DDD' } }));
+ const typesSig = [...BRAIN_ENTITY_TYPES].sort().join(',');
+ readJSONFile.mockImplementation(async () => ({
+ [mockPeer.instanceId]: { brainSeq: 0, brainChecksum: 'cached-DDD', brainChecksumTypes: typesSig },
+ }));
routeFetch({ checksum: { checksum: 'cached-DDD' }, snapshot: { records: {} } });
await syncWithPeer(mockPeer);
@@ -729,6 +742,28 @@ describe('syncOrchestrator', () => {
expect(applyBrainSnapshot).not.toHaveBeenCalled();
});
+ it('IGNORES a cached checksum from a different entity-type enrollment (version-skew healing)', async () => {
+ // An older install skipped unknown types (e.g. `songs`) while applying a
+ // snapshot yet cached the peer's checksum. Post-upgrade, that cache must
+ // NOT short-circuit reconcile — a stale/absent type signature is cold.
+ getBrainChecksum.mockResolvedValue('local-post-upgrade');
+ readJSONFile.mockImplementation(async () => ({
+ [mockPeer.instanceId]: {
+ brainSeq: 0,
+ brainChecksum: 'cached-DDD', // matches the remote, but from old code
+ brainChecksumTypes: 'people,projects', // pre-songs enrollment (also covers absent)
+ },
+ }));
+ routeFetch({ checksum: { checksum: 'cached-DDD' }, snapshot: { records: {}, checksum: 'cached-DDD' } });
+
+ await syncWithPeer(mockPeer);
+
+ // Stale signature → cache treated as cold → local checksum computed,
+ // mismatch → snapshot pulled and merged.
+ expect(getBrainChecksum).toHaveBeenCalled();
+ expect(applyBrainSnapshot).toHaveBeenCalled();
+ });
+
it('falls back to delta-only when peer is too old to expose /reconcile/checksum', async () => {
mockFetch.mockImplementation(async (url) => {
if (url.includes('/api/brain/sync')) return { ok: true, json: async () => ({ changes: [], maxSeq: 0, hasMore: false }) };