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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: serialize mind ledger hydration
[._.]/ Adam Eivydeeb19e78050
diff --git a/server/lib/agentRunEvents.js b/server/lib/agentRunEvents.jsindex 4e7db7d867..bee4855e63 100644--- a/server/lib/agentRunEvents.js+++ b/server/lib/agentRunEvents.js@@ -325,6 +325,21 @@ export function isStoredRunEvent(value) {const nullableId = (value) => (typeof value === 'string' && value.trim() ? value.trim().slice(0, 128) : null);+// Persistent-mind continuity is ledger metadata, not caller content. Keep it+// outside the bounded payload walk so a full caller object cannot evict the+// predecessor link that rollup coverage uses to detect a missing generation.+function redactEventData(data, mindEvent) {+ if (!mindEvent || !data || typeof data !== 'object' || Array.isArray(data)+ || !Object.hasOwn(data, 'previousSequence')) {+ return redactRunEventData(data);+ }+ const { previousSequence, ...callerData } = data;+ return {+ ...redactRunEventData(callerData),+ previousSequence,+ };+}+/*** Build a validated, redacted ledger envelope.*@@ -368,7 +383,7 @@ export function buildRunEvent({ kind, runId, agentId, taskId, mindId, turnId, seagentId: nullableId(agentId),taskId: nullableId(taskId),at: timestamp,- data: redactRunEventData(data)+ data: redactEventData(data, mindEvent)};if (mindEvent) {core.mindId = nullableId(mindId);diff --git a/server/lib/agentRunEvents.test.js b/server/lib/agentRunEvents.test.jsindex 55c8f354b9..00051ca591 100644--- a/server/lib/agentRunEvents.test.js+++ b/server/lib/agentRunEvents.test.js@@ -256,6 +256,20 @@ describe('redactRunEventData — privacy', () => {expect(event.data.prompt).toEqual({ redacted: 'content', chars: 20 });expect(event.data.body).toEqual({ redacted: 'content', chars: null });});++ it('reserves persistent-mind predecessor provenance outside the payload key cap', () => {+ const callerData = Object.fromEntries(Array.from({ length: RUN_EVENT_LIMITS.maxObjectKeys }, (_, index) => [`k${index}`, index]));+ const event = buildRunEvent({+ kind: 'mind.capability.request',+ mindId: 'cos-persistent-mind',+ sequence: 42,+ at: AT,+ data: { ...callerData, previousSequence: 41 },+ });++ expect(event.data.previousSequence).toBe(41);+ expect(event.data.k0).toBe(0);+ });});describe('projectRunStates — replayable status', () => {diff --git a/server/services/agentRunEventLog.js b/server/services/agentRunEventLog.jsindex 7ff66be68c..0bfc8ce43c 100644--- a/server/services/agentRunEventLog.js+++ b/server/services/agentRunEventLog.js@@ -138,6 +138,11 @@ let lastPrunedAt = null;// Serializes appends; also the handle callers await.let appendQueue = Promise.resolve();+// A read can be the first caller after a restart, while an append arrives in+// the same event-loop turn. Keep all first-load callers on one snapshot so a+// slower read cannot overwrite the append path's in-memory sequence/index+// state with an older view of disk.+let hydrationPromise = null;/** eventId → retention metadata, for the duplicate check. */function indexById(events, { persistentMind = false } = {}) {@@ -194,60 +199,69 @@ function isStoredDuplicate(eventId, cutoff) {async function hydrate() {if (activeIds) return;- let [active, archive, mindActive, mindArchive, sequenceStore] = await Promise.all([- readJSONLFile(ACTIVE_PATH),- readJSONLFile(ARCHIVE_PATH),- readJSONLFile(MIND_ACTIVE_PATH),- readJSONLFile(MIND_ARCHIVE_PATH),- readJSONFileStrict(MIND_SEQUENCE_PATH, { schemaVersion: MIND_SEQUENCE_SCHEMA_VERSION, minds: {} }),- ]);- const legacyArchive = archive.filter((event) => isPersistentMindEventKind(event?.kind));- const legacyActive = active.filter((event) => isPersistentMindEventKind(event?.kind));- if (legacyArchive.length > 0 || legacyActive.length > 0) {- const recovered = normalizeMindGenerations([- ...mindArchive,- ...mindActive,- ...legacyArchive,- ...legacyActive,+ if (hydrationPromise) return hydrationPromise;+ const pending = (async () => {+ let [active, archive, mindActive, mindArchive, sequenceStore] = await Promise.all([+ readJSONLFile(ACTIVE_PATH),+ readJSONLFile(ARCHIVE_PATH),+ readJSONLFile(MIND_ACTIVE_PATH),+ readJSONLFile(MIND_ARCHIVE_PATH),+ readJSONFileStrict(MIND_SEQUENCE_PATH, { schemaVersion: MIND_SEQUENCE_SCHEMA_VERSION, minds: {} }),]);- // Destination-first makes recovery retry-safe if a later source rewrite- // fails. This path handles upgrade -> rollback -> upgrade installs after- // migration 301 is already marked applied.- await writeJSONLines(MIND_ARCHIVE_PATH, recovered.archive);- await writeJSONLines(MIND_ACTIVE_PATH, recovered.active);- archive = archive.filter((event) => !isPersistentMindEventKind(event?.kind));- active = active.filter((event) => !isPersistentMindEventKind(event?.kind));- await writeJSONLines(ARCHIVE_PATH, archive);- await writeJSONLines(ACTIVE_PATH, active);- mindArchive = recovered.archive;- mindActive = recovered.active;- console.log(`🧠 Re-homed ${legacyArchive.length + legacyActive.length} rollback-era persistent mind event(s)`);- }- const invalidSequenceStore = !sequenceStore.ok || !sequenceStore.value- || typeof sequenceStore.value !== 'object' || Array.isArray(sequenceStore.value)- || sequenceStore.value.schemaVersion !== MIND_SEQUENCE_SCHEMA_VERSION- || !sequenceStore.value.minds || typeof sequenceStore.value.minds !== 'object'- || Array.isArray(sequenceStore.value.minds)- || Object.entries(sequenceStore.value.minds).some(([mindId, sequence]) => (- !mindId || mindId.length > 128 || !Number.isSafeInteger(sequence) || sequence < 0- ));- const validSequenceStore = !invalidSequenceStore;- activeIds = indexById(active);- archiveIds = indexById(archive);- mindActiveIds = indexById(mindActive, { persistentMind: true });- mindArchiveIds = indexById(mindArchive, { persistentMind: true });- activeCount = active.length;- mindActiveCount = mindActive.length;- mindSequenceCheckpointError = validSequenceStore- ? null- : 'Persistent mind sequence checkpoint is unreadable or invalid';- mindSequenceHighWater = new Map(validSequenceStore ? Object.entries(sequenceStore.value.minds) : []);- for (const event of [...mindArchive, ...mindActive]) {- if (!event?.mindId || !Number.isSafeInteger(event.sequence)) continue;- mindSequenceHighWater.set(- event.mindId,- Math.max(mindSequenceHighWater.get(event.mindId) ?? -1, event.sequence)- );+ const legacyArchive = archive.filter((event) => isPersistentMindEventKind(event?.kind));+ const legacyActive = active.filter((event) => isPersistentMindEventKind(event?.kind));+ if (legacyArchive.length > 0 || legacyActive.length > 0) {+ const recovered = normalizeMindGenerations([+ ...mindArchive,+ ...mindActive,+ ...legacyArchive,+ ...legacyActive,+ ]);+ // Destination-first makes recovery retry-safe if a later source rewrite+ // fails. This path handles upgrade -> rollback -> upgrade installs after+ // migration 301 is already marked applied.+ await writeJSONLines(MIND_ARCHIVE_PATH, recovered.archive);+ await writeJSONLines(MIND_ACTIVE_PATH, recovered.active);+ archive = archive.filter((event) => !isPersistentMindEventKind(event?.kind));+ active = active.filter((event) => !isPersistentMindEventKind(event?.kind));+ await writeJSONLines(ARCHIVE_PATH, archive);+ await writeJSONLines(ACTIVE_PATH, active);+ mindArchive = recovered.archive;+ mindActive = recovered.active;+ console.log(`🧠 Re-homed ${legacyArchive.length + legacyActive.length} rollback-era persistent mind event(s)`);+ }+ const invalidSequenceStore = !sequenceStore.ok || !sequenceStore.value+ || typeof sequenceStore.value !== 'object' || Array.isArray(sequenceStore.value)+ || sequenceStore.value.schemaVersion !== MIND_SEQUENCE_SCHEMA_VERSION+ || !sequenceStore.value.minds || typeof sequenceStore.value.minds !== 'object'+ || Array.isArray(sequenceStore.value.minds)+ || Object.entries(sequenceStore.value.minds).some(([mindId, sequence]) => (+ !mindId || mindId.length > 128 || !Number.isSafeInteger(sequence) || sequence < 0+ ));+ const validSequenceStore = !invalidSequenceStore;+ activeIds = indexById(active);+ archiveIds = indexById(archive);+ mindActiveIds = indexById(mindActive, { persistentMind: true });+ mindArchiveIds = indexById(mindArchive, { persistentMind: true });+ activeCount = active.length;+ mindActiveCount = mindActive.length;+ mindSequenceCheckpointError = validSequenceStore+ ? null+ : 'Persistent mind sequence checkpoint is unreadable or invalid';+ mindSequenceHighWater = new Map(validSequenceStore ? Object.entries(sequenceStore.value.minds) : []);+ for (const event of [...mindArchive, ...mindActive]) {+ if (!event?.mindId || !Number.isSafeInteger(event.sequence)) continue;+ mindSequenceHighWater.set(+ event.mindId,+ Math.max(mindSequenceHighWater.get(event.mindId) ?? -1, event.sequence)+ );+ }+ })();+ hydrationPromise = pending;+ try {+ await pending;+ } finally {+ if (hydrationPromise === pending) hydrationPromise = null;}}@@ -624,5 +638,6 @@ export function __resetRunEventLogCache() {mindSequenceHighWater = null;mindSequenceCheckpointError = null;lastPrunedAt = null;+ hydrationPromise = null;appendQueue = Promise.resolve();}diff --git a/server/services/agentRunEventLog.test.js b/server/services/agentRunEventLog.test.jsindex dbc2889c13..5918f6c3d6 100644--- a/server/services/agentRunEventLog.test.js+++ b/server/services/agentRunEventLog.test.js@@ -170,6 +170,18 @@ describe('persistent-mind ordering, replay, and cursors', () => {expect(events.every((event, index) => index === 0 || event.sequence > events[index - 1].sequence)).toBe(true);});+ it('keeps predecessor provenance when a capability payload fills the key budget', async () => {+ const data = Object.fromEntries(Array.from({ length: 40 }, (_, index) => [`k${index}`, index]));+ const result = await appendMindEvent({+ kind: 'mind.capability.request',+ eventId: 'mind-capability:wide',+ data,+ });++ expect(result.event.data.previousSequence).toBeNull();+ expect(result.event.data.k39).toBe(39);+ });+it('deduplicates an explicit event id without consuming another sequence', async () => {const first = await appendMessage('one');const duplicate = await appendMessage('one');