Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: reconcile persistent mind capability policies with main
[._.]/ Adam Eivy037fc0a3e3f9
diff --cc client/src/components/cos/PersistentMindTaskAccessControls.jsxindex 8adbea9509,6ee87125a0..d55036d2a6--- a/client/src/components/cos/PersistentMindTaskAccessControls.jsx+++ b/client/src/components/cos/PersistentMindTaskAccessControls.jsx@@@ -7,10 -7,7 +7,11 @@@ const normalizeCapabilities = (value) =createTasks: value?.createTasks === true,readPortos: value?.readPortos === true,writePortos: value?.writePortos === true,+ taskModelAllowlist: Array.isArray(value?.taskModelAllowlist)+ ? value.taskModelAllowlist.map(({ providerId, model }) => ({ providerId, model }))+ : [],+ ...(value?.taskModelAllowlistInvalid === true ? { taskModelAllowlistInvalid: true } : {}),+ ...(Array.isArray(value?.allowedAppIds) ? { allowedAppIds: [...new Set(value.allowedAppIds)] } : {}),});const OPTIONS = [@@@ -43,7 -43,7 +47,7 @@@ export default function PersistentMindTuseEffect(() => {if (!saving) setDraft(normalizeCapabilities(capabilities));- }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, saving]);- }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.readPortos, capabilities?.writePortos, capabilities?.allowedAppIds?.join('\0'), saving]);++ }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);const save = async (key, enabled) => {const previous = draft;@@@ -68,6 -65,29 +72,31 @@@}};+ const saveAllowedAppIds = async (appId, enabled) => {+ const current = allowedAppIds || taskApps.map((app) => app.id);+ const next = enabled+ ? [...new Set([...current, appId])]+ : current.filter((id) => id !== appId);+ const previous = draft;+ const nextCapabilities = { ...draft, allowedAppIds: next };++ delete nextCapabilities.taskModelAllowlistInvalid;++ if (draft.taskModelAllowlistInvalid) delete nextCapabilities.taskModelAllowlist;+ setDraft(nextCapabilities);+ setSaving(true);+ onSavingChange?.(true);+ try {+ await api.updateCosConfig({ persistentMindCapabilities: nextCapabilities }, { silent: true });+ onSaved?.(nextCapabilities);+ toast.success(`${taskApps.find((app) => app.id === appId)?.name || 'Managed app'} task access ${enabled ? 'enabled' : 'disabled'}`);+ } catch (error) {+ setDraft(previous);+ toast.error(error.message);+ } finally {+ setSaving(false);+ onSavingChange?.(false);+ }+ };+return (<div className="space-y-4">{OPTIONS.map((option) => {diff --cc client/src/components/cos/PersistentMindTaskModelAllowlistControls.jsxindex 41f11ea1f4,0000000000..6e00277d49mode 100644,000000..100644--- a/client/src/components/cos/PersistentMindTaskModelAllowlistControls.jsx+++ b/client/src/components/cos/PersistentMindTaskModelAllowlistControls.jsx@@@ -1,180 -1,0 +1,181 @@@+import { useEffect, useId, useMemo, useState } from 'react';+import * as api from '../../services/api';+import {+ filterHardwareCompatibleProviderModels,+ filterSelectableModels,+ selectableModelsForProvider,+} from '../../utils/providers.js';+import toast from '../ui/Toast';++const normalizeEntries = (value) => (Array.isArray(value) ? value : [])+ .filter((entry) => typeof entry?.providerId === 'string' && typeof entry?.model === 'string')+ .map((entry) => ({ providerId: entry.providerId, model: entry.model }));++const modelId = (entry) => typeof entry === 'string' ? entry : entry?.id;++const modelsFor = (provider) => filterHardwareCompatibleProviderModels(+ filterSelectableModels(selectableModelsForProvider(+ provider,+ provider?.models?.length ? provider.models : [provider?.defaultModel],+ )),+ provider,+).map(modelId).filter(Boolean);++const providerLabel = (provider) => `${provider.name || provider.id} (${provider.type})`;++export default function PersistentMindTaskModelAllowlistControls({+ capabilities,+ disabled = false,+ onSaved,+ onSavingChange,+}) {+ const idPrefix = useId();+ const [providers, setProviders] = useState([]);+ const [entries, setEntries] = useState(() => normalizeEntries(capabilities?.taskModelAllowlist));+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState(null);+ const policyInvalid = capabilities?.taskModelAllowlistInvalid === true;++ useEffect(() => {+ setEntries(normalizeEntries(capabilities?.taskModelAllowlist));+ }, [capabilities?.schemaVersion, capabilities?.taskModelAllowlist]);++ useEffect(() => {+ api.getProviders({ silent: true })+ .then((response) => setProviders((response?.providers || []).filter((provider) => (+ provider.enabled !== false && (provider.type === 'cli' || provider.type === 'tui')+ ))))+ .catch((requestError) => setError(requestError?.message || 'Coding providers are unavailable'));+ }, []);++ const providerById = useMemo(() => new Map(providers.map((provider) => [provider.id, provider])), [providers]);+ const availableProviders = useMemo(() => {+ const current = entries.map((entry) => providerById.get(entry.providerId)).filter(Boolean);+ const unavailable = entries+ .filter((entry) => !providerById.has(entry.providerId))+ .map((entry) => ({ id: entry.providerId, name: `${entry.providerId} (no longer available)`, type: 'unavailable', models: [] }));+ return [...providers, ...current.filter((provider) => !providers.includes(provider)), ...unavailable]+ .filter((provider, index, list) => list.findIndex((candidate) => candidate.id === provider.id) === index);+ }, [entries, providerById, providers]);++ const save = async (nextEntries) => {+ const previous = entries;+ const deduped = [...new Map(nextEntries.map((entry) => [`${entry.providerId}\0${entry.model}`, entry])).values()];+ setEntries(deduped);+ setSaving(true);+ setError(null);+ onSavingChange?.(true);+ try {+ const next = {+ schemaVersion: 3,+ createTasks: capabilities?.createTasks === true,+ readPortos: capabilities?.readPortos === true,+ writePortos: capabilities?.writePortos === true,+ taskModelAllowlist: deduped,++ ...(Array.isArray(capabilities?.allowedAppIds) ? { allowedAppIds: capabilities.allowedAppIds } : {}),+ };+ await api.updateCosConfig({ persistentMindCapabilities: next }, { silent: true });+ onSaved?.(next);+ toast.success(deduped.length ? 'Persistent mind task models restricted' : 'Persistent mind task model restriction cleared');+ } catch (requestError) {+ setEntries(previous);+ setError(requestError?.message || 'Could not save the task model policy');+ toast.error(requestError?.message || 'Could not save the task model policy');+ } finally {+ setSaving(false);+ onSavingChange?.(false);+ }+ };++ const addEntry = () => {+ const provider = availableProviders.find((candidate) => modelsFor(candidate).length > 0);+ if (!provider) {+ setError('No selectable coding models are available. Configure a CLI/TUI provider first.');+ return;+ }+ save([...entries, { providerId: provider.id, model: modelsFor(provider)[0] }]);+ };++ const updateEntry = (index, patch) => {+ const next = entries.map((entry, entryIndex) => entryIndex === index ? { ...entry, ...patch } : entry);+ if (patch.providerId) {+ const provider = providerById.get(patch.providerId);+ const models = modelsFor(provider);+ next[index].model = models[0] || '';+ }+ if (!next[index].model) return;+ save(next);+ };++ const removeEntry = (index) => save(entries.filter((_, entryIndex) => entryIndex !== index));++ return (+ <section className="rounded border border-port-border bg-port-bg/40 p-3" aria-labelledby={`${idPrefix}-heading`}>+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div>+ <h3 id={`${idPrefix}-heading`} className="text-sm font-semibold text-port-text">Task model allowlist</h3>+ <p className="mt-1 text-xs leading-relaxed text-port-text-muted">Limit the models the mind may choose when it queues agent tasks. This does not change the model used by the mind itself.</p>+ </div>+ <button+ type="button"+ onClick={addEntry}+ disabled={disabled || saving}+ className="rounded border border-port-accent/40 px-3 py-1.5 text-xs font-medium text-port-accent hover:bg-port-accent/10 disabled:opacity-50"+ >+ Add model+ </button>+ </div>+ {error && <p className="mt-3 rounded border border-port-warning/30 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">{error}</p>}+ {policyInvalid && <p className="mt-3 rounded border border-port-warning/30 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">The saved policy is invalid, so task model selection is currently blocked. Add a valid model pair to repair it.</p>}+ {!policyInvalid && entries.length === 0 ? (+ <p className="mt-3 text-xs text-port-text-muted">No restriction configured — all enabled coding-provider models remain available.</p>+ ) : !policyInvalid && (+ <div className="mt-3 space-y-2">+ {entries.map((entry, index) => {+ const provider = providerById.get(entry.providerId);+ const models = modelsFor(provider);+ const stale = !provider || !models.includes(entry.model);+ return (+ <div key={`${entry.providerId}-${entry.model}-${index}`} className="flex flex-col gap-2 sm:flex-row sm:items-end">+ <div className="min-w-0 flex-1">+ <label htmlFor={`${idPrefix}-provider-${index}`} className="mb-1 block text-[11px] text-port-text-muted">Provider</label>+ <select+ id={`${idPrefix}-provider-${index}`}+ value={entry.providerId}+ disabled={disabled || saving}+ onChange={(event) => updateEntry(index, { providerId: event.target.value })}+ className="w-full rounded border border-port-border bg-port-bg px-2 py-1.5 text-xs text-port-text"+ >+ {availableProviders.map((candidate) => <option key={candidate.id} value={candidate.id}>{providerLabel(candidate)}</option>)}+ </select>+ </div>+ <div className="min-w-0 flex-1">+ <label htmlFor={`${idPrefix}-model-${index}`} className="mb-1 block text-[11px] text-port-text-muted">Model</label>+ <select+ id={`${idPrefix}-model-${index}`}+ value={entry.model}+ disabled={disabled || saving || !provider}+ onChange={(event) => updateEntry(index, { model: event.target.value })}+ className={`w-full rounded border bg-port-bg px-2 py-1.5 text-xs text-port-text ${stale ? 'border-port-warning' : 'border-port-border'}`}+ >+ {stale && <option value={entry.model}>{entry.model} (no longer available)</option>}+ {models.map((model) => <option key={model} value={model}>{model}</option>)}+ </select>+ </div>+ <button+ type="button"+ onClick={() => removeEntry(index)}+ disabled={disabled || saving}+ className="self-start rounded border border-port-border px-2 py-1.5 text-xs text-port-text-muted hover:border-port-warning hover:text-port-warning sm:self-end"+ >+ Remove+ </button>+ </div>+ );+ })}+ </div>+ )}+ <p className="mt-3 text-[11px] leading-relaxed text-port-text-muted">Only exact provider/model pairs are accepted at queue time. A model removed from its provider is rejected until you remove it here.</p>+ </section>+ );+}diff --cc client/src/pages/PersistentMindTools.jsxindex 4bdec9e7db,c8b5c9c7e9..f8d4feca79--- a/client/src/pages/PersistentMindTools.jsx+++ b/client/src/pages/PersistentMindTools.jsx@@@ -87,20 -88,9 +94,21 @@@ export default function PersistentMindT<div className="mt-4"><PersistentMindTaskAccessControlscapabilities={data.capabilities}+ disabled={capabilitiesSaving}+ taskCatalog={taskCatalog}onSaved={updateCapabilities}- onSavingChange={onSavingChange}+ onSavingChange={handleCapabilitiesSavingChange}+ />+ </div>+ <div className="mt-4">+ <PersistentMindTaskModelAllowlistControls+ capabilities={data.capabilities}+ disabled={capabilitiesSaving}+ onSaved={(capabilities) => {+ updateCapabilities(capabilities);+ load();+ }}+ onSavingChange={handleCapabilitiesSavingChange}/></div></section>diff --cc client/src/pages/PersistentMindTools.test.jsxindex f66040cc37,568403912f..8bc4c36223--- a/client/src/pages/PersistentMindTools.test.jsx+++ b/client/src/pages/PersistentMindTools.test.jsx@@@ -86,6 -84,39 +86,40 @@@ describe('PersistentMindTools', () =>expect(api.getPersistentMindTools).toHaveBeenCalledTimes(2);});+ 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 },+ tools: [{ ...response().tools[0], granted: true }],+ taskCatalog: {+ apps: [+ { id: 'example-app', name: 'Example App', planOnly: false, granted: true },+ { id: 'second-app', name: 'Second App', planOnly: true, granted: true },+ ],+ providers: [],+ },+ }));+ renderPage();++ const secondApp = await screen.findByRole('checkbox', { name: 'Second App' });+ expect(secondApp).toBeChecked();+ await user.click(secondApp);++ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(+ { persistentMindCapabilities: {- schemaVersion: 2,++ schemaVersion: 3,+ createTasks: true,+ readPortos: false,+ writePortos: false,++ taskModelAllowlist: [],+ allowedAppIds: ['example-app'],+ } },+ { silent: true },+ ));+ expect(secondApp).not.toBeChecked();+ expect(screen.getByRole('link', { name: 'Example App' })).toHaveAttribute('href', '/apps/example-app/automation');+ });+it('does not let a stale catalog refresh restore a revoked grant', async () => {const user = userEvent.setup();let resolveCatalog;diff --cc server/lib/README.mdindex ed80d877e2,2f844ee862..e34ef557d6--- a/server/lib/README.md+++ b/server/lib/README.md@@@ -43,12 -43,12 +43,12 @@@ The barrel `server/lib/index.js` is a m| `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). |+| `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. || `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), its strict API schema, and safe partial-update merge that clears model/effort on a provider switch. |+ | `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. || `persistentMindPrompt.js` | Editable persistent-mind identity and operating-instructions schema/defaults; saving it never starts inference. |- | `persistentMindPublic.js` | `publicPersistentMindState(state)` — the sole client/socket projection of durable mind state: exposes lifecycle fields and queue count, drops queued message bodies/active wake payloads, and replaces free-form provider errors with coarse safe reasons. |+ | `persistentMindPublic.js` | `publicPersistentMindState(state)` — the sole client/socket projection of durable mind state: exposes lifecycle fields, queue count, and the derived next wake time; drops queued message bodies/active wake payloads, and replaces free-form provider errors with coarse safe reasons. || `heavyJobClaim.js` | Cross-process, machine-wide accelerator claim: `claimHeavyLocalJob({ kind, id, timeoutMs? })` either acquires an ephemeral `data/` lock or reports its active holder; dead-PID claims are reclaimed, and a spawned child can take over the recorded PID across a server restart. || `agentValidation.js` | Social-bot agent schemas (personality, Moltbook/Moltworld accounts, automation schedules, agent tools + Moltworld payloads) and CoS Feature Agent definitions. || `quotaBurnConfig.js` | Quota-burn plan shape: the provider families, the burn-job type alphabet + catalog the config page renders its form from, `QUOTA_BURN_BOUNDS` (the one bounds table the normalizer clamps to, the Zod schemas reject against, and the catalog descriptors publish as min/max), and total normalization (`normalizeQuotaBurnConfig`). Owns the dispatch-cap sentinel too (`QUOTA_BURN_UNLIMITED_DISPATCHES` / `isUnlimitedDispatchCap`) — -1 means the window is not counted, and is the default. Also owns the queued burn task's description shape (`burnTaskDescription` / `quotaBurnFamilyOfDescription`), shared with migration 225, and the `run once` vocabulary (`quotaBurnJobKey` / `jobIsSpent`, plus the two family predicates `familyIsConfigured` and `familyHasRunnableJobs`). Pure — no storage, no provider I/O. |diff --cc server/lib/persistentMindCapabilities.jsindex 9d5a712636,885f638f19..6fd7de41da--- a/server/lib/persistentMindCapabilities.js+++ b/server/lib/persistentMindCapabilities.js@@@ -101,17 -90,13 +102,22 @@@ export const PERSISTENT_MIND_VALIDATION]);export const persistentMindCapabilitiesSchema = portosSemanticToolGrantsSchema.extend({- schemaVersion: z.literal(PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION).optional(),+ // Accept the previous wire version so an older client can still change the+ // unrelated grants while this server normalizes the stored shape forward.+ schemaVersion: z.union([+ z.literal(PREVIOUS_PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION),+ z.literal(PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION),+ ]).optional(),createTasks: 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)+ .max(PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS.MAX_ENTRIES).optional(),+ // Omitted preserves the legacy grant to every runnable managed app. An+ // explicit list lets the user narrow that grant without changing the typed+ // task capability itself.+ allowedAppIds: z.array(z.string().trim().min(1).max(PERSISTENT_MIND_TASK_LIMITS.appIdChars))+ .max(PERSISTENT_MIND_TASK_LIMITS.maxAllowedAppIds).optional(),});export const persistentMindTaskRequestSchema = z.object({@@@ -188,18 -144,19 +194,27 @@@ export function isPersistentMindTaskModexport function normalizePersistentMindCapabilities(raw) {const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};const semanticGrants = normalizePortosSemanticToolGrants(source);+ const taskModelAllowlist = source.taskModelAllowlistInvalid === true+ ? { entries: [], invalid: true }+ : normalizeTaskModelAllowlist(source.taskModelAllowlist);+ const allowedAppIds = Array.isArray(source.allowedAppIds)+ ? [...new Set(source.allowedAppIds+ .filter((id) => typeof id === 'string')+ .map((id) => id.trim())+ .filter(Boolean)+ .filter((id) => id.length <= PERSISTENT_MIND_TASK_LIMITS.appIdChars))]+ .slice(0, PERSISTENT_MIND_TASK_LIMITS.maxAllowedAppIds)+ : undefined;return {schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,createTasks: source.createTasks === true,...semanticGrants,+ taskModelAllowlist: taskModelAllowlist.entries,+ // A malformed hand-edited persisted policy must not silently become the+ // unrestricted empty-list policy. This internal marker is omitted from+ // route input schemas and only affects fail-closed admission/catalog code.+ ...(taskModelAllowlist.invalid ? { taskModelAllowlistInvalid: true } : {}),+ ...(allowedAppIds !== undefined ? { allowedAppIds } : {}),};}diff --cc server/lib/persistentMindCapabilities.test.jsindex ce37122f0d,d44a0a4499..dda3272f08--- a/server/lib/persistentMindCapabilities.test.js+++ b/server/lib/persistentMindCapabilities.test.js@@@ -26,33 -25,19 +26,41 @@@ describe('persistent mind capabilities'it('validates and merges the explicit task-creation grant', () => {expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: 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(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 });});+ it('restricts task choices only when exact provider/model pairs are configured', () => {+ const restricted = normalizePersistentMindCapabilities({+ createTasks: true,+ taskModelAllowlist: [{ providerId: 'ollama', model: 'example-local' }],+ });+ expect(isPersistentMindTaskModelAllowed(restricted, 'ollama', 'example-local')).toBe(true);+ expect(isPersistentMindTaskModelAllowed(restricted, 'ollama', 'example-cloud')).toBe(false);+ expect(isPersistentMindTaskModelAllowed(restricted, 'codex', 'example-local')).toBe(false);+ expect(isPersistentMindTaskModelAllowed({}, 'codex', 'example-cloud')).toBe(true);+ });++ it('fails closed when a persisted task model policy is malformed', () => {+ const malformed = normalizePersistentMindCapabilities({+ taskModelAllowlist: [{ providerId: 'ollama', model: '' }],+ });+ expect(malformed.taskModelAllowlistInvalid).toBe(true);+ expect(isPersistentMindTaskModelAllowed(malformed, 'ollama', 'example-local')).toBe(false);+ expect(mergePersistentMindCapabilities(malformed, { readPortos: true }).taskModelAllowlistInvalid).toBe(true);+ });++ it('preserves legacy all-app access while normalizing an explicit app allowlist', () => {+ expect(normalizePersistentMindCapabilities({ createTasks: true })).not.toHaveProperty('allowedAppIds');+ expect(normalizePersistentMindCapabilities({ allowedAppIds: [' example-app ', 'example-app', '', 'second-app'] }))+ .toMatchObject({ allowedAppIds: ['example-app', 'second-app'] });+ });+it('accepts only bounded typed task requests and known PR dispositions', () => {const task = {description: 'Audit the local configuration contract',diff --cc server/routes/cosMindRoutes.test.jsindex 1b24c2a101,9beba1c852..a84ee294bd--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@@ -163,8 -163,15 +163,15 @@@ describe('persistent mind routes', () =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' },+ profile: {+ enabled: true,+ providerId: 'demo',+ model: 'demo-model',+ effort: 'high',+ thinkingInterface: 'text',+ wakeIntervalMinutes: 30,+ },- capabilities: { schemaVersion: 2, createTasks: true, readPortos: false, writePortos: false },+ capabilities: { schemaVersion: 3, createTasks: true, readPortos: false, writePortos: false, taskModelAllowlist: [] },harness: { type: 'api', recommendation: 'recommended' },imageCapability: { status: 'unknown' },autonomyMode: 'execute',diff --cc server/services/persistentMindTaskCapability.jsindex c33b386e41,096e7d49b4..b96b6f0331--- a/server/services/persistentMindTaskCapability.js+++ b/server/services/persistentMindTaskCapability.js@@@ -118,9 -114,8 +118,10 @@@ const appCatalogEntry = async (app) =>};};- export async function readPersistentMindTaskCatalog() {-export async function readPersistentMindTaskCatalog({ allowedAppIds = null, includeAllApps = false } = {}) {- const [apps, providers] = await Promise.all([getActiveApps(), listProviders()]);++export async function readPersistentMindTaskCatalog({ allowedAppIds, includeAllApps = false } = {}) {+ const [apps, providers, root] = await Promise.all([getActiveApps(), listProviders(), loadState()]);+ const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);++ const effectiveAllowedAppIds = Array.isArray(allowedAppIds) ? allowedAppIds : capabilities.allowedAppIds;const runnableApps = apps.filter((app) => isRunnableApp(app) && typeof app?.id === 'string' && app.id&& app.id.length <= PERSISTENT_MIND_TASK_LIMITS.appIdChars)@@@ -130,12 -125,15 +131,16 @@@candidates,deferCwdDependent: true,});+ const appCatalog = await Promise.all(runnableApps.map(appCatalogEntry));- const allowed = Array.isArray(allowedAppIds) ? new Set(allowedAppIds) : null;++ const allowed = Array.isArray(effectiveAllowedAppIds) ? new Set(effectiveAllowedAppIds) : null;return {- apps: await Promise.all(runnableApps.map(appCatalogEntry)),+ // The tools settings page needs to see revoked apps so it can restore them;+ // the model-facing catalog remains narrowed to the granted set.+ apps: includeAllApps || !allowed ? appCatalog : appCatalog.filter((app) => allowed.has(app.id)),providers: candidates.filter((provider) => readiness[provider.id]?.status === 'ready')- .map(providerCatalogEntry),+ .map((provider) => providerCatalogEntry(provider, capabilities))+ .filter(Boolean),providerReadiness: providerReadinessSummary(candidates, readiness),};}@@@ -270,13 -265,14 +275,16 @@@ const validateChoice = async (request,return { app, provider, preflight, readiness };};- async function queueOneTask({ request, taskId, apps }) {+ async function queueOneTask({ request, taskId, apps, allowedAppIds }) {+ if (Array.isArray(allowedAppIds) && !allowedAppIds.includes(request.appId)) {+ return { success: false, error: `Managed app '${request.appId}' is not authorized for Persistent Mind tasks; update Persistent Mind Tools permissions` };+ }const existing = await getTaskById(taskId);if (existing) return { success: true, duplicate: true, task: existing };- const providers = await listProviders();- const choice = await validateChoice(request, apps, providers);+ const [providers, root] = await Promise.all([listProviders(), loadState()]);+ const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);+ if (!capabilities.createTasks) return { success: false, error: 'Persistent mind task creation access is disabled' };+ const choice = await validateChoice(request, apps, providers, capabilities);if (choice.error) return { success: false, error: choice.error };const planOnly = request.planOnly === true;const task = await addTask({diff --cc server/services/persistentMindTaskCapability.test.jsindex 65a8d16012,2c443d2df7..26e6109c86--- a/server/services/persistentMindTaskCapability.test.js+++ b/server/services/persistentMindTaskCapability.test.js@@@ -111,38 -111,16 +111,48 @@@ describe('persistent mind CoS-task capaexpect(prompt).not.toContain('command');});+ it('publishes only allowlisted task models and rejects a model outside the policy', async () => {+ mocks.root.config.persistentMindCapabilities.taskModelAllowlist = [+ { providerId: 'codex', model: 'gpt-5-mini' },+ ];+ const catalog = await readPersistentMindTaskCatalog();+ expect(catalog.providers).toEqual([expect.objectContaining({+ id: 'codex',+ models: [{ id: 'gpt-5-mini', efforts: expect.any(Array) }],+ })]);++ const [result] = await executePersistentMindTaskRequests({+ taskRequests: [taskRequest({ model: 'gpt-5' })],+ turnId: 'turn-model-policy',+ wake: { kind: 'message', message: { id: 'message-model-policy' } },+ });+ expect(result).toMatchObject({ success: false, error: expect.stringContaining('not allowed') });+ expect(mocks.addTask).not.toHaveBeenCalled();+ });++ it('allows a configured pair after the policy is narrowed', async () => {+ mocks.root.config.persistentMindCapabilities.taskModelAllowlist = [+ { providerId: 'codex', model: 'gpt-5-mini' },+ ];+ const [result] = await executePersistentMindTaskRequests({+ taskRequests: [taskRequest({ model: 'gpt-5-mini' })],+ turnId: 'turn-model-policy-allowed',+ wake: { kind: 'message', message: { id: 'message-model-policy-allowed' } },+ });+ expect(result).toMatchObject({ success: true });+ expect(mocks.addTask).toHaveBeenCalledWith(expect.objectContaining({ model: 'gpt-5-mini' }), 'internal');+ });++ it('filters the model-facing catalog while retaining all apps for the settings inventory', async () => {+ mocks.apps.push({ id: 'second-app', name: 'Second App', repoPath: '/example/second-app' });++ const filtered = await readPersistentMindTaskCatalog({ allowedAppIds: ['portos'] });+ const inventory = await readPersistentMindTaskCatalog({ allowedAppIds: ['portos'], includeAllApps: true });++ expect(filtered.apps.map((app) => app.id)).toEqual(['portos']);+ expect(inventory.apps.map((app) => app.id)).toEqual(['portos', 'second-app']);+ });+it('omits blocked and unknown providers while publishing bounded reason-code aggregates', async () => {mocks.providers.push({ id: 'claude', name: 'Claude', type: 'cli', enabled: true, command: 'claude' },