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: restrict persistent mind task models
[._.]/ Adam Eivy720865d64f9c
diff --git a/client/src/components/cos/PersistentMindTaskAccessControls.jsx b/client/src/components/cos/PersistentMindTaskAccessControls.jsxindex 1f3d050dc8..415d319cb0 100644--- a/client/src/components/cos/PersistentMindTaskAccessControls.jsx+++ b/client/src/components/cos/PersistentMindTaskAccessControls.jsx@@ -3,10 +3,14 @@ import * as api from '../../services/api';import toast from '../ui/Toast';const normalizeCapabilities = (value) => ({- schemaVersion: 2,+ schemaVersion: 3,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 } : {}),});const OPTIONS = [@@ -39,16 +43,18 @@ export default function PersistentMindTaskAccessControls({useEffect(() => {if (!saving) setDraft(normalizeCapabilities(capabilities));- }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.readPortos, capabilities?.writePortos, saving]);+ }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, saving]);const save = async (key, enabled) => {const previous = draft;const next = { ...draft, [key]: enabled };+ const payload = { ...next };+ if (draft.taskModelAllowlistInvalid) delete payload.taskModelAllowlist;setDraft(next);setSaving(true);onSavingChange?.(true);try {- await api.updateCosConfig({ persistentMindCapabilities: next }, { silent: true });+ await api.updateCosConfig({ persistentMindCapabilities: payload }, { silent: true });onSaved?.(next);const option = OPTIONS.find((candidate) => candidate.key === key);toast.success(`${option?.label || 'Capability'} ${enabled ? 'enabled' : 'disabled'}`);@@ -90,6 +96,9 @@ export default function PersistentMindTaskAccessControls({<p className="font-medium text-port-text">Task landing policy stays authoritative</p><p className="mt-1">A task can run code review then merge, merge when CI is green, or leave open for human review. The selected per-task landing policy is never widened by this grant.</p></div>+ <p className="text-xs text-port-text-muted">+ An empty model list allows every currently configured coding model. Add exact provider/model pairs below to restrict task creation to a subscription or local-only lane.+ </p><p className="text-xs text-port-text-muted">All grants default off. CoS autonomy, capacity, daily budgets, task review defaults, CI, and the tool-specific validation remain authoritative.</p>diff --git a/client/src/components/cos/PersistentMindTaskModelAllowlistControls.jsx b/client/src/components/cos/PersistentMindTaskModelAllowlistControls.jsxnew file mode 100644index 0000000000..41f11ea1f4--- /dev/null+++ b/client/src/components/cos/PersistentMindTaskModelAllowlistControls.jsx@@ -0,0 +1,180 @@+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,+ };+ 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 --git a/client/src/components/cos/PersistentMindTaskModelAllowlistControls.test.jsx b/client/src/components/cos/PersistentMindTaskModelAllowlistControls.test.jsxnew file mode 100644index 0000000000..5f6dc10a43--- /dev/null+++ b/client/src/components/cos/PersistentMindTaskModelAllowlistControls.test.jsx@@ -0,0 +1,41 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { render, screen, waitFor } from '@testing-library/react';+import userEvent from '@testing-library/user-event';++const api = vi.hoisted(() => ({+ getProviders: vi.fn(),+ updateCosConfig: vi.fn(),+}));++vi.mock('../../services/api', () => api);+vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++import PersistentMindTaskModelAllowlistControls from './PersistentMindTaskModelAllowlistControls.jsx';++describe('PersistentMindTaskModelAllowlistControls', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ api.getProviders.mockResolvedValue({+ providers: [{ id: 'ollama', name: 'Ollama', type: 'cli', enabled: true, models: ['example-local', 'example-other'] }],+ });+ api.updateCosConfig.mockResolvedValue({ success: true });+ });++ it('adds an exact provider/model pair and persists the restriction', async () => {+ const user = userEvent.setup();+ render(<PersistentMindTaskModelAllowlistControls capabilities={{ createTasks: true, taskModelAllowlist: [] }} />);++ await user.click(await screen.findByRole('button', { name: 'Add model' }));++ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({+ persistentMindCapabilities: {+ schemaVersion: 3,+ createTasks: true,+ readPortos: false,+ writePortos: false,+ taskModelAllowlist: [{ providerId: 'ollama', model: 'example-local' }],+ },+ }, { silent: true }));+ expect(screen.getByLabelText('Model')).toHaveValue('example-local');+ });+});diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsxindex 5c9a401bd8..74d24ce160 100644--- a/client/src/components/cos/tabs/MindTab.test.jsx+++ b/client/src/components/cos/tabs/MindTab.test.jsx@@ -293,7 +293,7 @@ describe('MindTab', () => {await user.click(taskAccess);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- { persistentMindCapabilities: { schemaVersion: 2, createTasks: true, readPortos: false, writePortos: false } },+ { persistentMindCapabilities: { schemaVersion: 3, createTasks: true, readPortos: false, writePortos: false, taskModelAllowlist: [] } },{ silent: true },));expect(screen.getAllByText(/code review then merge/i).length).toBeGreaterThan(0);diff --git a/client/src/pages/PersistentMindTools.jsx b/client/src/pages/PersistentMindTools.jsxindex 5ee76ecf8f..526dc9aff1 100644--- a/client/src/pages/PersistentMindTools.jsx+++ b/client/src/pages/PersistentMindTools.jsx@@ -4,6 +4,7 @@ import * as api from '../services/api';import BrailleSpinner from '../components/BrailleSpinner';import Banner from '../components/ui/Banner';import PersistentMindTaskAccessControls from '../components/cos/PersistentMindTaskAccessControls';+import PersistentMindTaskModelAllowlistControls from '../components/cos/PersistentMindTaskModelAllowlistControls';export default function PersistentMindTools({ onCapabilitiesChange, onSavingChange }) {const [data, setData] = useState(null);@@ -85,6 +86,15 @@ export default function PersistentMindTools({ onCapabilitiesChange, onSavingChanonSavingChange={onSavingChange}/></div>+ <div className="mt-4">+ <PersistentMindTaskModelAllowlistControls+ capabilities={data.capabilities}+ onSaved={(capabilities) => {+ updateCapabilities(capabilities);+ load();+ }}+ />+ </div></section>{taskCatalog && (diff --git a/client/src/pages/PersistentMindTools.test.jsx b/client/src/pages/PersistentMindTools.test.jsxindex ac1293a3cb..f66040cc37 100644--- a/client/src/pages/PersistentMindTools.test.jsx+++ b/client/src/pages/PersistentMindTools.test.jsx@@ -5,6 +5,7 @@ import { MemoryRouter } from 'react-router';const api = vi.hoisted(() => ({getPersistentMindTools: vi.fn(),+ getProviders: vi.fn(),updateCosConfig: vi.fn(),}));@@ -43,6 +44,7 @@ describe('PersistentMindTools', () => {beforeEach(() => {vi.clearAllMocks();api.getPersistentMindTools.mockResolvedValue(response());+ api.getProviders.mockResolvedValue({ providers: [] });api.updateCosConfig.mockResolvedValue({ success: true });});@@ -73,7 +75,7 @@ describe('PersistentMindTools', () => {await user.click(toggle);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- { persistentMindCapabilities: { schemaVersion: 2, createTasks: true, readPortos: false, writePortos: false } },+ { persistentMindCapabilities: { schemaVersion: 3, createTasks: true, readPortos: false, writePortos: false, taskModelAllowlist: [] } },{ silent: true },));expect(await screen.findByText(/persistent-mind capabilities granted/)).toHaveTextContent('1 of 1');diff --git a/docs/features/cos-enhancement.md b/docs/features/cos-enhancement.mdindex 22ac4b5b09..54a8315ca6 100644--- a/docs/features/cos-enhancement.md+++ b/docs/features/cos-enhancement.md@@ -125,6 +125,12 @@ valid for GitHub/GitLab apps and is normalized to the existing unattendedafter inference, so stale prompts, disabled providers, invented model ids, andunsupported trackers fail closed.+Task model selection can be restricted in Persistent Mind Tools with an exact+provider/model allowlist. An empty list preserves the unrestricted catalog; a+non-empty list is applied to both the model choices sent to the mind and the+server-side queue admission check, which supports subscription-specific or+local-only task lanes. A removed or malformed allowlist fails closed.+`GET /api/cos/mind/tools` returns the authority inventory and, when task access isgranted, the same redacted task catalog used in the mind prompt. This keeps theMind Tools UI and the model-facing contract discoverable without granting thediff --git a/server/lib/README.md b/server/lib/README.mdindex 3cd2c7e72c..ed80d877e2 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). |+| `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. |diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.jsindex 7c1180e7bb..9d5a712636 100644--- a/server/lib/persistentMindCapabilities.js+++ b/server/lib/persistentMindCapabilities.js@@ -14,7 +14,19 @@ import {portosSemanticToolGrantsSchema,} from './cosToolContracts.js';-export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 2;+export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 3;+const PREVIOUS_PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 2;++export const PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS = Object.freeze({+ MAX_ENTRIES: 200,+ PROVIDER_ID_CHARS: 100,+ MODEL_CHARS: 200,+});++const persistentMindTaskModelAllowlistEntrySchema = z.object({+ providerId: z.string().trim().min(1).max(PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS.PROVIDER_ID_CHARS),+ model: z.string().trim().min(1).max(PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS.MODEL_CHARS),+}).strict();// 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@@ -89,8 +101,17 @@ export const PERSISTENT_MIND_VALIDATION_CHECKS = Object.freeze([]);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(),});export const persistentMindTaskRequestSchema = z.object({@@ -132,21 +153,66 @@ export function createDefaultPersistentMindCapabilities() {createTasks: false,readPortos: false,writePortos: false,+ taskModelAllowlist: [],};}+const normalizeTaskModelAllowlist = (value) => {+ if (value === undefined) return { entries: [], invalid: false };+ if (!Array.isArray(value) || value.length > PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS.MAX_ENTRIES) {+ return { entries: [], invalid: true };+ }+ const entries = [];+ const seen = new Set();+ for (const candidate of value) {+ const parsed = persistentMindTaskModelAllowlistEntrySchema.safeParse(candidate);+ if (!parsed.success) return { entries: [], invalid: true };+ const entry = parsed.data;+ const key = `${entry.providerId}\0${entry.model}`;+ if (seen.has(key)) continue;+ seen.add(key);+ entries.push(entry);+ }+ return { entries, invalid: false };+};++export function isPersistentMindTaskModelAllowed(capabilities, providerId, model) {+ const normalized = normalizePersistentMindCapabilities(capabilities);+ if (normalized.taskModelAllowlistInvalid || capabilities?.taskModelAllowlistInvalid === true) return false;+ if (normalized.taskModelAllowlist.length === 0) return true;+ return normalized.taskModelAllowlist.some((entry) => (+ entry.providerId === providerId && entry.model === model+ ));+}+export 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);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 } : {}),};}export function mergePersistentMindCapabilities(previous, update) {const prior = normalizePersistentMindCapabilities(previous);const patch = update && typeof update === 'object' && !Array.isArray(update) ? update : {};- return normalizePersistentMindCapabilities({ ...prior, ...patch });+ const merged = { ...prior, ...patch };+ // A valid replacement repairs a malformed persisted policy; unrelated grant+ // updates must retain the fail-closed marker until that happens.+ if (patch.taskModelAllowlist !== undefined) {+ delete merged.taskModelAllowlistInvalid;+ } else if (prior.taskModelAllowlistInvalid) {+ delete merged.taskModelAllowlist;+ }+ return normalizePersistentMindCapabilities(merged);}diff --git a/server/lib/persistentMindCapabilities.test.js b/server/lib/persistentMindCapabilities.test.jsindex 0803eabb5d..ce37122f0d 100644--- a/server/lib/persistentMindCapabilities.test.js+++ b/server/lib/persistentMindCapabilities.test.js@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest';import {createDefaultPersistentMindCapabilities,+ isPersistentMindTaskModelAllowed,mergePersistentMindCapabilities,normalizePersistentMindCapabilities,PERSISTENT_MIND_TOOL_CATALOG,@@ -25,11 +26,33 @@ 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({ 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('accepts only bounded typed task requests and known PR dispositions', () => {const task = {description: 'Audit the local configuration contract',diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsindex 6d2f1848be..1b24c2a101 100644--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@ -164,7 +164,7 @@ describe('persistent mind routes', () => {expect(res.body).toMatchObject({events: [], gap: false, state: { status: 'idle' },profile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high', thinkingInterface: 'text' },- 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',@@ -198,8 +198,8 @@ describe('persistent mind routes', () => {const res = await get('/mind/tools');expect(res.status).toBe(200);expect(res.body).toMatchObject({- schemaVersion: 2,- capabilities: { schemaVersion: 2, createTasks: true, readPortos: false, writePortos: false },+ schemaVersion: 3,+ capabilities: { schemaVersion: 3, createTasks: true, 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 }),diff --git a/server/services/persistentMindTaskCapability.js b/server/services/persistentMindTaskCapability.jsindex 17c15944c8..c33b386e41 100644--- a/server/services/persistentMindTaskCapability.js+++ b/server/services/persistentMindTaskCapability.js@@ -9,6 +9,7 @@import {PERSISTENT_MIND_TASK_LIMITS,+ isPersistentMindTaskModelAllowed,normalizePersistentMindCapabilities,persistentMindTaskRequestSchema,} from '../lib/persistentMindCapabilities.js';@@ -83,8 +84,11 @@ const selectableModelIds = (provider) => {return [...new Set(withDefault)].slice(0, MAX_CATALOG_MODELS);};-const providerCatalogEntry = (provider) => {- const models = selectableModelIds(provider);+const providerCatalogEntry = (provider, capabilities) => {+ const policy = normalizePersistentMindCapabilities(capabilities);+ const models = selectableModelIds(provider)+ .filter((model) => isPersistentMindTaskModelAllowed(capabilities, provider.id, model));+ if ((policy.taskModelAllowlist.length > 0 || policy.taskModelAllowlistInvalid) && models.length === 0) return null;return {id: provider.id,name: String(provider.name || provider.id).slice(0, 100),@@ -115,7 +119,8 @@ const appCatalogEntry = async (app) => {};export async function readPersistentMindTaskCatalog() {- const [apps, providers] = await Promise.all([getActiveApps(), listProviders()]);+ const [apps, providers, root] = await Promise.all([getActiveApps(), listProviders(), loadState()]);+ const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);const runnableApps = apps.filter((app) => isRunnableApp(app) && typeof app?.id === 'string' && app.id&& app.id.length <= PERSISTENT_MIND_TASK_LIMITS.appIdChars)@@ -129,7 +134,8 @@ export async function readPersistentMindTaskCatalog() {apps: await Promise.all(runnableApps.map(appCatalogEntry)),providers: candidates.filter((provider) => readiness[provider.id]?.status === 'ready')- .map(providerCatalogEntry),+ .map((provider) => providerCatalogEntry(provider, capabilities))+ .filter(Boolean),providerReadiness: providerReadinessSummary(candidates, readiness),};}@@ -183,7 +189,7 @@ Task creation access is OFF. Return an empty taskRequests array. You may recommereturn `# CoS agent task capabilityTask creation access is ON. You may request up to ${PERSISTENT_MIND_TASK_LIMITS.maxPerTurn} internal CoS agent tasks when the current wake calls for concrete delegated work. Implementation tasks run in an isolated worktree, open a pull request, and are auto-approved into the normal CoS scheduler. Plan-only tasks use the issue-only planning contract described below. The scheduler still enforces capacity, autonomy, and budget gates.-For each task, choose one configured app, provider, model (or "" for the provider's configured default), supported effort (or "" for the provider default), and exactly one PR completion policy:+For each task, choose one configured app, provider, model, supported effort (or "" for the provider default), and exactly one PR completion policy. If the task model allowlist below is non-empty, only its exact provider/model pairs are permitted; do not use a provider default or another model:- "review-then-merge": run the configured code-review loop, then merge only when its gate passes.- "merge-on-green": skip code review and merge after CI is green.- "leave-open": open the PR and wait for a human to review and merge it.@@ -223,7 +229,7 @@ const readinessError = (providerId, verdict) => {return `Provider '${providerId}' is not ready (${reasonCodes}); check Settings > AI Providers`;};-const validateChoice = async (request, apps, providers) => {+const validateChoice = async (request, apps, providers, capabilities) => {const app = apps.find((candidate) => candidate.id === request.appId && isRunnableApp(candidate));if (!app) return { error: `App '${request.appId}' has no configured repository` };const provider = providers.find((candidate) => (@@ -239,6 +245,9 @@ const validateChoice = async (request, apps, providers) => {if (request.model && !models.includes(request.model)) {return { error: `Model '${request.model}' is not configured for provider '${request.providerId}'` };}+ if (!isPersistentMindTaskModelAllowed(capabilities, request.providerId, request.model)) {+ return { error: `Model '${request.model}' is not allowed for persistent mind tasks on provider '${request.providerId}'` };+ }const efforts = effortLevelsForProvider(provider, request.model || null) || [];if (request.effort && !efforts.includes(request.effort)) {return { error: `Effort '${request.effort}' is not supported by provider '${request.providerId}'` };@@ -264,8 +273,10 @@ const validateChoice = async (request, apps, providers) => {async function queueOneTask({ request, taskId, apps }) {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 --git a/server/services/persistentMindTaskCapability.test.js b/server/services/persistentMindTaskCapability.test.jsindex 26a36620cd..65a8d16012 100644--- a/server/services/persistentMindTaskCapability.test.js+++ b/server/services/persistentMindTaskCapability.test.js@@ -111,6 +111,38 @@ describe('persistent mind CoS-task capability', () => {expect(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('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' },