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
import { resolvePersistentMindChosenName } from '../lib/persistentMindChosenName.js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import express from 'express';
import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
const mocks = vi.hoisted(() => ({
readPersistentMindEvents: vi.fn(),
readPersistentMindHistory: vi.fn(),
loadState: vi.fn(),
getPersistentMindState: vi.fn(),
enqueuePersistentMindMessage: vi.fn(),
appendPersistentMindAnnotation: vi.fn(),
createPersistentMindMemory: vi.fn(),
preparePersistentMindContext: vi.fn(),
promotePersistentMindMemory: vi.fn(),
readPersistentMindMemories: vi.fn(),
readPersistentMindRollups: vi.fn(),
updatePersistentMindMemory: vi.fn(),
getProviderById: vi.fn(),
createPersistentMindAttachment: vi.fn(),
deletePersistentMindAttachment: vi.fn(),
wakePersistentMind: vi.fn(),
startPersistentMind: vi.fn(),
pausePersistentMind: vi.fn(),
resumePersistentMind: vi.fn(),
stopPersistentMind: vi.fn(),
persistentMindUsageLimitRetryAt: vi.fn(() => null),
inspectPersistentMindRuntime: vi.fn(),
readPersistentMindVisibility: vi.fn(),
readPersistentMindTaskCatalog: vi.fn(),
readPersistentMindManagedApps: vi.fn(),
listMindToolRecipes: vi.fn(),
resolveImageCapability: vi.fn(),
cleanupPersistentMind: vi.fn(),
readPersistentMindJournal: vi.fn(),
correctPersistentMindJournalEvent: vi.fn(),
}));
vi.mock('../services/agentRunEventLog.js', () => ({
readPersistentMindEvents: mocks.readPersistentMindEvents,
readPersistentMindHistory: mocks.readPersistentMindHistory,
}));
vi.mock('../services/cosState.js', () => ({ loadState: mocks.loadState }));
vi.mock('../services/persistentMindContext.js', () => ({
appendPersistentMindAnnotation: mocks.appendPersistentMindAnnotation,
createPersistentMindMemory: mocks.createPersistentMindMemory,
preparePersistentMindContext: mocks.preparePersistentMindContext,
promotePersistentMindMemory: mocks.promotePersistentMindMemory,
readPersistentMindMemories: mocks.readPersistentMindMemories,
readPersistentMindName: async () => resolvePersistentMindChosenName(await mocks.readPersistentMindMemories()),
readPersistentMindRollups: mocks.readPersistentMindRollups,
updatePersistentMindMemory: mocks.updatePersistentMindMemory,
}));
vi.mock('../services/persistentMindJournal.js', () => ({
readPersistentMindJournal: mocks.readPersistentMindJournal,
correctPersistentMindJournalEvent: mocks.correctPersistentMindJournalEvent,
}));
vi.mock('../services/persistentMindProfile.js', () => ({ resolvePersistentMindProfile: async () => ({ ok: true }) }));
vi.mock('../services/providers.js', () => ({ getProviderById: mocks.getProviderById }));
vi.mock('../services/persistentMindAdapter.js', () => ({
persistentMindHarnessInfo: (provider) => ({
type: provider?.type || null,
label: provider?.type === 'api' ? 'Direct API' : 'Headless CLI',
recommendation: provider?.type === 'api' ? 'recommended' : 'supported',
detail: 'Structured provider harness.',
}),
}));
vi.mock('../services/persistentMindImageCapability.js', () => ({
resolvePersistentMindImageCapability: (...args) => mocks.resolveImageCapability(...args),
}));
vi.mock('../services/persistentMindMaintenance.js', () => ({
cleanupPersistentMind: (...args) => mocks.cleanupPersistentMind(...args),
}));
vi.mock('../services/persistentMindTaskCapability.js', () => ({
readPersistentMindTaskCatalog: mocks.readPersistentMindTaskCatalog,
}));
vi.mock('../services/persistentMindManagedApps.js', () => ({
readPersistentMindManagedApps: mocks.readPersistentMindManagedApps,
}));
vi.mock('../services/mindToolRecipes.js', () => ({
listRecipes: mocks.listMindToolRecipes,
}));
vi.mock('../services/persistentMindAttachments.js', () => ({
createPersistentMindAttachment: mocks.createPersistentMindAttachment,
deletePersistentMindAttachment: mocks.deletePersistentMindAttachment,
}));
vi.mock('../services/persistentMindSupervisor.js', () => ({
createPersistentMindAttachment: mocks.createPersistentMindAttachment,
deletePersistentMindAttachment: mocks.deletePersistentMindAttachment,
getPersistentMindState: mocks.getPersistentMindState,
enqueuePersistentMindMessage: mocks.enqueuePersistentMindMessage,
wakePersistentMind: mocks.wakePersistentMind,
startPersistentMind: mocks.startPersistentMind,
pausePersistentMind: mocks.pausePersistentMind,
resumePersistentMind: mocks.resumePersistentMind,
stopPersistentMind: mocks.stopPersistentMind,
persistentMindUsageLimitRetryAt: mocks.persistentMindUsageLimitRetryAt,
}));
vi.mock('../services/persistentMindRuntime.js', () => ({
inspectPersistentMindRuntime: mocks.inspectPersistentMindRuntime,
}));
vi.mock('../services/persistentMindVisibility.js', () => ({
readPersistentMindVisibility: mocks.readPersistentMindVisibility,
}));
import cosMindRoutes from './cosMindRoutes.js';
const app = () => {
const instance = express();
instance.use(express.json());
instance.use('/api/cos', cosMindRoutes);
instance.use(errorMiddleware);
return instance;
};
const get = (path) => request(app()).get(`/api/cos${path}`);
const post = (path, body) => request(app()).post(`/api/cos${path}`).send(body);
const put = (path, body) => request(app()).put(`/api/cos${path}`).send(body);
describe('persistent mind routes', () => {
it('projects the current protected name without changing trajectory identity or exposing memory records', async () => {
mocks.readPersistentMindMemories.mockResolvedValue([
{ content: 'My chosen name is Earlier.', protection: 'core-identity' },
{ content: 'Example Star', tags: ['mind:chosen-name', 'mind:core-identity'] },
]);
const res = await get('/mind');
expect(res.status).toBe(200);
expect(res.body.identity).toEqual({ mindId: 'cos-persistent-mind', name: 'Example Star' });
expect(res.body.memories).toBeUndefined();
mocks.readPersistentMindMemories.mockResolvedValue([]);
expect((await get('/mind')).body.identity.name).toBeNull();
});
beforeEach(() => {
vi.clearAllMocks();
mocks.readPersistentMindEvents.mockResolvedValue({ events: [], cursor: null, gap: false, hasMore: false, snapshot: {} });
mocks.readPersistentMindHistory.mockResolvedValue([{ eventId: 'event-1' }]);
mocks.getPersistentMindState.mockResolvedValue({
enabled: true, status: 'idle', started: false, queuedMessages: [{ id: 'private', text: 'must not leak' }],
activeTurn: null, lastCompletedTurnId: null, lastCompletedAt: null, nextEligibleWakeAt: null,
failureCount: 0, pauseReason: null, lastError: 'provider failed with \"apiKey\": \"secret-value\"',
});
mocks.loadState.mockResolvedValue({ config: {
domainAutonomy: { cos: 'execute' },
persistentMindCapabilities: { schemaVersion: 1, createTasks: true },
persistentMindProfile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high' },
persistentMindPrompt: { schemaVersion: 1, identity: 'Resident mind', instructions: 'Stay grounded.' },
} });
mocks.getProviderById.mockResolvedValue({ id: 'demo', type: 'api' });
mocks.resolveImageCapability.mockResolvedValue({ status: 'unknown', reason: 'No authoritative metadata.', settingsPath: '/settings?tab=ai-providers' });
mocks.readPersistentMindMemories.mockResolvedValue([{ id: 'memory-1', content: 'A durable fact', sourceAgentId: 'cos-persistent-mind' }]);
mocks.readPersistentMindRollups.mockResolvedValue([]);
mocks.readPersistentMindJournal.mockResolvedValue([]);
mocks.preparePersistentMindContext.mockResolvedValue({ text: '# Context', chars: 9, approximateTokens: 3, summaryState: 'empty' });
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 });
mocks.pausePersistentMind.mockResolvedValue({ success: true });
mocks.resumePersistentMind.mockResolvedValue({ success: true });
mocks.stopPersistentMind.mockResolvedValue({ success: true });
mocks.cleanupPersistentMind.mockResolvedValue({
success: true,
scopes: ['history'],
historyEventsCleared: 12,
historyEventsPreserved: 0,
rollupsCleared: 2,
memoriesArchived: 0,
runtimeResidueCleared: true,
});
mocks.inspectPersistentMindRuntime.mockResolvedValue({
observedAt: '2026-08-27T12:00:00.000Z',
inference: {
active: false,
providerId: 'demo',
model: 'demo-model',
residency: { status: 'provider-managed', backend: null, loaded: null },
},
context: { chars: 9, maxChars: 32000, approximateTokens: 3, summaryState: 'empty', memoryCount: 1 },
system: { memory: { total: 100, used: 40, free: 60, usagePercent: 40 } },
});
mocks.readPersistentMindVisibility.mockResolvedValue({
schemaVersion: 1,
capturedAt: '2026-08-27T12:00:00.000Z',
freshness: { state: 'fresh', ageMs: 0, ttlMs: 30_000 },
readiness: 'degraded',
truncated: false,
workspaces: [{ appId: 'demo-app', appName: 'Demo App', readiness: 'degraded', preflight: { warnings: [] } }],
});
mocks.readPersistentMindTaskCatalog.mockResolvedValue({
apps: [{ id: 'demo-app', name: 'Demo App', planOnly: true }],
providers: [{ id: 'codex', name: 'Codex', type: 'cli', models: [{ id: 'gpt-5', efforts: ['low', 'high'] }] }],
});
mocks.listMindToolRecipes.mockResolvedValue({ recipes: [] });
mocks.readPersistentMindManagedApps.mockResolvedValue([
{ id: 'demo-app', name: 'Demo App', planOnly: true, forge: 'github', fullName: 'example/demo', granted: true, repoPath: '/repos/demo' },
]);
});
it('requests an immediate manual wake', async () => {
mocks.wakePersistentMind.mockResolvedValue({ success: true });
const res = await post('/mind/wake');
expect(res.status).toBe(200);
expect(res.body.success).toBe(true);
expect(mocks.wakePersistentMind).toHaveBeenCalledOnce();
});
it('serves a bounded cursor snapshot with only the safe profile fields', async () => {
const res = await get('/mind?cursor=12%3Amind-message%3Aone&limit=25');
expect(res.status).toBe(200);
expect(mocks.readPersistentMindEvents).toHaveBeenCalledWith({ mindId: 'cos-persistent-mind', cursor: '12:mind-message:one', limit: 25 });
expect(res.body).toMatchObject({
events: [], gap: false, state: { status: 'idle' },
profile: {
enabled: true,
providerId: 'demo',
model: 'demo-model',
effort: 'high',
thinkingInterface: 'text',
wakeIntervalMinutes: 30,
},
capabilities: { schemaVersion: 15, createTasks: true, fileIssues: false, auditReports: false, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, promoteEidoverseFoundations: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [], toolExposureRetentionTurns: 3, toolExposureAllSchemas: false },
harness: { type: 'api', recommendation: 'recommended' },
imageCapability: { status: 'unknown' },
autonomyMode: 'execute',
});
expect(res.body.profile).not.toHaveProperty('credential');
expect(res.body).not.toHaveProperty('snapshot');
expect(res.body.state).not.toHaveProperty('queuedMessages');
expect(res.body.state.queuedMessageCount).toBe(1);
expect(JSON.stringify(res.body)).not.toContain('secret-value');
});
it('exposes per-call execution receipts for completed and failed turns without their message bodies', async () => {
mocks.readPersistentMindEvents.mockResolvedValue({
events: [], cursor: null, gap: false, hasMore: false,
snapshot: {
messages: [{ messageId: 'private', text: 'must not leak' }],
turns: [
// A turn from before receipts existed contributes no row at all.
{ id: 'turn-old', status: 'completed', providerId: 'demo', model: 'demo-model', calls: [] },
{
id: 'turn-temp',
status: 'failed',
startedAt: '2026-08-27T12:00:00.000Z',
completedAt: '2026-08-27T12:00:05.000Z',
providerId: 'demo-alt',
model: 'alt-model',
effort: 'max',
thinkingPresetId: 'preset-deep',
calls: [
{
purpose: 'turn', round: 0, runId: 'run-1', providerId: 'demo-alt', model: 'alt-model',
effort: 'max', thinkingPresetId: 'preset-deep', thinkingPresetLabel: 'Deep think',
temporaryRoute: true, elapsedMs: 900, outcome: 'completed',
usage: { state: 'unknown', source: 'unavailable', inputTokens: null, outputTokens: null, totalTokens: null, costUsd: null },
},
{
purpose: 'tool-round', round: 1, runId: null, providerId: 'demo-alt', model: 'alt-model',
effort: 'max', thinkingPresetId: 'preset-deep', thinkingPresetLabel: 'Deep think',
temporaryRoute: true, elapsedMs: null, outcome: 'denied', reason: 'CoS actions budget exhausted',
usage: { state: 'unknown', source: 'unavailable', inputTokens: null, outputTokens: null, totalTokens: null, costUsd: null },
},
],
},
],
},
});
const res = await get('/mind');
expect(res.status).toBe(200);
expect(res.body.turnExecutions).toHaveLength(1);
expect(res.body.turnExecutions[0]).toMatchObject({
turnId: 'turn-temp',
status: 'failed',
providerId: 'demo-alt',
model: 'alt-model',
effort: 'max',
thinkingPresetId: 'preset-deep',
});
expect(res.body.turnExecutions[0].calls.map((call) => [call.purpose, call.outcome, call.elapsedMs])).toEqual([
['turn', 'completed', 900],
['tool-round', 'denied', null],
]);
expect(res.body.turnExecutions[0].calls[0].usage).toMatchObject({ state: 'unknown', totalTokens: null });
expect(res.body).not.toHaveProperty('snapshot');
expect(JSON.stringify(res.body)).not.toContain('must not leak');
});
it('previews scoped maintainer prerequisites and composes its charter without rewriting custom text', async () => {
const root = await mocks.loadState();
root.config.persistentMindMaintainer = { enabled: true, appIds: ['demo-app'] };
mocks.readPersistentMindManagedApps.mockResolvedValue([{ id: 'demo-app', name: 'Demo', fullName: 'example/project', forge: 'github', granted: false }]);
const setup = await get('/mind/maintainer');
expect(setup.status).toBe(200);
expect(setup.body.ready).toBe(false);
expect(setup.body.apps[0]).toMatchObject({ id: 'demo-app', granted: false });
await get('/mind/context');
expect(mocks.preparePersistentMindContext).toHaveBeenLastCalledWith(expect.objectContaining({
instructions: expect.stringContaining('Stay grounded.\n\n# Development maintainer role'),
}));
expect(root.config.persistentMindPrompt.instructions).toBe('Stay grounded.');
});
it('exposes the editable prompt, owned memories, derived rollups, and exact context preview', async () => {
const res = await get('/mind/context');
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
prompt: { identity: 'Resident mind', instructions: 'Stay grounded.' },
preview: { text: '# Context', summaryState: 'empty' },
memories: [{ id: 'memory-1', content: 'A durable fact' }],
rollups: [],
harness: { type: 'api', recommendation: 'recommended' },
});
expect(mocks.preparePersistentMindContext).toHaveBeenCalledWith(expect.objectContaining({
mindId: 'cos-persistent-mind',
identity: 'Resident mind',
instructions: 'Stay grounded.',
memories: expect.any(Array),
}));
});
it('serves a server-described inventory of persistent-mind tools', async () => {
const res = await get('/mind/tools');
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
semanticTools: expect.arrayContaining([
expect.objectContaining({ name: 'eidoverse.status', granted: false, input_schema: expect.any(Object) }),
expect.objectContaining({ name: 'cos.create-task', granted: true }),
]),
schemaVersion: 15,
capabilities: { schemaVersion: 15, createTasks: true, fileIssues: false, auditReports: false, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, promoteEidoverseFoundations: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [], toolExposureRetentionTurns: 3, toolExposureAllSchemas: false },
boundaries: expect.arrayContaining([expect.stringMatching(/arbitrary shell/i)]),
tools: expect.arrayContaining([
expect.objectContaining({ id: 'cos.create-task', capability: 'createTasks', granted: true, defaultEnabled: false }),
expect.objectContaining({ id: 'portos.read', capability: 'readPortos', granted: false, defaultEnabled: false }),
expect.objectContaining({ id: 'portos.write', capability: 'writePortos', granted: false, defaultEnabled: false }),
expect.objectContaining({ id: 'mind.cleanup', capability: 'manageMind', granted: false, defaultEnabled: false }),
expect.objectContaining({ id: 'voice.call-user', capability: 'callUser', granted: false, defaultEnabled: false }),
]),
// Coding providers stay off this settings payload. The page configures
// grants and the model allowlist; the wake-time prompt still gets the catalog.
taskCatalog: null,
managedApps: [{ id: 'demo-app', name: 'Demo App', planOnly: true, forge: 'github', granted: true }],
});
expect(mocks.readPersistentMindTaskCatalog).not.toHaveBeenCalled();
// The roster never leaks a filesystem path to the browser.
expect(res.body.managedApps[0].repoPath).toBeUndefined();
expect(res.body.tools.find((tool) => tool.id === 'cos.create-task').guardrails).toEqual(expect.arrayContaining([
expect.stringMatching(/isolated-worktree/i),
]));
});
it('keeps revoked managed apps in the settings roster so they can be restored', async () => {
mocks.loadState.mockResolvedValue({ config: {
persistentMindCapabilities: { schemaVersion: 3, createTasks: true, allowedAppIds: [] },
} });
mocks.readPersistentMindManagedApps.mockResolvedValue([
{ id: 'demo-app', name: 'Demo App', planOnly: true, forge: 'github', fullName: 'example/demo', granted: false },
]);
const res = await get('/mind/tools');
expect(res.status).toBe(200);
expect(res.body.managedApps).toEqual([
{ id: 'demo-app', name: 'Demo App', planOnly: true, forge: 'github', fullName: 'example/demo', granted: false },
]);
});
it('loads the shared roster for the issue grant alone, so its allowlist edits see every app', async () => {
mocks.loadState.mockResolvedValue({ config: {
persistentMindCapabilities: { schemaVersion: 12, createTasks: false, fileIssues: true },
} });
mocks.readPersistentMindManagedApps.mockResolvedValue([
{ id: 'demo-app', name: 'Demo App', planOnly: true, forge: 'github', fullName: 'example/demo', granted: true },
{ id: 'plan-app', name: 'Plan App', planOnly: false, forge: null, fullName: null, granted: true },
]);
const res = await get('/mind/tools');
expect(res.status).toBe(200);
expect(res.body.taskCatalog).toBeNull();
// The PLAN.md app is present even though it can never take an issue: the
// allowlist is shared, so a forge-only roster would silently revoke it.
expect(res.body.managedApps.map((app) => app.id)).toEqual(['demo-app', 'plan-app']);
expect(mocks.readPersistentMindTaskCatalog).not.toHaveBeenCalled();
});
it('exposes live context, system, inference, and model-residency telemetry', async () => {
mocks.getPersistentMindState.mockResolvedValue({
enabled: true,
started: true,
status: 'thinking',
activeTurn: { id: 'turn-1', providerId: 'ollama', model: 'active-model' },
});
mocks.getProviderById.mockResolvedValue({ id: 'ollama', type: 'api' });
const res = await get('/mind/runtime');
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
inference: { active: false, providerId: 'demo', model: 'demo-model', residency: { status: 'provider-managed' } },
context: { approximateTokens: 3, memoryCount: 1 },
system: { memory: { usagePercent: 40 } },
});
expect(mocks.inspectPersistentMindRuntime).toHaveBeenCalledWith(expect.objectContaining({
state: expect.objectContaining({ status: 'thinking' }),
profile: expect.objectContaining({ providerId: 'demo', model: 'demo-model' }),
prompt: expect.objectContaining({ identity: 'Resident mind' }),
provider: expect.objectContaining({ id: 'ollama' }),
}));
expect(mocks.getProviderById).toHaveBeenCalledWith('ollama');
});
it('hands the usage-limit probe schedule to the runtime inspector', async () => {
// A usage-limit autopause clears nextEligibleWakeAt, so the readiness probe
// is the only thing that knows when a quota block clears. The route is
// where that read happens — the inspector never reaches for the scheduler.
mocks.persistentMindUsageLimitRetryAt.mockReturnValue('2026-09-01T00:30:00.000Z');
const res = await get('/mind/runtime');
expect(res.status).toBe(200);
expect(mocks.inspectPersistentMindRuntime).toHaveBeenCalledWith(expect.objectContaining({
usageLimitRetryAt: '2026-09-01T00:30:00.000Z',
}));
});
it('serves the shared environment visibility projection and accepts an explicit refresh', async () => {
const res = await get('/mind/visibility?refresh=true');
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
schemaVersion: 1,
readiness: 'degraded',
freshness: { state: 'fresh' },
workspaces: [{ appId: 'demo-app', readiness: 'degraded' }],
});
expect(mocks.readPersistentMindVisibility).toHaveBeenCalledWith(expect.objectContaining({
force: true,
state: expect.objectContaining({ status: 'idle' }),
profile: expect.objectContaining({ providerId: 'demo' }),
provider: expect.objectContaining({ id: 'demo' }),
}));
});
it('creates and edits only validated persistent-mind memories', async () => {
const created = await post('/mind/memories', { content: 'A new fact' });
expect(created.status).toBe(201);
expect(mocks.createPersistentMindMemory).toHaveBeenCalledWith({
content: 'A new fact', type: 'observation', category: 'other', tags: [], importance: 0.5,
});
const updated = await put('/mind/memories/memory-1', { content: 'An edited fact' });
expect(updated.status).toBe(200);
expect(mocks.updatePersistentMindMemory).toHaveBeenCalledWith('memory-1', { content: 'An edited fact' });
expect((await put('/mind/memories/memory-1', {})).status).toBe(400);
});
it('validates protection on memory create and edit without changing legacy defaults', async () => {
expect((await post('/mind/memories', { content: 'An enduring identity.', protection: 'core-identity' })).status).toBe(201);
expect(mocks.createPersistentMindMemory).toHaveBeenLastCalledWith(expect.objectContaining({ protection: 'core-identity' }));
expect((await put('/mind/memories/memory-1', { protection: 'important' })).status).toBe(200);
expect(mocks.updatePersistentMindMemory).toHaveBeenLastCalledWith('memory-1', { protection: 'important' });
expect((await put('/mind/memories/memory-1', { protection: 'standard' })).status).toBe(200);
expect((await put('/mind/memories/memory-1', { protection: 'invalid' })).status).toBe(400);
});
it('returns not found when an edited memory is not owned by this mind', async () => {
mocks.updatePersistentMindMemory.mockResolvedValue(null);
expect((await put('/mind/memories/foreign', { content: 'No access' })).status).toBe(404);
});
it('stops the mind and performs only an explicitly confirmed cleanup', async () => {
expect((await post('/mind/cleanup', { scopes: ['history'], confirmation: 'no' })).status).toBe(400);
expect(mocks.stopPersistentMind).not.toHaveBeenCalled();
const res = await post('/mind/cleanup', {
scopes: ['history'],
reason: 'Discard stale failures',
confirmation: 'CLEAR',
});
expect(res.status).toBe(200);
expect(mocks.stopPersistentMind).toHaveBeenCalledWith({ waitForTurn: true });
expect(mocks.cleanupPersistentMind).toHaveBeenCalledWith({
scopes: ['history'],
reason: 'Discard stale failures',
requestedBy: 'user',
});
expect(res.body).toMatchObject({
success: true,
historyEventsCleared: 12,
state: { status: 'idle' },
});
});
it('rejects malformed cursors, oversized pages, and unknown query fields', async () => {
expect((await get('/mind?cursor=broken')).status).toBe(400);
expect((await get('/mind?limit=501')).status).toBe(400);
expect((await get('/mind?secret=1')).status).toBe(400);
expect(mocks.readPersistentMindEvents).not.toHaveBeenCalled();
});
it('passes the caller id through so a retried message is idempotent', async () => {
const first = await post('/mind/messages', { id: 'message-1', text: 'Consider the next bounded slice.' });
mocks.enqueuePersistentMindMessage.mockResolvedValue({ success: true, duplicate: true, messageId: 'message-1' });
const retry = await post('/mind/messages', { id: 'message-1', text: 'Consider the next bounded slice.' });
expect(first.status).toBe(202);
expect(retry.status).toBe(202);
expect(retry.body.duplicate).toBe(true);
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('surfaces unreadable pending image storage as a retryable 503', async () => {
mocks.enqueuePersistentMindMessage.mockResolvedValueOnce({
success: false,
error: 'The stored image could not be read right now.',
code: 'ATTACHMENT_UNAVAILABLE',
status: 503,
});
const res = await post('/mind/messages', { id: 'message-image', images: ['attachment-1'] });
expect(res.status).toBe(503);
expect(res.body.code).toBe('ATTACHMENT_UNAVAILABLE');
});
it('validates the displayed temporary selection and requires its preset id to match', async () => {
const thinkingPreset = { id: 'deep', label: 'Deep', providerId: 'example-provider', model: 'example-model', effort: '' };
const input = { id: 'selected-message', text: 'Use this selection.', thinkingPresetId: 'deep', thinkingPreset };
expect((await post('/mind/messages', input)).status).toBe(202);
expect(mocks.enqueuePersistentMindMessage).toHaveBeenCalledWith(input);
mocks.enqueuePersistentMindMessage.mockClear();
for (const patch of [
{ thinkingPresetId: 'other' },
{ thinkingPreset: { ...thinkingPreset, effort: 'invalid' } },
{ thinkingPreset: { ...thinkingPreset, credential: 'redacted-example' } },
]) {
expect((await post('/mind/messages', { ...input, ...patch })).status).toBe(400);
}
expect(mocks.enqueuePersistentMindMessage).not.toHaveBeenCalled();
});
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);
expect((await post('/mind/pause', { reason: '' })).status).toBe(400);
const accepted = await post('/mind/annotations', {
id: 'annotation-1', text: 'Keep this as context.', turnId: 'turn-1', targetEventId: 'event-1',
});
expect(accepted.status).toBe(202);
expect(mocks.appendPersistentMindAnnotation).toHaveBeenCalledWith({
id: 'annotation-1', text: 'Keep this as context.', turnId: 'turn-1', targetEventId: 'event-1',
});
});
it('rejects an annotation target outside the retained mind ledger', async () => {
mocks.readPersistentMindHistory.mockResolvedValue([]);
const res = await post('/mind/annotations', {
id: 'annotation-1', text: 'Dangling idea.', targetEventId: 'missing',
});
expect(res.status).toBe(404);
expect(mocks.appendPersistentMindAnnotation).not.toHaveBeenCalled();
});
it('projects lifecycle state instead of returning queued message bodies', async () => {
mocks.pausePersistentMind.mockResolvedValue({
success: true,
state: {
enabled: true, started: true, status: 'paused', queuedMessages: [{ id: 'private', text: 'must not leak' }],
pauseReason: 'Paused from Mind page', activeTurn: null, failureCount: 0,
},
});
const res = await post('/mind/pause', { reason: 'Paused from Mind page' });
expect(res.status).toBe(200);
expect(res.body.state).toMatchObject({ status: 'paused', queuedMessageCount: 1 });
expect(JSON.stringify(res.body)).not.toContain('must not leak');
});
it('fails visibly when the supervisor refuses a lifecycle transition', async () => {
mocks.startPersistentMind.mockResolvedValue({ success: false, error: 'Lifecycle transition refused' });
const res = await post('/mind/start');
expect(res.status).toBe(409);
expect(res.body.error).toBe('Lifecycle transition refused');
});
it('requires explicit approval before promoting a redacted event summary', async () => {
expect((await post('/mind/events/event-1/promote', { id: 'promotion-1', approved: false, content: 'Safe summary' })).status).toBe(400);
const res = await post('/mind/events/event-1/promote', {
id: 'promotion-1', approved: true, content: 'Safe summary', type: 'insight', category: 'other',
});
expect(res.status).toBe(201);
expect(mocks.promotePersistentMindMemory).toHaveBeenCalledWith(expect.objectContaining({
id: 'promotion-1', approved: true, content: 'Safe summary', sourceEventId: 'event-1',
}));
});
it('refuses action annotations for an event outside the retained mind ledger', async () => {
mocks.readPersistentMindHistory.mockResolvedValue([]);
expect((await post('/mind/events/missing/acknowledge', { id: 'ack-1' })).status).toBe(404);
expect((await post('/mind/events/missing/promote', {
id: 'promotion-1', approved: true, content: 'Safe summary',
})).status).toBe(404);
expect(mocks.appendPersistentMindAnnotation).not.toHaveBeenCalled();
expect(mocks.promotePersistentMindMemory).not.toHaveBeenCalled();
});
it('serves the sealed bundle as a download and refuses a short passphrase', async () => {
expect((await post('/mind/bundle/export', { scopes: ['profile'], passphrase: 'short' })).status).toBe(400);
const res = await post('/mind/bundle/export', { scopes: ['profile'], passphrase: 'an example bundle passphrase' });
expect(res.status).toBe(200);
expect(res.headers['content-type']).toContain('application/octet-stream');
expect(res.headers['content-disposition']).toMatch(/^attachment; filename="portos-mind-.+\.portos-mind"$/);
expect(res.headers['cache-control']).toBe('no-store');
const [magicLine, headerLine] = res.text.split('\n');
expect(magicLine).toBe('portos-mind-bundle/1');
expect(JSON.parse(headerLine).scopes).toEqual(['profile']);
// The response body is the sealed file; nothing readable rides along with it.
expect(res.text).not.toContain('Resident mind');
});
it('refuses an unknown scope rather than exporting the ones it recognizes', async () => {
const res = await post('/mind/bundle/export', { scopes: ['profile', 'everything'], passphrase: 'an example bundle passphrase' });
expect(res.status).toBe(400);
});
it('refuses the whole export when a selected scope cannot be read', async () => {
mocks.readPersistentMindMemories.mockRejectedValue(new Error('memory backend is unavailable'));
const res = await post('/mind/bundle/export', { scopes: ['profile', 'memories'], passphrase: 'an example bundle passphrase' });
expect(res.status).toBe(409);
expect(res.body.code).toBe('MIND_BUNDLE_SCOPE_UNREADABLE');
expect(res.body.error).toContain('memories');
});
it('serves the journal filtered by kind and status, and never exposes the stored envelope', async () => {
const entry = (overrides) => ({
schemaVersion: 1, id: 'decision-1', mindId: 'cos-persistent-mind', kind: 'decision',
statement: 'We ship the importer first.', status: 'active',
source: { sequences: [12] }, supersedes: null, supersededBy: null, resolution: null, retiredBy: null,
provenance: { providerId: 'demo', model: 'demo-model', promptVersion: 1, createdAt: '2026-09-01T00:00:00.000Z', updatedAt: '2026-09-01T00:00:00.000Z' },
...overrides,
});
mocks.readPersistentMindJournal.mockResolvedValue([
entry({}),
entry({ id: 'decision-0', status: 'superseded', supersededBy: 'decision-1', retiredBy: 'mind', statement: 'We ship the exporter first.' }),
]);
const res = await get('/mind/journal?kind=decision&status=active');
expect(res.status).toBe(200);
expect(mocks.readPersistentMindJournal).toHaveBeenCalledWith('cos-persistent-mind', { kind: 'decision', status: 'active' });
expect(res.body.counts).toEqual({ active: 1, superseded: 1, resolved: 0 });
// The wire shape is the public projection: no schemaVersion, no mindId, no
// nested provenance envelope.
expect(res.body.events[0]).toEqual({
id: 'decision-1', kind: 'decision', statement: 'We ship the importer first.', status: 'active',
sourceSequences: [12], supersedes: null, supersededBy: null, resolution: null, retiredBy: null,
createdAt: '2026-09-01T00:00:00.000Z', updatedAt: '2026-09-01T00:00:00.000Z',
providerId: 'demo', model: 'demo-model',
});
expect((await get('/mind/journal?status=invented')).status).toBe(400);
});
it('lets the user retire or settle one entry, and refuses any other status write', async () => {
mocks.correctPersistentMindJournalEvent.mockResolvedValue({
success: true,
changed: true,
event: {
schemaVersion: 1, id: 'decision-1', mindId: 'cos-persistent-mind', kind: 'decision',
statement: 'We ship the importer first.', status: 'superseded',
source: { sequences: [12] }, supersedes: null, supersededBy: null, resolution: null, retiredBy: 'user',
provenance: { providerId: null, model: null, promptVersion: 1, createdAt: '2026-09-01T00:00:00.000Z', updatedAt: '2026-09-02T00:00:00.000Z' },
},
});
const res = await post('/mind/journal/decision-1/correct', { action: 'retire' });
expect(res.status).toBe(200);
expect(res.body.event).toMatchObject({ status: 'superseded', retiredBy: 'user' });
expect(mocks.correctPersistentMindJournalEvent).toHaveBeenCalledWith({
mindId: 'cos-persistent-mind', eventId: 'decision-1', action: 'retire',
});
// No free status write and no delete verb: a retired statement can only be
// brought back by the mind's own supersede operation.
expect((await post('/mind/journal/decision-1/correct', { action: 'delete' })).status).toBe(400);
expect((await post('/mind/journal/decision-1/correct', { status: 'active' })).status).toBe(400);
mocks.correctPersistentMindJournalEvent.mockResolvedValue({ success: false, error: 'Journal entry not found', status: 404, code: 'NOT_FOUND' });
expect((await post('/mind/journal/missing/correct', { action: 'resolve' })).status).toBe(404);
});
});