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: guard Persistent Mind image recovery (#5172)
[._.]/ Adam Eivy69cef83ce12a
diff --git a/docs/SELF_UPDATE.md b/docs/SELF_UPDATE.mdindex e6baacddd6..63a6a68ca8 100644--- a/docs/SELF_UPDATE.md+++ b/docs/SELF_UPDATE.md@@ -59,3 +59,9 @@ When `isFork` is true, `UpdateTab` replaces the single "Update Now" button with| Update from Fork As-Is | `execute` with `acknowledgeFork: true` |Keep these three behaviors distinct. Collapsing them strips the user's agency over what touches their GitHub fork.++## Image-bearing Persistent Mind work must drain before source transitions++The 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.diff --git a/scripts/migrations/303-persistent-mind-image-attachments.test.js b/scripts/migrations/303-persistent-mind-image-attachments.test.jsindex ae6dbcd0e7..71843b6511 100644--- a/scripts/migrations/303-persistent-mind-image-attachments.test.js+++ b/scripts/migrations/303-persistent-mind-image-attachments.test.js@@ -62,6 +62,44 @@ describe('migration 303 — persistent mind image attachments', () => {expect(JSON.parse(await readFile(statePath(), 'utf8')).persistentMind).toEqual(current);});+ it('preserves image-bearing queued and active messages byte-for-byte', async () => {+ const image = {+ attachmentId: 'attachment-example',+ filename: 'mind-attachment-example.png',+ path: '/api/screenshots/mind-attachment-example.png',+ originalName: 'diagram.png',+ mimeType: 'image/png',+ size: 128,+ uploadedAt: '2026-08-27T00:00:00.000Z',+ };+ const queuedMessages = [{+ id: 'queued-image-message',+ text: 'Keep this queue entry.',+ images: [image],+ createdAt: '2026-08-27T00:01:00.000Z',+ }];+ const activeTurn = {+ id: 'active-image-turn',+ wake: {+ kind: 'message',+ message: {+ id: 'active-image-message',+ text: '',+ images: [{ ...image, attachmentId: 'attachment-active' }],+ createdAt: '2026-08-27T00:02:00.000Z',+ },+ },+ };+ await writeFile(statePath(), JSON.stringify({+ persistentMind: { schemaVersion: 2, queuedMessages, activeTurn },+ }));++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });+ const migrated = JSON.parse(await readFile(statePath(), 'utf8')).persistentMind;+ expect(migrated.queuedMessages).toEqual(queuedMessages);+ expect(migrated.activeTurn).toEqual(activeTurn);+ });+it('leaves invalid and missing persistent mind slices untouched', async () => {await writeFile(statePath(), JSON.stringify({ config: {} }));await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-persistent-mind' });diff --git a/server/lib/README.md b/server/lib/README.mdindex 932238c165..3cd2c7e72c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -42,7 +42,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `agentRunEvents.js` | CoS run lifecycle-event envelope (#4540) — pure half of the append-only ledger in `services/agentRunEventLog.js`. `AGENT_RUN_EVENT_KINDS` (closed vocabulary: spawned, handoff, output, reconnected, paused, resumed, interrupted, pr-verified, orphan-recovered, runner-recovered, finalized), `agentRunEventSchema` (Zod, `.strict()`), `buildRunEvent()` which redacts then mints a CONTENT-derived `eventId` (sha256 of the canonicalized envelope) so a redelivered lifecycle transition dedupes instead of double-counting, `redactRunEventData()` (drops prompt/description/output/result-class keys to a `{ redacted, chars }` stub, scrubs the home-dir prefix out of every remaining string via `scrubHomePath`, runs `redactOutput`, and caps string/array/key/depth per `RUN_EVENT_LIMITS`), and `projectRunStates()` — the clock-free fold that derives current run status from the ordered stream, so replay-after-restart and read-current-status are one code path. Unknown kinds fold as no-ops so a newer install's ledger replays on an older one. || `agentRunReconcile.js` | CoS run reconciliation (#4540) — pure diff between a ledger projection (`projectRunStates`) and the durable run record. Closed finding vocabulary `RUN_RECONCILE_FINDINGS` (`record-open`, `record-missing`, `verdict-mismatch`, `ledger-open`), `diffRunRecord()`, `reconcileRunRecords()` with a zero-filled per-kind summary, and `planRunRecordRepair()` — the metadata patch that closes a record the ledger proves is finished. Repairs are one-directional (ledger → record) by design: a record closed while the ledger missed the close is reported, never back-filled, so the stream stays an audit of the record rather than a copy of it. I/O half: `services/agentRunReconciler.js`. || `agentSentinel.js` | The `.agent-done` completion sentinel: `DONE_SENTINEL_NAME`, `doneSentinelName(agentId)` → the per-instance filename `.agent-done-<agentId>` (worktree-less agents share one workspace, so a shared name lets concurrent runs clobber — and finalize on — each other's signal), `doneSentinelPath(workspacePath, agentId)` → the single path every producer and consumer resolves, + pure `parseSentinelPayload(contents)` → `{ summary, payload }`. Back-compat — a plain-markdown sentinel yields `payload: null`; a JSON object yields its structured `payload` for a programmatic-I/O task type's `processTaskOutput` hook. `salvageSentinelPayload(contents)` (async) is the lenient second tier — runs `jsonExtract` over a fenced/prose-trailed/control-char-corrupted envelope so a less-capable model's near-valid output still surfaces its `payload` instead of being dropped. `extractSentinelPayloadFromTranscript(transcript, isPayload)` (async) is the third tier for programmatic-I/O types ONLY — scans the ANSI-stripped PTY transcript, newest balanced JSON block first, for a payload the model PRINTED instead of writing, and adopts it only if the owning hook's shape predicate accepts it (#3640). `PROGRAMMATIC_OUTPUT_COMPLETION_HEADING` names the briefing section that prints this run's absolute sentinel path — a task-type hook renders its prompt before spawn, so it points the agent at that section by name rather than at a filename it cannot know. |-| `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, bounded exponential backoff, watchdog staleness, and next-wake projection. |+| `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. || `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus the bounded typed CoS-task request contract (app/provider/model/effort and PR completion policy). || `cosToolContracts.js` | Provider-neutral `portos_tool` catalog/call schema version, request-id and per-turn bounds, catalog query formats, and Persistent Mind tool-call shape. || `persistentMindTrajectory.js` | Pure persistent-mind trajectory vocabulary, sequence cursor parsing, replay projection, provenance-tagged rollup validation, and hard-budget context assembly with explicit empty/missing/failed/stale summary states. |diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.jsindex 2ccc40cbc3..d40488febb 100644--- a/server/lib/persistentMind.js+++ b/server/lib/persistentMind.js@@ -403,6 +403,29 @@ export function requeuePersistentMindWake(raw, wake) {return { ...state, selfWake: sanitized };}+/**+ * Report whether a source transition can safely cross a reader that predates+ * image-bearing Persistent Mind messages. Counts only durable queued/active+ * 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 : [])+ .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,+ queuedImageMessages,+ activeImageMessage,+ };+}+export function persistentMindTurnIsStale(raw, now = Date.now(), staleMs = PERSISTENT_MIND_LIMITS.WATCHDOG_STALE_MS) {const active = normalizePersistentMindState(raw).activeTurn;if (!active) return false;diff --git a/server/lib/persistentMind.test.js b/server/lib/persistentMind.test.jsindex 46a1cce914..06633e6ee1 100644--- a/server/lib/persistentMind.test.js+++ b/server/lib/persistentMind.test.js@@ -5,6 +5,7 @@ import {nextPersistentMindWakeAt,normalizePersistentMindState,persistentMindBackoffMs,+ persistentMindImageWorkGuard,persistentMindTurnIsStale,requeuePersistentMindWake,takeNextPersistentMindWake,@@ -132,6 +133,55 @@ describe('persistent mind state', () => {expect(state.queuedMessages).toEqual([]);});+ it('preserves image references when a stopped active turn returns to the queue', () => {+ const image = {+ attachmentId: 'attachment-1',+ filename: 'mind-attachment-1.png',+ originalName: 'diagram.png',+ mimeType: 'image/png',+ size: 128,+ uploadedAt: iso(1),+ };+ const state = normalizePersistentMindState({+ enabled: true,+ started: false,+ status: 'thinking',+ activeTurn: {+ id: 'turn-1',+ wake: {+ kind: 'message',+ message: { id: 'message-1', text: '', images: [image], createdAt: iso(1) },+ },+ startedAt: iso(1),+ heartbeatAt: iso(1),+ },+ });++ expect(state.activeTurn).toBeNull();+ expect(state.queuedMessages).toEqual([+ expect.objectContaining({+ id: 'message-1',+ images: [expect.objectContaining({ attachmentId: 'attachment-1' })],+ }),+ ]);+ });++ it('fails the source-transition guard for raw queued or active image work', () => {+ expect(persistentMindImageWorkGuard({+ queuedMessages: [{ id: 'queued-image', images: [{ attachmentId: 'attachment-1' }] }],+ activeTurn: {+ wake: {+ kind: 'message',+ message: { id: 'active-image', images: [{ attachmentId: 'attachment-2' }] },+ },+ },+ })).toEqual({ safe: false, 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 });+ });+it('caps exponential backoff and detects stale heartbeats at the boundary', () => {expect(persistentMindBackoffMs(1)).toBe(PERSISTENT_MIND_LIMITS.BACKOFF_BASE_MS);expect(persistentMindBackoffMs(99)).toBe(PERSISTENT_MIND_LIMITS.BACKOFF_MAX_MS);diff --git a/server/routes/update.js b/server/routes/update.jsindex 58e1c09d71..5e99d9c8cd 100644--- a/server/routes/update.js+++ b/server/routes/update.js@@ -3,9 +3,11 @@ import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { UPSTREAM_FULL_NAME } from '../lib/gitRemote.js';+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';const router = Router();@@ -40,6 +42,25 @@ function agentsActiveError(n) {);}+const persistentMindImageWorkError = (guard) => {+ const work = [+ guard.queuedImageMessages > 0+ ? `${guard.queuedImageMessages} queued image message${guard.queuedImageMessages === 1 ? '' : 's'}`+ : null,+ 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.',+ { status: 409, code: 'PERSISTENT_MIND_IMAGES_IN_FLIGHT' },+ );+};++async function getPersistentMindImageWorkGuard() {+ const state = await loadState();+ return persistentMindImageWorkGuard(state.persistentMind);+}+const ignoreSchema = z.object({version: z.string().min(1, 'version is required')});@@ -63,8 +84,11 @@ const executeSchema = z.object({// restart out from under a running agent).router.get('/status', asyncHandler(async (req, res) => {await updateChecker.clearStaleUpdateInProgress();- const status = await updateChecker.getUpdateStatus();- res.json({ ...status, activeCosAgents: countActiveCosAgents() });+ const [status, persistentMindImages] = await Promise.all([+ updateChecker.getUpdateStatus(),+ getPersistentMindImageWorkGuard(),+ ]);+ res.json({ ...status, activeCosAgents: countActiveCosAgents(), persistentMindImages });}));// POST /api/update/check — triggers manual check@@ -158,6 +182,8 @@ router.post('/execute', asyncHandler(async (req, res) => {// an agent could start in during that work.const preCheck = countActiveCosAgents();if (preCheck > 0) throw agentsActiveError(preCheck);+ const preImageCheck = await getPersistentMindImageWorkGuard();+ if (!preImageCheck.safe) throw persistentMindImageWorkError(preImageCheck);const status = await updateChecker.getUpdateStatus();@@ -228,6 +254,11 @@ router.post('/execute', asyncHandler(async (req, res) => {await updateChecker.setUpdateInProgress(false);throw agentsActiveError(postLock);}+ const postLockImageCheck = await getPersistentMindImageWorkGuard();+ if (!postLockImageCheck.safe) {+ await updateChecker.setUpdateInProgress(false);+ throw persistentMindImageWorkError(postLockImageCheck);+ }const io = req.app.get('io');diff --git a/server/routes/update.test.js b/server/routes/update.test.jsindex ceaa27785b..32d1c80929 100644--- a/server/routes/update.test.js+++ b/server/routes/update.test.js@@ -27,10 +27,19 @@ vi.mock('../services/agentState.js', () => ({getActiveAgentIds: vi.fn().mockReturnValue([]),spawningTasks: mockSpawningTasks}));+const { mockCosState } = vi.hoisted(() => ({+ mockCosState: {+ persistentMind: { queuedMessages: [], activeTurn: null },+ },+}));+vi.mock('../services/cosState.js', () => ({+ loadState: vi.fn(async () => mockCosState),+}));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 updateRoutes from './update.js';const makeApp = () => {@@ -58,6 +67,8 @@ describe('POST /api/update/execute — reconcile gating (issue #1779)', () => {updateChecker.setUpdateInProgress.mockResolvedValue(true);executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });getActiveAgentIds.mockReturnValue([]);+ mockCosState.persistentMind = { queuedMessages: [], activeTurn: null };+ loadState.mockImplementation(async () => mockCosState);});it('rejects reconcile when the install is already in sync (even with a cached release)', async () => {@@ -148,6 +159,8 @@ describe('POST /api/update/execute — active CoS agent gating', () => {updateChecker.getUpdateStatus.mockResolvedValue(baseStatus());executeUpdate.mockResolvedValue({ success: true, version: '1.26.0' });getActiveAgentIds.mockReturnValue([]);+ mockCosState.persistentMind = { queuedMessages: [], activeTurn: null };+ loadState.mockImplementation(async () => mockCosState);});it('rejects a normal update with 409 AGENTS_ACTIVE while an agent is live (no restart)', async () => {@@ -202,6 +215,49 @@ describe('POST /api/update/execute — active CoS agent gating', () => {expect(res.status).toBe(200);expect(executeUpdate).toHaveBeenCalled();});++ it('rejects before locking when queued image work cannot survive an older reader', async () => {+ mockCosState.persistentMind = {+ queuedMessages: [{ id: 'message-example', images: [{ attachmentId: 'attachment-example' }] }],+ activeTurn: null,+ };++ const res = await request(makeApp()).post('/api/update/execute').send({});++ 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(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 () => {+ reads += 1;+ return reads === 1+ ? { persistentMind: { queuedMessages: [], activeTurn: null } }+ : {+ persistentMind: {+ queuedMessages: [],+ activeTurn: {+ wake: {+ kind: 'message',+ message: { id: 'message-example', images: [{ attachmentId: 'attachment-example' }] },+ },+ },+ },+ };+ });++ const res = await request(makeApp()).post('/api/update/execute').send({});++ expect(res.status).toBe(409);+ expect(res.body.code).toBe('PERSISTENT_MIND_IMAGES_IN_FLIGHT');+ expect(updateChecker.setUpdateInProgress).toHaveBeenNthCalledWith(1, true);+ expect(updateChecker.setUpdateInProgress).toHaveBeenCalledWith(false);+ expect(executeUpdate).not.toHaveBeenCalled();+ });});describe('GET /api/update/status — activeCosAgents', () => {@@ -211,6 +267,8 @@ describe('GET /api/update/status — activeCosAgents', () => {updateChecker.clearStaleUpdateInProgress.mockResolvedValue(false);updateChecker.getUpdateStatus.mockResolvedValue(baseStatus());getActiveAgentIds.mockReturnValue([]);+ mockCosState.persistentMind = { queuedMessages: [], activeTurn: null };+ loadState.mockImplementation(async () => mockCosState);});it('reports the live agent count so the UI can suppress update actions', async () => {@@ -241,5 +299,10 @@ describe('GET /api/update/status — activeCosAgents', () => {const res = await request(makeApp()).get('/api/update/status');expect(res.status).toBe(200);expect(res.body.activeCosAgents).toBe(0);+ expect(res.body.persistentMindImages).toEqual({+ safe: true,+ queuedImageMessages: 0,+ activeImageMessage: false,+ });});});diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsindex 333811e59e..ba0cfde292 100644--- a/server/services/persistentMindSupervisor.test.js+++ b/server/services/persistentMindSupervisor.test.js@@ -207,8 +207,21 @@ describe('persistent mind supervisor', () => {expect(mock.root.persistentMind).toMatchObject({ status: 'degraded', pauseReason: 'Pinned provider unavailable' });});- it('recovers an orphaned turn without losing or duplicating its accepted message', async () => {- const message = { id: 'message-1', text: 'Do not lose me.', createdAt: new Date(1).toISOString() };+ it('recovers an orphaned image turn without losing images or duplicating acceptance', async () => {+ const message = {+ id: 'message-1',+ text: 'Do not lose this image.',+ images: [{+ attachmentId: 'attachment-example',+ filename: 'mind-attachment-example.png',+ path: '/api/screenshots/mind-attachment-example.png',+ originalName: 'diagram.png',+ mimeType: 'image/png',+ size: 128,+ uploadedAt: new Date(1).toISOString(),+ }],+ createdAt: new Date(1).toISOString(),+ };mock.root.persistentMind = {...createDefaultPersistentMindState(),enabled: true,@@ -236,6 +249,8 @@ describe('persistent mind supervisor', () => {turnId: 'turn-orphan',data: expect.objectContaining({ status: 'interrupted' }),}));+ expect(mock.appendMindEvent.mock.calls.map(([event]) => event.kind))+ .not.toContain('mind.message.accepted');});it('records pause, stop, and disable boundaries even without an active provider turn', async () => {