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: add persistent mind cleanup controls
[._.]/ Adam Eivy5e7dba4763ae
diff --git a/client/src/components/cos/PersistentMindMaintenancePanel.jsx b/client/src/components/cos/PersistentMindMaintenancePanel.jsxnew file mode 100644index 0000000000..8ec5ebd317--- /dev/null+++ b/client/src/components/cos/PersistentMindMaintenancePanel.jsx@@ -0,0 +1,131 @@+import { useId, useState } from 'react';+import { Brain, Database, Eraser, MessagesSquare, ShieldCheck } from 'lucide-react';+import * as api from '../../services/api';+import Banner from '../ui/Banner';++const CLEANUP_OPTIONS = [+ {+ scope: 'context',+ icon: Brain,+ label: 'Rebuild derived context',+ detail: 'Clears cached rollups and failure/backoff residue. Retained history is summarized again on a later wake.',+ },+ {+ scope: 'history',+ icon: MessagesSquare,+ label: 'Clear conversation history',+ detail: 'Permanently removes the retained trajectory and its rollups. Pending messages remain queued for the next start.',+ },+ {+ scope: 'memories',+ icon: Database,+ label: 'Archive curated memories',+ detail: 'Removes all Persistent Mind-owned active memories from future context without hard-deleting them from Brain.',+ },+];++export default function PersistentMindMaintenancePanel({+ selfCleanupEnabled = false,+ onOpenTools,+ onCleaned,+}) {+ const idPrefix = useId();+ const [selected, setSelected] = useState(() => new Set(['context']));+ const [confirmation, setConfirmation] = useState('');+ const [pending, setPending] = useState(false);+ const [error, setError] = useState(null);+ const [result, setResult] = useState(null);++ const toggle = (scope, enabled) => {+ setSelected((current) => {+ const next = new Set(current);+ if (enabled) next.add(scope);+ else next.delete(scope);+ return next;+ });+ setResult(null);+ };++ const cleanup = async () => {+ if (pending || confirmation !== 'CLEAR' || selected.size === 0) return;+ setPending(true);+ setError(null);+ setResult(null);+ await api.cleanupPersistentMind({+ scopes: CLEANUP_OPTIONS.map(({ scope }) => scope).filter((scope) => selected.has(scope)),+ confirmation: 'CLEAR',+ }, { silent: true })+ .then(async (next) => {+ setResult(next);+ setConfirmation('');+ await onCleaned?.(next);+ })+ .catch((nextError) => setError(nextError?.message || 'Could not clean the persistent mind'))+ .finally(() => setPending(false));+ };++ return (+ <div className="space-y-4">+ <section className="rounded border border-port-border bg-port-card p-4" aria-labelledby="mind-cleanup-heading">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h3 id="mind-cleanup-heading" className="flex items-center gap-2 text-sm font-semibold text-port-text">+ <Eraser size={17} aria-hidden="true" /> Clean mindspace+ </h3>+ <p className="mt-1 max-w-3xl text-xs text-port-text-muted">Choose exactly what has become stale. Cleanup stops the mind first to create a consistent boundary; its AI profile, operating prompt, tools, and queued messages are preserved.</p>+ </div>+ <span className="rounded-full border border-port-border px-2.5 py-1 text-xs text-port-text-muted">Machine-local only</span>+ </div>++ <fieldset className="mt-4 grid gap-3 lg:grid-cols-3">+ <legend className="sr-only">Mindspace cleanup scopes</legend>+ {CLEANUP_OPTIONS.map(({ scope, icon: Icon, label, detail }) => {+ const id = `${idPrefix}-${scope}`;+ return (+ <div key={scope} className={`rounded border p-3 transition-colors ${selected.has(scope) ? 'border-port-accent bg-port-accent/5' : 'border-port-border bg-port-bg/30'}`}>+ <span className="flex items-start gap-3">+ <input id={id} type="checkbox" checked={selected.has(scope)} disabled={pending} onChange={(event) => toggle(scope, event.target.checked)} className="mt-1 h-4 w-4 accent-port-accent disabled:opacity-50" />+ <span>+ <label htmlFor={id} className="flex cursor-pointer items-center gap-2 text-sm font-medium text-port-text"><Icon size={15} aria-hidden="true" /> {label}</label>+ <span className="mt-1 block text-xs text-port-text-muted">{detail}</span>+ </span>+ </span>+ </div>+ );+ })}+ </fieldset>++ <div className="mt-4 rounded border border-port-warning/40 bg-port-warning/10 p-3">+ <label htmlFor={`${idPrefix}-confirmation`} className="text-xs font-medium text-port-text">Type CLEAR to run the selected cleanup</label>+ <div className="mt-2 flex flex-col gap-2 sm:flex-row">+ <input id={`${idPrefix}-confirmation`} value={confirmation} disabled={pending} onChange={(event) => setConfirmation(event.target.value)} autoComplete="off" className="min-w-0 flex-1 rounded border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text disabled:opacity-50" />+ <button type="button" onClick={cleanup} disabled={pending || selected.size === 0 || confirmation !== 'CLEAR'} className="inline-flex min-h-10 items-center justify-center gap-2 rounded bg-port-warning px-4 text-sm font-medium text-black disabled:cursor-not-allowed disabled:opacity-50">+ <Eraser size={16} className={pending ? 'animate-pulse' : ''} aria-hidden="true" /> {pending ? 'Cleaning…' : 'Clean selected mindspace'}+ </button>+ </div>+ </div>+ </section>++ {error && (+ <Banner tone="error" title="Cleanup failed">+ {error}. Some cleanup steps may already have completed; reload to inspect the current state before retrying.+ </Banner>+ )}+ {result && (+ <Banner tone="success" title="Mindspace cleaned">+ Archived {result.memoriesArchived || 0} memories, cleared {result.historyEventsCleared || 0} history events and {result.rollupsCleared || 0} context rollups. Persistent Mind is stopped and ready for a deliberate fresh start.+ </Banner>+ )}++ <section className="rounded border border-port-border bg-port-card p-4" aria-labelledby="mind-self-cleanup-heading">+ <h3 id="mind-self-cleanup-heading" className="flex items-center gap-2 text-sm font-semibold text-port-text"><ShieldCheck size={16} aria-hidden="true" /> Self-maintenance authority</h3>+ <p className="mt-1 text-xs text-port-text-muted">+ {selfCleanupEnabled+ ? 'The mind may request the same bounded cleanup during a turn. History cleanup preserves that current turn so its final reply remains attributable.'+ : 'Self-cleanup is off by default. Grant it in Tools if the mind should be able to discard stale state on its own.'}+ </p>+ {!selfCleanupEnabled && onOpenTools && <button type="button" onClick={onOpenTools} className="mt-3 rounded border border-port-border px-3 py-1.5 text-xs font-medium text-port-accent hover:border-port-accent">Open Tools permissions</button>}+ </section>+ </div>+ );+}diff --git a/client/src/components/cos/PersistentMindTaskAccessControls.jsx b/client/src/components/cos/PersistentMindTaskAccessControls.jsxindex d55036d2a6..f535b71ca4 100644--- a/client/src/components/cos/PersistentMindTaskAccessControls.jsx+++ b/client/src/components/cos/PersistentMindTaskAccessControls.jsx@@ -5,6 +5,7 @@ import toast from '../ui/Toast';const normalizeCapabilities = (value) => ({schemaVersion: 3,createTasks: value?.createTasks === true,+ manageMind: value?.manageMind === true,readPortos: value?.readPortos === true,writePortos: value?.writePortos === true,taskModelAllowlist: Array.isArray(value?.taskModelAllowlist)@@ -30,6 +31,11 @@ const OPTIONS = [label: 'Allow mind to queue CoS agent tasks',hint: 'Queues typed tasks through isolated worktrees, capacity, budget, review, CI, and landing-policy gates.',},+ {+ key: 'manageMind',+ label: 'Allow mind to clean up its mindspace',+ hint: 'Lets the mind archive only its own memories, forget older trajectory history, or rebuild derived context. Cleanup remains bounded and auditable.',+ },];export default function PersistentMindTaskAccessControls({@@ -47,7 +53,7 @@ export default function PersistentMindTaskAccessControls({useEffect(() => {if (!saving) setDraft(normalizeCapabilities(capabilities));- }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);+ }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.manageMind, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);const save = async (key, enabled) => {const previous = draft;diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsxindex 00537ae36d..608ea985d5 100644--- a/client/src/components/cos/tabs/MindTab.jsx+++ b/client/src/components/cos/tabs/MindTab.jsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useRef, useState } from 'react';import { useSearchParams } from 'react-router';-import { ArrowUp, Brain, Check, CirclePause, CirclePlay, Cpu, Database, ImagePlus, MessageCircle, RefreshCw, Settings2, Square, StickyNote, Upload, Wrench, X } from 'lucide-react';+import { ArrowUp, Brain, Check, CirclePause, CirclePlay, Cpu, Database, Eraser, ImagePlus, MessageCircle, RefreshCw, Settings2, Square, StickyNote, Upload, Wrench, X } from 'lucide-react';import { Link } from 'react-router';import useMounted from '../../../hooks/useMounted';import { useSocket } from '../../../hooks/useSocket';@@ -13,6 +13,7 @@ import Banner from '../../ui/Banner';import FilePickerButton from '../../ui/FilePickerButton';import TabPills from '../../ui/TabPills';import PersistentMindContextPanel from '../PersistentMindContextPanel';+import PersistentMindMaintenancePanel from '../PersistentMindMaintenancePanel';import PersistentMindProfileControls from '../PersistentMindProfileControls';import PersistentMindRuntimePanel, { PersistentMindThoughtStatus } from '../PersistentMindRuntimePanel';import PersistentMindVisibilityPanel from '../PersistentMindVisibilityPanel';@@ -24,10 +25,11 @@ const MAX_BACKFILL_PAGES = 5;const MAX_VISIBLE_EVENTS = PAGE_LIMIT * MAX_BACKFILL_PAGES;const MAX_MESSAGE_IMAGES = 8;const MAX_MESSAGE_IMAGE_BYTES = 10 * 1024 * 1024;-const MIND_PANELS = new Set(['context', 'memories', 'tools', 'settings']);+const MIND_PANELS = new Set(['context', 'memories', 'maintenance', 'tools', 'settings']);const MIND_PANEL_TABS = [{ id: 'context', label: 'Context', icon: Brain },{ id: 'memories', label: 'Memories', icon: Database },+ { id: 'maintenance', label: 'Cleanup', icon: Eraser },{ id: 'tools', label: 'Tools', icon: Wrench },{ id: 'settings', label: 'Settings', icon: Settings2 },];@@ -50,6 +52,7 @@ const EVENT_LABELS = {'mind.capability.request': 'Action request','mind.capability.result': 'Action outcome','mind.memory.promoted': 'Memory promoted',+ 'mind.maintenance.completed': 'Mindspace cleaned',};const eventLabel = (kind) => EVENT_LABELS[kind] || 'System state';@@ -526,6 +529,15 @@ export default function MindTab() {}};+ const handleMindspaceCleaned = async (result) => {+ cursorRef.current = null;+ setEvents([]);+ setMind((current) => current ? { ...current, state: result.state || current.state } : current);+ setContextRefreshKey((current) => current + 1);+ await loadHistory({ reset: true });+ void loadRuntime();+ };+const state = mind?.state;const selectedEvent = events?.find((event) => event.eventId === selectedEventId) || null;const isPaused = state?.status === 'paused';@@ -715,6 +727,7 @@ export default function MindTab() {<div className="grid grid-cols-2 gap-2 xl:grid-cols-1"><MindStateButton icon={Brain} label="Context" value={runtime?.context?.approximateTokens == null ? 'Unavailable' : `~${runtime.context.approximateTokens.toLocaleString()} tokens`} detail={`${runtime?.context?.chars?.toLocaleString() || '—'} characters`} onClick={() => openPanel('context')} /><MindStateButton icon={Database} label="Memories" value={runtime?.context?.memoryCount == null ? 'Unavailable' : `${runtime.context.memoryCount} accessible`} detail="Created and curated" onClick={() => openPanel('memories')} />+ <MindStateButton icon={Eraser} label="Cleanup" value={mind?.capabilities?.manageMind ? 'Self-maintenance on' : 'User controlled'} detail="Memories, history, and context" onClick={() => openPanel('maintenance')} /><MindStateButton icon={Wrench} label="Tools" value={grantedCapabilityCount > 0 ? `${grantedCapabilityCount} grant${grantedCapabilityCount === 1 ? '' : 's'} enabled` : 'No grants'} detail="Narrow, typed authority" onClick={() => openPanel('tools')} /><MindStateButton icon={Cpu} label="Settings" value={runtime?.inference?.active ? 'Running now' : runtime?.inference?.residency?.status === 'loaded' ? 'Loaded in memory' : 'Not running'} detail={runtime?.inference?.model || mind?.profile?.model || 'Not configured'} onClick={() => openPanel('settings')} /></div>@@ -742,7 +755,14 @@ export default function MindTab() {<PersistentMindContextPanel view="context" refreshKey={contextRefreshKey} /></div>}{(visitedPanels.has('memories') || activePanel === 'memories') && <div hidden={activePanel !== 'memories'}>- <PersistentMindContextPanel view="memories" onMemoriesChanged={() => setContextRefreshKey((current) => current + 1)} />+ <PersistentMindContextPanel view="memories" refreshKey={contextRefreshKey} onMemoriesChanged={() => setContextRefreshKey((current) => current + 1)} />+ </div>}+ {(visitedPanels.has('maintenance') || activePanel === 'maintenance') && <div hidden={activePanel !== 'maintenance'}>+ <PersistentMindMaintenancePanel+ selfCleanupEnabled={mind?.capabilities?.manageMind === true}+ onOpenTools={() => openPanel('tools')}+ onCleaned={handleMindspaceCleaned}+ /></div>}{(visitedPanels.has('tools') || activePanel === 'tools') && <div hidden={activePanel !== 'tools'}><PersistentMindTools onCapabilitiesChange={(capabilities) => setMind((current) => current ? { ...current, capabilities } : current)} onSavingChange={setCapabilitiesSaving} />@@ -818,7 +838,7 @@ export default function MindTab() {function MindStateButton({ icon: Icon, label, value, detail, onClick }) {return (- <button type="button" onClick={onClick} className="group rounded-2xl border border-port-border bg-port-card p-3 text-left transition-colors hover:border-port-accent/60 hover:bg-port-accent/5">+ <button type="button" aria-label={label} onClick={onClick} className="group rounded-2xl border border-port-border bg-port-card p-3 text-left transition-colors hover:border-port-accent/60 hover:bg-port-accent/5"><span className="flex items-center gap-2 text-[11px] font-semibold uppercase tracking-[0.14em] text-port-text-muted group-hover:text-port-accent"><Icon size={14} aria-hidden="true" /> {label}</span>diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsxindex 8313b052bd..f67082e428 100644--- a/client/src/components/cos/tabs/MindTab.test.jsx+++ b/client/src/components/cos/tabs/MindTab.test.jsx@@ -24,6 +24,7 @@ const api = vi.hoisted(() => ({getPersistentMindVisibility: vi.fn(),createPersistentMindMemory: vi.fn(),updatePersistentMindMemory: vi.fn(),+ cleanupPersistentMind: vi.fn(),}));const socket = vi.hoisted(() => {@@ -66,7 +67,7 @@ const response = (overrides = {}) => ({snapshot: {},state: { enabled: true, started: true, status: 'waiting', pauseReason: null },profile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high', thinkingInterface: 'text', wakeIntervalMinutes: 30 },- capabilities: { schemaVersion: 1, createTasks: false },+ capabilities: { schemaVersion: 3, createTasks: false, manageMind: false, readPortos: false, writePortos: false },autonomyMode: 'execute',...overrides,});@@ -117,7 +118,7 @@ describe('MindTab', () => {harness: { type: 'api', label: 'Direct API', recommendation: 'recommended', detail: 'Structured and reliable.' },});api.getPersistentMindTools.mockResolvedValue({- capabilities: { schemaVersion: 2, createTasks: false, readPortos: false, writePortos: false },+ capabilities: { schemaVersion: 3, createTasks: false, manageMind: false, readPortos: false, writePortos: false },tools: [{id: 'cos.create-task',name: 'Create CoS task',@@ -160,6 +161,15 @@ describe('MindTab', () => {});api.createPersistentMindMemory.mockResolvedValue({ success: true });api.updatePersistentMindMemory.mockResolvedValue({ success: true });+ api.cleanupPersistentMind.mockResolvedValue({+ success: true,+ memoriesArchived: 0,+ historyEventsCleared: 5,+ historyEventsPreserved: 0,+ rollupsCleared: 2,+ runtimeResidueCleared: true,+ state: { enabled: true, started: false, status: 'idle', pauseReason: null },+ });});it('restores event details from the URL and keeps the chat composer single-purpose', async () => {@@ -321,7 +331,7 @@ describe('MindTab', () => {await user.click(taskAccess);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- { persistentMindCapabilities: { schemaVersion: 3, createTasks: true, readPortos: false, writePortos: false, taskModelAllowlist: [] } },+ { persistentMindCapabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },{ silent: true },));expect(screen.getAllByText(/code review then merge/i).length).toBeGreaterThan(0);@@ -331,13 +341,33 @@ describe('MindTab', () => {it('reports every enabled typed-tool grant in the dashboard status', async () => {api.getPersistentMind.mockResolvedValue(response({- capabilities: { schemaVersion: 2, createTasks: false, readPortos: true, writePortos: true },+ capabilities: { schemaVersion: 3, createTasks: false, manageMind: false, readPortos: true, writePortos: true },}));renderTab();expect(await screen.findByText('2 grants enabled')).toBeInTheDocument();});+ it('cleans selected mindspace through an inline confirmation and refreshes the stopped state', async () => {+ const user = userEvent.setup();+ renderTab('/cos/mind?panel=maintenance');++ expect(await screen.findByRole('heading', { name: 'Clean mindspace' })).toBeInTheDocument();+ expect(screen.getByRole('tab', { name: 'Cleanup' })).toHaveAttribute('aria-selected', 'true');+ expect(screen.getByLabelText('Rebuild derived context')).toBeChecked();+ expect(screen.getByLabelText('Clear conversation history')).not.toBeChecked();+ await user.click(screen.getByLabelText('Clear conversation history'));+ await user.type(screen.getByLabelText('Type CLEAR to run the selected cleanup'), 'CLEAR');+ await user.click(screen.getByRole('button', { name: 'Clean selected mindspace' }));++ await waitFor(() => expect(api.cleanupPersistentMind).toHaveBeenCalledWith({+ scopes: ['context', 'history'],+ confirmation: 'CLEAR',+ }, { silent: true }));+ expect(await screen.findByText('Mindspace cleaned')).toBeInTheDocument();+ await waitFor(() => expect(api.getPersistentMind).toHaveBeenCalledTimes(2));+ });+it('keeps Start gated until a capability save finishes', async () => {const user = userEvent.setup();let finishSave;diff --git a/client/src/pages/PersistentMindTools.test.jsx b/client/src/pages/PersistentMindTools.test.jsxindex 8bc4c36223..5e5bcae04a 100644--- a/client/src/pages/PersistentMindTools.test.jsx+++ b/client/src/pages/PersistentMindTools.test.jsx@@ -62,7 +62,7 @@ describe('PersistentMindTools', () => {api.getPersistentMindTools.mockResolvedValueOnce(response()).mockResolvedValueOnce(response({- capabilities: { schemaVersion: 1, createTasks: true },+ capabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false },tools: [{ ...response().tools[0], granted: true }],taskCatalog: {apps: [{ id: 'example-app', name: 'Example App', planOnly: true }],@@ -75,7 +75,7 @@ describe('PersistentMindTools', () => {await user.click(toggle);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- { persistentMindCapabilities: { schemaVersion: 3, createTasks: true, readPortos: false, writePortos: false, taskModelAllowlist: [] } },+ { persistentMindCapabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },{ silent: true },));expect(await screen.findByText(/persistent-mind capabilities granted/)).toHaveTextContent('1 of 1');@@ -86,10 +86,31 @@ describe('PersistentMindTools', () => {expect(api.getPersistentMindTools).toHaveBeenCalledTimes(2);});+ it('grants self-maintenance separately from broader PortOS write access', async () => {+ const user = userEvent.setup();+ renderPage();++ const toggle = await screen.findByRole('checkbox', { name: 'Allow mind to clean up its mindspace' });+ await user.click(toggle);++ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(+ { persistentMindCapabilities: {+ schemaVersion: 3,+ createTasks: false,+ manageMind: true,+ readPortos: false,+ writePortos: false,+ taskModelAllowlist: [],+ } },+ { silent: true },+ ));+ expect(screen.getByRole('checkbox', { name: 'Allow bounded PortOS updates' })).not.toBeChecked();+ });+it('lets the user narrow task access to individual managed apps', async () => {const user = userEvent.setup();api.getPersistentMindTools.mockResolvedValueOnce(response({- capabilities: { schemaVersion: 2, createTasks: true, readPortos: false, writePortos: false },+ capabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false },tools: [{ ...response().tools[0], granted: true }],taskCatalog: {apps: [@@ -109,6 +130,7 @@ describe('PersistentMindTools', () => {{ persistentMindCapabilities: {schemaVersion: 3,createTasks: true,+ manageMind: false,readPortos: false,writePortos: false,taskModelAllowlist: [],@@ -138,7 +160,7 @@ describe('PersistentMindTools', () => {await user.click(toggle);await waitFor(() => expect(toggle).not.toBeChecked());resolveCatalog(response({- capabilities: { schemaVersion: 1, createTasks: true },+ capabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false },tools: [{ ...response().tools[0], granted: true }],taskCatalog: { apps: [{ id: 'stale-app', name: 'Stale App', planOnly: false }], providers: [] },}));diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex 992d145b87..e29b9c4d14 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -113,6 +113,9 @@ export const createPersistentMindMemory = (body, options = {}) => request('/cos/export const updatePersistentMindMemory = (memoryId, body, options = {}) => request(`/cos/mind/memories/${encodeURIComponent(memoryId)}`, {method: 'PUT', body: JSON.stringify(body), ...options,});+export const cleanupPersistentMind = (body, options = {}) => request('/cos/mind/cleanup', {+ method: 'POST', body: JSON.stringify(body), ...options,+});// Chief of Staffexport const getCosStatus = () => request('/cos');diff --git a/server/lib/README.md b/server/lib/README.mdindex e34ef557d6..901e92c081 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -43,7 +43,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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, 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), including the optional exact provider/model task allowlist. |+| `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus bounded typed CoS-task and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes). || `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. || `persistentMindProfile.js` | Versioned, default-off persistent-mind provider profile (`enabled`, provider/model/effort, text interface, maximum quiet interval), its strict API schema, duration resolver, and safe partial-update merge that clears model/effort on a provider switch. |diff --git a/server/lib/apiRouteCatalog.generated.json b/server/lib/apiRouteCatalog.generated.jsonindex a483493c25..ac59471c3d 100644--- a/server/lib/apiRouteCatalog.generated.json+++ b/server/lib/apiRouteCatalog.generated.json@@ -5567,7 +5567,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 151+ "line": 161}]},@@ -5578,7 +5578,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 280+ "line": 301}]},@@ -5589,7 +5589,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 265+ "line": 286}]},@@ -5600,7 +5600,18 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 270+ "line": 291+ }+ ]+ },+ {+ "method": "POST",+ "path": "/api/cos/mind/cleanup",+ "mountPath": "/api/cos",+ "sources": [+ {+ "source": "server/routes/cosMindRoutes.js",+ "line": 276}]},@@ -5611,7 +5622,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 180+ "line": 191}]},@@ -5622,7 +5633,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 306+ "line": 327}]},@@ -5633,7 +5644,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 319+ "line": 340}]},@@ -5644,7 +5655,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 251+ "line": 262}]},@@ -5655,7 +5666,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 257+ "line": 268}]},@@ -5666,7 +5677,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 275+ "line": 296}]},@@ -5677,7 +5688,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 292+ "line": 313}]},@@ -5688,7 +5699,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 298+ "line": 319}]},@@ -5699,7 +5710,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 232+ "line": 243}]},@@ -5710,7 +5721,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 288+ "line": 309}]},@@ -5721,7 +5732,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 302+ "line": 323}]},@@ -5732,7 +5743,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 207+ "line": 218}]},@@ -5743,7 +5754,7 @@"sources": [{"source": "server/routes/cosMindRoutes.js",- "line": 241+ "line": 252}]},@@ -22916,8 +22927,8 @@],"stats": {"mounts": 145,- "operations": 2067,- "declarations": 2070,+ "operations": 2068,+ "declarations": 2071,"sourceFiles": 224}}diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.jsindex 6fd7de41da..e74aaf10ba 100644--- a/server/lib/persistentMindCapabilities.js+++ b/server/lib/persistentMindCapabilities.js@@ -28,6 +28,12 @@ const persistentMindTaskModelAllowlistEntrySchema = z.object({model: z.string().trim().min(1).max(PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS.MODEL_CHARS),}).strict();+export const PERSISTENT_MIND_CLEANUP_SCOPES = Object.freeze([+ 'context',+ 'history',+ 'memories',+]);+// The persistent mind has a deliberately smaller surface than ordinary CoS// agents. Keep this catalog beside the capability schema so the API and the UI// describe the same grants instead of maintaining a second client-only list.@@ -72,6 +78,20 @@ export const PERSISTENT_MIND_TOOL_CATALOG = Object.freeze(['Calls use stable request ids so retries within the bounded retention window cannot repeat an accepted action',],}),+ Object.freeze({+ id: 'mind.cleanup',+ capability: 'manageMind',+ name: 'Clean up mindspace',+ description: 'Archive mind-owned memories, clear conversation history, or rebuild the derived context cache.',+ kind: 'typed-action',+ defaultEnabled: false,+ guardrails: [+ 'Only Persistent Mind-owned machine-local state is in scope',+ 'Memory cleanup archives records instead of hard-deleting them',+ 'History cleanup preserves the turn requesting it and resets derived rollups',+ 'Every cleanup leaves a bounded maintenance record in the new trajectory',+ ],+ }),]);export const PERSISTENT_MIND_TOOL_BOUNDARIES = Object.freeze([@@ -109,6 +129,7 @@ export const persistentMindCapabilitiesSchema = portosSemanticToolGrantsSchema.ez.literal(PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION),]).optional(),createTasks: z.boolean().optional(),+ manageMind: z.boolean().optional(),// An empty list preserves the legacy unrestricted task catalog. Once any// entries are configured, requests must name one of these exact pairs.taskModelAllowlist: z.array(persistentMindTaskModelAllowlistEntrySchema)@@ -120,6 +141,14 @@ export const persistentMindCapabilitiesSchema = portosSemanticToolGrantsSchema.e.max(PERSISTENT_MIND_TASK_LIMITS.maxAllowedAppIds).optional(),});+export const persistentMindCleanupRequestSchema = z.object({+ scopes: z.array(z.enum(PERSISTENT_MIND_CLEANUP_SCOPES))+ .min(1)+ .max(PERSISTENT_MIND_CLEANUP_SCOPES.length)+ .refine((scopes) => new Set(scopes).size === scopes.length, 'cleanup scopes must be unique'),+ reason: z.string().trim().min(1).max(300).optional(),+}).strict();+export const persistentMindTaskRequestSchema = z.object({description: z.string().trim().min(1).max(PERSISTENT_MIND_TASK_LIMITS.descriptionChars),prompt: z.string().trim().min(1).max(PERSISTENT_MIND_TASK_LIMITS.promptChars),@@ -157,6 +186,7 @@ export function createDefaultPersistentMindCapabilities() {return {schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,createTasks: false,+ manageMind: false,readPortos: false,writePortos: false,taskModelAllowlist: [],@@ -208,6 +238,7 @@ export function normalizePersistentMindCapabilities(raw) {return {schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,createTasks: source.createTasks === true,+ manageMind: source.manageMind === true,...semanticGrants,taskModelAllowlist: taskModelAllowlist.entries,// A malformed hand-edited persisted policy must not silently become thediff --git a/server/lib/persistentMindCapabilities.test.js b/server/lib/persistentMindCapabilities.test.jsindex dda3272f08..596b8972ec 100644--- a/server/lib/persistentMindCapabilities.test.js+++ b/server/lib/persistentMindCapabilities.test.js@@ -6,6 +6,7 @@ import {normalizePersistentMindCapabilities,PERSISTENT_MIND_TOOL_CATALOG,persistentMindCapabilitiesSchema,+ persistentMindCleanupRequestSchema,persistentMindTaskRequestSchema,} from './persistentMindCapabilities.js';@@ -15,24 +16,34 @@ describe('persistent mind capabilities', () => {expect.objectContaining({ id: 'cos.create-task', capability: 'createTasks', defaultEnabled: false }),expect.objectContaining({ id: 'portos.read', capability: 'readPortos', defaultEnabled: false }),expect.objectContaining({ id: 'portos.write', capability: 'writePortos', defaultEnabled: false }),+ expect.objectContaining({ id: 'mind.cleanup', capability: 'manageMind', defaultEnabled: false }),]);});it('keeps task creation opt-in across fresh and legacy config', () => {- expect(createDefaultPersistentMindCapabilities()).toMatchObject({ createTasks: false, readPortos: false, writePortos: false });- expect(normalizePersistentMindCapabilities(null)).toMatchObject({ createTasks: false, readPortos: false, writePortos: false });+ expect(createDefaultPersistentMindCapabilities()).toMatchObject({ createTasks: false, manageMind: false, readPortos: false, writePortos: false });+ expect(normalizePersistentMindCapabilities(null)).toMatchObject({ createTasks: false, manageMind: false, readPortos: false, writePortos: false });expect(normalizePersistentMindCapabilities({ createTasks: 'true', readPortos: 'true' })).toMatchObject({ createTasks: false, readPortos: false });});it('validates and merges the explicit task-creation grant', () => {- expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, readPortos: true, writePortos: false }).success).toBe(true);+ expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, manageMind: true, readPortos: true, writePortos: false }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 2, createTasks: true }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ taskModelAllowlist: [{ providerId: 'ollama', model: 'example-local' }] }).success).toBe(true);+ expect(normalizePersistentMindCapabilities({ schemaVersion: 2, createTasks: true }))+ .toMatchObject({ schemaVersion: 3, createTasks: true, manageMind: false });expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: ['example-app', 'second-app'] }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: Array.from({ length: 51 }, (_, index) => `app-${index}`) }).success).toBe(false);expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, shell: true }).success).toBe(false);expect(mergePersistentMindCapabilities({ createTasks: false }, { createTasks: true }))- .toMatchObject({ createTasks: true, readPortos: false, writePortos: false });+ .toMatchObject({ createTasks: true, manageMind: false, readPortos: false, writePortos: false });+ });++ it('accepts only unique bounded mindspace cleanup scopes', () => {+ expect(persistentMindCleanupRequestSchema.safeParse({ scopes: ['context', 'history', 'memories'], reason: 'Old failures are no longer useful' }).success).toBe(true);+ expect(persistentMindCleanupRequestSchema.safeParse({ scopes: [] }).success).toBe(false);+ expect(persistentMindCleanupRequestSchema.safeParse({ scopes: ['history', 'history'] }).success).toBe(false);+ expect(persistentMindCleanupRequestSchema.safeParse({ scopes: ['everything'] }).success).toBe(false);});it('restricts task choices only when exact provider/model pairs are configured', () => {diff --git a/server/lib/persistentMindTrajectory.js b/server/lib/persistentMindTrajectory.jsindex 3e43f04cc9..1cc2cdc489 100644--- a/server/lib/persistentMindTrajectory.js+++ b/server/lib/persistentMindTrajectory.js@@ -31,6 +31,7 @@ export const PERSISTENT_MIND_EVENT_KINDS = Object.freeze(['mind.failed','mind.turn.completed','mind.memory.promoted',+ 'mind.maintenance.completed',]);const MIND_KIND_SET = new Set(PERSISTENT_MIND_EVENT_KINDS);diff --git a/server/lib/socketEventCatalog.generated.json b/server/lib/socketEventCatalog.generated.jsonindex 5cb879dfe7..868851b29b 100644--- a/server/lib/socketEventCatalog.generated.json+++ b/server/lib/socketEventCatalog.generated.json@@ -999,7 +999,7 @@{"direction": "server-to-client","source": "client/src/components/cos/tabs/MindTab.jsx",- "line": 326+ "line": 329},{"direction": "server-to-client",@@ -1456,7 +1456,7 @@{"direction": "server-to-client","source": "client/src/components/cos/tabs/MindTab.jsx",- "line": 327+ "line": 330},{"direction": "server-to-client",@@ -1474,7 +1474,7 @@{"direction": "server-to-client","source": "client/src/components/cos/tabs/MindTab.jsx",- "line": 328+ "line": 331},{"direction": "server-to-client",diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.jsindex b4f01d355a..3093d560df 100644--- a/server/routes/cosMindRoutes.js+++ b/server/routes/cosMindRoutes.js@@ -9,6 +9,7 @@ import { MAX_SCREENSHOT_BYTES } from '../lib/uploadLimits.js';import {normalizePersistentMindCapabilities,PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,+ PERSISTENT_MIND_CLEANUP_SCOPES,PERSISTENT_MIND_TOOL_BOUNDARIES,PERSISTENT_MIND_TOOL_CATALOG,} from '../lib/persistentMindCapabilities.js';@@ -34,6 +35,7 @@ import {} from '../services/persistentMindContext.js';import { getProviderById } from '../services/providers.js';import { persistentMindHarnessInfo } from '../services/persistentMindAdapter.js';+import { cleanupPersistentMind } from '../services/persistentMindMaintenance.js';import { resolvePersistentMindImageCapability } from '../services/persistentMindImageCapability.js';import { readPersistentMindTaskCatalog } from '../services/persistentMindTaskCapability.js';import { inspectPersistentMindRuntime } from '../services/persistentMindRuntime.js';@@ -130,6 +132,14 @@ const memoryUpdateSchema = z.object(memoryFields).partial().strict().refine('At least one memory field is required');const memoryParamsSchema = z.object({ memoryId: z.string().trim().min(1).max(128) }).strict();+const cleanupSchema = z.object({+ scopes: z.array(z.enum(PERSISTENT_MIND_CLEANUP_SCOPES))+ .min(1)+ .max(PERSISTENT_MIND_CLEANUP_SCOPES.length)+ .refine((scopes) => new Set(scopes).size === scopes.length, 'cleanup scopes must be unique'),+ reason: z.string().trim().min(1).max(300).optional(),+ confirmation: z.literal('CLEAR'),+}).strict();const requireSuccess = (result) => {if (result?.success === false) {@@ -263,6 +273,16 @@ router.put('/mind/memories/:memoryId', asyncHandler(async (req, res) => {res.json({ success: true, memory });}));+router.post('/mind/cleanup', asyncHandler(async (req, res) => {+ const { confirmation: _confirmation, ...input } = validateRequest(cleanupSchema, req.body);+ // A user-initiated cleanup creates a stable boundary: stop inference first so+ // an in-flight turn cannot immediately repopulate state from the old context.+ await stopPersistentMind({ waitForTurn: true });+ const result = await cleanupPersistentMind({ ...input, requestedBy: 'user' });+ const state = await getPersistentMindState();+ res.json({ ...result, state: publicPersistentMindState(state) });+}));+router.post('/mind/attachments', asyncHandler(async (req, res) => {const input = validateRequest(attachmentUploadSchema, req.body);res.status(201).json(requireSuccess(await createPersistentMindAttachment(input)));diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsindex a84ee294bd..ef38895fd2 100644--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@ -27,6 +27,7 @@ const mocks = vi.hoisted(() => ({readPersistentMindVisibility: vi.fn(),readPersistentMindTaskCatalog: vi.fn(),resolveImageCapability: vi.fn(),+ cleanupPersistentMind: vi.fn(),}));vi.mock('../services/agentRunEventLog.js', () => ({@@ -55,6 +56,9 @@ vi.mock('../services/persistentMindAdapter.js', () => ({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,}));@@ -132,6 +136,15 @@ describe('persistent mind routes', () => {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: {@@ -171,7 +184,7 @@ describe('persistent mind routes', () => {thinkingInterface: 'text',wakeIntervalMinutes: 30,},- capabilities: { schemaVersion: 3, createTasks: true, readPortos: false, writePortos: false, taskModelAllowlist: [] },+ capabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },harness: { type: 'api', recommendation: 'recommended' },imageCapability: { status: 'unknown' },autonomyMode: 'execute',@@ -206,12 +219,13 @@ describe('persistent mind routes', () => {expect(res.status).toBe(200);expect(res.body).toMatchObject({schemaVersion: 3,- capabilities: { schemaVersion: 3, createTasks: true, readPortos: false, writePortos: false, taskModelAllowlist: [] },+ capabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },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 }),]),taskCatalog: {apps: [{ id: 'demo-app', planOnly: true }],@@ -225,7 +239,7 @@ describe('persistent mind routes', () => {it('marks revoked managed apps without removing them from the settings inventory', async () => {mocks.loadState.mockResolvedValue({ config: {- persistentMindCapabilities: { schemaVersion: 2, createTasks: true, allowedAppIds: [] },+ persistentMindCapabilities: { schemaVersion: 3, createTasks: true, allowedAppIds: [] },} });mocks.readPersistentMindTaskCatalog.mockResolvedValue({apps: [{ id: 'demo-app', name: 'Demo App', planOnly: true }],@@ -298,6 +312,30 @@ describe('persistent mind routes', () => {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);diff --git a/server/services/agentRunEventLog.js b/server/services/agentRunEventLog.jsindex 0bfc8ce43c..ee464b2fb4 100644--- a/server/services/agentRunEventLog.js+++ b/server/services/agentRunEventLog.js@@ -178,6 +178,17 @@ function normalizeMindGenerations(events) {return { archive, active };}+const relinkMindPredecessors = (events) => {+ const previousByMind = new Map();+ return [...events]+ .sort((a, b) => a.sequence - b.sequence || String(a.eventId).localeCompare(String(b.eventId)))+ .map((event) => {+ const previousSequence = previousByMind.get(event.mindId) ?? null;+ previousByMind.set(event.mindId, event.sequence);+ return { ...event, data: { ...event.data, previousSequence } };+ });+};+/*** Have we already stored this event, in a copy a reader can still see?*@@ -515,6 +526,54 @@ export async function readPersistentMindHistory(mindId = PERSISTENT_MIND_ID) {.sort((a, b) => a.sequence - b.sequence || String(a.eventId).localeCompare(String(b.eventId)));}+/**+ * Remove one mind's retained trajectory behind the same queue as appends.+ * A cleanup requested by the mind itself may preserve its current turn and+ * originating message so the final reply still has visible provenance.+ */+export function clearPersistentMindHistory({+ mindId = PERSISTENT_MIND_ID,+ preserveTurnId = null,+ preserveMessageId = null,+} = {}) {+ const operation = appendQueue.then(async () => {+ await hydrate();+ const [archive, active] = await Promise.all([+ readJSONLFile(MIND_ARCHIVE_PATH),+ readJSONLFile(MIND_ACTIVE_PATH),+ ]);+ const stored = [...archive, ...active].filter(isMindShapedEvent);+ const shouldPreserve = (event) => event.mindId !== mindId+ || (preserveTurnId && event.turnId === preserveTurnId)+ || (preserveMessageId && event.data?.messageId === preserveMessageId);+ const kept = relinkMindPredecessors(stored.filter(shouldPreserve));+ const removed = stored.filter((event) => event.mindId === mindId && !shouldPreserve(event));+ const generations = normalizeMindGenerations(kept);++ if (generations.archive.length === 0) {+ if (await pathExists(MIND_ARCHIVE_PATH)) await unlink(MIND_ARCHIVE_PATH);+ } else {+ await writeJSONLines(MIND_ARCHIVE_PATH, generations.archive);+ }+ await writeJSONLines(MIND_ACTIVE_PATH, generations.active);++ mindArchiveIds = indexById(generations.archive, { persistentMind: true });+ mindActiveIds = indexById(generations.active, { persistentMind: true });+ mindActiveCount = generations.active.length;+ console.log(`🧹 Cleared ${removed.length} persistent mind history event(s)`);+ return {+ cleared: removed.length,+ preserved: generations.archive.filter((event) => event.mindId === mindId).length+ + generations.active.filter((event) => event.mindId === mindId).length,+ };+ });+ appendQueue = operation.then(+ () => undefined,+ (error) => console.error(`❌ Failed to clear persistent mind history: ${error.message}`),+ );+ return operation;+}+/*** Cursor-aware mind tail read. A missing predecessor is explicit `gap: true`;* the same response carries a fresh projection and retained tail so a clientdiff --git a/server/services/agentRunEventLog.test.js b/server/services/agentRunEventLog.test.jsindex 5918f6c3d6..600f82ea1d 100644--- a/server/services/agentRunEventLog.test.js+++ b/server/services/agentRunEventLog.test.js@@ -22,6 +22,7 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => {const {appendRunEvent,appendMindEvent,+ clearPersistentMindHistory,readRunEvents,readPersistentMindEvents,readPersistentMindHistory,@@ -270,6 +271,39 @@ describe('persistent-mind ordering, replay, and cursors', () => {expect(page).toMatchObject({ gap: false, hasMore: false, truncated: true });expect(page.events.map((item) => item.data.messageId)).toEqual(['two', 'three']);});++ it('clears one mind while preserving the requesting turn and monotonic sequence', async () => {+ const old = await appendMessage('old');+ const currentMessage = await appendMessage('current');+ const wake = await appendMindEvent({+ kind: 'mind.wake',+ turnId: 'turn-current',+ eventId: 'mind-wake:turn-current',+ });+ await appendMindEvent({+ kind: 'mind.wake',+ mindId: 'future-mind',+ turnId: 'future-turn',+ eventId: 'mind-wake:future-turn',+ });++ const result = await clearPersistentMindHistory({+ preserveTurnId: 'turn-current',+ preserveMessageId: 'current',+ });+ const retained = await readPersistentMindHistory();+ const later = await appendMessage('later');++ expect(result).toEqual({ cleared: 1, preserved: 2 });+ expect(retained.map((item) => item.eventId)).toEqual([+ currentMessage.event.eventId,+ wake.event.eventId,+ ]);+ expect(retained[0].data.previousSequence).toBeNull();+ expect(retained[1].data.previousSequence).toBe(retained[0].sequence);+ expect(later.event.sequence).toBeGreaterThan(old.event.sequence);+ expect(await readPersistentMindHistory('future-mind')).toHaveLength(1);+ });});describe('retention / rotation bound', () => {diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.jsindex c30d88109c..8a0f0a778e 100644--- a/server/services/cosToolRegistry.js+++ b/server/services/cosToolRegistry.js@@ -14,10 +14,12 @@ import { canonicalStringify } from '../lib/objects.js';import { sha256Text } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';import {+ persistentMindCleanupRequestSchema,persistentMindTaskRequestSchema,} from '../lib/persistentMindCapabilities.js';import { dispatchTool, getToolSpecs, getToolSpecsForIntent } from './voice/tools.js';import { executePersistentMindTaskRequests } from './persistentMindTaskCapability.js';+import { cleanupPersistentMind } from './persistentMindMaintenance.js';const MAX_CALL_RESULTS = 500;const MAX_IDEMPOTENCY_TOMBSTONES = 10_000;@@ -112,13 +114,34 @@ const taskTool = Object.freeze({adapter: { kind: 'persistent-mind-task' },});-const toolCatalog = (intent) => [taskTool, ...voiceTools(intent)];+const mindCleanupTool = Object.freeze({+ type: 'portos_tool',+ name: 'mind.cleanup',+ version: COS_TOOL_SCHEMA_VERSION,+ providerName: 'mind_cleanup',+ aliases: ['mind_cleanup'],+ description: 'Clean Persistent Mind-owned memories, trajectory history, or derived context when stale information is no longer useful.',+ input_schema: zodToOpenApiSchema(persistentMindCleanupRequestSchema),+ output_schema: objectOutputSchema,+ policy: {+ scopes: ['mind'],+ requiredCapabilities: ['manageMind'],+ sideEffect: 'destructive',+ idempotent: true,+ async: false,+ confirmation: 'capability-grant',+ },+ adapter: { kind: 'persistent-mind-maintenance' },+});++const toolCatalog = (intent) => [taskTool, mindCleanupTool, ...voiceTools(intent)];const toolCalls = new Map();const toolCallFingerprints = new Map();const normalizeToolCapabilities = (raw) => ({...normalizePortosSemanticToolGrants(raw),createTasks: raw?.createTasks === true,+ manageMind: raw?.manageMind === true,});const publicTool = (tool, { scope, capabilities }) => ({@@ -239,6 +262,14 @@ const executeAdapter = async (tool, args, context) => {if (tool.adapter.kind === 'voice-tool') {return dispatchTool(tool.adapter.legacyName, args, { sideEffects: [], signal: context.signal });}+ if (tool.adapter.kind === 'persistent-mind-maintenance') {+ return cleanupPersistentMind({+ ...args,+ requestedBy: 'mind',+ preserveTurnId: context.turnId || null,+ preserveMessageId: context.wake?.kind === 'message' ? context.wake.message?.id || null : null,+ });+ }const [outcome] = await executePersistentMindTaskRequests({taskRequests: [args],turnId: context.turnId,diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.jsindex ca95179817..b9bc0d3880 100644--- a/server/services/cosToolRegistry.test.js+++ b/server/services/cosToolRegistry.test.js@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const mocks = vi.hoisted(() => ({dispatch: vi.fn(),executeTasks: vi.fn(),+ cleanupMind: vi.fn(),}));const specs = [@@ -40,6 +41,9 @@ vi.mock('./voice/tools.js', () => ({vi.mock('./persistentMindTaskCapability.js', () => ({executePersistentMindTaskRequests: (...args) => mocks.executeTasks(...args),}));+vi.mock('./persistentMindMaintenance.js', () => ({+ cleanupPersistentMind: (...args) => mocks.cleanupMind(...args),+}));import {__testing,@@ -55,12 +59,13 @@ beforeEach(() => {__testing.toolCallFingerprints.clear();mocks.dispatch.mockResolvedValue({ ok: true });mocks.executeTasks.mockResolvedValue([{ success: true, task: { id: 'task-1' }, duplicate: false }]);+ mocks.cleanupMind.mockResolvedValue({ ok: true, success: true, state: 'completed', historyEventsCleared: 8 });});describe('cosToolRegistry', () => {it('exports a compact canonical catalog and provider translations', () => {const catalog = getCosToolCatalog({ scope: 'mind', capabilities: { readPortos: true } });- expect(catalog.tools.map((tool) => tool.name)).toEqual(['cos.create-task', 'brain.search', 'brain.capture']);+ expect(catalog.tools.map((tool) => tool.name)).toEqual(['cos.create-task', 'mind.cleanup', 'brain.search', 'brain.capture']);expect(catalog.tools.find((tool) => tool.name === 'brain.search').granted).toBe(true);expect(catalog.tools.find((tool) => tool.name === 'brain.capture').granted).toBe(false);const openai = formatCosToolCatalog(catalog, 'openai');@@ -99,6 +104,34 @@ describe('cosToolRegistry', () => {})).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });});+ it('executes cleanup only with the dedicated mind capability and preserves current provenance', async () => {+ const signal = new AbortController().signal;+ const call = { requestId: 'cleanup-1', name: 'mind.cleanup', arguments: { scopes: ['history'], reason: 'Stale failures' } };+ await expect(executeCosToolCall({+ call,+ authority: { scope: 'mind', capabilities: { manageMind: false } },+ })).rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });++ const result = await executeCosToolCall({+ call,+ authority: { scope: 'mind', capabilities: { manageMind: true } },+ context: {+ turnId: 'turn-current',+ wake: { kind: 'message', message: { id: 'message-current' } },+ signal,+ },+ });++ expect(result).toMatchObject({ state: 'completed', result: { historyEventsCleared: 8 } });+ expect(mocks.cleanupMind).toHaveBeenCalledWith({+ scopes: ['history'],+ reason: 'Stale failures',+ requestedBy: 'mind',+ preserveTurnId: 'turn-current',+ preserveMessageId: 'message-current',+ });+ });+it('coalesces a repeated request id and rejects changed arguments', async () => {const first = await executeCosToolCall({call: { requestId: 'same-1', name: 'brain.search', arguments: { query: 'one' } },diff --git a/server/services/persistentMindContext.js b/server/services/persistentMindContext.jsindex 9a266a074e..01bb39c816 100644--- a/server/services/persistentMindContext.js+++ b/server/services/persistentMindContext.js@@ -56,6 +56,17 @@ export async function readPersistentMindRollups(mindId = PERSISTENT_MIND_ID) {.sort((a, b) => a.source.fromSequence - b.source.fromSequence);}+/** Drop derived summaries for one mind so the next wake rebuilds from retained history. */+export function clearPersistentMindRollups(mindId = PERSISTENT_MIND_ID) {+ return queueRollupWrite(async () => {+ const store = await loadRollupStore();+ const rollups = store.rollups.filter((rollup) => rollup.mindId !== mindId);+ const cleared = store.rollups.length - rollups.length;+ await atomicWrite(ROLLUP_PATH, { schemaVersion: ROLLUP_STORE_SCHEMA_VERSION, rollups });+ return { cleared };+ });+}+/** Full active memories explicitly owned by this mind, newest importance first. */export async function readPersistentMindMemories(mindId = PERSISTENT_MIND_ID) {const result = await memoryBackend.getMemories({@@ -69,6 +80,35 @@ export async function readPersistentMindMemories(mindId = PERSISTENT_MIND_ID) {return details.filter((memory) => memory?.status === 'active' && memory.sourceAgentId === mindId);}+/**+ * Archive every active memory owned by this mind. Archival removes the records+ * from effective context while keeping recovery possible through Brain.+ */+export async function archivePersistentMindMemories(mindId = PERSISTENT_MIND_ID) {+ let archived = 0;+ while (true) {+ const result = await memoryBackend.getMemories({+ status: 'active',+ sourceAgentId: mindId,+ sortBy: 'createdAt',+ sortOrder: 'asc',+ limit: 100,+ });+ const candidates = result.memories || [];+ if (candidates.length === 0) break;+ let batchArchived = 0;+ for (const candidate of candidates) {+ const memory = await memoryBackend.peekMemory(candidate.id);+ if (memory?.status !== 'active' || memory.sourceAgentId !== mindId) continue;+ await memoryBackend.deleteMemory(memory.id, false);+ archived += 1;+ batchArchived += 1;+ }+ if (batchArchived === 0) break;+ }+ return { archived };+}+export function recordPersistentMindRollup(input) {const rollup = buildPersistentMindRollup(input);return queueRollupWrite(async () => {diff --git a/server/services/persistentMindContext.test.js b/server/services/persistentMindContext.test.jsindex b84f5fb1e7..e56a249b80 100644--- a/server/services/persistentMindContext.test.js+++ b/server/services/persistentMindContext.test.js@@ -10,6 +10,7 @@ const mock = vi.hoisted(() => ({getMemories: vi.fn(async () => ({ memories: [] })),peekMemory: vi.fn(),createMemory: vi.fn(async (input) => ({ id: 'memory-automatic-1', ...input })),+ deleteMemory: vi.fn(async (id) => ({ success: true, id })),},}));@@ -33,6 +34,8 @@ vi.mock('./memoryBackend.js', () => mock.memoryApi);const {appendPersistentMindAnnotation,+ archivePersistentMindMemories,+ clearPersistentMindRollups,createPersistentMindMemoryFromCandidate,preparePersistentMindContext,promotePersistentMindMemory,@@ -63,6 +66,7 @@ beforeEach(() => {mock.memoryApi.getMemories.mockClear();mock.memoryApi.peekMemory.mockClear();mock.memoryApi.createMemory.mockClear();+ mock.memoryApi.deleteMemory.mockClear();});afterAll(() => rmSync(CONTEXT_DIR, { recursive: true, force: true }));@@ -229,6 +233,35 @@ describe('persistent mind rollups', () => {await expect(preparePersistentMindContext()).rejects.toThrow('rollup cache is unreadable');expect(readFileSync(ROLLUPS, 'utf8')).toBe('{broken');});++ it('clears only the selected mind derived rollups', async () => {+ mock.history = [event(1), event(2), event(3)];+ await preparePersistentMindContext({ recentEventLimit: 1, summarize: async () => 'Default mind summary.' });+ const foreign = (await readPersistentMindRollups())[0];+ writeFileSync(ROLLUPS, JSON.stringify({+ schemaVersion: 1,+ rollups: [foreign, { ...foreign, id: 'future-mind:1-2:v1', mindId: 'future-mind' }],+ }));++ await expect(clearPersistentMindRollups()).resolves.toEqual({ cleared: 1 });+ expect(await readPersistentMindRollups()).toEqual([]);+ expect(await readPersistentMindRollups('future-mind')).toHaveLength(1);+ });+});++describe('persistent mind memory cleanup', () => {+ it('archives active memories owned by the mind without hard-deleting them', async () => {+ mock.memoryApi.getMemories+ .mockResolvedValueOnce({ memories: [{ id: 'memory-owned' }, { id: 'memory-foreign' }] })+ .mockResolvedValueOnce({ memories: [] });+ mock.memoryApi.peekMemory+ .mockResolvedValueOnce({ id: 'memory-owned', status: 'active', sourceAgentId: 'cos-persistent-mind' })+ .mockResolvedValueOnce({ id: 'memory-foreign', status: 'active', sourceAgentId: 'other-agent' });++ await expect(archivePersistentMindMemories()).resolves.toEqual({ archived: 1 });+ expect(mock.memoryApi.deleteMemory).toHaveBeenCalledWith('memory-owned', false);+ expect(mock.memoryApi.deleteMemory).not.toHaveBeenCalledWith('memory-foreign', expect.anything());+ });});describe('trajectory annotations and Brain promotion', () => {diff --git a/server/services/persistentMindMaintenance.js b/server/services/persistentMindMaintenance.jsnew file mode 100644index 0000000000..b34f6aa1cf--- /dev/null+++ b/server/services/persistentMindMaintenance.js@@ -0,0 +1,81 @@+/** User-triggered and capability-gated cleanup for Persistent Mind-owned state. */++import { randomUUID } from 'crypto';+import {+ persistentMindCleanupRequestSchema,+} from '../lib/persistentMindCapabilities.js';+import { PERSISTENT_MIND_ID } from '../lib/persistentMindTrajectory.js';+import {+ appendMindEvent,+ clearPersistentMindHistory,+} from './agentRunEventLog.js';+import {+ archivePersistentMindMemories,+ clearPersistentMindRollups,+} from './persistentMindContext.js';+import { resetPersistentMindRuntimeResidue } from './persistentMindSupervisor.js';++export async function cleanupPersistentMind({+ mindId = PERSISTENT_MIND_ID,+ scopes,+ reason,+ requestedBy = 'user',+ preserveTurnId = null,+ preserveMessageId = null,+} = {}) {+ const request = persistentMindCleanupRequestSchema.parse({ scopes, ...(reason ? { reason } : {}) });+ const selected = new Set(request.scopes);+ const clearHistory = selected.has('history');+ const clearContext = clearHistory || selected.has('context');+ const results = {+ memoriesArchived: 0,+ historyEventsCleared: 0,+ historyEventsPreserved: 0,+ rollupsCleared: 0,+ runtimeResidueCleared: clearHistory || selected.has('context'),+ };++ if (selected.has('memories')) {+ const memoryResult = await archivePersistentMindMemories(mindId);+ results.memoriesArchived = memoryResult.archived;+ }+ if (clearContext) {+ const rollupResult = await clearPersistentMindRollups(mindId);+ results.rollupsCleared = rollupResult.cleared;+ }+ if (clearHistory) {+ const historyResult = await clearPersistentMindHistory({+ mindId,+ preserveTurnId,+ preserveMessageId,+ });+ results.historyEventsCleared = historyResult.cleared;+ results.historyEventsPreserved = historyResult.preserved;+ }+ if (results.runtimeResidueCleared) await resetPersistentMindRuntimeResidue();++ const eventId = `mind-maintenance:${randomUUID()}`;+ const auditResult = await appendMindEvent({+ kind: 'mind.maintenance.completed',+ mindId,+ turnId: preserveTurnId,+ eventId,+ data: {+ displayText: 'Mindspace cleanup completed',+ requestedBy: requestedBy === 'mind' ? 'mind' : 'user',+ reason: request.reason || null,+ scopes: request.scopes,+ ...results,+ },+ });+ return {+ ok: true,+ success: true,+ state: 'completed',+ scopes: request.scopes,+ reason: request.reason || null,+ auditRecorded: auditResult.appended === true || auditResult.duplicate === true,+ ...results,+ eventId: auditResult.appended === true || auditResult.duplicate === true ? eventId : null,+ };+}diff --git a/server/services/persistentMindMaintenance.test.js b/server/services/persistentMindMaintenance.test.jsnew file mode 100644index 0000000000..38441ba2f0--- /dev/null+++ b/server/services/persistentMindMaintenance.test.js@@ -0,0 +1,73 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ appendMindEvent: vi.fn(async (event) => ({ appended: true, event })),+ clearHistory: vi.fn(async () => ({ cleared: 12, preserved: 3 })),+ archiveMemories: vi.fn(async () => ({ archived: 4 })),+ clearRollups: vi.fn(async () => ({ cleared: 2 })),+ resetRuntime: vi.fn(async () => ({ status: 'thinking' })),+}));++vi.mock('./agentRunEventLog.js', () => ({+ appendMindEvent: (...args) => mocks.appendMindEvent(...args),+ clearPersistentMindHistory: (...args) => mocks.clearHistory(...args),+}));+vi.mock('./persistentMindContext.js', () => ({+ archivePersistentMindMemories: (...args) => mocks.archiveMemories(...args),+ clearPersistentMindRollups: (...args) => mocks.clearRollups(...args),+}));+vi.mock('./persistentMindSupervisor.js', () => ({+ resetPersistentMindRuntimeResidue: (...args) => mocks.resetRuntime(...args),+}));++const { cleanupPersistentMind } = await import('./persistentMindMaintenance.js');++beforeEach(() => vi.clearAllMocks());++describe('persistent mind maintenance', () => {+ it('clears selected owned state and preserves the requesting turn', async () => {+ const result = await cleanupPersistentMind({+ scopes: ['history', 'memories'],+ requestedBy: 'mind',+ preserveTurnId: 'turn-current',+ preserveMessageId: 'message-current',+ reason: 'Discard stale failures',+ });++ expect(mocks.archiveMemories).toHaveBeenCalledWith('cos-persistent-mind');+ expect(mocks.clearRollups).toHaveBeenCalledWith('cos-persistent-mind');+ expect(mocks.clearHistory).toHaveBeenCalledWith({+ mindId: 'cos-persistent-mind',+ preserveTurnId: 'turn-current',+ preserveMessageId: 'message-current',+ });+ expect(mocks.resetRuntime).toHaveBeenCalledTimes(1);+ expect(mocks.appendMindEvent).toHaveBeenCalledWith(expect.objectContaining({+ kind: 'mind.maintenance.completed',+ turnId: 'turn-current',+ data: expect.objectContaining({+ requestedBy: 'mind',+ reason: 'Discard stale failures',+ scopes: ['history', 'memories'],+ }),+ }));+ expect(result).toMatchObject({+ success: true,+ memoriesArchived: 4,+ historyEventsCleared: 12,+ historyEventsPreserved: 3,+ rollupsCleared: 2,+ runtimeResidueCleared: true,+ auditRecorded: true,+ });+ });++ it('does not clear unrelated surfaces for a memory-only request', async () => {+ await cleanupPersistentMind({ scopes: ['memories'] });++ expect(mocks.archiveMemories).toHaveBeenCalledTimes(1);+ expect(mocks.clearRollups).not.toHaveBeenCalled();+ expect(mocks.clearHistory).not.toHaveBeenCalled();+ expect(mocks.resetRuntime).not.toHaveBeenCalled();+ });+});diff --git a/server/services/persistentMindSupervisor.js b/server/services/persistentMindSupervisor.jsindex be775d4229..f48e3b3bc3 100644--- a/server/services/persistentMindSupervisor.js+++ b/server/services/persistentMindSupervisor.js@@ -1069,6 +1069,21 @@ export async function refreshPersistentMindWakeCadence() {return result.state;}+/** Clear failure/backoff residue without changing lifecycle or queued work. */+export async function resetPersistentMindRuntimeResidue() {+ const result = await mutateMindState((mind) => ({+ mind: {+ ...mind,+ failureCount: 0,+ lastError: null,+ nextEligibleWakeAt: null,+ pauseReason: mind.status === 'paused' ? mind.pauseReason : null,+ },+ }));+ emitMindStatus(result.state);+ return result.state;+}+export async function setPersistentMindEnabled(enabled) {if (!enabled) {runtimeGeneration += 1;@@ -1169,7 +1184,7 @@ export async function resumePersistentMind() {return result.value;}-export async function stopPersistentMind() {+export async function stopPersistentMind({ waitForTurn = false } = {}) {runtimeGeneration += 1;activeAbortController?.abort('Persistent mind stopped');cancel(PERSISTENT_MIND_WAKE_EVENT_ID);@@ -1201,6 +1216,11 @@ export async function stopPersistentMind() {});}emitMindStatus(result.state);+ if (waitForTurn && activeRun) {+ await activeRun.catch((error) => {+ console.error(`❌ Failed while settling stopped persistent mind turn: ${error.message}`);+ });+ }return { success: true };}diff --git a/server/services/persistentMindSupervisor.test.js b/server/services/persistentMindSupervisor.test.jsindex 5e53c7afab..a40a81fbb6 100644--- a/server/services/persistentMindSupervisor.test.js+++ b/server/services/persistentMindSupervisor.test.js@@ -380,6 +380,31 @@ describe('persistent mind supervisor', () => {}));});+ it('can wait for an aborted active turn to settle before cleanup starts', async () => {+ const pending = deferred();+ await supervisor.registerPersistentMindTurnAdapter({+ prepare: vi.fn(async () => ({ ok: true, provider: { id: 'example-cloud' } })),+ run: vi.fn(() => pending.promise),+ });+ await supervisor.setPersistentMindEnabled(true);+ await supervisor.startPersistentMind();+ await supervisor.enqueuePersistentMindMessage({ id: 'message-cleanup', text: 'This turn will be interrupted.' });+ const drain = supervisor.drainPersistentMind();+ await vi.waitFor(() => expect(mock.root.persistentMind.activeTurn).not.toBeNull());++ let stopped = false;+ const stopping = supervisor.stopPersistentMind({ waitForTurn: true }).then(() => {+ stopped = true;+ });+ await vi.waitFor(() => expect(mock.root.persistentMind.activeTurn).toBeNull());+ expect(stopped).toBe(false);++ pending.resolve({ events: [{ kind: 'mind.thought', id: 'late-result', data: {} }] });+ await Promise.all([drain, stopping]);+ expect(stopped).toBe(true);+ expect(mock.root.persistentMind).toMatchObject({ started: false, status: 'idle' });+ });+it('requeues a message and degrades visibly when the pinned provider is unavailable', async () => {await supervisor.registerPersistentMindTurnAdapter({prepare: vi.fn(async () => ({ ok: false, error: 'Pinned provider unavailable' })),diff --git a/server/services/persistentMindVisibility.test.js b/server/services/persistentMindVisibility.test.jsindex 50b9df33ca..ce9ab580f1 100644--- a/server/services/persistentMindVisibility.test.js+++ b/server/services/persistentMindVisibility.test.js@@ -73,11 +73,12 @@ describe('persistent mind visibility', () => {runtime: { status: 'ready', context: { pressure: 'nominal' } },provider: { status: 'configured', type: 'api' },actions: {- grants: { createTasks: true, readPortos: false, writePortos: false },+ grants: { createTasks: true, manageMind: false, readPortos: false, writePortos: false },tools: expect.arrayContaining([expect.objectContaining({ id: 'cos.create-task', granted: true }),expect.objectContaining({ id: 'portos.read', granted: false }),expect.objectContaining({ id: 'portos.write', granted: false }),+ expect.objectContaining({ id: 'mind.cleanup', granted: false }),]),},scheduler: { autonomy: 'execute', capacity: { status: 'unknown' } },