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: close Persistent Mind update races (#5172)
[._.]/ Adam Eivye5d17344c694
diff --git a/docs/SELF_UPDATE.md b/docs/SELF_UPDATE.mdindex 63a6a68ca8..20b29b3a08 100644--- a/docs/SELF_UPDATE.md+++ b/docs/SELF_UPDATE.md@@ -64,4 +64,4 @@ Keep these three behaviors distinct. Collapsing them strips the user's agency ovThe managed update route refuses to restart into a different source revision while a queued Persistent Mind message or active turn carries image references. `GET /api/update/status` reports the privacy-safe `persistentMindImages` preflight (`safe`, queued count, and active-turn boolean), and `POST /api/update/execute` re-checks it before and after acquiring the update lock.-To recover, stop or drain the image-bearing messages, confirm the preflight is safe, create a normal PortOS backup, and retry the update. Claimed historical images do not block updates once their message has completed. PortOS does not offer a managed rollback command; manually checking out an older source revision while image-bearing work is queued or active is unsupported because schema-v2 readers cannot preserve those references.+To recover, drain the image-bearing messages, confirm the preflight is safe, create a normal PortOS backup, and retry the update. If a stopped or unavailable provider prevents the queue from draining, create a backup that includes `data/cos/state.json` and `data/screenshots/`, then explicitly retry the API request with `acknowledgePersistentMindImageBackup: true`; that acknowledgement is the recovery escape hatch and is never sent silently by the UI. Invalid or unreadable Persistent Mind state blocks the transition until it is restored from backup. Claimed historical images do not block updates once their message has completed. PortOS does not offer a managed rollback command; manually checking out an older source revision while image-bearing work is queued or active is unsupported because schema-v2 readers cannot preserve those references.diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.jsindex d40488febb..4814d61d0a 100644--- a/server/lib/persistentMind.js+++ b/server/lib/persistentMind.js@@ -409,18 +409,31 @@ export function requeuePersistentMindWake(raw, wake) {* work; completed historical assets do not make rollback unsafe.*/export function persistentMindImageWorkGuard(raw) {- const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};- const queuedImageMessages = (Array.isArray(source.queuedMessages) ? source.queuedMessages : [])+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);+ const hasValidImages = (value) => value.images === undefined || Array.isArray(value.images);+ const source = raw == null ? {} : raw;+ const queuedMessages = source?.queuedMessages;+ const activeTurn = source?.activeTurn;+ const activeMessage = activeTurn?.wake?.kind === 'message' ? activeTurn.wake.message : null;+ const trusted = isRecord(source)+ && (queuedMessages === undefined || (+ Array.isArray(queuedMessages)+ && queuedMessages.every((message) => isRecord(message) && hasValidImages(message))+ ))+ && (activeTurn == null || isRecord(activeTurn))+ && (activeMessage == null || (isRecord(activeMessage) && hasValidImages(activeMessage)));+ if (!trusted) {+ return { safe: false, trusted: false, queuedImageMessages: 0, activeImageMessage: false };+ }+ const queuedImageMessages = (Array.isArray(queuedMessages) ? queuedMessages : []).filter((message) => Array.isArray(message?.images) && message.images.length > 0).length;- const activeMessage = source.activeTurn?.wake?.kind === 'message'- ? source.activeTurn.wake.message- : null;const activeImageMessage = Boolean(activeMessage && Array.isArray(activeMessage.images) && activeMessage.images.length > 0,);return {safe: queuedImageMessages === 0 && !activeImageMessage,+ trusted: true,queuedImageMessages,activeImageMessage,};diff --git a/server/lib/persistentMind.test.js b/server/lib/persistentMind.test.jsindex 06633e6ee1..c71e2e8b2f 100644--- a/server/lib/persistentMind.test.js+++ b/server/lib/persistentMind.test.js@@ -175,11 +175,15 @@ describe('persistent mind state', () => {message: { id: 'active-image', images: [{ attachmentId: 'attachment-2' }] },},},- })).toEqual({ safe: false, queuedImageMessages: 1, activeImageMessage: true });+ })).toEqual({ safe: false, trusted: true, queuedImageMessages: 1, activeImageMessage: true });expect(persistentMindImageWorkGuard({queuedMessages: [{ id: 'text-only', text: 'Safe to preserve.' }],pendingAttachments: [{ attachmentId: 'completed-asset', claimedBy: 'completed-message' }],- })).toEqual({ safe: true, queuedImageMessages: 0, activeImageMessage: false });+ })).toEqual({ safe: true, trusted: true, queuedImageMessages: 0, activeImageMessage: false });+ expect(persistentMindImageWorkGuard({+ queuedMessages: { corrupted: true },+ activeTurn: null,+ })).toEqual({ safe: false, trusted: false, queuedImageMessages: 0, activeImageMessage: false });});it('caps exponential backoff and detects stale heartbeats at the boundary', () => {diff --git a/server/routes/update.js b/server/routes/update.jsindex 5e99d9c8cd..f98b09fede 100644--- a/server/routes/update.js+++ b/server/routes/update.js@@ -7,7 +7,7 @@ import { persistentMindImageWorkGuard } from '../lib/persistentMind.js';import * as updateChecker from '../services/updateChecker.js';import { executeUpdate } from '../services/updateExecutor.js';import { getActiveAgentIds, spawningTasks } from '../services/agentState.js';-import { loadState } from '../services/cosState.js';+import { readPersistentMindStateForSafetyCheck, withStateLock } from '../services/cosState.js';const router = Router();@@ -50,17 +50,25 @@ const persistentMindImageWorkError = (guard) => {guard.activeImageMessage ? 'one active image turn' : null,].filter(Boolean).join(' and ');return new ServerError(- `Persistent Mind has ${work}. Drain or stop the image-bearing work, create a backup, ` +- 'then retry the update. Older source readers cannot preserve image references.',+ `Persistent Mind has ${work}. Drain the image-bearing work, or create a backup and retry ` ++ 'with acknowledgePersistentMindImageBackup: true. Older source readers cannot preserve image references.',{ status: 409, code: 'PERSISTENT_MIND_IMAGES_IN_FLIGHT' },);};async function getPersistentMindImageWorkGuard() {- const state = await loadState();- return persistentMindImageWorkGuard(state.persistentMind);+ const snapshot = await readPersistentMindStateForSafetyCheck();+ if (!snapshot.trusted) {+ return { safe: false, trusted: false, queuedImageMessages: 0, activeImageMessage: false };+ }+ return persistentMindImageWorkGuard(snapshot.persistentMind);}+const persistentMindStateUntrustedError = () => new ServerError(+ 'Persistent Mind state could not be validated. Restore data/cos/state.json from backup before updating.',+ { status: 409, code: 'PERSISTENT_MIND_STATE_UNTRUSTED' },+);+const ignoreSchema = z.object({version: z.string().min(1, 'version is required')});@@ -71,6 +79,7 @@ const syncForkSchema = z.object({const executeSchema = z.object({acknowledgeFork: z.boolean().optional(),+ acknowledgePersistentMindImageBackup: z.boolean().optional(),// Reconcile a half-updated install (issue #1779): run update.sh to pull +// install + build + restart even when there's no NEWER GitHub release — the// user did a bare `git pull` and just needs the rest of the update steps.@@ -168,7 +177,7 @@ router.post('/sync-fork', asyncHandler(async (req, res) => {// POST /api/update/execute — kicks off updaterouter.post('/execute', asyncHandler(async (req, res) => {- const { acknowledgeFork, reconcile } = validateRequest(executeSchema, req.body || {});+ const { acknowledgeFork, acknowledgePersistentMindImageBackup, reconcile } = validateRequest(executeSchema, req.body || {});// Never restart PortOS out from under a live CoS agent. Both a normal update// and a reconcile run update.sh, which pm2-restarts THIS server process and@@ -183,7 +192,10 @@ router.post('/execute', asyncHandler(async (req, res) => {const preCheck = countActiveCosAgents();if (preCheck > 0) throw agentsActiveError(preCheck);const preImageCheck = await getPersistentMindImageWorkGuard();- if (!preImageCheck.safe) throw persistentMindImageWorkError(preImageCheck);+ if (!preImageCheck.trusted) throw persistentMindStateUntrustedError();+ if (!preImageCheck.safe && !acknowledgePersistentMindImageBackup) {+ throw persistentMindImageWorkError(preImageCheck);+ }const status = await updateChecker.getUpdateStatus();@@ -254,9 +266,13 @@ router.post('/execute', asyncHandler(async (req, res) => {await updateChecker.setUpdateInProgress(false);throw agentsActiveError(postLock);}- const postLockImageCheck = await getPersistentMindImageWorkGuard();- if (!postLockImageCheck.safe) {+ const postLockImageCheck = await withStateLock(() => getPersistentMindImageWorkGuard()).catch(async (error) => {+ await updateChecker.setUpdateInProgress(false);+ throw error;+ });+ if (!postLockImageCheck.trusted || (!postLockImageCheck.safe && !acknowledgePersistentMindImageBackup)) {await updateChecker.setUpdateInProgress(false);+ if (!postLockImageCheck.trusted) throw persistentMindStateUntrustedError();throw persistentMindImageWorkError(postLockImageCheck);}diff --git a/server/routes/update.test.js b/server/routes/update.test.jsindex 32d1c80929..db4720ddc5 100644--- a/server/routes/update.test.js+++ b/server/routes/update.test.js@@ -33,13 +33,17 @@ const { mockCosState } = vi.hoisted(() => ({},}));vi.mock('../services/cosState.js', () => ({- loadState: vi.fn(async () => mockCosState),+ readPersistentMindStateForSafetyCheck: vi.fn(async () => ({+ trusted: true,+ persistentMind: mockCosState.persistentMind,+ })),+ withStateLock: vi.fn(async (fn) => fn()),}));import * as updateChecker from '../services/updateChecker.js';import { executeUpdate } from '../services/updateExecutor.js';import { getActiveAgentIds } from '../services/agentState.js';-import { loadState } from '../services/cosState.js';+import { readPersistentMindStateForSafetyCheck } from '../services/cosState.js';import updateRoutes from './update.js';const makeApp = () => {@@ -68,7 +72,10 @@ describe('POST /api/update/execute — reconcile gating (issue #1779)', () => {executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });getActiveAgentIds.mockReturnValue([]);mockCosState.persistentMind = { queuedMessages: [], activeTurn: null };- loadState.mockImplementation(async () => mockCosState);+ readPersistentMindStateForSafetyCheck.mockImplementation(async () => ({+ trusted: true,+ persistentMind: mockCosState.persistentMind,+ }));});it('rejects reconcile when the install is already in sync (even with a cached release)', async () => {@@ -160,7 +167,10 @@ describe('POST /api/update/execute — active CoS agent gating', () => {executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });getActiveAgentIds.mockReturnValue([]);mockCosState.persistentMind = { queuedMessages: [], activeTurn: null };- loadState.mockImplementation(async () => mockCosState);+ readPersistentMindStateForSafetyCheck.mockImplementation(async () => ({+ trusted: true,+ persistentMind: mockCosState.persistentMind,+ }));});it('rejects a normal update with 409 AGENTS_ACTIVE while an agent is live (no restart)', async () => {@@ -226,18 +236,19 @@ describe('POST /api/update/execute — active CoS agent gating', () => {expect(res.status).toBe(409);expect(res.body.code).toBe('PERSISTENT_MIND_IMAGES_IN_FLIGHT');- expect(res.body.error).toMatch(/Drain or stop the image-bearing work, create a backup/);+ expect(res.body.error).toMatch(/Drain the image-bearing work, or create a backup/);expect(updateChecker.setUpdateInProgress).not.toHaveBeenCalled();expect(executeUpdate).not.toHaveBeenCalled();});it('re-checks image work after locking and releases the update lock on a race', async () => {let reads = 0;- loadState.mockImplementation(async () => {+ readPersistentMindStateForSafetyCheck.mockImplementation(async () => {reads += 1;return reads === 1- ? { persistentMind: { queuedMessages: [], activeTurn: null } }+ ? { trusted: true, persistentMind: { queuedMessages: [], activeTurn: null } }: {+ trusted: true,persistentMind: {queuedMessages: [],activeTurn: {@@ -258,6 +269,44 @@ describe('POST /api/update/execute — active CoS agent gating', () => {expect(updateChecker.setUpdateInProgress).toHaveBeenCalledWith(false);expect(executeUpdate).not.toHaveBeenCalled();});++ it('releases the update lock when the post-lock safety read fails', async () => {+ readPersistentMindStateForSafetyCheck+ .mockResolvedValueOnce({ trusted: true, persistentMind: { queuedMessages: [], activeTurn: null } })+ .mockRejectedValueOnce(new Error('state read failed'));++ const res = await request(makeApp()).post('/api/update/execute').send({});++ expect(res.status).toBe(500);+ expect(updateChecker.setUpdateInProgress).toHaveBeenNthCalledWith(1, true);+ expect(updateChecker.setUpdateInProgress).toHaveBeenCalledWith(false);+ expect(executeUpdate).not.toHaveBeenCalled();+ });++ it('fails closed when persisted Persistent Mind state is untrusted', async () => {+ readPersistentMindStateForSafetyCheck.mockResolvedValue({ trusted: false, persistentMind: null });++ const res = await request(makeApp()).post('/api/update/execute').send({});++ expect(res.status).toBe(409);+ expect(res.body.code).toBe('PERSISTENT_MIND_STATE_UNTRUSTED');+ expect(updateChecker.setUpdateInProgress).not.toHaveBeenCalled();+ expect(executeUpdate).not.toHaveBeenCalled();+ });++ it('allows an explicit backup acknowledgement when queued image work cannot drain', async () => {+ mockCosState.persistentMind = {+ queuedMessages: [{ id: 'message-example', images: [{ attachmentId: 'attachment-example' }] }],+ activeTurn: null,+ };++ const res = await request(makeApp()).post('/api/update/execute').send({+ acknowledgePersistentMindImageBackup: true,+ });++ expect(res.status).toBe(200);+ expect(executeUpdate).toHaveBeenCalled();+ });});describe('GET /api/update/status — activeCosAgents', () => {@@ -268,7 +317,10 @@ describe('GET /api/update/status — activeCosAgents', () => {updateChecker.getUpdateStatus.mockResolvedValue(baseStatus());getActiveAgentIds.mockReturnValue([]);mockCosState.persistentMind = { queuedMessages: [], activeTurn: null };- loadState.mockImplementation(async () => mockCosState);+ readPersistentMindStateForSafetyCheck.mockImplementation(async () => ({+ trusted: true,+ persistentMind: mockCosState.persistentMind,+ }));});it('reports the live agent count so the UI can suppress update actions', async () => {@@ -301,6 +353,7 @@ describe('GET /api/update/status — activeCosAgents', () => {expect(res.body.activeCosAgents).toBe(0);expect(res.body.persistentMindImages).toEqual({safe: true,+ trusted: true,queuedImageMessages: 0,activeImageMessage: false,});diff --git a/server/services/cosState.js b/server/services/cosState.jsindex 448df49b39..cfefab84ff 100644--- a/server/services/cosState.js+++ b/server/services/cosState.js@@ -247,6 +247,22 @@ export async function loadState() {return stateCache;}+// Read only the persisted Persistent Mind shape for source-transition safety+// checks. Unlike loadState(), this deliberately does not replace malformed JSON+// with defaults: an update gate must distinguish "known empty" from "could not+// establish what is queued" before switching to an older source reader.+export async function readPersistentMindStateForSafetyCheck() {+ await ensureDirectories();+ if (!existsSync(STATE_FILE)) return { trusted: true, persistentMind: null };+ const content = await readFile(STATE_FILE, 'utf-8');+ if (!isValidJSON(content)) return { trusted: false, persistentMind: null };+ const state = safeJSONParse(content, null, { logError: true, context: 'CoS state safety check' });+ if (!state || typeof state !== 'object' || Array.isArray(state)) {+ return { trusted: false, persistentMind: null };+ }+ return { trusted: true, persistentMind: state.persistentMind };+}+export async function saveState(state) {await ensureDirectories();stateCache = state;diff --git a/server/services/persistentMindSupervisor.attachments.test.js b/server/services/persistentMindSupervisor.attachments.test.jsindex de481c958f..ef6266ea96 100644--- a/server/services/persistentMindSupervisor.attachments.test.js+++ b/server/services/persistentMindSupervisor.attachments.test.js@@ -19,6 +19,7 @@ const mocks = vi.hoisted(() => ({appendMindEvent: vi.fn(async (event) => ({ appended: true, event })),prepareContext: vi.fn(async () => ({ text: '', chars: 0, summaryState: 'empty' })),acquireSlot: vi.fn(async () => ({ ok: true, release: vi.fn() })),+ updateInProgress: false,}));vi.mock('./cosState.js', () => ({@@ -28,6 +29,10 @@ vi.mock('./cosState.js', () => ({isDaemonRunning: vi.fn(() => true),}));+vi.mock('./updateChecker.js', () => ({+ isUpdateInProgress: vi.fn(() => mocks.updateInProgress),+}));+vi.mock('../lib/fileUtils.js', () => ({PATHS: { screenshots: '/tmp/portos-mind-attachments' },detectImageFormat: mocks.detectImageFormat,@@ -111,6 +116,7 @@ describe('persistent mind image attachment lifecycle', () => {mocks.root = makeRoot();mocks.scheduled.clear();mocks.emitted.length = 0;+ mocks.updateInProgress = false;mocks.saveImageUpload.mockReset();mocks.saveImageUpload.mockResolvedValue({filename: 'mind-attachment-1.png',@@ -139,6 +145,16 @@ describe('persistent mind image attachment lifecycle', () => {supervisor.__resetPersistentMindSupervisorForTests();});+ it('rejects attachment uploads while a source transition is in progress', async () => {+ mocks.updateInProgress = true;++ await expect(supervisor.createPersistentMindAttachment({+ filename: 'diagram.png',+ data: PNG.toString('base64'),+ })).resolves.toMatchObject({ success: false, code: 'UPDATE_IN_PROGRESS', status: 409 });+ expect(mocks.saveImageUpload).not.toHaveBeenCalled();+ });+it('stores a safe pending record, claims it atomically, and preserves it on retry', async () => {const uploaded = await supervisor.createPersistentMindAttachment({ filename: 'diagram.png', data: 'encoded-image' });expect(uploaded).toMatchObject({diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.jsindex 71749a3ccd..d009662aa9 100644--- a/server/services/persistentMindSupervisor.js+++ b/server/services/persistentMindSupervisor.js@@ -45,6 +45,7 @@ import { acquireCosActionReservation, acquireCosGlobalSlot } from './cosAdmissioimport { appendMindEvent } from './agentRunEventLog.js';import { preparePersistentMindContext } from './persistentMindContext.js';import { resolvePersistentMindProfile } from './persistentMindProfile.js';+import { isUpdateInProgress } from './updateChecker.js';import { publicPersistentMindState } from '../lib/persistentMindPublic.js';export const PERSISTENT_MIND_WAKE_EVENT_ID = 'cos-persistent-mind-wake';@@ -320,6 +321,12 @@ export async function createPersistentMindAttachment({ filename, data } = {}) {if (typeof filename !== 'string' || !filename.trim() || typeof data !== 'string' || !data.trim()) {return attachmentFailure('Image filename and base64 data are required', { code: 'VALIDATION_ERROR' });}+ if (isUpdateInProgress()) {+ return attachmentFailure('Persistent Mind image admission is paused during a PortOS update', {+ code: 'UPDATE_IN_PROGRESS',+ status: 409,+ });+ }await cleanupPersistentMindAttachments();const attachmentId = randomUUID();const originalName = sanitizeFilename(filename).slice(0, PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_NAME_CHARS) || `image-${attachmentId}`;@@ -353,6 +360,15 @@ export async function createPersistentMindAttachment({ filename, data } = {}) {return attachmentFailure('Stored image metadata was invalid', { code: 'INVALID_ATTACHMENT' });}const result = await mutateMindState(async (mind) => {+ if (isUpdateInProgress()) {+ return {+ mind,+ value: attachmentFailure('Persistent Mind image admission is paused during a PortOS update', {+ code: 'UPDATE_IN_PROGRESS',+ status: 409,+ }),+ };+ }const retainedMessageIds = new Set([...mind.recentMessageIds,...mind.queuedMessages.map((message) => message.id),@@ -1147,6 +1163,15 @@ export async function enqueuePersistentMindMessage({ id = randomUUID(), text, im: nowIso();await cleanupPersistentMindAttachments();const result = await mutateMindState(async (mind) => {+ if (attachmentIds.length > 0 && isUpdateInProgress()) {+ return {+ mind,+ value: attachmentFailure('Persistent Mind image admission is paused during a PortOS update', {+ code: 'UPDATE_IN_PROGRESS',+ status: 409,+ }),+ };+ }const existingMessage = findMessageById(mind, messageId);const claimedRecords = claimedAttachmentsForMessage(mind, messageId);const duplicate = Boolean(existingMessage) || mind.recentMessageIds.includes(messageId);diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsindex ba0cfde292..f428955bc0 100644--- a/server/services/persistentMindSupervisor.test.js+++ b/server/services/persistentMindSupervisor.test.js@@ -15,6 +15,7 @@ const mock = vi.hoisted(() => ({acquireSlot: vi.fn(async () => ({ ok: true, release: vi.fn() })),appendMindEvent: vi.fn(async (event) => ({ appended: true, event })),prepareContext: vi.fn(async () => ({ text: 'bounded context', chars: 15, summaryState: 'not-needed' })),+ updateInProgress: false,daemonRunning: true,profile: {ok: true,@@ -66,6 +67,10 @@ vi.mock('./persistentMindProfile.js', () => ({resolvePersistentMindProfile: vi.fn(async () => mock.profile),}));+vi.mock('./updateChecker.js', () => ({+ isUpdateInProgress: vi.fn(() => mock.updateInProgress),+}));+const supervisor = await import('./persistentMindSupervisor.js');const makeRoot = () => ({@@ -93,6 +98,7 @@ describe('persistent mind supervisor', () => {mock.emitted.length = 0;mock.budget = { withinBudget: true, exceeded: null };mock.daemonRunning = true;+ mock.updateInProgress = false;mock.recordUsage.mockClear();mock.profile = {ok: true,@@ -195,6 +201,20 @@ describe('persistent mind supervisor', () => {});});+ it('rejects new image messages while a source transition is in progress', async () => {+ mock.updateInProgress = true;++ await expect(supervisor.enqueuePersistentMindMessage({+ id: 'message-during-update',+ images: ['attachment-example'],+ })).resolves.toMatchObject({+ success: false,+ code: 'UPDATE_IN_PROGRESS',+ status: 409,+ });+ expect(mock.root.persistentMind.queuedMessages).toEqual([]);+ });+it('pauses before adapter preparation when the pinned profile cannot resolve', async () => {const prepare = vi.fn();await supervisor.registerPersistentMindTurnAdapter({ prepare, run: vi.fn() });