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

fix: preserve Persistent Mind message idempotency (#5169)

Adam Eivy5ef199bc4975
diff --git a/scripts/migrations/303-persistent-mind-image-attachments.js b/scripts/migrations/303-persistent-mind-image-attachments.js
index 184bdffd0a..6b20cebb86 100644
--- a/scripts/migrations/303-persistent-mind-image-attachments.js
+++ b/scripts/migrations/303-persistent-mind-image-attachments.js
@@ -23,7 +23,8 @@ export default {
return { updated: 0, reason: 'no-persistent-mind' };
}
if (existing.schemaVersion === PERSISTENT_MIND_SCHEMA_VERSION
- && Array.isArray(existing.pendingAttachments)) {
+ && Array.isArray(existing.pendingAttachments)
+ && Array.isArray(existing.recentMessageFingerprints)) {
return { updated: 0, reason: 'already-applied' };
}
@@ -33,6 +34,9 @@ export default {
pendingAttachments: Array.isArray(existing.pendingAttachments)
? existing.pendingAttachments
: [],
+ recentMessageFingerprints: Array.isArray(existing.recentMessageFingerprints)
+ ? existing.recentMessageFingerprints
+ : [],
};
await atomicWrite(statePath, state);
console.log('🧠 migration 303: added Persistent Mind image attachment state');
diff --git a/scripts/migrations/303-persistent-mind-image-attachments.test.js b/scripts/migrations/303-persistent-mind-image-attachments.test.js
index 34c3a68e58..ae6dbcd0e7 100644
--- a/scripts/migrations/303-persistent-mind-image-attachments.test.js
+++ b/scripts/migrations/303-persistent-mind-image-attachments.test.js
@@ -43,13 +43,19 @@ describe('migration 303 — persistent mind image attachments', () => {
expect(migrated).toMatchObject({
schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,
pendingAttachments: [],
+ recentMessageFingerprints: [],
queuedMessages: legacy.queuedMessages,
activeTurn: legacy.activeTurn,
});
});
it('is idempotent once the schema and pending index are present', async () => {
- const current = { schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION, pendingAttachments: [], enabled: false };
+ const current = {
+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,
+ pendingAttachments: [],
+ recentMessageFingerprints: [],
+ enabled: false,
+ };
await writeFile(statePath(), JSON.stringify({ persistentMind: current }));
await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });
diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.js
index 1d974d3193..fdfd797a07 100644
--- a/server/lib/persistentMind.js
+++ b/server/lib/persistentMind.js
@@ -6,6 +6,7 @@
* rules without depending on module-level process state.
*/
+import { createHash } from 'crypto';
import { PERSISTENT_MIND_ID } from './persistentMindTrajectory.js';
import { MAX_SCREENSHOT_BYTES } from './uploadLimits.js';
import { sanitizeFilename } from './mimeTypes.js';
@@ -70,6 +71,10 @@ const asCount = (value) => (
Number.isSafeInteger(value) && value >= 0 ? value : 0
);
+const asFingerprint = (value) => (
+ typeof value === 'string' && /^[a-f0-9]{64}$/.test(value) ? value : null
+);
+
const asAttachmentId = (value) => {
if (typeof value !== 'string') return null;
const id = value.trim();
@@ -164,6 +169,21 @@ export function normalizePersistentMindMessageImage(value) {
};
}
+/** Hash the bounded message content used to validate retries after completion. */
+export function persistentMindMessageFingerprint(value) {
+ const images = Array.isArray(value?.images)
+ ? value.images.map((image) => (typeof image === 'string' ? image : image?.attachmentId))
+ .map(asAttachmentId)
+ .filter(Boolean)
+ : [];
+ return createHash('sha256')
+ .update(JSON.stringify({
+ text: asBoundedString(value?.text, PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS),
+ images,
+ }))
+ .digest('hex');
+}
+
/** Build the safe upload response without exposing claim bookkeeping. */
export function publicPersistentMindAttachment(value) {
const attachment = normalizePersistentMindAttachment(value);
@@ -279,6 +299,15 @@ export function normalizePersistentMindState(raw) {
if (!id || recentMessageIds.includes(id)) continue;
recentMessageIds.push(id);
}
+ const recentMessageFingerprints = [];
+ const seenFingerprintIds = new Set();
+ for (const candidate of Array.isArray(source.recentMessageFingerprints) ? source.recentMessageFingerprints : []) {
+ const id = asId(candidate?.id);
+ const fingerprint = asFingerprint(candidate?.fingerprint);
+ if (!id || !fingerprint || seenFingerprintIds.has(id)) continue;
+ seenFingerprintIds.add(id);
+ recentMessageFingerprints.push({ id, fingerprint });
+ }
const pendingAttachments = [];
const seenAttachmentIds = new Set();
for (const candidate of Array.isArray(source.pendingAttachments) ? source.pendingAttachments : []) {
@@ -325,6 +354,7 @@ export function normalizePersistentMindState(raw) {
selfWake,
activeTurn,
recentMessageIds: recentMessageIds.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),
+ recentMessageFingerprints: recentMessageFingerprints.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),
lastCompletedTurnId: asId(source.lastCompletedTurnId) || null,
lastCompletedAt: asIso(source.lastCompletedAt),
nextEligibleWakeAt: asIso(source.nextEligibleWakeAt),
diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.js
index e0a8a4b78a..fe47463972 100644
--- a/server/services/persistentMindSupervisor.js
+++ b/server/services/persistentMindSupervisor.js
@@ -20,6 +20,7 @@ import {
normalizePersistentMindMessageImage,
nextPersistentMindWakeAt,
normalizePersistentMindState,
+ persistentMindMessageFingerprint,
persistentMindBackoffMs,
persistentMindTurnIsStale,
publicPersistentMindAttachment,
@@ -534,10 +535,19 @@ async function completeTurn(turnId, result, generation) {
const messageId = mind.activeTurn.wake.kind === 'message'
? mind.activeTurn.wake.message.id
: null;
+ const messageFingerprint = messageId
+ ? persistentMindMessageFingerprint(mind.activeTurn.wake.message)
+ : null;
const recentMessageIds = messageId
? [...mind.recentMessageIds.filter((id) => id !== messageId), messageId]
.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS)
: mind.recentMessageIds;
+ const recentMessageFingerprints = messageId
+ ? [...mind.recentMessageFingerprints.filter((entry) => entry.id !== messageId), {
+ id: messageId,
+ fingerprint: messageFingerprint,
+ }].slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS)
+ : mind.recentMessageFingerprints;
const requestedWake = result?.selfWake && typeof result.selfWake === 'object'
? {
id: `wake-${randomUUID()}`,
@@ -555,6 +565,7 @@ async function completeTurn(turnId, result, generation) {
...mind,
activeTurn: null,
recentMessageIds,
+ recentMessageFingerprints,
selfWake: requestedWake,
lastCompletedTurnId: turnId,
lastCompletedAt: completedAt,
@@ -1021,10 +1032,24 @@ export async function enqueuePersistentMindMessage({ id = randomUUID(), text, im
const existingMessage = findMessageById(mind, messageId);
const claimedRecords = claimedAttachmentsForMessage(mind, messageId);
const duplicate = Boolean(existingMessage) || mind.recentMessageIds.includes(messageId);
+ const requestedFingerprint = persistentMindMessageFingerprint({
+ text: messageText,
+ images: attachmentIds,
+ });
+ const recentFingerprint = mind.recentMessageFingerprints.find((entry) => entry.id === messageId)?.fingerprint;
const existingImageIds = existingMessage
? imageIdsForMessage(existingMessage)
: claimedRecords.map((attachment) => attachment.attachmentId);
if (duplicate) {
+ if (!existingMessage && recentFingerprint && recentFingerprint !== requestedFingerprint) {
+ return {
+ mind,
+ value: attachmentFailure('A retry must use the same Persistent Mind message content', {
+ code: 'IDEMPOTENCY_CONFLICT',
+ status: 409,
+ }),
+ };
+ }
if (existingMessage && existingMessage.text !== messageText) {
return {
mind,
diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.js
index 15317899f6..fa246c6c18 100644
--- a/server/services/persistentMindSupervisor.test.js
+++ b/server/services/persistentMindSupervisor.test.js
@@ -174,6 +174,11 @@ describe('persistent mind supervisor', () => {
expect(mock.acquireSlot).toHaveBeenCalledTimes(1);
expect(mock.root.persistentMind.activeTurn).toBeNull();
expect(mock.root.persistentMind.recentMessageIds).toContain('message-1');
+ expect(mock.root.persistentMind.recentMessageFingerprints).toEqual([
+ { id: 'message-1', fingerprint: expect.stringMatching(/^[a-f0-9]{64}$/) },
+ ]);
+ expect(await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Changed after completion.' }))
+ .toMatchObject({ success: false, code: 'IDEMPOTENCY_CONFLICT', status: 409 });
expect(mock.recordUsage).toHaveBeenCalledWith('cos', expect.objectContaining({ actions: 1 }));
});