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: let persistent mind queue agent tasks
Adam Eivy7203042a7093
diff --git a/client/src/components/cos/PersistentMindProfileControls.jsx b/client/src/components/cos/PersistentMindProfileControls.jsxindex 1c9c83f941..2492ba624c 100644--- a/client/src/components/cos/PersistentMindProfileControls.jsx+++ b/client/src/components/cos/PersistentMindProfileControls.jsx@@ -170,7 +170,7 @@ export default function PersistentMindProfileControls({</div>)}<p className="text-xs text-port-text-muted">- Thinking effort appears when the selected provider and model support it. File-changing work remains an explicit typed CoS task; an unavailable or invalid pin pauses the mind instead of falling back.+ Thinking effort appears when the selected provider and model support it. An unavailable or invalid pin pauses the mind instead of falling back; agent-task authority is granted separately below.</p></div>);diff --git a/client/src/components/cos/PersistentMindTaskAccessControls.jsx b/client/src/components/cos/PersistentMindTaskAccessControls.jsxnew file mode 100644index 0000000000..33d8c49de3--- /dev/null+++ b/client/src/components/cos/PersistentMindTaskAccessControls.jsx@@ -0,0 +1,71 @@+import { useEffect, useId, useState } from 'react';+import * as api from '../../services/api';+import toast from '../ui/Toast';++const normalizeCapabilities = (value) => ({+ schemaVersion: 1,+ createTasks: value?.createTasks === true,+});++export default function PersistentMindTaskAccessControls({+ capabilities,+ disabled = false,+ onSaved,+ onSavingChange,+}) {+ const createTasksId = useId();+ const [draft, setDraft] = useState(() => normalizeCapabilities(capabilities));+ const [saving, setSaving] = useState(false);++ useEffect(() => {+ if (!saving) setDraft(normalizeCapabilities(capabilities));+ }, [capabilities?.schemaVersion, capabilities?.createTasks, saving]);++ const save = async (createTasks) => {+ const previous = draft;+ const next = { ...draft, createTasks };+ setDraft(next);+ setSaving(true);+ onSavingChange?.(true);+ try {+ await api.updateCosConfig({ persistentMindCapabilities: next }, { silent: true });+ onSaved?.(next);+ toast.success(createTasks ? 'Persistent mind task access enabled' : 'Persistent mind task access disabled');+ } catch (error) {+ setDraft(previous);+ toast.error(error.message);+ } finally {+ setSaving(false);+ onSavingChange?.(false);+ }+ };++ return (+ <div className="space-y-3">+ <div className="flex items-start justify-between gap-4">+ <div>+ <label htmlFor={createTasksId} className="text-sm text-port-text">Allow mind to queue CoS agent tasks</label>+ <p className="mt-0.5 text-xs text-port-text-muted">+ Grants the reasoning loop one typed action: create auto-approved internal tasks in isolated worktrees. It cannot edit files or run arbitrary tools directly.+ </p>+ </div>+ <input+ id={createTasksId}+ type="checkbox"+ checked={draft.createTasks}+ disabled={disabled || saving}+ onChange={(event) => save(event.target.checked)}+ className="mt-1 h-4 w-4 accent-port-accent disabled:opacity-50"+ />+ </div>+ <div className="rounded border border-port-border bg-port-bg/40 px-3 py-2 text-xs text-port-text-muted">+ <p className="font-medium text-port-text">The mind chooses per task</p>+ <p className="mt-1">Target app · AI provider · model · thinking effort · priority</p>+ <p className="mt-1">Landing gate: code review then merge · merge when CI is green · leave open for human review</p>+ </div>+ <p className="text-xs text-port-text-muted">+ The grant defaults off. Capacity, CoS autonomy, daily budgets, configured review defaults, and CI remain authoritative after a task is queued.+ </p>+ </div>+ );+}diff --git a/client/src/components/cos/tabs/MindTab.jsx b/client/src/components/cos/tabs/MindTab.jsxindex 47af729dee..2d15fcd85a 100644--- a/client/src/components/cos/tabs/MindTab.jsx+++ b/client/src/components/cos/tabs/MindTab.jsx@@ -12,6 +12,7 @@ import TabPills from '../../ui/TabPills';import PersistentMindContextPanel from '../PersistentMindContextPanel';import PersistentMindProfileControls from '../PersistentMindProfileControls';import PersistentMindRuntimePanel, { PersistentMindThoughtStatus } from '../PersistentMindRuntimePanel';+import PersistentMindTaskAccessControls from '../PersistentMindTaskAccessControls';const PAGE_LIMIT = 200;const MAX_BACKFILL_PAGES = 5;@@ -82,6 +83,7 @@ export default function MindTab() {const [eventActionPending, setEventActionPending] = useState(null);const [lifecycleError, setLifecycleError] = useState(null);const [profileSaving, setProfileSaving] = useState(false);+ const [taskAccessSaving, setTaskAccessSaving] = useState(false);const [showActivity, setShowActivity] = useState(false);const [runtime, setRuntime] = useState(null);const [runtimeError, setRuntimeError] = useState(null);@@ -115,7 +117,12 @@ export default function MindTab() {sawGap ||= response.gap === true;sawTruncation ||= response.truncated === true;cursor = response.gap === true ? response.cursor : response.cursor || cursor;- setMind({ state: response.state, profile: response.profile, autonomyMode: response.autonomyMode });+ setMind({+ state: response.state,+ profile: response.profile,+ capabilities: response.capabilities,+ autonomyMode: response.autonomyMode,+ });page += 1;needsMore = response.hasMore === true && !sawGap;if (!needsMore) break;@@ -295,6 +302,7 @@ export default function MindTab() {const selectedEvent = events?.find((event) => event.eventId === selectedEventId) || null;const isPaused = state?.status === 'paused';const profileReady = Boolean(mind?.profile?.enabled && mind.profile.providerId && mind.profile.model);+ const setupSaving = profileSaving || taskAccessSaving;const visibleEvents = (events || []).filter((event) => showActivity || !['mind.wake', 'mind.model.request', 'mind.model.result', 'mind.turn.completed',].includes(event.kind));@@ -357,10 +365,20 @@ export default function MindTab() {onSaved={(profile) => setMind((current) => current ? { ...current, profile } : current)}onSavingChange={setProfileSaving}/>+ <div className="mt-4 border-t border-port-border pt-4">+ <h3 className="text-sm font-semibold text-port-text">Agent task access</h3>+ <p className="mb-3 mt-1 text-xs text-port-text-muted">Choose whether this mind may turn a concrete recommendation into a typed task with its own run profile and landing gate.</p>+ <PersistentMindTaskAccessControls+ capabilities={mind?.capabilities}+ disabled={!mind}+ onSaved={(capabilities) => setMind((current) => current ? { ...current, capabilities } : current)}+ onSavingChange={setTaskAccessSaving}+ />+ </div>{!state?.started && (<div className="mt-4 flex flex-col gap-2 border-t border-port-border pt-4 sm:flex-row sm:items-center sm:justify-between">- <p className="text-xs text-port-text-muted">{profileSaving ? 'Saving the AI profile…' : profileReady ? 'The saved AI profile is ready.' : 'Enable the profile and select both an AI provider and model to start.'}</p>- <ActionButton label="Start persistent mind" icon={CirclePlay} pending={lifecyclePending === 'start'} disabled={loading || profileSaving || !profileReady} onClick={() => runLifecycle('start')} />+ <p className="text-xs text-port-text-muted">{setupSaving ? 'Saving persistent mind settings…' : profileReady ? 'The saved AI profile is ready.' : 'Enable the profile and select both an AI provider and model to start.'}</p>+ <ActionButton label="Start persistent mind" icon={CirclePlay} pending={lifecyclePending === 'start'} disabled={loading || setupSaving || !profileReady} onClick={() => runLifecycle('start')} /></div>)}</section>diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsxindex b9874884ef..ccf592e6b8 100644--- a/client/src/components/cos/tabs/MindTab.test.jsx+++ b/client/src/components/cos/tabs/MindTab.test.jsx@@ -57,6 +57,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' },+ capabilities: { schemaVersion: 1, createTasks: false },autonomyMode: 'execute',...overrides,});@@ -211,6 +212,23 @@ describe('MindTab', () => {await waitFor(() => expect(api.startPersistentMind).toHaveBeenCalledTimes(1));});+ it('persists the separate opt-in task-creation grant', async () => {+ const user = userEvent.setup();+ renderTab('/cos/mind?view=setup');++ const taskAccess = await screen.findByRole('checkbox', { name: 'Allow mind to queue CoS agent tasks' });+ expect(taskAccess).not.toBeChecked();+ await user.click(taskAccess);++ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(+ { persistentMindCapabilities: { schemaVersion: 1, createTasks: true } },+ { silent: true },+ ));+ expect(screen.getByText(/code review then merge/i)).toBeInTheDocument();+ expect(screen.getByText(/merge when CI is green/i)).toBeInTheDocument();+ expect(screen.getByText(/leave open for human review/i)).toBeInTheDocument();+ });+it('keeps a failed message for a visible idempotent retry', async () => {const user = userEvent.setup();api.sendPersistentMindMessage.mockRejectedValueOnce(new Error('Provider unavailable'));diff --git a/server/lib/README.md b/server/lib/README.mdindex c4fb5451d0..1f4c85a8bd 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -41,6 +41,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, 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). || `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. || `persistentMindPrompt.js` | Editable persistent-mind identity and operating-instructions schema/defaults; saving it never starts inference. |diff --git a/server/lib/index.js b/server/lib/index.jsindex e0ee397cce..8e8d644220 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -216,6 +216,7 @@ export * from './agentOutputMarkers.js';export * from './agentRunEvents.js';export * from './agentRunReconcile.js';export * from './persistentMind.js';+export * from './persistentMindCapabilities.js';export * from './persistentMindTrajectory.js';export * from './persistentMindProfile.js';export * from './persistentMindPrompt.js';diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.jsnew file mode 100644index 0000000000..7d4e47a4b1--- /dev/null+++ b/server/lib/persistentMindCapabilities.js@@ -0,0 +1,61 @@+/**+ * Opt-in action capabilities for the persistent Chief-of-Staff mind.+ *+ * Provider/profile configuration controls inference. This separate slice+ * controls which typed side effects a completed mind turn may request, so an+ * existing conversation-only install never gains new authority on upgrade.+ */++import { z } from 'zod';+import { EFFORT_LEVELS } from './providerModels.js';+import { PR_COMPLETION_VALUES } from './prDisposition.js';++export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 1;++export const PERSISTENT_MIND_TASK_LIMITS = Object.freeze({+ maxPerTurn: 5,+ descriptionChars: 500,+ promptChars: 12_000,+ appIdChars: 128,+ providerIdChars: 100,+ modelChars: 200,+});++export const persistentMindCapabilitiesSchema = z.object({+ schemaVersion: z.literal(PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION).optional(),+ createTasks: z.boolean().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),+ priority: z.enum(['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']).optional().default('MEDIUM'),+ appId: z.string().trim().min(1).max(PERSISTENT_MIND_TASK_LIMITS.appIdChars),+ providerId: z.string().trim().min(1).max(PERSISTENT_MIND_TASK_LIMITS.providerIdChars),+ // Empty means "use this provider's configured default" — a real choice for+ // providers whose CLI owns model selection and publishes no concrete ids.+ model: z.string().trim().max(PERSISTENT_MIND_TASK_LIMITS.modelChars),+ effort: z.union([z.literal(''), z.enum(EFFORT_LEVELS)]).optional().default(''),+ prCompletion: z.enum(PR_COMPLETION_VALUES),+}).strict();++export function createDefaultPersistentMindCapabilities() {+ return {+ schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,+ createTasks: false,+ };+}++export function normalizePersistentMindCapabilities(raw) {+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};+ return {+ schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,+ createTasks: source.createTasks === true,+ };+}++export function mergePersistentMindCapabilities(previous, update) {+ const prior = normalizePersistentMindCapabilities(previous);+ const patch = update && typeof update === 'object' && !Array.isArray(update) ? update : {};+ return normalizePersistentMindCapabilities({ ...prior, ...patch });+}diff --git a/server/lib/persistentMindCapabilities.test.js b/server/lib/persistentMindCapabilities.test.jsnew file mode 100644index 0000000000..8693abf8d0--- /dev/null+++ b/server/lib/persistentMindCapabilities.test.js@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest';+import {+ createDefaultPersistentMindCapabilities,+ mergePersistentMindCapabilities,+ normalizePersistentMindCapabilities,+ persistentMindCapabilitiesSchema,+ persistentMindTaskRequestSchema,+} from './persistentMindCapabilities.js';++describe('persistent mind capabilities', () => {+ it('keeps task creation opt-in across fresh and legacy config', () => {+ expect(createDefaultPersistentMindCapabilities()).toMatchObject({ createTasks: false });+ expect(normalizePersistentMindCapabilities(null)).toMatchObject({ createTasks: false });+ expect(normalizePersistentMindCapabilities({ createTasks: 'true' })).toMatchObject({ createTasks: false });+ });++ it('validates and merges the explicit task-creation grant', () => {+ expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true }).success).toBe(true);+ expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, shell: true }).success).toBe(false);+ expect(mergePersistentMindCapabilities({ createTasks: false }, { createTasks: true }))+ .toMatchObject({ createTasks: true });+ });++ it('accepts only bounded typed task requests and known PR dispositions', () => {+ const task = {+ description: 'Audit the local configuration contract',+ prompt: 'Inspect the repository and implement the bounded fix.',+ priority: 'HIGH',+ appId: 'portos',+ providerId: 'codex',+ model: 'gpt-5',+ effort: 'high',+ prCompletion: 'review-then-merge',+ };+ expect(persistentMindTaskRequestSchema.safeParse(task).success).toBe(true);+ expect(persistentMindTaskRequestSchema.safeParse({ ...task, prCompletion: 'merge-now' }).success).toBe(false);+ expect(persistentMindTaskRequestSchema.safeParse({ ...task, priority: 'URGENT' }).success).toBe(false);+ });+});diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.jsindex 29ff3528f3..0e6db80819 100644--- a/server/routes/cosMindRoutes.js+++ b/server/routes/cosMindRoutes.js@@ -5,6 +5,7 @@ import { z } from 'zod';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { getDomainMode } from '../lib/domainAutonomy.js';import { PERSISTENT_MIND_LIMITS } from '../lib/persistentMind.js';+import { normalizePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';import {PERSISTENT_MIND_ID,PERSISTENT_MIND_TRAJECTORY_LIMITS,@@ -110,6 +111,7 @@ router.get('/mind', asyncHandler(async (req, res) => {loadState(),]);const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);+ const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);const provider = profile.providerId ? await getProviderById(profile.providerId) : null;const { snapshot: _snapshot, ...publicHistory } = history;res.json({@@ -122,6 +124,7 @@ router.get('/mind', asyncHandler(async (req, res) => {effort: profile.effort || null,thinkingInterface: profile.thinkingInterface,},+ capabilities,harness: persistentMindHarnessInfo(provider),autonomyMode: getDomainMode(root.config, 'cos'),});diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsindex 1cf4aa26fd..95d7e9b2b5 100644--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@ -85,6 +85,7 @@ describe('persistent mind routes', () => {});mocks.loadState.mockResolvedValue({ config: {domainAutonomy: { cos: 'execute' },+ persistentMindCapabilities: { schemaVersion: 1, createTasks: true },persistentMindProfile: { enabled: true, providerId: 'demo', model: 'demo-model', effort: 'high' },persistentMindPrompt: { schemaVersion: 1, identity: 'Resident mind', instructions: 'Stay grounded.' },} });@@ -121,6 +122,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: 1, createTasks: true },harness: { type: 'api', recommendation: 'recommended' },autonomyMode: 'execute',});diff --git a/server/routes/cosStatusRoutes.js b/server/routes/cosStatusRoutes.jsindex af5fd60682..0276f8c948 100644--- a/server/routes/cosStatusRoutes.js+++ b/server/routes/cosStatusRoutes.js@@ -12,6 +12,7 @@ import { validateRequest } from '../lib/validation.js';import { z } from 'zod';import { DOMAIN_IDS, DOMAIN_MODES } from '../lib/domainAutonomy.js';import { BUDGET_LIMIT_FIELDS } from '../lib/domainBudgets.js';+import { persistentMindCapabilitiesSchema } from '../lib/persistentMindCapabilities.js';import { persistentMindProfileSchema } from '../lib/persistentMindProfile.js';import { persistentMindPromptSchema } from '../lib/persistentMindPrompt.js';@@ -55,6 +56,9 @@ export const cosConfigSchema = z.object({// `alwaysOn`: saving or enabling this profile never starts background work.persistentMindProfile: persistentMindProfileSchema.optional(),persistentMindPrompt: persistentMindPromptSchema.optional(),+ // Separate opt-in action grant: an enabled reasoning profile does not imply+ // authority to create and execute agent tasks.+ persistentMindCapabilities: persistentMindCapabilitiesSchema.optional(),// Per-domain autonomy guardrails (#711): partial map of domainId → mode.// Partial is fine — updateConfig() merges it over the stored map.domainAutonomy: z.object(diff --git a/server/services/cos.js b/server/services/cos.jsindex 29ae4db7ee..89644fcb14 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -35,6 +35,7 @@ import { todayInTimezone } from '../lib/timezone.js';import { getUserTimezone } from './userTimezone.js';import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';import { normalizeDomainBudgets, remainingActionBudget } from '../lib/domainBudgets.js';+import { mergePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';import { mergePersistentMindProfile } from '../lib/persistentMindProfile.js';import { mergePersistentMindPrompt } from '../lib/persistentMindPrompt.js';import { getDomainBudgetStatus } from './domainUsage.js';@@ -225,6 +226,7 @@ export async function updateConfig(updates) {// Same for domainBudgets — a PATCH naming one domain (or one cap on one// domain) must merge field-by-field over the rest, not replace the map.const priorDomainBudgets = state.config.domainBudgets;+ const priorPersistentMindCapabilities = state.config.persistentMindCapabilities;const priorPersistentMindProfile = state.config.persistentMindProfile;const priorPersistentMindPrompt = state.config.persistentMindPrompt;state.config = { ...state.config, ...updates };@@ -247,6 +249,12 @@ export async function updateConfig(updates) {updates.persistentMindProfile,);}+ if (updates.persistentMindCapabilities !== undefined) {+ state.config.persistentMindCapabilities = mergePersistentMindCapabilities(+ priorPersistentMindCapabilities,+ updates.persistentMindCapabilities,+ );+ }if (updates.persistentMindPrompt !== undefined) {state.config.persistentMindPrompt = mergePersistentMindPrompt(priorPersistentMindPrompt,diff --git a/server/services/cosState.js b/server/services/cosState.jsindex 596905f327..9bc7087a72 100644--- a/server/services/cosState.js+++ b/server/services/cosState.js@@ -12,6 +12,7 @@ import { ensureDirs, safeJSONParse, PATHS, atomicWrite } from '../lib/fileUtils.import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';import { normalizeDomainBudgets } from '../lib/domainBudgets.js';import { createDefaultPersistentMindState, normalizePersistentMindState } from '../lib/persistentMind.js';+import { createDefaultPersistentMindCapabilities, normalizePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';import { createDefaultPersistentMindProfile, normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';import { createDefaultPersistentMindPrompt, normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';import { DEFAULT_ALWAYS_APPROVE_KINDS } from './taskLearning/safetyKind.js';@@ -68,6 +69,9 @@ export const DEFAULT_CONFIG = {// installs stay disabled until the user explicitly starts it.persistentMindProfile: createDefaultPersistentMindProfile(),persistentMindPrompt: createDefaultPersistentMindPrompt(),+ // Action grants are independent of the provider profile. Existing and fresh+ // conversation-only installs never gain task-creation authority on upgrade.+ persistentMindCapabilities: createDefaultPersistentMindCapabilities(),// Per-domain autonomy guardrails (#711). Each domain is off | dry-run | execute.// Default is `execute` for every domain, reproducing pre-#711 behavior so no// migration is needed — an install with no stored value reads `execute`.@@ -228,6 +232,7 @@ export async function loadState() {config: {...DEFAULT_CONFIG,...persistedConfig,+ persistentMindCapabilities: normalizePersistentMindCapabilities(persistedConfig.persistentMindCapabilities),persistentMindProfile: normalizePersistentMindProfile(persistedConfig.persistentMindProfile),persistentMindPrompt: normalizePersistentMindPrompt(persistedConfig.persistentMindPrompt),},diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.jsindex 0b386565d4..782c767aea 100644--- a/server/services/persistentMindAdapter.js+++ b/server/services/persistentMindAdapter.js@@ -9,6 +9,11 @@*/import { z } from 'zod';+import {+ PERSISTENT_MIND_TASK_LIMITS,+ normalizePersistentMindCapabilities,+ persistentMindTaskRequestSchema,+} from '../lib/persistentMindCapabilities.js';import { PERSISTENT_MIND_ID } from '../lib/persistentMindTrajectory.js';import { parseLLMJSON } from '../lib/llmText.js';import { loadState } from './cosState.js';@@ -16,6 +21,11 @@ import { readPersistentMindMemories } from './persistentMindContext.js';import { normalizePersistentMindPrompt } from '../lib/persistentMindPrompt.js';import { runPromptThroughProvider } from './promptRunner.js';import { stopRun } from './runner.js';+import {+ buildPersistentMindTaskCapabilityPrompt,+ executePersistentMindTaskRequests,+ readPersistentMindTaskCatalog,+} from './persistentMindTaskCapability.js';const HEARTBEAT_INTERVAL_MS = 60_000;@@ -31,6 +41,10 @@ export const persistentMindResponseSchema = z.object({thinkingSummary: z.string().trim().max(4_000).optional().default(''),message: z.string().trim().max(8_000).optional().default(''),memoryCandidates: z.array(memoryCandidateSchema).max(5).optional().default([]),+ taskRequests: z.array(persistentMindTaskRequestSchema)+ .max(PERSISTENT_MIND_TASK_LIMITS.maxPerTurn)+ .optional()+ .default([]),selfWake: z.object({reason: z.string().trim().min(1).max(500),delayMinutes: z.number().int().min(1).max(10_080),@@ -78,21 +92,24 @@ const currentWakeText = (wake) => {return `This is a self-directed wake. Continue one worthwhile thread from the trajectory.\nreason=${wake?.reason || 'scheduled reflection'}`;};-export function buildPersistentMindTurnPrompt({ context, wake }) {+export function buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt }) {return `${context.text}# Current wake${currentWakeText(wake)}+${taskCapabilityPrompt}+# Response contractReturn ONLY one JSON object with this shape:{"thinkingSummary": "A concise, user-visible working note explaining what you considered and why. Do not reveal hidden chain-of-thought.","message": "The conversational reply. Required for a human message; optional for a self-directed wake.","memoryCandidates": [{ "content": "A durable fact worth proposing", "summary": "Short label", "type": "fact", "category": "other", "tags": ["optional"] }],+ "taskRequests": [{ "description": "Concise queue label", "prompt": "Complete instructions for the agent", "priority": "MEDIUM", "appId": "configured-app-id", "providerId": "configured-provider-id", "model": "configured-model-id-or-empty-for-default", "effort": "high", "prCompletion": "review-then-merge" }],"selfWake": { "reason": "Why another wake would be useful", "delayMinutes": 60 }}-Use an empty array when there is no durable memory candidate and null when no earlier follow-up is needed. Memory candidates are proposals only; a human decides whether to promote them. This lane cannot mutate files, call tools, contact people, or perform external actions.`;+Use empty arrays when there is no durable memory candidate or task request, and null when no earlier follow-up is needed. Memory candidates are proposals only; a human decides whether to promote them. Typed CoS task creation is the only action capability in this lane and is available only when the capability section says ON. This lane still cannot mutate files directly, call arbitrary tools, contact people, or perform other external actions.`;}const summaryEventLines = (events) => (Array.isArray(events) ? events : []).map((event) => {@@ -174,21 +191,35 @@ export function createPersistentMindTurnAdapter() {return result.text.trim();},- async run({ turnId, wake, provider, model, effort, signal, context, heartbeat }) {+ async run({ turnId, wake, provider, model, effort, signal, context, heartbeat, recordCapabilityEvent }) {+ const root = await loadState();+ const taskAccess = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);+ const taskCatalog = taskAccess.createTasks ? await readPersistentMindTaskCatalog() : undefined;+ const taskCapabilityPrompt = buildPersistentMindTaskCapabilityPrompt({+ enabled: taskAccess.createTasks,+ catalog: taskCatalog,+ });const result = await runPinnedPrompt({provider,model,effort,signal,heartbeat,- prompt: buildPersistentMindTurnPrompt({ context, wake }),+ prompt: buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt }),responseSchema: persistentMindResponseSchema,});const parsed = persistentMindResponseSchema.parse(parseLLMJSON(result.text));const message = parsed.message || (wake?.kind === 'message' ? parsed.thinkingSummary : '');- if (!parsed.thinkingSummary && !message && parsed.memoryCandidates.length === 0) {- throw new Error('Persistent mind returned no visible thought, reply, or memory candidate');+ if (!parsed.thinkingSummary && !message && parsed.memoryCandidates.length === 0 && parsed.taskRequests.length === 0) {+ throw new Error('Persistent mind returned no visible thought, reply, memory candidate, or task request');}+ await executePersistentMindTaskRequests({+ taskRequests: parsed.taskRequests,+ turnId,+ wake,+ signal,+ recordCapabilityEvent,+ });const events = [];if (parsed.thinkingSummary) {events.push({diff --git a/server/services/persistentMindAdapter.test.js b/server/services/persistentMindAdapter.test.jsindex e4df19167e..83a7620757 100644--- a/server/services/persistentMindAdapter.test.js+++ b/server/services/persistentMindAdapter.test.js@@ -5,12 +5,19 @@ const mock = vi.hoisted(() => ({memories: [{ id: 'memory-1', type: 'fact', content: 'A durable fact.', sourceAgentId: 'cos-persistent-mind', status: 'active' }],runPrompt: vi.fn(),stopRun: vi.fn(),+ readTaskCatalog: vi.fn(),+ executeTaskRequests: vi.fn(),}));vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => mock.root) }));vi.mock('./persistentMindContext.js', () => ({ readPersistentMindMemories: vi.fn(async () => mock.memories) }));vi.mock('./promptRunner.js', () => ({ runPromptThroughProvider: (...args) => mock.runPrompt(...args) }));vi.mock('./runner.js', () => ({ stopRun: (...args) => mock.stopRun(...args) }));+vi.mock('./persistentMindTaskCapability.js', () => ({+ buildPersistentMindTaskCapabilityPrompt: ({ enabled }) => `Task access: ${enabled ? 'ON' : 'OFF'}`,+ readPersistentMindTaskCatalog: (...args) => mock.readTaskCatalog(...args),+ executePersistentMindTaskRequests: (...args) => mock.executeTaskRequests(...args),+}));const { createPersistentMindTurnAdapter, persistentMindHarnessInfo } = await import('./persistentMindAdapter.js');@@ -18,6 +25,9 @@ const profile = { provider: { id: 'example-api', type: 'api' }, model: 'example-beforeEach(() => {vi.clearAllMocks();+ mock.root.config.persistentMindCapabilities = { createTasks: true };+ mock.readTaskCatalog.mockResolvedValue({ apps: [{ id: 'portos' }], providers: [{ id: 'codex' }] });+ mock.executeTaskRequests.mockResolvedValue([]);mock.runPrompt.mockResolvedValue({ text: JSON.stringify({thinkingSummary: 'I connected the new request to the durable fact.',message: 'Here is the answer.',@@ -60,6 +70,42 @@ describe('persistent mind adapter', () => {expect(result.events.map((event) => event.kind)).toEqual(['mind.thought', 'mind.reply', 'mind.memory.candidate',]);+ expect(mock.runPrompt.mock.calls[0][0].prompt).toContain('Task access: ON');+ });++ it('executes bounded typed task requests through the supervised capability', async () => {+ const taskRequest = {+ description: 'Audit the local configuration contract',+ prompt: 'Inspect the repository and implement the bounded fix.',+ priority: 'HIGH',+ appId: 'portos',+ providerId: 'codex',+ model: 'gpt-5',+ effort: 'high',+ prCompletion: 'review-then-merge',+ };+ mock.runPrompt.mockResolvedValue({ text: JSON.stringify({+ thinkingSummary: 'This is concrete delegated work.',+ message: 'I am requesting the task now.',+ taskRequests: [taskRequest],+ }) });+ const recordCapabilityEvent = vi.fn(async () => true);+ const signal = new AbortController().signal;+ await createPersistentMindTurnAdapter().run({+ turnId: 'turn-task',+ wake: { kind: 'message', message: { id: 'message-task', text: 'Queue the audit.' } },+ ...profile,+ signal,+ context: { text: '# Context' },+ recordCapabilityEvent,+ });+ expect(mock.executeTaskRequests).toHaveBeenCalledWith({+ taskRequests: [taskRequest],+ turnId: 'turn-task',+ wake: expect.objectContaining({ kind: 'message' }),+ signal,+ recordCapabilityEvent,+ });});it('keeps slow provider calls alive with a bounded periodic heartbeat', async () => {@@ -77,7 +123,9 @@ describe('persistent mind adapter', () => {heartbeat,});- await Promise.resolve();+ // The task-capability grant and bounded provider/app catalog are resolved+ // before inference starts; flush that read-only preflight too.+ await vi.advanceTimersByTimeAsync(0);expect(heartbeat).toHaveBeenCalledTimes(1);await vi.advanceTimersByTimeAsync(60_000);expect(heartbeat).toHaveBeenCalledTimes(2);diff --git a/server/services/persistentMindTaskCapability.js b/server/services/persistentMindTaskCapability.jsnew file mode 100644index 0000000000..47be0356e2--- /dev/null+++ b/server/services/persistentMindTaskCapability.js@@ -0,0 +1,245 @@+/**+ * Supervised CoS-task capability for the persistent mind.+ *+ * The model receives a bounded catalog and may return typed task requests. This+ * service re-checks the user's grant after inference, validates every selected+ * app/provider/model/effort against current configuration, records the request+ * and outcome in the mind trajectory, and only then queues an internal task.+ */++import {+ PERSISTENT_MIND_TASK_LIMITS,+ normalizePersistentMindCapabilities,+ persistentMindTaskRequestSchema,+} from '../lib/persistentMindCapabilities.js';+import { PERSISTENT_MIND_ID } from '../lib/persistentMindTrajectory.js';+import { antigravityBaseModels, effortLevelsForProvider, filterSelectableModels } from '../lib/providerModels.js';+import { PR_COMPLETIONS } from '../lib/prDisposition.js';+import { sha256Text } from '../lib/fileUtils.js';+import { getActiveApps } from './apps.js';+import { loadState } from './cosState.js';+import { addTask, getTaskById } from './cosTaskStore.js';+import { listProviders } from './providers.js';++const MAX_CATALOG_APPS = 50;+const MAX_CATALOG_PROVIDERS = 50;+const MAX_CATALOG_MODELS = 60;+const MAX_CATALOG_PROMPT_CHARS = 16_000;+const MAX_CATALOG_APP_PROMPT_CHARS = 4_000;++const selectableModelIds = (provider) => {+ const stored = filterSelectableModels(antigravityBaseModels(provider?.models))+ .filter((model) => typeof model === 'string' && model.trim()+ && model.trim().length <= PERSISTENT_MIND_TASK_LIMITS.modelChars)+ .map((model) => model.trim());+ const configuredDefault = filterSelectableModels([provider?.defaultModel])[0];+ const withDefault = typeof configuredDefault === 'string' && configuredDefault.trim()+ && configuredDefault.trim().length <= PERSISTENT_MIND_TASK_LIMITS.modelChars+ ? [configuredDefault.trim(), ...stored]+ : stored;+ return [...new Set(withDefault)].slice(0, MAX_CATALOG_MODELS);+};++const providerCatalogEntry = (provider) => {+ const models = selectableModelIds(provider);+ return {+ id: provider.id,+ name: String(provider.name || provider.id).slice(0, 100),+ type: provider.type || null,+ models: models.map((model) => ({+ id: model,+ efforts: effortLevelsForProvider(provider, model) || [],+ })),+ };+};++export async function readPersistentMindTaskCatalog() {+ const [apps, providers] = await Promise.all([getActiveApps(), listProviders()]);+ return {+ apps: apps+ .filter((app) => typeof app?.id === 'string' && app.id+ && app.id.length <= PERSISTENT_MIND_TASK_LIMITS.appIdChars)+ .slice(0, MAX_CATALOG_APPS)+ .map((app) => ({ id: app.id, name: String(app.name || app.id).slice(0, 100) })),+ providers: providers+ .filter((provider) => provider?.enabled !== false && typeof provider?.id === 'string' && provider.id+ && provider.id.length <= PERSISTENT_MIND_TASK_LIMITS.providerIdChars)+ .slice(0, MAX_CATALOG_PROVIDERS)+ .map(providerCatalogEntry),+ };+}++const boundedPromptCatalog = (catalog) => {+ const bounded = { apps: [], providers: [] };+ for (const app of Array.isArray(catalog?.apps) ? catalog.apps : []) {+ bounded.apps.push(app);+ if (JSON.stringify({ apps: bounded.apps }).length > MAX_CATALOG_APP_PROMPT_CHARS) {+ bounded.apps.pop();+ break;+ }+ }+ for (const provider of Array.isArray(catalog?.providers) ? catalog.providers : []) {+ const kept = { ...provider, models: [] };+ bounded.providers.push(kept);+ if (JSON.stringify(bounded).length > MAX_CATALOG_PROMPT_CHARS) {+ bounded.providers.pop();+ break;+ }+ for (const model of Array.isArray(provider.models) ? provider.models : []) {+ kept.models.push(model);+ if (JSON.stringify(bounded).length > MAX_CATALOG_PROMPT_CHARS) {+ kept.models.pop();+ break;+ }+ }+ }+ return bounded;+};++export function buildPersistentMindTaskCapabilityPrompt({ enabled, catalog = { apps: [], providers: [] } } = {}) {+ if (!enabled) {+ return `# CoS agent task capability+Task creation access is OFF. Return an empty taskRequests array. You may recommend a task conversationally, but must not claim it was queued.`;+ }+ const promptCatalog = boundedPromptCatalog(catalog);+ return `# CoS agent task capability+Task 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. Each task runs in an isolated worktree, opens a pull request, and is auto-approved into the normal CoS scheduler. 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:+- "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.++Configured choices (ids are authoritative; do not invent ids):+${JSON.stringify(promptCatalog)}++Use taskRequests only for specific, non-duplicate work. Put the complete agent instructions in prompt and a concise queue label in description. In your conversational message describe the request as pending; do not claim the task was created or completed because the capability outcome is recorded only after inference.`;+}++const wakeIdentity = (wake, turnId) => (+ wake?.kind === 'message' ? wake.message?.id : wake?.id+) || turnId;++const taskIdFor = (wakeId, index) => (+ `sys-mind-${sha256Text(`${PERSISTENT_MIND_ID}:${wakeId}:${index}`).slice(0, 24)}`+);++const boundedError = (error) => String(error?.message || error || 'Task creation failed').slice(0, 300);++const validateChoice = (request, apps, providers) => {+ const app = apps.find((candidate) => candidate.id === request.appId);+ if (!app) return { error: `App '${request.appId}' is not active` };+ const provider = providers.find((candidate) => candidate.id === request.providerId && candidate.enabled !== false);+ if (!provider) return { error: `Provider '${request.providerId}' is not enabled` };+ const models = selectableModelIds(provider);+ if (request.model && !models.includes(request.model)) {+ return { error: `Model '${request.model}' is not configured for 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}'` };+ }+ return { app, provider };+};++async function queueOneTask({ request, taskId, apps, providers }) {+ const existing = await getTaskById(taskId);+ if (existing) return { success: true, duplicate: true, task: existing };+ const choice = validateChoice(request, apps, providers);+ if (choice.error) return { success: false, error: choice.error };+ const task = await addTask({+ id: taskId,+ description: request.description,+ prompt: request.prompt,+ priority: request.priority,+ app: request.appId,+ provider: request.providerId,+ model: request.model || undefined,+ effort: request.effort || undefined,+ useWorktree: true,+ openPR: true,+ prCompletion: request.prCompletion,+ simplify: true,+ worktreeChangesExpected: true,+ approvalRequired: false,+ }, 'internal');+ return { success: true, duplicate: task.duplicate === true, task };+}++const eventDataFor = (request, outcome, displayText) => ({+ displayText,+ appId: request.appId,+ providerId: request.providerId,+ model: request.model || null,+ effort: request.effort || null,+ prCompletion: request.prCompletion,+ ...(outcome ? {+ success: outcome.success === true,+ duplicate: outcome.duplicate === true,+ taskId: outcome.task?.id || null,+ } : {}),+ ...(outcome?.error ? { status: boundedError(outcome.error) } : {}),+});++/**+ * Execute model-returned requests sequentially so capability events preserve+ * request order. A stable wake+index id makes a replay after a crash at-most-once.+ */+export async function executePersistentMindTaskRequests({+ taskRequests,+ turnId,+ wake,+ signal,+ recordCapabilityEvent,+} = {}) {+ const requests = Array.isArray(taskRequests)+ ? taskRequests.slice(0, PERSISTENT_MIND_TASK_LIMITS.maxPerTurn)+ : [];+ if (requests.length === 0) return [];++ const [root, apps, providers] = await Promise.all([loadState(), getActiveApps(), listProviders()]);+ const enabled = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities).createTasks;+ const record = typeof recordCapabilityEvent === 'function'+ ? recordCapabilityEvent+ : () => Promise.resolve();+ const sourceWakeId = wakeIdentity(wake, turnId);+ const results = [];++ for (const [index, candidate] of requests.entries()) {+ const parsed = persistentMindTaskRequestSchema.safeParse(candidate);+ const capabilityId = `cos-task-${sha256Text(`${sourceWakeId}:${index}`).slice(0, 24)}`;+ if (!parsed.success) {+ const outcome = { success: false, error: 'Task request failed validation' };+ await record({+ kind: 'result',+ id: capabilityId,+ data: { displayText: `CoS task request ${index + 1} was rejected`, success: false, status: outcome.error },+ });+ results.push(outcome);+ continue;+ }++ const request = parsed.data;+ await record({+ kind: 'request',+ id: capabilityId,+ data: eventDataFor(request, null, `Requested CoS task ${index + 1} for ${request.appId}`),+ });+ const taskId = taskIdFor(sourceWakeId, index);+ const outcome = signal?.aborted+ ? { success: false, error: 'Persistent mind turn was interrupted before task creation' }+ : enabled+ ? await Promise.resolve()+ .then(() => queueOneTask({ request, taskId, apps, providers }))+ .then((value) => value, (error) => ({ success: false, error: boundedError(error) }))+ : { success: false, error: 'Persistent mind task creation access is disabled' };+ const displayText = outcome.success+ ? `${outcome.duplicate ? 'Reused' : 'Queued'} CoS task ${outcome.task.id}`+ : `CoS task request ${index + 1} was not queued`;+ await record({ kind: 'result', id: capabilityId, data: eventDataFor(request, outcome, displayText) });+ results.push(outcome);+ }+ return results;+}++export const PERSISTENT_MIND_TASK_PR_COMPLETIONS = PR_COMPLETIONS;diff --git a/server/services/persistentMindTaskCapability.test.js b/server/services/persistentMindTaskCapability.test.jsnew file mode 100644index 0000000000..40cacc21ac--- /dev/null+++ b/server/services/persistentMindTaskCapability.test.js@@ -0,0 +1,171 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ root: { config: { persistentMindCapabilities: { createTasks: true } } },+ apps: [{ id: 'portos', name: 'PortOS' }],+ providers: [{+ id: 'codex', name: 'Codex', type: 'cli', enabled: true, command: 'codex',+ defaultModel: 'gpt-5', models: ['gpt-5', 'gpt-5-mini'],+ }],+ existing: null,+ addTask: vi.fn(),+}));++vi.mock('./apps.js', () => ({ getActiveApps: vi.fn(async () => mocks.apps) }));+vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => mocks.root) }));+vi.mock('./cosTaskStore.js', () => ({+ addTask: (...args) => mocks.addTask(...args),+ getTaskById: vi.fn(async () => mocks.existing),+}));+vi.mock('./providers.js', () => ({ listProviders: vi.fn(async () => mocks.providers) }));++const {+ buildPersistentMindTaskCapabilityPrompt,+ executePersistentMindTaskRequests,+ readPersistentMindTaskCatalog,+} = await import('./persistentMindTaskCapability.js');++const taskRequest = (overrides = {}) => ({+ description: 'Audit the local configuration contract',+ prompt: 'Inspect the repository, implement the bounded fix, and verify it.',+ priority: 'HIGH',+ appId: 'portos',+ providerId: 'codex',+ model: 'gpt-5',+ effort: 'high',+ prCompletion: 'review-then-merge',+ ...overrides,+});++beforeEach(() => {+ vi.clearAllMocks();+ mocks.root = { config: { persistentMindCapabilities: { createTasks: true } } };+ mocks.providers = [{+ id: 'codex', name: 'Codex', type: 'cli', enabled: true, command: 'codex',+ defaultModel: 'gpt-5', models: ['gpt-5', 'gpt-5-mini'],+ }];+ mocks.existing = null;+ mocks.addTask.mockResolvedValue({ id: 'sys-mind-stable', status: 'pending', autoApproved: true });+});++describe('persistent mind CoS-task capability', () => {+ it('publishes only bounded app/provider/model/effort choices to the mind', async () => {+ const catalog = await readPersistentMindTaskCatalog();+ expect(catalog).toEqual({+ apps: [{ id: 'portos', name: 'PortOS' }],+ providers: [{+ id: 'codex', name: 'Codex', type: 'cli',+ models: [+ { id: 'gpt-5', efforts: expect.arrayContaining(['high']) },+ { id: 'gpt-5-mini', efforts: expect.arrayContaining(['high']) },+ ],+ }],+ });+ const prompt = buildPersistentMindTaskCapabilityPrompt({ enabled: true, catalog });+ expect(prompt).toContain('"review-then-merge"');+ expect(prompt).toContain('"merge-on-green"');+ expect(prompt).toContain('"leave-open"');+ expect(prompt).not.toContain('command');+ });++ it('bounds a large configured catalog before it enters the reasoning prompt', () => {+ const catalog = {+ apps: Array.from({ length: 100 }, (_, index) => ({ id: `app-${index}`, name: 'A'.repeat(100) })),+ providers: Array.from({ length: 50 }, (_, providerIndex) => ({+ id: `provider-${providerIndex}`,+ name: 'P'.repeat(100),+ type: 'cli',+ models: Array.from({ length: 60 }, (_, modelIndex) => ({+ id: `model-${providerIndex}-${modelIndex}-${'m'.repeat(120)}`,+ efforts: ['low', 'medium', 'high', 'xhigh', 'max'],+ })),+ })),+ };+ const prompt = buildPersistentMindTaskCapabilityPrompt({ enabled: true, catalog });+ expect(prompt.length).toBeLessThan(20_000);+ expect(prompt).toContain('app-0');+ expect(prompt).toContain('provider-0');+ });++ it('queues an auto-approved isolated task with the chosen run and PR policy', async () => {+ const recordCapabilityEvent = vi.fn(async () => true);+ const results = await executePersistentMindTaskRequests({+ taskRequests: [taskRequest()],+ turnId: 'turn-1',+ wake: { kind: 'message', message: { id: 'message-1' } },+ recordCapabilityEvent,+ });++ expect(results).toMatchObject([{ success: true, duplicate: false }]);+ expect(mocks.addTask).toHaveBeenCalledWith(expect.objectContaining({+ id: expect.stringMatching(/^sys-mind-/),+ app: 'portos', provider: 'codex', model: 'gpt-5', effort: 'high',+ useWorktree: true, openPR: true, prCompletion: 'review-then-merge',+ simplify: true, approvalRequired: false,+ }), 'internal');+ expect(recordCapabilityEvent.mock.calls.map(([event]) => event.kind)).toEqual(['request', 'result']);+ });++ it('fails closed when access is revoked after inference', async () => {+ mocks.root.config.persistentMindCapabilities.createTasks = false;+ const recordCapabilityEvent = vi.fn(async () => true);+ const [result] = await executePersistentMindTaskRequests({+ taskRequests: [taskRequest({ prCompletion: 'leave-open' })],+ turnId: 'turn-2',+ wake: { kind: 'self', id: 'wake-2' },+ recordCapabilityEvent,+ });+ expect(result).toMatchObject({ success: false, error: expect.stringContaining('disabled') });+ expect(mocks.addTask).not.toHaveBeenCalled();+ expect(recordCapabilityEvent).toHaveBeenCalledTimes(2);+ });++ it('allows an explicit provider-default model choice', async () => {+ await executePersistentMindTaskRequests({+ taskRequests: [taskRequest({ model: '', effort: '', prCompletion: 'merge-on-green' })],+ turnId: 'turn-default-model',+ wake: { kind: 'message', message: { id: 'message-default-model' } },+ });+ const queued = mocks.addTask.mock.calls[0][0];+ expect(queued.provider).toBe('codex');+ expect(queued.model).toBeUndefined();+ expect(queued.effort).toBeUndefined();+ });++ it('rejects invented models and unsupported effort before queueing', async () => {+ const results = await executePersistentMindTaskRequests({+ taskRequests: [taskRequest({ model: 'invented' }), taskRequest({ effort: 'ultra' })],+ turnId: 'turn-3',+ wake: { kind: 'message', message: { id: 'message-3' } },+ });+ expect(results[0]).toMatchObject({ success: false, error: expect.stringContaining('not configured') });+ expect(results[1]).toMatchObject({ success: false, error: expect.stringContaining('not supported') });+ expect(mocks.addTask).not.toHaveBeenCalled();+ });++ it('allows only the provider default when no concrete models are configured', async () => {+ mocks.providers = [{+ id: 'codex', name: 'Codex', type: 'cli', enabled: true, command: 'codex',+ defaultModel: 'codex-configured-default', models: [],+ }];+ const results = await executePersistentMindTaskRequests({+ taskRequests: [taskRequest({ model: 'invented' }), taskRequest({ model: '', effort: '' })],+ turnId: 'turn-empty-catalog',+ wake: { kind: 'message', message: { id: 'message-empty-catalog' } },+ });+ expect(results[0]).toMatchObject({ success: false, error: expect.stringContaining('not configured') });+ expect(results[1]).toMatchObject({ success: true });+ expect(mocks.addTask).toHaveBeenCalledTimes(1);+ });++ it('reuses the stable task id when a wake is replayed after queueing', async () => {+ mocks.existing = { id: 'sys-mind-existing', status: 'pending', taskType: 'internal' };+ const [result] = await executePersistentMindTaskRequests({+ taskRequests: [taskRequest({ prCompletion: 'merge-on-green' })],+ turnId: 'turn-retry',+ wake: { kind: 'message', message: { id: 'message-stable' } },+ });+ expect(result).toMatchObject({ success: true, duplicate: true, task: { id: 'sys-mind-existing' } });+ expect(mocks.addTask).not.toHaveBeenCalled();+ });+});