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
feat: persist Persistent Mind image attachments (#5169)
Adam Eivyb7de8827eded
diff --git a/scripts/migrations/298-persistent-mind-runtime-state.test.js b/scripts/migrations/298-persistent-mind-runtime-state.test.jsindex 7afac729c9..f88917e955 100644--- a/scripts/migrations/298-persistent-mind-runtime-state.test.js+++ b/scripts/migrations/298-persistent-mind-runtime-state.test.js@@ -29,7 +29,7 @@ describe('migration 298 — persistent mind runtime state', () => {running: true,config: { alwaysOn: true },agents: { a1: { status: 'completed' } },- persistentMind: { schemaVersion: 2, mindId: 'cos-persistent-mind', enabled: false, started: false, status: 'disabled' },+ persistentMind: { schemaVersion: 3, mindId: 'cos-persistent-mind', enabled: false, started: false, status: 'disabled', pendingAttachments: [] },});});diff --git a/scripts/migrations/299-persistent-mind-identity.test.js b/scripts/migrations/299-persistent-mind-identity.test.jsindex 484b2358f9..9ead3cb3e0 100644--- a/scripts/migrations/299-persistent-mind-identity.test.js+++ b/scripts/migrations/299-persistent-mind-identity.test.js@@ -28,7 +28,7 @@ describe('migration 299 — persistent mind identity', () => {expect(readJson(statePath)).toMatchObject({running: true,persistentMind: {- schemaVersion: 2,+ schemaVersion: 3,mindId: 'cos-persistent-mind',enabled: true,customFutureField: 'preserve',@@ -38,7 +38,7 @@ describe('migration 299 — persistent mind identity', () => {it('is idempotent', async () => {writeFileSync(statePath, JSON.stringify({- persistentMind: { schemaVersion: 2, mindId: 'cos-persistent-mind' },+ persistentMind: { schemaVersion: 3, mindId: 'cos-persistent-mind' },}));await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });});diff --git a/scripts/migrations/303-persistent-mind-image-attachments.js b/scripts/migrations/303-persistent-mind-image-attachments.jsnew file mode 100644index 0000000000..184bdffd0a--- /dev/null+++ b/scripts/migrations/303-persistent-mind-image-attachments.js@@ -0,0 +1,41 @@+/** Add the bounded pending-attachment index to Persistent Mind state. */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { PERSISTENT_MIND_SCHEMA_VERSION } from '../../server/lib/persistentMind.js';+import { atomicWrite, safeJSONParse } from '../../server/lib/fileUtils.js';++export default {+ async up({ rootDir }) {+ const statePath = join(rootDir, 'data', 'cos', 'state.json');+ const raw = await readFile(statePath, 'utf8').catch((error) => {+ if (error.code === 'ENOENT') return null;+ throw error;+ });+ if (raw == null) return { updated: 0, reason: 'no-state' };++ const state = safeJSONParse(raw, null, { logError: false });+ if (!state || typeof state !== 'object' || Array.isArray(state)) {+ return { updated: 0, reason: 'invalid-state' };+ }+ const existing = state.persistentMind;+ if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {+ return { updated: 0, reason: 'no-persistent-mind' };+ }+ if (existing.schemaVersion === PERSISTENT_MIND_SCHEMA_VERSION+ && Array.isArray(existing.pendingAttachments)) {+ return { updated: 0, reason: 'already-applied' };+ }++ state.persistentMind = {+ ...existing,+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,+ pendingAttachments: Array.isArray(existing.pendingAttachments)+ ? existing.pendingAttachments+ : [],+ };+ await atomicWrite(statePath, state);+ console.log('🧠 migration 303: added Persistent Mind image attachment state');+ return { updated: 1 };+ },+};diff --git a/scripts/migrations/303-persistent-mind-image-attachments.test.js b/scripts/migrations/303-persistent-mind-image-attachments.test.jsnew file mode 100644index 0000000000..34c3a68e58--- /dev/null+++ b/scripts/migrations/303-persistent-mind-image-attachments.test.js@@ -0,0 +1,66 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdtemp, mkdir, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import migration from './303-persistent-mind-image-attachments.js';+import { PERSISTENT_MIND_SCHEMA_VERSION } from '../../server/lib/persistentMind.js';++let rootDir;++afterEach(async () => {+ if (rootDir) await rm(rootDir, { recursive: true, force: true });+ rootDir = null;+});++const statePath = () => join(rootDir, 'data', 'cos', 'state.json');++describe('migration 303 — persistent mind image attachments', () => {+ beforeEach(async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'portos-mind-attachments-'));+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ });++ it('does nothing when no CoS state exists yet', async () => {+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'no-state' });+ });++ it('adds the pending index while preserving legacy text-only queued and active state', async () => {+ const legacy = {+ schemaVersion: 2,+ enabled: true,+ started: true,+ status: 'thinking',+ queuedMessages: [{ id: 'message-1', text: 'Keep this text.', createdAt: '2026-08-27T00:00:00.000Z' }],+ activeTurn: {+ id: 'turn-1',+ wake: { kind: 'message', message: { id: 'message-2', text: 'Keep this wake.', createdAt: '2026-08-27T00:01:00.000Z' } },+ },+ };+ await writeFile(statePath(), JSON.stringify({ config: {}, persistentMind: legacy }));++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 1 });+ const migrated = JSON.parse(await readFile(statePath(), 'utf8')).persistentMind;+ expect(migrated).toMatchObject({+ schemaVersion: PERSISTENT_MIND_SCHEMA_VERSION,+ pendingAttachments: [],+ 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 };+ await writeFile(statePath(), JSON.stringify({ persistentMind: current }));++ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });+ expect(JSON.parse(await readFile(statePath(), 'utf8')).persistentMind).toEqual(current);+ });++ 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' });++ await writeFile(statePath(), '{broken');+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'invalid-state' });+ });+});diff --git a/server/lib/persistentMind.js b/server/lib/persistentMind.jsindex ac75c0d4c9..1d974d3193 100644--- a/server/lib/persistentMind.js+++ b/server/lib/persistentMind.js@@ -7,8 +7,20 @@*/import { PERSISTENT_MIND_ID } from './persistentMindTrajectory.js';+import { MAX_SCREENSHOT_BYTES } from './uploadLimits.js';+import { sanitizeFilename } from './mimeTypes.js';+import { isSafeFilename } from './pathSafety.js';-export const PERSISTENT_MIND_SCHEMA_VERSION = 2;+export const PERSISTENT_MIND_SCHEMA_VERSION = 3;++export const PERSISTENT_MIND_IMAGE_EXTENSIONS = Object.freeze(['.png', '.jpg', '.jpeg', '.gif', '.webp']);+export const PERSISTENT_MIND_IMAGE_MIME_TYPES = Object.freeze({+ png: 'image/png',+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ gif: 'image/gif',+ webp: 'image/webp',+});export const PERSISTENT_MIND_STATUSES = ['disabled',@@ -26,8 +38,16 @@ export const PERSISTENT_MIND_WAKE_KINDS = ['message', 'self'];export const PERSISTENT_MIND_LIMITS = Object.freeze({MAX_QUEUED_MESSAGES: 100,MAX_RECENT_MESSAGE_IDS: 200,+ MAX_MESSAGE_IMAGES: 8,MAX_MESSAGE_CHARS: 8_000,MAX_REASON_CHARS: 500,+ MAX_ATTACHMENT_ID_CHARS: 128,+ MAX_ATTACHMENT_FILENAME_CHARS: 255,+ MAX_ATTACHMENT_NAME_CHARS: 200,+ MAX_PENDING_ATTACHMENTS: 800,+ MAX_ATTACHMENT_CLEANUP_PER_PASS: 50,+ MAX_ATTACHMENT_BYTES: MAX_SCREENSHOT_BYTES,+ PENDING_ATTACHMENT_TTL_MS: 24 * 60 * 60 * 1000,BACKOFF_BASE_MS: 5_000,BACKOFF_MAX_MS: 15 * 60_000,WATCHDOG_STALE_MS: 5 * 60_000,@@ -50,13 +70,133 @@ const asCount = (value) => (Number.isSafeInteger(value) && value >= 0 ? value : 0);+const asAttachmentId = (value) => {+ if (typeof value !== 'string') return null;+ const id = value.trim();+ return id.length <= PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_ID_CHARS+ && /^[A-Za-z0-9_-]+$/.test(id) ? id : null;+};++const asAttachmentFilename = (value) => {+ if (typeof value !== 'string') return null;+ const filename = value.trim();+ return filename.length <= PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_FILENAME_CHARS+ && isSafeFilename(filename, PERSISTENT_MIND_IMAGE_EXTENSIONS)+ && /^[A-Za-z0-9][A-Za-z0-9._-]*\.(?:png|jpg|jpeg|gif|webp)$/i.test(filename)+ ? filename+ : null;+};++const asAttachmentMimeType = (value) => (+ typeof value === 'string' && Object.values(PERSISTENT_MIND_IMAGE_MIME_TYPES).includes(value)+ ? value+ : null+);++const asAttachmentSize = (value) => (+ Number.isSafeInteger(value) && value > 0 && value <= PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_BYTES+ ? value+ : null+);++const attachmentPath = (filename) => {+ const safeFilename = asAttachmentFilename(filename);+ return safeFilename ? `/api/screenshots/${encodeURIComponent(safeFilename)}` : null;+};++/** True when a value is a safe server-issued Mind attachment id. */+export function isPersistentMindAttachmentId(value) {+ return asAttachmentId(value) !== null;+}++/** Convert a stored screenshot filename into the only client-visible reference. */+export function persistentMindAttachmentPath(filename) {+ return attachmentPath(filename);+}++/** Normalize the bounded, machine-local pending attachment record. */+export function normalizePersistentMindAttachment(value) {+ const attachmentId = asAttachmentId(value?.attachmentId);+ const filename = asAttachmentFilename(value?.filename);+ const originalName = typeof value?.originalName === 'string'+ ? sanitizeFilename(value.originalName).slice(0, PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_NAME_CHARS) || filename+ : filename;+ const mimeType = asAttachmentMimeType(value?.mimeType);+ const size = asAttachmentSize(value?.size);+ const uploadedAt = asIso(value?.uploadedAt || value?.createdAt);+ const claimedBy = value?.claimedBy == null ? null : asId(value.claimedBy);+ if (!attachmentId || !filename || !mimeType || size === null || !uploadedAt) return null;+ if (value?.claimedBy != null && !claimedBy) return null;+ const expiresAt = claimedBy+ ? null+ : asIso(value?.expiresAt)+ || new Date(Date.parse(uploadedAt) + PERSISTENT_MIND_LIMITS.PENDING_ATTACHMENT_TTL_MS).toISOString();+ return {+ attachmentId,+ filename,+ originalName,+ mimeType,+ size,+ uploadedAt,+ expiresAt,+ claimedBy,+ claimedAt: asIso(value?.claimedAt),+ claimIndex: Number.isSafeInteger(value?.claimIndex)+ && value.claimIndex >= 0+ && value.claimIndex < PERSISTENT_MIND_LIMITS.MAX_MESSAGE_IMAGES+ ? value.claimIndex+ : null,+ };+}++/** Build the durable image reference stored on a queued or active message. */+export function normalizePersistentMindMessageImage(value) {+ const attachment = normalizePersistentMindAttachment(value);+ if (!attachment) return null;+ return {+ attachmentId: attachment.attachmentId,+ filename: attachment.filename,+ path: attachmentPath(attachment.filename),+ originalName: attachment.originalName,+ mimeType: attachment.mimeType,+ size: attachment.size,+ uploadedAt: attachment.uploadedAt,+ };+}++/** Build the safe upload response without exposing claim bookkeeping. */+export function publicPersistentMindAttachment(value) {+ const attachment = normalizePersistentMindAttachment(value);+ if (!attachment) return null;+ return {+ attachmentId: attachment.attachmentId,+ filename: attachment.filename,+ path: attachmentPath(attachment.filename),+ originalName: attachment.originalName,+ mimeType: attachment.mimeType,+ size: attachment.size,+ uploadedAt: attachment.uploadedAt,+ expiresAt: attachment.expiresAt,+ };+}+const sanitizeMessage = (value) => {const id = asId(value?.id);const text = asBoundedString(value?.text, PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS);- if (!id || !text) return null;+ const images = [];+ const seenImageIds = new Set();+ for (const candidate of Array.isArray(value?.images) ? value.images : []) {+ const image = normalizePersistentMindMessageImage(candidate);+ if (!image || seenImageIds.has(image.attachmentId)) continue;+ seenImageIds.add(image.attachmentId);+ images.push(image);+ if (images.length >= PERSISTENT_MIND_LIMITS.MAX_MESSAGE_IMAGES) break;+ }+ if (!id || (!text && images.length === 0)) return null;return {id,text,+ ...(images.length > 0 ? { images } : {}),createdAt: asIso(value?.createdAt) || new Date(0).toISOString(),};};@@ -108,6 +248,7 @@ export function createDefaultPersistentMindState() {status: 'disabled',pauseReason: null,queuedMessages: [],+ pendingAttachments: [],selfWake: null,activeTurn: null,recentMessageIds: [],@@ -138,6 +279,15 @@ export function normalizePersistentMindState(raw) {if (!id || recentMessageIds.includes(id)) continue;recentMessageIds.push(id);}+ const pendingAttachments = [];+ const seenAttachmentIds = new Set();+ for (const candidate of Array.isArray(source.pendingAttachments) ? source.pendingAttachments : []) {+ const attachment = normalizePersistentMindAttachment(candidate);+ if (!attachment || seenAttachmentIds.has(attachment.attachmentId)) continue;+ seenAttachmentIds.add(attachment.attachmentId);+ pendingAttachments.push(attachment);+ if (pendingAttachments.length >= PERSISTENT_MIND_LIMITS.MAX_PENDING_ATTACHMENTS) break;+ }const enabled = source.enabled === true;const started = enabled && source.started === true;@@ -171,6 +321,7 @@ export function normalizePersistentMindState(raw) {status,pauseReason: asBoundedString(source.pauseReason, PERSISTENT_MIND_LIMITS.MAX_REASON_CHARS) || null,queuedMessages,+ pendingAttachments,selfWake,activeTurn,recentMessageIds: recentMessageIds.slice(-PERSISTENT_MIND_LIMITS.MAX_RECENT_MESSAGE_IDS),diff --git a/server/lib/persistentMind.test.js b/server/lib/persistentMind.test.jsindex eaf1daa22f..30e48906a6 100644--- a/server/lib/persistentMind.test.js+++ b/server/lib/persistentMind.test.js@@ -19,6 +19,7 @@ describe('persistent mind state', () => {started: false,status: 'disabled',queuedMessages: [],+ pendingAttachments: [],selfWake: null,activeTurn: null,});@@ -81,6 +82,55 @@ describe('persistent mind state', () => {expect(completed.queuedMessages).toHaveLength(0);});+ it('preserves bounded image references for image-only messages through requeue normalization', () => {+ const attachment = {+ attachmentId: 'attachment-1',+ filename: 'mind-attachment-1.png',+ originalName: 'diagram.png',+ mimeType: 'image/png',+ size: 128,+ uploadedAt: iso(1),+ claimedBy: 'message-1',+ expiresAt: null,+ };+ const state = normalizePersistentMindState({+ enabled: true,+ started: true,+ status: 'waiting',+ pendingAttachments: [attachment],+ queuedMessages: [{ id: 'message-1', text: '', images: [attachment], createdAt: iso(1) }],+ });+ expect(state.pendingAttachments).toMatchObject([{ attachmentId: 'attachment-1', claimedBy: 'message-1', expiresAt: null }]);+ expect(state.queuedMessages[0]).toMatchObject({+ id: 'message-1',+ text: '',+ images: [{ attachmentId: 'attachment-1', path: '/api/screenshots/mind-attachment-1.png' }],+ });+ const requeued = requeuePersistentMindWake({ ...state, queuedMessages: [] }, {+ kind: 'message',+ message: state.queuedMessages[0],+ });+ expect(requeued.queuedMessages[0].images).toEqual(state.queuedMessages[0].images);+ });++ it('drops image-only messages whose durable image reference is not safe', () => {+ const state = normalizePersistentMindState({+ queuedMessages: [{+ id: 'message-1',+ text: '',+ images: [{+ attachmentId: 'attachment-1',+ filename: '../outside.png',+ originalName: 'outside.png',+ mimeType: 'image/png',+ size: 128,+ uploadedAt: iso(1),+ }],+ }],+ });+ expect(state.queuedMessages).toEqual([]);+ });+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/cosMindRoutes.js b/server/routes/cosMindRoutes.jsindex 80ed2b8cea..6bf496a7cc 100644--- a/server/routes/cosMindRoutes.js+++ b/server/routes/cosMindRoutes.js@@ -5,6 +5,7 @@ import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { getDomainMode } from '../lib/domainAutonomy.js';import { PERSISTENT_MIND_LIMITS } from '../lib/persistentMind.js';+import { MAX_SCREENSHOT_BYTES } from '../lib/uploadLimits.js';import {normalizePersistentMindCapabilities,PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,@@ -37,6 +38,8 @@ import { readPersistentMindTaskCatalog } from '../services/persistentMindTaskCapimport { inspectPersistentMindRuntime } from '../services/persistentMindRuntime.js';import { readPersistentMindVisibility } from '../services/persistentMindVisibility.js';import {+ createPersistentMindAttachment,+ deletePersistentMindAttachment,enqueuePersistentMindMessage,getPersistentMindState,pausePersistentMind,@@ -50,6 +53,16 @@ const router = Router();const idempotencyId = z.string().trim().min(1).max(200);const eventId = z.string().trim().min(1).max(128);const text = z.string().trim().min(1).max(PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS);+const messageText = z.string().trim().max(PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS).optional();+const attachmentId = z.string()+ .trim()+ .min(1)+ .max(PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_ID_CHARS)+ .regex(/^[A-Za-z0-9_-]+$/, 'invalid attachment id');+const imageReference = z.union([+ attachmentId,+ z.object({ attachmentId }).strict(),+]);const mindReadSchema = z.object({cursor: z.string().max(260).refine((value) => parsePersistentMindCursor(value) !== null, 'Invalid cursor').optional(),limit: z.coerce.number().int().positive().max(PERSISTENT_MIND_TRAJECTORY_LIMITS.maxPageSize).optional(),@@ -57,7 +70,25 @@ const mindReadSchema = z.object({const visibilityReadSchema = z.object({refresh: z.enum(['true', 'false']).transform((value) => value === 'true').optional(),}).strict();-const messageSchema = z.object({ id: idempotencyId, text }).strict();+const messageSchema = z.object({+ id: idempotencyId,+ text: messageText,+ images: z.array(imageReference).max(PERSISTENT_MIND_LIMITS.MAX_MESSAGE_IMAGES).optional(),+}).strict().superRefine((value, ctx) => {+ const images = Array.isArray(value.images) ? value.images : [];+ const ids = images.map((image) => typeof image === 'string' ? image : image.attachmentId);+ if (!value.text && ids.length === 0) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['text'], message: 'text or at least one image is required' });+ }+ if (new Set(ids).size !== ids.length) {+ ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['images'], message: 'image references must be unique' });+ }+});+const attachmentUploadSchema = z.object({+ filename: z.string().trim().min(1).max(PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_FILENAME_CHARS),+ data: z.string().min(1).max(Math.ceil(MAX_SCREENSHOT_BYTES * 4 / 3) + 16),+}).strict();+const attachmentParamsSchema = z.object({ attachmentId }).strict();const annotationSchema = z.object({id: idempotencyId,text,@@ -101,7 +132,10 @@ const memoryParamsSchema = z.object({ memoryId: z.string().trim().min(1).max(128const requireSuccess = (result) => {if (result?.success === false) {- throw new ServerError(result.error || 'Persistent mind request was refused', { status: 409, code: 'INVALID_STATE' });+ throw new ServerError(result.error || 'Persistent mind request was refused', {+ status: Number.isInteger(result.status) ? result.status : 409,+ code: result.code || 'INVALID_STATE',+ });}return result;};@@ -216,6 +250,16 @@ router.put('/mind/memories/:memoryId', asyncHandler(async (req, res) => {res.json({ success: true, memory });}));+router.post('/mind/attachments', asyncHandler(async (req, res) => {+ const input = validateRequest(attachmentUploadSchema, req.body);+ res.status(201).json(requireSuccess(await createPersistentMindAttachment(input)));+}));++router.delete('/mind/attachments/:attachmentId', asyncHandler(async (req, res) => {+ const { attachmentId: id } = validateRequest(attachmentParamsSchema, req.params);+ res.json(requireSuccess(await deletePersistentMindAttachment(id)));+}));+router.post('/mind/messages', asyncHandler(async (req, res) => {const input = validateRequest(messageSchema, req.body);res.status(202).json(requireSuccess(await enqueuePersistentMindMessage(input)));diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsindex 58f2610fc5..62dd75cd41 100644--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@ -17,6 +17,8 @@ const mocks = vi.hoisted(() => ({readPersistentMindRollups: vi.fn(),updatePersistentMindMemory: vi.fn(),getProviderById: vi.fn(),+ createPersistentMindAttachment: vi.fn(),+ deletePersistentMindAttachment: vi.fn(),startPersistentMind: vi.fn(),pausePersistentMind: vi.fn(),resumePersistentMind: vi.fn(),@@ -53,6 +55,8 @@ vi.mock('../services/persistentMindTaskCapability.js', () => ({readPersistentMindTaskCatalog: mocks.readPersistentMindTaskCatalog,}));vi.mock('../services/persistentMindSupervisor.js', () => ({+ createPersistentMindAttachment: mocks.createPersistentMindAttachment,+ deletePersistentMindAttachment: mocks.deletePersistentMindAttachment,getPersistentMindState: mocks.getPersistentMindState,enqueuePersistentMindMessage: mocks.enqueuePersistentMindMessage,startPersistentMind: mocks.startPersistentMind,@@ -104,6 +108,19 @@ describe('persistent mind routes', () => {mocks.createPersistentMindMemory.mockResolvedValue({ id: 'memory-2', content: 'A new fact', sourceAgentId: 'cos-persistent-mind' });mocks.updatePersistentMindMemory.mockResolvedValue({ id: 'memory-1', content: 'An edited fact', sourceAgentId: 'cos-persistent-mind' });mocks.enqueuePersistentMindMessage.mockResolvedValue({ success: true, duplicate: false, messageId: 'message-1' });+ mocks.createPersistentMindAttachment.mockResolvedValue({+ success: true,+ attachment: {+ attachmentId: 'attachment-1',+ filename: 'mind-attachment-1.png',+ path: '/api/screenshots/mind-attachment-1.png',+ originalName: 'diagram.png',+ mimeType: 'image/png',+ size: 12,+ expiresAt: '2026-08-28T00:00:00.000Z',+ },+ });+ mocks.deletePersistentMindAttachment.mockResolvedValue({ success: true, attachmentId: 'attachment-1' });mocks.appendPersistentMindAnnotation.mockResolvedValue({ appended: true, duplicate: false });mocks.promotePersistentMindMemory.mockResolvedValue({ success: true, memory: { id: 'memory-1' } });mocks.startPersistentMind.mockResolvedValue({ success: true });@@ -271,6 +288,36 @@ describe('persistent mind routes', () => {expect(mocks.enqueuePersistentMindMessage).toHaveBeenNthCalledWith(2, { id: 'message-1', text: 'Consider the next bounded slice.' });});+ it('admits image-only messages and forwards strict image references', async () => {+ const res = await post('/mind/messages', { id: 'message-image', images: ['attachment-1'] });+ expect(res.status).toBe(202);+ expect(mocks.enqueuePersistentMindMessage).toHaveBeenCalledWith({+ id: 'message-image', images: ['attachment-1'],+ });+ });++ it('rejects empty, duplicate, oversized, and traversal image references', async () => {+ expect((await post('/mind/messages', { id: 'empty' })).status).toBe(400);+ expect((await post('/mind/messages', { id: 'duplicate', images: ['attachment-1', 'attachment-1'] })).status).toBe(400);+ expect((await post('/mind/messages', {+ id: 'too-many',+ images: Array.from({ length: 9 }, (_, index) => `attachment-${index}`),+ })).status).toBe(400);+ expect((await post('/mind/messages', { id: 'traversal', images: ['../screenshot.png'] })).status).toBe(400);+ expect(mocks.enqueuePersistentMindMessage).not.toHaveBeenCalled();+ });++ it('stores and removes attachments through the Mind-specific endpoints', async () => {+ const upload = await post('/mind/attachments', { filename: 'diagram.png', data: 'iVBORw0KGgo=' });+ expect(upload.status).toBe(201);+ expect(mocks.createPersistentMindAttachment).toHaveBeenCalledWith({ filename: 'diagram.png', data: 'iVBORw0KGgo=' });+ expect(upload.body.attachment).toMatchObject({ attachmentId: 'attachment-1', path: '/api/screenshots/mind-attachment-1.png' });++ const deleteResponse = await request(app()).delete('/api/cos/mind/attachments/attachment-1');+ expect(deleteResponse.status).toBe(200);+ expect(mocks.deletePersistentMindAttachment).toHaveBeenCalledWith('attachment-1');+ });+it('validates annotation targets and lifecycle inputs', async () => {expect((await post('/mind/annotations', { id: '', text: 'Idea' })).status).toBe(400);expect((await post('/mind/annotations', { id: 'annotation-1', text: 'Idea', extra: true })).status).toBe(400);diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 07184766a6..7e26061e0f 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -2411,7 +2411,7 @@ describe('canQueueImprovementTasks — autonomous queuing gate', () => {describe('persistent mind — default-off CoS state integration (#5064)', () => {it('adds no cold-bootstrap provider work to a fresh CoS state', () => {expect(DEFAULT_STATE.persistentMind).toMatchObject({- schemaVersion: 2,+ schemaVersion: 3,mindId: 'cos-persistent-mind',enabled: false,started: false,diff --git a/server/services/persistentMindSupervisor.attachments.test.js b/server/services/persistentMindSupervisor.attachments.test.jsnew file mode 100644index 0000000000..e2dff15ae3--- /dev/null+++ b/server/services/persistentMindSupervisor.attachments.test.js@@ -0,0 +1,244 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createDefaultPersistentMindState } from '../lib/persistentMind.js';++const mocks = vi.hoisted(() => ({+ root: null,+ scheduled: new Map(),+ emitted: [],+ saveImageUpload: vi.fn(),+ resolveScreenshot: vi.fn(),+ detectImageFormat: vi.fn(),+ sanitizeFilename: vi.fn((value) => String(value).replace(/[^a-zA-Z0-9._-]/g, '_')),+ readFile: vi.fn(),+ unlink: vi.fn(),+ 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() })),+}));++vi.mock('./cosState.js', () => ({+ loadState: vi.fn(async () => mocks.root),+ saveState: vi.fn(async (state) => { mocks.root = state; }),+ withStateLock: vi.fn(async (fn) => fn()),+ isDaemonRunning: vi.fn(() => true),+}));++vi.mock('../lib/fileUtils.js', () => ({+ PATHS: { screenshots: '/tmp/portos-mind-attachments' },+ detectImageFormat: mocks.detectImageFormat,+ resolveScreenshot: mocks.resolveScreenshot,+ sanitizeFilename: mocks.sanitizeFilename,+ saveImageUpload: mocks.saveImageUpload,+}));++vi.mock('fs/promises', async (importOriginal) => ({+ ...(await importOriginal()),+ readFile: mocks.readFile,+ unlink: mocks.unlink,+}));++vi.mock('./cosEvents.js', () => ({+ cosEvents: { emit: vi.fn((...args) => mocks.emitted.push(args)) },+ emitLog: vi.fn(),+}));++vi.mock('./eventScheduler.js', () => ({+ schedule: vi.fn((config) => {+ mocks.scheduled.set(config.id, config);+ return config;+ }),+ cancel: vi.fn((id) => mocks.scheduled.delete(id)),+}));++vi.mock('./domainUsage.js', () => ({+ getDomainBudgetStatus: vi.fn(async () => ({ withinBudget: true, exceeded: null })),+ recordDomainUsage: vi.fn(async () => {}),+}));++vi.mock('./cosLocalEndpointSlots.js', () => ({+ acquireLocalEndpointProviderSlot: (...args) => mocks.acquireSlot(...args),+}));++vi.mock('./agentRunEventLog.js', () => ({+ appendMindEvent: (...args) => mocks.appendMindEvent(...args),+}));++vi.mock('./persistentMindContext.js', () => ({+ preparePersistentMindContext: (...args) => mocks.prepareContext(...args),+}));++vi.mock('./persistentMindProfile.js', () => ({+ resolvePersistentMindProfile: vi.fn(async () => ({+ ok: true,+ provider: { id: 'example-cloud' },+ model: 'example-model',+ effort: 'high',+ })),+}));++const supervisor = await import('./persistentMindSupervisor.js');++const PNG = Buffer.from('example-png-bytes');+const uploadRecord = (overrides = {}) => ({+ attachmentId: 'attachment-1',+ filename: 'mind-attachment-1.png',+ originalName: 'diagram.png',+ mimeType: 'image/png',+ size: PNG.length,+ uploadedAt: '2026-08-27T00:00:00.000Z',+ expiresAt: '2026-08-28T00:00:00.000Z',+ ...overrides,+});++const makeRoot = () => ({+ paused: false,+ config: { domainAutonomy: { cos: 'execute' }, maxConcurrentAgents: 3 },+ agents: {},+ persistentMind: createDefaultPersistentMindState(),+});++describe('persistent mind image attachment lifecycle', () => {+ beforeEach(() => {+ mocks.root = makeRoot();+ mocks.scheduled.clear();+ mocks.emitted.length = 0;+ mocks.saveImageUpload.mockReset();+ mocks.saveImageUpload.mockResolvedValue({+ filename: 'mind-attachment-1.png',+ filePath: '/tmp/portos-mind-attachments/mind-attachment-1.png',+ size: PNG.length,+ mime: 'image/png',+ });+ mocks.resolveScreenshot.mockImplementation((filename) => filename+ ? `/tmp/portos-mind-attachments/${filename}`+ : null);+ mocks.detectImageFormat.mockReset();+ mocks.detectImageFormat.mockReturnValue({ mime: 'image/png' });+ mocks.readFile.mockReset();+ mocks.readFile.mockResolvedValue(PNG);+ mocks.unlink.mockReset();+ mocks.unlink.mockResolvedValue(undefined);+ mocks.appendMindEvent.mockClear();+ mocks.acquireSlot.mockClear();+ supervisor.__resetPersistentMindSupervisorForTests();+ });++ 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({+ success: true,+ attachment: {+ attachmentId: expect.any(String),+ filename: 'mind-attachment-1.png',+ path: '/api/screenshots/mind-attachment-1.png',+ mimeType: 'image/png',+ size: PNG.length,+ },+ });+ expect(uploaded.attachment).not.toHaveProperty('filePath');+ expect(uploaded.attachment).not.toHaveProperty('data');+ const attachmentId = uploaded.attachment.attachmentId;+ expect(mocks.root.persistentMind.pendingAttachments).toMatchObject([{+ attachmentId,+ filename: 'mind-attachment-1.png',+ claimedBy: null,+ expiresAt: expect.any(String),+ }]);++ const accepted = await supervisor.enqueuePersistentMindMessage({+ id: 'message-1',+ text: 'Review this diagram.',+ images: [attachmentId],+ });+ expect(accepted).toEqual({ success: true, duplicate: false, messageId: 'message-1' });+ expect(mocks.root.persistentMind.pendingAttachments[0]).toMatchObject({+ attachmentId,+ claimedBy: 'message-1',+ expiresAt: null,+ claimIndex: 0,+ });+ expect(mocks.root.persistentMind.queuedMessages[0]).toMatchObject({+ id: 'message-1',+ text: 'Review this diagram.',+ images: [{ attachmentId, path: '/api/screenshots/mind-attachment-1.png' }],+ });+ expect(mocks.appendMindEvent).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'mind.message.accepted',+ data: expect.objectContaining({+ imageCount: 1,+ images: [expect.objectContaining({ attachmentId, path: '/api/screenshots/mind-attachment-1.png' })],+ }),+ }));++ const retry = await supervisor.enqueuePersistentMindMessage({+ id: 'message-1',+ text: 'Review this diagram.',+ images: [attachmentId],+ });+ expect(retry).toEqual({ success: true, duplicate: true, messageId: 'message-1' });+ expect(mocks.root.persistentMind.queuedMessages).toHaveLength(1);+ expect(mocks.appendMindEvent).toHaveBeenCalledTimes(2);+ });++ it('deletes only unclaimed files and leaves claimed historical assets alone', async () => {+ mocks.root.persistentMind.pendingAttachments = [uploadRecord()];+ await expect(supervisor.deletePersistentMindAttachment('attachment-1')).resolves.toEqual({+ success: true,+ attachmentId: 'attachment-1',+ });+ expect(mocks.unlink).toHaveBeenCalledTimes(1);+ expect(mocks.root.persistentMind.pendingAttachments).toEqual([]);++ mocks.root.persistentMind.pendingAttachments = [uploadRecord({ claimedBy: 'message-1', expiresAt: null })];+ await expect(supervisor.deletePersistentMindAttachment('attachment-1')).resolves.toMatchObject({+ success: false,+ code: 'ATTACHMENT_ALREADY_CLAIMED',+ status: 409,+ });+ expect(mocks.unlink).toHaveBeenCalledTimes(1);+ expect(mocks.root.persistentMind.pendingAttachments).toHaveLength(1);+ });++ it('cleans expired unclaimed files in a bounded pass without touching claimed files', async () => {+ mocks.root.persistentMind.pendingAttachments = [+ uploadRecord({ attachmentId: 'expired', filename: 'expired.png', expiresAt: '2026-08-26T00:00:00.000Z' }),+ uploadRecord({ attachmentId: 'claimed', filename: 'claimed.png', claimedBy: 'message-1', expiresAt: null }),+ ];++ await expect(supervisor.cleanupPersistentMindAttachments({ now: Date.parse('2026-08-27T00:00:00.000Z') }))+ .resolves.toMatchObject({ success: true, removed: 1, examined: 1 });+ expect(mocks.unlink).toHaveBeenCalledTimes(1);+ expect(mocks.root.persistentMind.pendingAttachments).toMatchObject([{ attachmentId: 'claimed', claimedBy: 'message-1' }]);+ });++ it('cleans a pending upload whose stored bytes fail validation', async () => {+ mocks.root.persistentMind.pendingAttachments = [uploadRecord({ expiresAt: '2026-08-28T00:00:00.000Z' })];+ mocks.detectImageFormat.mockReturnValue(null);++ await expect(supervisor.cleanupPersistentMindAttachments({ now: Date.parse('2026-08-27T00:00:00.000Z') }))+ .resolves.toMatchObject({ success: true, removed: 1, examined: 1 });+ expect(mocks.unlink).toHaveBeenCalledTimes(1);+ expect(mocks.root.persistentMind.pendingAttachments).toEqual([]);+ });++ it('rejects a changed retry and a missing or invalid image before queue mutation', async () => {+ mocks.root.persistentMind.pendingAttachments = [uploadRecord()];+ const first = await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Original caption.', images: ['attachment-1'] });+ expect(first.success).toBe(true);+ const changedText = await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Changed caption.', images: ['attachment-1'] });+ expect(changedText).toMatchObject({ success: false, code: 'IDEMPOTENCY_CONFLICT', status: 409 });+ const changedImages = await supervisor.enqueuePersistentMindMessage({ id: 'message-1', text: 'Original caption.', images: [] });+ expect(changedImages).toMatchObject({ success: false, code: 'IDEMPOTENCY_CONFLICT', status: 409 });++ mocks.root.persistentMind = createDefaultPersistentMindState();+ const missing = await supervisor.enqueuePersistentMindMessage({ id: 'message-2', images: ['missing'] });+ expect(missing).toMatchObject({ success: false, code: 'ATTACHMENT_NOT_FOUND', status: 400 });++ mocks.root.persistentMind.pendingAttachments = [uploadRecord({ attachmentId: 'bad-image' })];+ mocks.detectImageFormat.mockReturnValue(null);+ const invalid = await supervisor.enqueuePersistentMindMessage({ id: 'message-3', images: ['bad-image'] });+ expect(invalid).toMatchObject({ success: false, code: 'ATTACHMENT_NOT_FOUND', status: 400 });+ expect(mocks.root.persistentMind.queuedMessages).toEqual([]);+ expect(mocks.root.persistentMind.pendingAttachments).toEqual([]);+ });+});diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.jsindex 1bc77f0896..e0a8a4b78a 100644--- a/server/services/persistentMindSupervisor.js+++ b/server/services/persistentMindSupervisor.js@@ -10,17 +10,29 @@*/import { randomUUID } from 'crypto';+import { readFile, unlink } from 'fs/promises';import { getDomainMode } from '../lib/domainAutonomy.js';import {PERSISTENT_MIND_LIMITS,createDefaultPersistentMindState,+ isPersistentMindAttachmentId,+ normalizePersistentMindAttachment,+ normalizePersistentMindMessageImage,nextPersistentMindWakeAt,normalizePersistentMindState,persistentMindBackoffMs,persistentMindTurnIsStale,+ publicPersistentMindAttachment,requeuePersistentMindWake,takeNextPersistentMindWake,} from '../lib/persistentMind.js';+import {+ detectImageFormat,+ PATHS,+ resolveScreenshot,+ sanitizeFilename,+ saveImageUpload,+} from '../lib/fileUtils.js';import { isDaemonRunning, loadState, saveState, withStateLock } from './cosState.js';import { cosEvents, emitLog } from './cosEvents.js';import { schedule, cancel } from './eventScheduler.js';@@ -57,6 +69,240 @@ async function mutateMindState(mutator) {});}+const attachmentFailure = (error, { code = 'INVALID_ATTACHMENT', status = 400 } = {}) => ({+ success: false,+ error,+ code,+ status,+});++const normalizeRequestedAttachmentIds = (images) => {+ if (images === undefined) return [];+ if (!Array.isArray(images) || images.length > PERSISTENT_MIND_LIMITS.MAX_MESSAGE_IMAGES) return null;+ const ids = images.map((image) => {+ const value = typeof image === 'string' ? image : image?.attachmentId;+ return typeof value === 'string' ? value.trim() : null;+ });+ if (ids.some((id) => !id || !isPersistentMindAttachmentId(id))) return null;+ if (new Set(ids).size !== ids.length) return null;+ return ids;+};++const normalizeMessageText = (text) => (+ typeof text === 'string' ? text.trim().slice(0, PERSISTENT_MIND_LIMITS.MAX_MESSAGE_CHARS) : ''+);++const imageIdsForMessage = (message) => (+ Array.isArray(message?.images)+ ? message.images.map((image) => image?.attachmentId).filter(isPersistentMindAttachmentId)+ : []+);++const sameAttachmentIds = (left, right) => (+ left.length === right.length && left.every((id, index) => id === right[index])+);++const findMessageById = (mind, messageId) => {+ const queued = mind.queuedMessages.find((message) => message.id === messageId);+ if (queued) return queued;+ return mind.activeTurn?.wake.kind === 'message' && mind.activeTurn.wake.message.id === messageId+ ? mind.activeTurn.wake.message+ : null;+};++const claimedAttachmentsForMessage = (mind, messageId) => mind.pendingAttachments+ .map((attachment, index) => ({ attachment, index }))+ .filter(({ attachment }) => attachment.claimedBy === messageId)+ .sort((left, right) => (+ (left.attachment.claimIndex ?? Number.MAX_SAFE_INTEGER)+ - (right.attachment.claimIndex ?? Number.MAX_SAFE_INTEGER)+ || left.index - right.index+ ))+ .map(({ attachment }) => attachment);++const messageFromAttachments = ({ id, text, createdAt, attachments }) => ({+ id,+ text,+ ...(attachments.length > 0 ? {+ images: attachments.map(normalizePersistentMindMessageImage).filter(Boolean),+ } : {}),+ createdAt,+});++const verifyStoredAttachment = async (attachment) => {+ const filePath = resolveScreenshot(attachment.filename);+ if (!filePath) return false;+ const bytes = await readFile(filePath).then((value) => value, () => null);+ const detected = detectImageFormat(bytes);+ return Boolean(+ detected+ && detected.mime === attachment.mimeType+ && bytes.length === attachment.size,+ );+};++const removeStoredAttachmentFile = async (attachment) => {+ const filePath = resolveScreenshot(attachment.filename);+ if (!filePath) return true;+ return unlink(filePath).then(+ () => true,+ (error) => {+ if (error?.code === 'ENOENT') return true;+ console.error(`❌ Failed to remove Persistent Mind attachment ${attachment.attachmentId}: ${error.message}`);+ return false;+ },+ );+};++const removeUploadAfterStateFailure = async (filePath, attachmentId) => unlink(filePath).then(+ () => true,+ (error) => {+ if (error?.code !== 'ENOENT') {+ console.error(`❌ Failed to clean up Persistent Mind upload ${attachmentId}: ${error.message}`);+ }+ return false;+ },+);++const resolveMessageAttachments = async (mind, attachmentIds, messageId) => {+ const byId = new Map(mind.pendingAttachments.map((attachment) => [attachment.attachmentId, attachment]));+ const attachments = [];+ for (const attachmentId of attachmentIds) {+ const attachment = byId.get(attachmentId);+ if (!attachment) {+ return { error: attachmentFailure('Persistent mind attachment was not found', { code: 'ATTACHMENT_NOT_FOUND' }) };+ }+ if (attachment.claimedBy && attachment.claimedBy !== messageId) {+ return { error: attachmentFailure('Persistent mind attachment is already claimed by another message', { code: 'ATTACHMENT_ALREADY_CLAIMED', status: 409 }) };+ }+ const expiresAt = attachment.expiresAt ? Date.parse(attachment.expiresAt) : null;+ if (!attachment.claimedBy && (!Number.isFinite(expiresAt) || expiresAt <= Date.now())) {+ return { error: attachmentFailure('Persistent mind attachment has expired', { code: 'ATTACHMENT_EXPIRED' }) };+ }+ if (!await verifyStoredAttachment(attachment)) {+ return { error: attachmentFailure('Persistent mind attachment is missing or invalid', { code: 'INVALID_ATTACHMENT' }) };+ }+ attachments.push(attachment);+ }+ return { attachments };+};++/** Remove expired or invalid unclaimed files in one bounded maintenance pass. */+export async function cleanupPersistentMindAttachments({ now = Date.now() } = {}) {+ const result = await mutateMindState(async (mind) => {+ let examined = 0;+ let removed = 0;+ const pendingAttachments = [];+ for (const attachment of mind.pendingAttachments) {+ if (attachment.claimedBy || examined >= PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_CLEANUP_PER_PASS) {+ pendingAttachments.push(attachment);+ continue;+ }+ examined += 1;+ const expiresAt = attachment.expiresAt ? Date.parse(attachment.expiresAt) : null;+ const expired = !attachment.claimedBy && Number.isFinite(expiresAt) && expiresAt <= now;+ const valid = expired ? false : await verifyStoredAttachment(attachment);+ if (!expired && valid) {+ pendingAttachments.push(attachment);+ continue;+ }+ if (await removeStoredAttachmentFile(attachment)) removed += 1;+ else pendingAttachments.push(attachment);+ }+ return {+ mind: removed > 0 ? { ...mind, pendingAttachments } : mind,+ value: { success: true, removed, examined },+ };+ });+ return result.value;+}++/** Store one validated image and register its server-owned pending record. */+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' });+ }+ await cleanupPersistentMindAttachments();+ const attachmentId = randomUUID();+ const originalName = sanitizeFilename(filename).slice(0, PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_NAME_CHARS) || `image-${attachmentId}`;+ const saved = await saveImageUpload(PATHS.screenshots, {+ filename: `mind-${attachmentId}-${originalName}`,+ data,+ }, { maxBytes: PERSISTENT_MIND_LIMITS.MAX_ATTACHMENT_BYTES });+ const uploadedAt = nowIso();+ const attachment = normalizePersistentMindAttachment({+ attachmentId,+ filename: saved.filename,+ originalName,+ mimeType: saved.mime,+ size: saved.size,+ uploadedAt,+ expiresAt: new Date(Date.now() + PERSISTENT_MIND_LIMITS.PENDING_ATTACHMENT_TTL_MS).toISOString(),+ });+ if (!attachment) {+ await removeUploadAfterStateFailure(saved.filePath, attachmentId);+ return attachmentFailure('Stored image metadata was invalid', { code: 'INVALID_ATTACHMENT' });+ }+ const result = await mutateMindState((mind) => {+ const retainedMessageIds = new Set([+ ...mind.recentMessageIds,+ ...mind.queuedMessages.map((message) => message.id),+ ...(mind.activeTurn?.wake.kind === 'message' ? [mind.activeTurn.wake.message.id] : []),+ ]);+ // Old claimed records are metadata only once their message leaves the+ // idempotency window. Keep their files and message references durable, but+ // do not let the pending-record index grow without bound.+ const pendingAttachments = mind.pendingAttachments.filter((item) => (+ !item.claimedBy || retainedMessageIds.has(item.claimedBy)+ ));+ if (pendingAttachments.length >= PERSISTENT_MIND_LIMITS.MAX_PENDING_ATTACHMENTS) {+ return {+ mind,+ value: attachmentFailure('Persistent mind has too many pending image uploads', {+ code: 'ATTACHMENT_QUEUE_FULL',+ status: 409,+ }),+ };+ }+ return {+ mind: { ...mind, pendingAttachments: [...pendingAttachments, attachment] },+ value: { success: true, attachment: publicPersistentMindAttachment(attachment) },+ };+ }).then(+ (value) => value,+ async (error) => {+ await removeUploadAfterStateFailure(saved.filePath, attachmentId);+ throw error;+ },+ );+ if (!result.value.success) {+ await removeUploadAfterStateFailure(saved.filePath, attachmentId);+ }+ return result.value;+}++/** Delete an unclaimed pending image and its machine-local bytes. */+export async function deletePersistentMindAttachment(attachmentId) {+ if (!isPersistentMindAttachmentId(attachmentId)) {+ return attachmentFailure('Invalid persistent mind attachment id', { code: 'VALIDATION_ERROR' });+ }+ const result = await mutateMindState(async (mind) => {+ const attachment = mind.pendingAttachments.find((item) => item.attachmentId === attachmentId);+ if (!attachment) return { mind, value: attachmentFailure('Persistent mind attachment was not found', { code: 'ATTACHMENT_NOT_FOUND', status: 404 }) };+ if (attachment.claimedBy) {+ return { mind, value: attachmentFailure('Claimed persistent mind attachments cannot be removed', { code: 'ATTACHMENT_ALREADY_CLAIMED', status: 409 }) };+ }+ if (!await removeStoredAttachmentFile(attachment)) {+ return { mind, value: attachmentFailure('Persistent mind attachment could not be removed', { code: 'ATTACHMENT_DELETE_FAILED', status: 500 }) };+ }+ return {+ mind: { ...mind, pendingAttachments: mind.pendingAttachments.filter((item) => item.attachmentId !== attachmentId) },+ value: { success: true, attachmentId },+ };+ });+ return result.value;+}+function emitMindStatus(state) {cosEvents.emit('persistent-mind:status', publicPersistentMindState(state));}@@ -760,47 +1006,133 @@ export async function stopPersistentMind() {return { success: true };}-export async function enqueuePersistentMindMessage({ id = randomUUID(), text, createdAt = nowIso() } = {}) {- const message = normalizePersistentMindState({ queuedMessages: [{ id, text, createdAt }] }).queuedMessages[0];- if (!message) return { success: false, error: 'Message id and text are required' };- const result = await mutateMindState((mind) => {- const duplicate = mind.recentMessageIds.includes(message.id)- || mind.queuedMessages.some((queued) => queued.id === message.id)- || (mind.activeTurn?.wake.kind === 'message' && mind.activeTurn.wake.message.id === message.id);- if (duplicate) return { mind, value: { success: true, duplicate: true, messageId: message.id } };+export async function enqueuePersistentMindMessage({ id = randomUUID(), text, images, createdAt = nowIso() } = {}) {+ const messageId = typeof id === 'string' ? id.trim().slice(0, 200) : '';+ const messageText = normalizeMessageText(text);+ const attachmentIds = normalizeRequestedAttachmentIds(images);+ if (!messageId || attachmentIds === null || (!messageText && attachmentIds.length === 0)) {+ return attachmentFailure('Message id and text or at least one image are required', { code: 'VALIDATION_ERROR' });+ }+ const messageCreatedAt = typeof createdAt === 'string' && Number.isFinite(Date.parse(createdAt))+ ? new Date(createdAt).toISOString()+ : nowIso();+ await cleanupPersistentMindAttachments();+ const result = await mutateMindState(async (mind) => {+ const existingMessage = findMessageById(mind, messageId);+ const claimedRecords = claimedAttachmentsForMessage(mind, messageId);+ const duplicate = Boolean(existingMessage) || mind.recentMessageIds.includes(messageId);+ const existingImageIds = existingMessage+ ? imageIdsForMessage(existingMessage)+ : claimedRecords.map((attachment) => attachment.attachmentId);+ if (duplicate) {+ if (existingMessage && existingMessage.text !== messageText) {+ return {+ mind,+ value: attachmentFailure('A retry must use the same Persistent Mind message text', {+ code: 'IDEMPOTENCY_CONFLICT',+ status: 409,+ }),+ };+ }+ if (!sameAttachmentIds(existingImageIds, attachmentIds)) {+ return {+ mind,+ value: attachmentFailure('A retry must use the same Persistent Mind image references', {+ code: 'IDEMPOTENCY_CONFLICT',+ status: 409,+ }),+ };+ }+ const resolved = await resolveMessageAttachments(mind, attachmentIds, messageId);+ if (resolved.error) return { mind, value: resolved.error };+ return {+ mind,+ value: {+ success: true,+ duplicate: true,+ messageId,+ acceptedMessage: existingMessage || messageFromAttachments({+ id: messageId,+ text: messageText,+ createdAt: messageCreatedAt,+ attachments: resolved.attachments,+ }),+ },+ };+ }+ if (claimedRecords.length > 0 && !sameAttachmentIds(+ claimedRecords.map((attachment) => attachment.attachmentId),+ attachmentIds,+ )) {+ return {+ mind,+ value: attachmentFailure('A retry must use the same Persistent Mind image references', {+ code: 'IDEMPOTENCY_CONFLICT',+ status: 409,+ }),+ };+ }+ const resolved = await resolveMessageAttachments(mind, attachmentIds, messageId);+ if (resolved.error) return { mind, value: resolved.error };const acceptedMessageCount = mind.queuedMessages.length+ (mind.activeTurn?.wake.kind === 'message' ? 1 : 0);if (acceptedMessageCount >= PERSISTENT_MIND_LIMITS.MAX_QUEUED_MESSAGES) {- return { mind, value: { success: false, error: 'Persistent mind message queue is full' } };+ return { mind, value: attachmentFailure('Persistent mind message queue is full', { code: 'QUEUE_FULL', status: 409 }) };}+ const claimedAt = nowIso();+ const requestedIds = new Set(attachmentIds);+ const pendingAttachments = mind.pendingAttachments.map((attachment) => {+ if (!requestedIds.has(attachment.attachmentId)) return attachment;+ return {+ ...attachment,+ claimedBy: messageId,+ claimedAt,+ claimIndex: attachmentIds.indexOf(attachment.attachmentId),+ expiresAt: null,+ };+ });+ const message = messageFromAttachments({+ id: messageId,+ text: messageText,+ createdAt: messageCreatedAt,+ attachments: resolved.attachments,+ });return {mind: {...mind,+ pendingAttachments,queuedMessages: [...mind.queuedMessages, message],status: mind.started && mind.status !== 'paused' ? 'waiting' : mind.status,},- value: { success: true, duplicate: false, messageId: message.id },+ value: { success: true, duplicate: false, messageId, acceptedMessage: message },};});if (result.value.success) {// Retry the stable event id even when the mutable queue already saw this// message. The ledger deduplicates a healthy first append; if the first// append was dropped, the caller's idempotent retry repairs the trajectory.+ const acceptedMessage = result.value.acceptedMessage;await appendMindEvent({kind: 'mind.message.accepted',mindId: result.state.mindId,- eventId: `mind-message:${message.id}`,- at: message.createdAt,+ eventId: `mind-message:${messageId}`,+ at: acceptedMessage.createdAt,data: {- messageId: message.id,- displayText: message.text,- textChars: message.text.length,+ messageId,+ displayText: acceptedMessage.text,+ textChars: acceptedMessage.text.length,+ imageCount: Array.isArray(acceptedMessage.images) ? acceptedMessage.images.length : 0,+ images: Array.isArray(acceptedMessage.images)+ ? acceptedMessage.images.map(normalizePersistentMindMessageImage).filter(Boolean)+ : [],},});}if (result.value.success && result.state.started) await scheduleNextWake();emitMindStatus(result.state);- return result.value;+ const publicResult = { ...result.value };+ delete publicResult.acceptedMessage;+ return publicResult;}export async function requestPersistentMindWake({ sourceTurnId, reason, notBefore = nowIso() } = {}) {@@ -850,6 +1182,7 @@ export async function checkPersistentMindWatchdog() {export async function initializePersistentMindSupervisor() {supervisorStopping = false;+ await cleanupPersistentMindAttachments();const recovered = await mutateMindState((mind) => {if (!mind.enabled || !mind.started) return { mind };let next = mind;