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: redesign Chief of Staff configuration
[._.]/ Adam Eivy14331a95b9be
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 5b336adfb7..1e2b484646 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -578,85 +578,6 @@ export const getDomainBudget = (config, domainId) => {};};-// Autonomy level presets for CoS behavior-export const AUTONOMY_LEVELS = [- {- id: 'standby',- label: 'Standby',- color: 'green',- description: 'Only processes user-defined tasks from TASKS.md',- params: {- maxConcurrentAgents: 1,- maxConcurrentAgentsPerProject: 1,- improvementEnabled: false,- proactiveMode: false,- idleReviewEnabled: false,- immediateExecution: false- }- },- {- id: 'assistant',- label: 'Assistant',- color: 'blue',- description: 'Processes user tasks plus improvement tasks on schedule',- params: {- maxConcurrentAgents: 2,- maxConcurrentAgentsPerProject: 1,- improvementEnabled: true,- proactiveMode: false,- idleReviewEnabled: false,- immediateExecution: true- }- },- {- id: 'manager',- label: 'Manager',- color: 'yellow',- description: 'Full task processing with app improvements, no proactive mode',- params: {- maxConcurrentAgents: 3,- maxConcurrentAgentsPerProject: 2,- improvementEnabled: true,- proactiveMode: false,- idleReviewEnabled: true,- immediateExecution: true- }- },- {- id: 'yolo',- label: 'YOLO',- color: 'red',- description: 'Maximum autonomy with proactive task creation',- params: {- maxConcurrentAgents: 5,- maxConcurrentAgentsPerProject: 3,- improvementEnabled: true,- proactiveMode: true,- idleReviewEnabled: true,- immediateExecution: true- }- }-];--// Get params for a specific autonomy level-export const computeAutonomyParams = (levelId) => {- const level = AUTONOMY_LEVELS.find(l => l.id === levelId);- return level ? level.params : null;-};--// Detect which autonomy level matches the current config (or null for custom)-export const detectAutonomyLevel = (config) => {- if (!config) return null;-- for (const level of AUTONOMY_LEVELS) {- const matches = Object.entries(level.params).every(([key, value]) => {- return config[key] === value;- });- if (matches) return level.id;- }- return null; // Custom configuration-};-// Avatar style labels for displayexport const AVATAR_STYLE_LABELS = {svg: 'Digital (SVG)',diff --git a/client/src/components/cos/tabs/ConfigRow.jsx b/client/src/components/cos/tabs/ConfigRow.jsxindex 7ae12d9481..2c6347ed62 100644--- a/client/src/components/cos/tabs/ConfigRow.jsx+++ b/client/src/components/cos/tabs/ConfigRow.jsx@@ -1,38 +1,76 @@import { useId } from 'react';-export default function ConfigRow({ label, value, editing, type, inputValue, onChange, suffix, tooltip }) {- // The row's text already reads as the control's label, so pair the two rather- // than duplicating it into an aria-label — that also makes the text a click- // target for the checkbox, which is otherwise a 16px hit area.+export default function ConfigRow({+ label,+ description,+ value,+ editing,+ type,+ inputValue,+ onChange,+ suffix,+ options = [],+ min,+ max,+ step,+}) {const controlId = useId();+ const isCheckbox = type === 'checkbox';+return (- <div className="flex items-center justify-between p-4" title={tooltip}>- <label htmlFor={controlId} className="text-gray-400 cursor-help">{label}</label>+ <div className="flex min-h-24 flex-col justify-between gap-3 rounded-lg border border-port-border bg-port-card p-3.5">+ <div>+ <label htmlFor={controlId} className="text-sm font-medium text-port-text">{label}</label>+ {description && <p className="mt-1 text-xs leading-relaxed text-port-text-muted">{description}</p>}+ </div>+{editing ? (- <div className="flex items-center gap-2">- {type === 'checkbox' ? (- <input- id={controlId}- type="checkbox"- checked={inputValue}- onChange={e => onChange(e.target.checked)}- className="w-4 h-4 rounded border-port-border bg-port-bg text-port-accent focus:ring-port-accent"- />- ) : (- <>+ isCheckbox ? (+ <label htmlFor={controlId} className="flex cursor-pointer items-center justify-between gap-3">+ <span className={`text-xs font-medium ${inputValue ? 'text-port-success' : 'text-port-text-muted'}`}>+ {inputValue ? 'Enabled' : 'Disabled'}+ </span>+ <span className={`relative inline-flex h-6 w-11 shrink-0 rounded-full transition-colors has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-port-accent has-[:focus-visible]:ring-offset-2 has-[:focus-visible]:ring-offset-port-card ${inputValue ? 'bg-port-accent' : 'bg-port-border'}`}><inputid={controlId}- type="number"- value={inputValue}- onChange={e => onChange(parseInt(e.target.value, 10) || 0)}- className="w-24 px-2 py-1 bg-port-bg border border-port-border rounded text-white text-sm text-right"+ type="checkbox"+ checked={Boolean(inputValue)}+ onChange={(event) => onChange(event.target.checked)}+ className="peer sr-only"/>- {suffix && <span className="text-gray-500 text-sm">{suffix}</span>}- </>- )}- </div>+ <span className={`m-1 h-4 w-4 rounded-full bg-white transition-transform ${inputValue ? 'translate-x-5' : ''}`} />+ </span>+ </label>+ ) : type === 'select' ? (+ <select+ id={controlId}+ value={inputValue}+ onChange={(event) => onChange(event.target.value)}+ className="w-full rounded-md border border-port-border bg-port-bg px-3 py-2 text-sm text-port-text"+ >+ {options.map((option) => (+ <option key={option.value} value={option.value}>{option.label}</option>+ ))}+ </select>+ ) : (+ <div className="flex items-center gap-2">+ <input+ id={controlId}+ type="number"+ min={min}+ max={max}+ step={step}+ value={inputValue}+ onChange={(event) => onChange(Number(event.target.value))}+ className="min-w-0 flex-1 rounded-md border border-port-border bg-port-bg px-3 py-2 text-right text-sm text-port-text"+ />+ {suffix && <span className="shrink-0 text-xs text-port-text-muted">{suffix}</span>}+ </div>+ )) : (- <span className="text-white">{value}</span>+ <span className={`text-sm font-semibold ${isCheckbox && inputValue ? 'text-port-success' : 'text-port-text'}`}>+ {value}+ </span>)}</div>);diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsxindex 848731ef7d..f58f1b8fe1 100644--- a/client/src/components/cos/tabs/ConfigTab.jsx+++ b/client/src/components/cos/tabs/ConfigTab.jsx@@ -1,275 +1,243 @@-import { useState, useEffect, useCallback } from 'react';-import { Settings, Activity, CheckCircle, FileText, X } from 'lucide-react';+import { useCallback, useEffect, useState } from 'react';+import { Link } from 'react-router';+import {+ Activity,+ Brain,+ CheckCircle,+ Database,+ ExternalLink,+ FileText,+ Gauge,+ Palette,+ Server,+ Settings,+ ShieldCheck,+ Sparkles,+ X,+} from 'lucide-react';import toast from '../../ui/Toast';import * as api from '../../../services/api';import PersistentMindProfileControls from '../PersistentMindProfileControls';+import { PersistentMindThoughtStatus } from '../PersistentMindRuntimePanel';import ConfigRow from './ConfigRow';-import { AUTONOMY_LEVELS, detectAutonomyLevel, AVATAR_STYLE_LABELS, AUTONOMY_DOMAINS, DOMAIN_AUTONOMY_MODES, getDomainMode, DOMAIN_BUDGET_FIELDS, getDomainBudget, normalizeBudgetLimit } from '../constants';+import {+ AVATAR_STYLE_LABELS,+ AUTONOMY_DOMAINS,+ DOMAIN_AUTONOMY_MODES,+ DOMAIN_BUDGET_FIELDS,+ getDomainBudget,+ getDomainMode,+ normalizeBudgetLimit,+} from '../constants';import ProviderModelSelector from '../../ProviderModelSelector';import useProviderModels from '../../../hooks/useProviderModels';+import { timeAgo } from '../../../utils/formatters';-// Color classes for autonomy level buttons-const LEVEL_COLORS = {- green: {- base: 'border-port-success/40 bg-port-success/5 text-port-success hover:bg-port-success/10',- active: 'ring-2 ring-port-success border-port-success bg-port-success text-white shadow-sm'+const DOMAIN_MODE_COLORS = {+ off: {+ base: 'border-port-border text-port-text-muted hover:bg-port-border/30',+ active: 'border-port-border bg-port-border text-port-text',},- blue: {- base: 'border-port-accent/30 bg-port-accent/10 text-port-accent hover:bg-port-accent/20',- active: 'ring-2 ring-port-accent border-port-accent bg-port-accent text-white shadow-sm'+ 'dry-run': {+ base: 'border-port-warning/30 text-port-warning hover:bg-port-warning/10',+ active: 'border-port-warning bg-port-warning text-port-bg',},- yellow: {- base: 'border-yellow-500/30 bg-yellow-500/10 text-yellow-400 hover:bg-yellow-500/20',- active: 'ring-2 ring-yellow-500 border-yellow-500 bg-yellow-400 text-yellow-950 shadow-sm'+ execute: {+ base: 'border-port-success/30 text-port-success hover:bg-port-success/10',+ active: 'border-port-success bg-port-success text-white',},- red: {- base: 'border-red-500/30 bg-red-500/10 text-red-400 hover:bg-red-500/20',- active: 'ring-2 ring-red-600 border-red-600 bg-red-500 text-white shadow-sm'- }-};--// Parameter labels for display-const PARAM_LABELS = {- maxConcurrentAgents: 'Agents',- maxConcurrentAgentsPerProject: 'Per Project',- improvementEnabled: 'Improve',- proactiveMode: 'Proactive',- idleReviewEnabled: 'Idle',- immediateExecution: 'Immediate'-};--// Format param value for display-const formatParamValue = (_key, value) => {- if (typeof value === 'boolean') return value ? 'Yes' : 'No';- return String(value);};-// AutonomyControl component-function AutonomyControl({ config, onLevelChange }) {- const [hoveredLevel, setHoveredLevel] = useState(null);- const currentLevel = detectAutonomyLevel(config);- const isCustom = currentLevel === null;+const PRIORITY_OPTIONS = ['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']+ .map((value) => ({ value, label: value[0] + value.slice(1).toLowerCase() }));- const handleLevelClick = (level) => {- // Success toast is owned by onLevelChange so it only fires once the PUT- // resolves — a failed level change must not report success.- onLevelChange(level.params, level.label);- };+const getDefaultFormData = (config, avatarStyle) => ({+ healthCheckIntervalMs: config?.healthCheckIntervalMs ?? 900_000,+ maxConcurrentAgents: config?.maxConcurrentAgents ?? 3,+ maxConcurrentAgentsPerProject: config?.maxConcurrentAgentsPerProject ?? 2,+ maxProcessMemoryMb: config?.maxProcessMemoryMb ?? 2_048,+ maxTotalProcesses: config?.maxTotalProcesses ?? 50,+ startOnBoot: Boolean(config?.alwaysOn || config?.autoStart),+ improvementEnabled: config?.improvementEnabled ?? config?.selfImprovementEnabled ?? true,+ proactiveMode: config?.proactiveMode ?? true,+ idleReviewEnabled: config?.idleReviewEnabled ?? true,+ idleReviewPriority: config?.idleReviewPriority ?? 'MEDIUM',+ autonomousJobsEnabled: config?.autonomousJobsEnabled ?? true,+ autoApproveInvestigations: config?.autoApproveInvestigations ?? false,+ appReviewCooldownMinutes: Math.round((config?.appReviewCooldownMs ?? 1_800_000) / 60_000),+ avatarStyle: config?.avatarStyle || avatarStyle || 'svg',+ dynamicAvatar: config?.dynamicAvatar ?? true,+});- // Get the level to show in preview (hovered or current)- const previewLevel = hoveredLevel- ? AUTONOMY_LEVELS.find(l => l.id === hoveredLevel)- : currentLevel- ? AUTONOMY_LEVELS.find(l => l.id === currentLevel)- : null;+const configPayload = (formData) => ({+ healthCheckIntervalMs: formData.healthCheckIntervalMs,+ maxConcurrentAgents: formData.maxConcurrentAgents,+ maxConcurrentAgentsPerProject: formData.maxConcurrentAgentsPerProject,+ maxProcessMemoryMb: formData.maxProcessMemoryMb,+ maxTotalProcesses: formData.maxTotalProcesses,+ alwaysOn: formData.startOnBoot,+ // Clear the legacy alias so turning boot startup off is not defeated by the+ // server's `alwaysOn || autoStart` compatibility read.+ autoStart: false,+ improvementEnabled: formData.improvementEnabled,+ proactiveMode: formData.proactiveMode,+ idleReviewEnabled: formData.idleReviewEnabled,+ idleReviewPriority: formData.idleReviewPriority,+ autonomousJobsEnabled: formData.autonomousJobsEnabled,+ autoApproveInvestigations: formData.autoApproveInvestigations,+ appReviewCooldownMs: formData.appReviewCooldownMinutes * 60_000,+ avatarStyle: formData.avatarStyle,+ dynamicAvatar: formData.dynamicAvatar,+});+function SectionHeading({ icon: Icon, title, description }) {return (- <div className="bg-port-card border border-port-border rounded-lg p-4 mb-6">- <div className="flex items-center justify-between mb-3">- <h4 className="text-sm font-medium text-gray-400">Autonomy Level</h4>- {isCustom && (- <span className="px-2 py-0.5 text-xs bg-gray-500/20 text-gray-400 rounded border border-gray-500/30">- Custom- </span>- )}- </div>-- {/* Level buttons */}- <div className="grid grid-cols-4 gap-2 mb-3">- {AUTONOMY_LEVELS.map((level) => {- const isActive = currentLevel === level.id;- const colorClasses = LEVEL_COLORS[level.color];-- return (- <button- key={level.id}- onClick={() => handleLevelClick(level)}- onMouseEnter={() => setHoveredLevel(level.id)}- onMouseLeave={() => setHoveredLevel(null)}- className={`- px-3 py-2 text-sm font-medium rounded-lg border transition-all- ${isActive ? colorClasses.active : colorClasses.base}- `}- >- {level.label}- </button>- );- })}+ <div className="flex items-start gap-3">+ <span className="mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-port-accent/10 text-port-accent">+ <Icon size={17} aria-hidden="true" />+ </span>+ <div>+ <h4 className="text-sm font-semibold text-port-text">{title}</h4>+ {description && <p className="mt-0.5 text-xs leading-relaxed text-port-text-muted">{description}</p>}</div>-- {/* Description */}- {previewLevel && (- <p className="text-sm text-gray-500 mb-3">- {previewLevel.description}- </p>- )}-- {/* Parameters preview - always visible */}- {previewLevel && (- <div className="grid grid-cols-4 gap-2 text-xs">- {Object.entries(previewLevel.params).map(([key, value]) => {- const isDifferent = hoveredLevel && config && config[key] !== value;- return (- <div- key={key}- className={`- px-2 py-1 rounded- ${isDifferent- ? 'bg-yellow-500/20 text-yellow-400'- : 'bg-port-bg text-gray-400'- }- `}- >- <span className="font-medium">{PARAM_LABELS[key]}:</span>{' '}- {formatParamValue(key, value)}- </div>- );- })}- </div>- )}</div>);}-// Mode pill colors for the per-domain selector-const DOMAIN_MODE_COLORS = {- off: {- base: 'border-gray-500/30 bg-gray-500/10 text-gray-400 hover:bg-gray-500/20',- active: 'ring-2 ring-gray-500 border-gray-500 bg-gray-500 text-white'- },- 'dry-run': {- base: 'border-yellow-500/30 bg-yellow-500/10 text-yellow-400 hover:bg-yellow-500/20',- active: 'ring-2 ring-yellow-500 border-yellow-500 bg-yellow-400 text-yellow-950'- },- execute: {- base: 'border-port-success/30 bg-port-success/10 text-port-success hover:bg-port-success/20',- active: 'ring-2 ring-port-success border-port-success bg-port-success text-white'- }-};--// Per-domain autonomy guardrails (#711) — independent off | dry-run | execute-// knob per domain. Each change PATCHes only its domain (server merges).-function DomainAutonomyControl({ config, onDomainChange }) {+function DomainAutomationControl({ config, usage, onDomainChange, onBudgetChange }) {return (- <div className="bg-port-card border border-port-border rounded-lg p-4 mb-6">- <h4 className="text-sm font-medium text-gray-400 mb-1">Domain Guardrails</h4>- <p className="text-xs text-gray-600 mb-3">- Fine-grained control over what each domain does automatically. Default is Execute.- </p>- <div className="space-y-3">- {AUTONOMY_DOMAINS.map((domain) => {- const current = getDomainMode(config, domain.id);- return (- <div key={domain.id} className="flex items-center justify-between gap-3">- <div className="min-w-0">- <span className="text-sm text-gray-300">{domain.label}</span>- <p className="text-xs text-gray-600 truncate">{domain.description}</p>- </div>- <div className="flex gap-1 shrink-0">- {DOMAIN_AUTONOMY_MODES.map((mode) => {- const isActive = current === mode.id;- const colors = DOMAIN_MODE_COLORS[mode.id];- return (- <button- key={mode.id}- onClick={() => onDomainChange(domain.id, mode.id, mode.label, domain.label)}- title={mode.description}- className={`px-2.5 py-1 text-xs font-medium rounded-md border transition-all ${isActive ? colors.active : colors.base}`}- >- {mode.label}- </button>- );- })}+ <div className="grid gap-3 md:grid-cols-2">+ {AUTONOMY_DOMAINS.map((domain) => {+ const current = getDomainMode(config, domain.id);+ const budget = getDomainBudget(config, domain.id);+ const domainUsage = usage?.[domain.id] || { actions: 0, ms: 0 };+ const minutesUsed = Math.round((domainUsage.ms || 0) / 60_000);++ return (+ <article key={domain.id} className="rounded-lg border border-port-border bg-port-card p-4">+ <div className="flex items-start justify-between gap-3">+ <div>+ <h5 className="text-sm font-medium text-port-text">{domain.label}</h5>+ <p className="mt-1 text-xs leading-relaxed text-port-text-muted">{domain.description}</p></div>+ <span className="shrink-0 rounded-full bg-port-bg px-2 py-1 text-[11px] text-port-text-muted">+ {domainUsage.actions || 0} actions · {minutesUsed} min today+ </span></div>- );- })}- </div>++ <div className="mt-3 grid grid-cols-3 gap-1" role="group" aria-label={`${domain.label} mode`}>+ {DOMAIN_AUTONOMY_MODES.map((mode) => {+ const active = current === mode.id;+ const colors = DOMAIN_MODE_COLORS[mode.id];+ return (+ <button+ key={mode.id}+ type="button"+ aria-pressed={active}+ title={mode.description}+ onClick={() => onDomainChange(domain.id, mode.id, mode.label, domain.label)}+ className={`rounded-md border px-2 py-1.5 text-xs font-medium transition-colors ${active ? colors.active : colors.base}`}+ >+ {mode.label}+ </button>+ );+ })}+ </div>++ <div className="mt-3 grid grid-cols-2 gap-2 border-t border-port-border pt-3">+ {DOMAIN_BUDGET_FIELDS.map((field) => {+ const inputId = `budget-${domain.id}-${field.id}`;+ const cap = budget[field.id];+ const used = field.usageKey === 'actions'+ ? domainUsage.actions || 0+ : (domainUsage.ms || 0) / 60_000;+ const capped = cap != null && used >= cap;+ return (+ <div key={field.id}>+ <label htmlFor={inputId} className="mb-1 block text-[11px] text-port-text-muted">{field.label}</label>+ <input+ id={inputId}+ key={`${inputId}-${cap ?? ''}`}+ type="number"+ min="0"+ inputMode="numeric"+ defaultValue={cap ?? ''}+ placeholder="Unlimited"+ onBlur={(event) => onBudgetChange(domain.id, field.id, event.target.value, domain.label, field.label)}+ className={`w-full rounded-md border bg-port-bg px-2 py-1.5 text-xs text-port-text ${capped ? 'border-port-warning' : 'border-port-border'}`}+ />+ </div>+ );+ })}+ </div>+ </article>+ );+ })}</div>);}-// Per-domain daily budgets (#711) — caps on autonomous work per domain plus a-// readout of today's usage. Each cap PATCHes only its field on blur (the server-// field-merges). Blank/0 = unlimited. Token/$ caps are intentionally absent —-// CLI subscription providers report no per-run cost to enforce against.-function DomainBudgetControl({ config, usage, onBudgetChange }) {+function PersistentMindStatus({ mind, loaded, error }) {+ const state = mind?.state;+ const model = mind?.profile?.model;+ const supervisor = !loaded+ ? 'Loading…'+ : error ? 'Unavailable'+ : state?.started ? 'Started'+ : state?.enabled ? 'Ready, not started'+ : 'Disabled';+return (- <div className="bg-port-card border border-port-border rounded-lg p-4 mb-6">- <h4 className="text-sm font-medium text-gray-400 mb-1">Domain Budgets</h4>- <p className="text-xs text-gray-600 mb-3">- Daily caps on autonomous work per domain — blank or 0 means unlimited. Once a- cap is reached the domain pauses until the counters reset at midnight (UTC).- </p>- <div className="space-y-3">- {AUTONOMY_DOMAINS.map((domain) => {- const budget = getDomainBudget(config, domain.id);- const u = usage?.[domain.id] || { actions: 0, ms: 0 };- const minutesUsed = Math.round((u.ms || 0) / 60000);- return (- <div key={domain.id} className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2">- <div className="min-w-0">- <span className="text-sm text-gray-300">{domain.label}</span>- <p className="text-xs text-gray-600">- Today: {u.actions || 0} actions · {minutesUsed} min- </p>- </div>- <div className="flex gap-3 shrink-0">- {DOMAIN_BUDGET_FIELDS.map((field) => {- const inputId = `budget-${domain.id}-${field.id}`;- const cap = budget[field.id];- // Compare exact minutes (not the rounded display) so the- // highlight matches server enforcement, which gates on raw ms.- const used = field.usageKey === 'actions' ? (u.actions || 0) : (u.ms || 0) / 60000;- const over = cap != null && used >= cap;- return (- <div key={field.id} className="flex flex-col">- <label htmlFor={inputId} className="text-[10px] text-gray-500 mb-0.5">{field.label}</label>- <input- id={inputId}- // Remount when the persisted cap changes so the uncontrolled- // input reflects external updates without fighting typing.- key={`${inputId}-${cap ?? ''}`}- type="number"- min="0"- inputMode="numeric"- defaultValue={cap ?? ''}- placeholder="∞"- onBlur={(e) => onBudgetChange(domain.id, field.id, e.target.value, domain.label, field.label)}- className={`w-20 px-2 py-1 text-xs rounded-md border bg-port-bg text-gray-200 ${over ? 'border-port-warning text-port-warning' : 'border-port-border'}`}- />- </div>- );- })}- </div>- </div>- );- })}+ <div className="rounded-lg border border-port-border bg-port-card p-4">+ <div className="flex flex-wrap items-center justify-between gap-2">+ <PersistentMindThoughtStatus state={state} model={model} />+ <Link to="/cos/mind" className="inline-flex items-center gap-1 text-xs font-medium text-port-accent hover:underline">+ Open mind <ExternalLink size={13} aria-hidden="true" />+ </Link>+ </div>+ <div className="mt-4 grid grid-cols-3 gap-2">+ <div className="rounded-md bg-port-bg p-2.5">+ <span className="block text-[10px] font-medium uppercase tracking-wide text-port-text-muted">Supervisor</span>+ <span className="mt-1 block text-xs font-semibold text-port-text">{supervisor}</span>+ </div>+ <div className="rounded-md bg-port-bg p-2.5">+ <span className="block text-[10px] font-medium uppercase tracking-wide text-port-text-muted">Queued</span>+ <span aria-label="Queued persistent mind messages" className="mt-1 block text-xs font-semibold text-port-text">{loaded && !error ? state?.queuedMessageCount || 0 : '—'}</span>+ </div>+ <div className="rounded-md bg-port-bg p-2.5">+ <span className="block text-[10px] font-medium uppercase tracking-wide text-port-text-muted">Last turn</span>+ <span className="mt-1 block text-xs font-semibold text-port-text">{state?.lastCompletedAt ? timeAgo(state.lastCompletedAt) : 'None yet'}</span>+ </div></div>+ {(error || state?.lastError || state?.pauseReason) && (+ <p className="mt-3 rounded-md border border-port-warning/30 bg-port-warning/10 px-3 py-2 text-xs text-port-warning">+ {error || state.lastError || state.pauseReason}+ </p>+ )}+ <p className="mt-3 text-xs leading-relaxed text-port-text-muted">+ Enabling a profile only configures its reasoning lane. Starting, pausing, conversation, context, and task access remain on the Persistent Mind page.+ </p></div>);}-const getDefaultFormData = (config, avatarStyle) => ({- healthCheckIntervalMs: config?.healthCheckIntervalMs || 900000,- maxConcurrentAgents: config?.maxConcurrentAgents || 3,- maxConcurrentAgentsPerProject: config?.maxConcurrentAgentsPerProject || 2,- maxProcessMemoryMb: config?.maxProcessMemoryMb || 2048,- autoStart: config?.autoStart || false,- improvementEnabled: config?.improvementEnabled ?? config?.selfImprovementEnabled ?? true,- proactiveMode: config?.proactiveMode ?? true,- idleReviewEnabled: config?.idleReviewEnabled ?? true,- immediateExecution: config?.immediateExecution ?? true,- autoApproveInvestigations: config?.autoApproveInvestigations ?? false,- avatarStyle: config?.avatarStyle || avatarStyle || 'svg'-});-export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle }) {- const { providers, availableModels, setSelectedProviderId: setProviderHook, setSelectedModel: setModelHook, selectedProviderId: hookProviderId, selectedModel: hookModel } = useProviderModels();+ const {+ providers,+ availableModels,+ setSelectedProviderId: setProviderHook,+ setSelectedModel: setModelHook,+ selectedProviderId: hookProviderId,+ selectedModel: hookModel,+ } = useProviderModels();const [embeddingProviderId, setEmbeddingProviderId] = useState(config?.embeddingProviderId || 'lmstudio');const [embeddingModel, setEmbeddingModel] = useState(config?.embeddingModel || '');+ const [editing, setEditing] = useState(false);+ const [saving, setSaving] = useState(false);+ const [formData, setFormData] = useState(() => getDefaultFormData(config, avatarStyle));+ const [budgetUsage, setBudgetUsage] = useState({});+ const [mindStatus, setMindStatus] = useState({ data: null, loaded: false, error: null });- // Sync local state when config prop updatesuseEffect(() => {if (config?.embeddingProviderId) {setEmbeddingProviderId(config.embeddingProviderId);@@ -281,370 +249,268 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle })}}, [config?.embeddingProviderId, config?.embeddingModel, setProviderHook, setModelHook]);- const [editing, setEditing] = useState(false);- const [formData, setFormData] = useState(() => getDefaultFormData(config, avatarStyle));-useEffect(() => {- if (!editing) {- setFormData(prev => ({- ...prev,- ...getDefaultFormData(config, avatarStyle)- }));- }+ if (!editing) setFormData(getDefaultFormData(config, avatarStyle));}, [config, avatarStyle, editing]);+ const refreshBudgetUsage = useCallback(() => (+ api.getCosBudgetUsage({ silent: true })+ .then((response) => setBudgetUsage(response?.usage || {}))+ .catch(() => {})+ ), []);++ const refreshMindStatus = useCallback(() => (+ api.getPersistentMind({ limit: 1 }, { silent: true })+ .then((data) => setMindStatus({ data, loaded: true, error: null }))+ .catch((error) => setMindStatus((current) => ({+ ...current,+ loaded: true,+ error: error?.message || 'Persistent mind status is unavailable',+ })))+ ), []);++ useEffect(() => { void refreshBudgetUsage(); }, [refreshBudgetUsage]);+ useEffect(() => {+ void refreshMindStatus();+ const interval = setInterval(() => { void refreshMindStatus(); }, 15_000);+ return () => clearInterval(interval);+ }, [refreshMindStatus]);+const handleCancel = () => {setFormData(getDefaultFormData(config, avatarStyle));setEditing(false);};- const handleLevelChange = async (params, label) => {- // Optimistically reflect the new params via a functional update. Success toast- // / refresh only fire after the request resolves.- const revertKeys = Object.fromEntries(Object.keys(params).map(k => [k, formData[k]]));- setFormData(prev => ({ ...prev, ...params }));- try {- await api.updateCosConfig(params, { silent: true });- if (label) toast.success(`Autonomy level set to ${label}`);- onUpdate();- } catch (err) {- // Roll back only keys still holding THIS request's optimistic value — a newer- // successful level pick (or edit) to the same key must win, so a late-failing- // request can't clobber it with the stale value it captured at click time.- setFormData(prev => {- const next = { ...prev };- for (const key of Object.keys(params)) {- if (prev[key] === params[key]) next[key] = revertKeys[key];- }- return next;- });- toast.error(err.message);- }+ const handleSave = () => {+ setSaving(true);+ return api.updateCosConfig(configPayload(formData), { silent: true })+ .then(() => {+ toast.success('Configuration updated');+ setEditing(false);+ onUpdate();+ })+ .catch((error) => toast.error(error.message))+ .finally(() => setSaving(false));};- // Today's per-domain usage for the Domain Budgets readout (#711).- const [budgetUsage, setBudgetUsage] = useState({});- const refreshBudgetUsage = useCallback(() => {- api.getCosBudgetUsage({ silent: true })- .then((res) => setBudgetUsage(res?.usage || {}))- .catch(() => {});- }, []);- useEffect(() => { refreshBudgetUsage(); }, [refreshBudgetUsage]);-- const handleDomainChange = async (domainId, mode, modeLabel, domainLabel) => {- // Custom error toast ⇒ pass { silent: true } so the helper doesn't also- // toast; and only show success / refresh AFTER the PUT actually resolves.- try {- await api.updateCosConfig({ domainAutonomy: { [domainId]: mode } }, { silent: true });- toast.success(`${domainLabel} autonomy set to ${modeLabel}`);- onUpdate();- } catch (err) {- toast.error(err.message);- }- };+ const handleDomainChange = (domainId, mode, modeLabel, domainLabel) => (+ api.updateCosConfig({ domainAutonomy: { [domainId]: mode } }, { silent: true })+ .then(() => {+ toast.success(`${domainLabel} autonomy set to ${modeLabel}`);+ onUpdate();+ void refreshMindStatus();+ })+ .catch((error) => toast.error(error.message))+ );- const handleBudgetChange = async (domainId, field, rawValue, domainLabel, fieldLabel) => {- // Empty / 0 / NaN / negative → null (unlimited), mirroring the server.+ const handleBudgetChange = (domainId, field, rawValue, domainLabel, fieldLabel) => {const value = normalizeBudgetLimit(rawValue);const current = getDomainBudget(config, domainId)[field];- if ((current ?? null) === value) return; // no-op (e.g. blur without edit)- try {- await api.updateCosConfig({ domainBudgets: { [domainId]: { [field]: value } } }, { silent: true });- toast.success(`${domainLabel} ${fieldLabel} ${value == null ? 'set to unlimited' : `capped at ${value}`}`);- onUpdate();- refreshBudgetUsage();- } catch (err) {- toast.error(err.message);- }- };-- const handleSave = async () => {- // Keep the user in edit mode on failure — only close the editor and toast- // success once the config PUT actually resolves.- try {- await api.updateCosConfig(formData, { silent: true });- toast.success('Configuration updated');- setEditing(false);- onUpdate();- } catch (err) {- toast.error(err.message);- }+ if ((current ?? null) === value) return Promise.resolve();+ return api.updateCosConfig({ domainBudgets: { [domainId]: { [field]: value } } }, { silent: true })+ .then(() => {+ toast.success(`${domainLabel} ${fieldLabel} ${value == null ? 'set to unlimited' : `capped at ${value}`}`);+ onUpdate();+ void refreshBudgetUsage();+ })+ .catch((error) => toast.error(error.message));};return (- <div className="space-y-6">- <div className="flex items-center justify-between">- <h3 className="text-lg font-semibold text-white">Configuration</h3>- <div className="flex gap-2">+ <div className="mx-auto max-w-6xl space-y-7 pb-6">+ <header className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">+ <div>+ <h3 className="text-lg font-semibold text-port-text">Chief of Staff settings</h3>+ <p className="mt-1 max-w-2xl text-sm text-port-text-muted">+ Configure capacity, automatic work, the persistent mind, and supporting services. Domain guardrails are the authoritative autonomy controls.+ </p>+ </div>+ <div className="flex flex-wrap gap-2"><button+ type="button"onClick={onEvaluate}- className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-accent/20 hover:bg-port-accent/30 text-port-accent rounded-lg transition-colors"- title="Immediately check for pending tasks and spawn agents to work on them (normally runs on the evaluation interval)"+ className="inline-flex items-center gap-2 rounded-lg bg-port-accent/15 px-3 py-2 text-sm text-port-accent transition-colors hover:bg-port-accent/25"+ title="Immediately check for pending tasks and spawn eligible agents">- <Activity size={14} />- Force Evaluate+ <Activity size={14} /> Force Evaluate</button>{!editing ? (<button+ type="button"onClick={() => setEditing(true)}- className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-white rounded-lg transition-colors"+ className="inline-flex items-center gap-2 rounded-lg bg-port-border px-3 py-2 text-sm text-port-text transition-colors hover:bg-port-border/80">- <Settings size={14} />- Edit+ <Settings size={14} /> Edit settings</button>) : (<><button+ type="button"onClick={handleCancel}- className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-border hover:bg-port-border/80 text-gray-300 rounded-lg transition-colors"+ disabled={saving}+ className="inline-flex items-center gap-2 rounded-lg bg-port-border px-3 py-2 text-sm text-port-text-muted disabled:opacity-50">- <X size={14} />- Cancel+ <X size={14} /> Cancel</button><button+ type="button"onClick={handleSave}- className="flex items-center gap-2 px-3 py-1.5 text-sm bg-port-success/20 hover:bg-port-success/30 text-port-success rounded-lg transition-colors"+ disabled={saving}+ className="inline-flex items-center gap-2 rounded-lg bg-port-success/15 px-3 py-2 text-sm text-port-success transition-colors hover:bg-port-success/25 disabled:opacity-50">- <CheckCircle size={14} />- Save+ <CheckCircle size={14} /> {saving ? 'Saving…' : 'Save settings'}</button></>)}</div>- </div>-- {/* Autonomy Level Control */}- <AutonomyControl config={config} onLevelChange={handleLevelChange} />-- {/* Per-domain Autonomy Guardrails */}- <DomainAutonomyControl config={config} onDomainChange={handleDomainChange} />-- <DomainBudgetControl config={config} usage={budgetUsage} onBudgetChange={handleBudgetChange} />-- <div>- <h4 className="text-sm font-medium text-gray-400 mb-2">Persistent Mind</h4>- <div className="bg-port-card border border-port-border rounded-lg p-4">- <PersistentMindProfileControls profile={config?.persistentMindProfile} onSaved={onUpdate} />+ </header>++ <section className="space-y-3" aria-labelledby="persistent-mind-config-heading">+ <div id="persistent-mind-config-heading">+ <SectionHeading+ icon={Brain}+ title="Persistent Mind"+ description="Live supervisor status beside the pinned provider profile used for every wake."+ /></div>- </div>-- <div className="bg-port-card border border-port-border rounded-lg divide-y divide-port-border">- <ConfigRow- label="Health Check Interval"- value={`${formData.healthCheckIntervalMs / 60000}m`}- editing={editing}- type="number"- inputValue={formData.healthCheckIntervalMs / 60000}- onChange={v => setFormData(f => ({ ...f, healthCheckIntervalMs: v * 60000 }))}- suffix="minutes"- tooltip="How often CoS runs system health checks (PM2 processes, memory usage, etc.)"- />- <ConfigRow- label="Max Concurrent Agents"- value={formData.maxConcurrentAgents}- editing={editing}- type="number"- inputValue={formData.maxConcurrentAgents}- onChange={v => setFormData(f => ({ ...f, maxConcurrentAgents: v }))}- tooltip="Maximum total number of AI agents that can run simultaneously across all projects"- />- <ConfigRow- label="Max Agents Per Project"- value={formData.maxConcurrentAgentsPerProject}- editing={editing}- type="number"- inputValue={formData.maxConcurrentAgentsPerProject}- onChange={v => setFormData(f => ({ ...f, maxConcurrentAgentsPerProject: v }))}- tooltip="Maximum agents per individual project — prevents one project from using all available slots"- />- <ConfigRow- label="Max Process Memory"- value={`${formData.maxProcessMemoryMb} MB`}- editing={editing}- type="number"- inputValue={formData.maxProcessMemoryMb}- onChange={v => setFormData(f => ({ ...f, maxProcessMemoryMb: v }))}- suffix="MB"- tooltip="Memory threshold for health alerts - processes exceeding this will be flagged. The local model servers (llama-server, MTPLX) are exempt: their memory is the model they loaded"- />- <ConfigRow- label="Auto Start"- value={formData.autoStart ? 'Enabled' : 'Disabled'}- editing={editing}- type="checkbox"- inputValue={formData.autoStart}- onChange={v => setFormData(f => ({ ...f, autoStart: v }))}- tooltip="Automatically start the CoS daemon when the server starts"- />- <ConfigRow- label="Improvement Tasks"- value={formData.improvementEnabled ? 'Enabled' : 'Disabled'}- editing={editing}- type="checkbox"- inputValue={formData.improvementEnabled}- onChange={v => setFormData(f => ({ ...f, improvementEnabled: v }))}- tooltip="Allow CoS to run improvement tasks for PortOS and managed apps (security audits, code quality, etc.)"- />- <ConfigRow- label="Proactive Mode"- value={formData.proactiveMode ? 'Enabled' : 'Disabled'}- editing={editing}- type="checkbox"- inputValue={formData.proactiveMode}- onChange={v => setFormData(f => ({ ...f, proactiveMode: v }))}- tooltip="Proactively find and create tasks based on mission goals"- />- <ConfigRow- label="Idle Review"- value={formData.idleReviewEnabled ? 'Enabled' : 'Disabled'}- editing={editing}- type="checkbox"- inputValue={formData.idleReviewEnabled}- onChange={v => setFormData(f => ({ ...f, idleReviewEnabled: v }))}- tooltip="Review apps for improvements when no user tasks are pending"- />- <ConfigRow- label="Immediate Execution"- value={formData.immediateExecution ? 'Enabled' : 'Disabled'}- editing={editing}- type="checkbox"- inputValue={formData.immediateExecution}- onChange={v => setFormData(f => ({ ...f, immediateExecution: v }))}- tooltip="Execute new tasks immediately instead of waiting for evaluation interval"- />- <ConfigRow- label="Auto-approve Investigations"- value={formData.autoApproveInvestigations ? 'Enabled' : 'Disabled'}- editing={editing}- type="checkbox"- inputValue={formData.autoApproveInvestigations}- onChange={v => setFormData(f => ({ ...f, autoApproveInvestigations: v }))}- tooltip="Automatically process system failure investigations, including investigations held because a failure is looping or part of a storm"- />- </div>-- {/* Avatar Style */}- <div>- <h4 className="text-sm font-medium text-gray-400 mb-2">Appearance</h4>- <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-4">- <div- className="flex items-center justify-between"- title="Choose the default visual style for the CoS avatar in the sidebar panel"- >- <span className="text-gray-400 cursor-help">Default Avatar Style</span>- <select- aria-label="Default Avatar Style"- value={formData.avatarStyle}- disabled={!editing}- onChange={(e) => {- const style = e.target.value;- setFormData(prev => ({ ...prev, avatarStyle: style }));- }}- className="bg-port-bg border border-port-border rounded px-3 py-1.5 text-white text-sm disabled:opacity-50 disabled:cursor-not-allowed"- >- {Object.entries(AVATAR_STYLE_LABELS).map(([value, label]) => (- <option key={value} value={value}>{label}</option>- ))}- </select>- </div>- <div- className="flex items-center justify-between"- title="When enabled, the avatar style changes automatically based on the active task type, provider, or priority"- >- <div>- <span className="text-gray-400 cursor-help">Dynamic Avatar</span>- <p className="text-xs text-gray-600 mt-0.5">Auto-switch style based on task type, provider, or priority</p>- </div>- <button- type="button"- role="switch"- aria-checked={!!config?.dynamicAvatar}- aria-label="Dynamic Avatar"- onClick={async () => {- const newVal = !config?.dynamicAvatar;- await api.updateCosConfig({ dynamicAvatar: newVal });- toast.success(`Dynamic avatar ${newVal ? 'enabled' : 'disabled'}`);+ <div className="grid gap-3 lg:grid-cols-[minmax(0,0.9fr)_minmax(0,1.1fr)]">+ <PersistentMindStatus mind={mindStatus.data} loaded={mindStatus.loaded} error={mindStatus.error} />+ <div className="rounded-lg border border-port-border bg-port-card p-4">+ <PersistentMindProfileControls+ profile={config?.persistentMindProfile}+ onSaved={() => {onUpdate();+ void refreshMindStatus();}}- className={`relative inline-flex h-6 w-11 items-center rounded-full transition-colors ${- config?.dynamicAvatar ? 'bg-port-accent' : 'bg-port-border'- }`}- >- <span- className={`inline-block h-4 w-4 transform rounded-full bg-white transition-transform ${- config?.dynamicAvatar ? 'translate-x-6' : 'translate-x-1'- }`}- />- </button>+ /></div></div>- </div>+ </section>++ <section className="space-y-3" aria-labelledby="automation-heading">+ <div id="automation-heading">+ <SectionHeading+ icon={ShieldCheck}+ title="Automation guardrails"+ description="Choose what each domain may do automatically and cap its daily action or runtime allowance. Blank budgets are unlimited."+ />+ </div>+ <DomainAutomationControl+ config={config}+ usage={budgetUsage}+ onDomainChange={handleDomainChange}+ onBudgetChange={handleBudgetChange}+ />+ </section>- {/* Memory Embeddings */}- <div>- <h4 className="text-sm font-medium text-gray-400 mb-2">Memory Embeddings</h4>- <div className="bg-port-card border border-port-border rounded-lg p-4">+ <section className="space-y-3" aria-labelledby="capacity-heading">+ <div id="capacity-heading">+ <SectionHeading icon={Gauge} title="Capacity and health" description="Concurrency and health thresholds for the local CoS runtime." />+ </div>+ <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">+ <ConfigRow label="Concurrent agents" description="Maximum active agents across all projects." value={formData.maxConcurrentAgents} editing={editing} type="number" inputValue={formData.maxConcurrentAgents} min={1} onChange={(value) => setFormData((current) => ({ ...current, maxConcurrentAgents: value }))} />+ <ConfigRow label="Agents per project" description="Prevents one project from consuming every agent slot." value={formData.maxConcurrentAgentsPerProject} editing={editing} type="number" inputValue={formData.maxConcurrentAgentsPerProject} min={1} onChange={(value) => setFormData((current) => ({ ...current, maxConcurrentAgentsPerProject: value }))} />+ <ConfigRow label="Process memory alert" description="Flags non-model processes above this memory use." value={`${formData.maxProcessMemoryMb} MB`} editing={editing} type="number" inputValue={formData.maxProcessMemoryMb} min={128} suffix="MB" onChange={(value) => setFormData((current) => ({ ...current, maxProcessMemoryMb: value }))} />+ <ConfigRow label="Process count alert" description="Flags an unexpectedly large PM2 process fleet." value={formData.maxTotalProcesses} editing={editing} type="number" inputValue={formData.maxTotalProcesses} min={1} onChange={(value) => setFormData((current) => ({ ...current, maxTotalProcesses: value }))} />+ <ConfigRow label="Health check interval" description="How often CoS checks processes and memory." value={`${formData.healthCheckIntervalMs / 60_000} min`} editing={editing} type="number" inputValue={formData.healthCheckIntervalMs / 60_000} min={1} suffix="minutes" onChange={(value) => setFormData((current) => ({ ...current, healthCheckIntervalMs: value * 60_000 }))} />+ <ConfigRow label="Start on server boot" description="Start the CoS daemon when PortOS starts." value={formData.startOnBoot ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.startOnBoot} onChange={(value) => setFormData((current) => ({ ...current, startOnBoot: value }))} />+ </div>+ </section>++ <section className="space-y-3" aria-labelledby="work-heading">+ <div id="work-heading">+ <SectionHeading icon={Sparkles} title="Work generation and scheduling" description="Independent switches for how eligible work enters and moves through the queue." />+ </div>+ <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">+ <ConfigRow label="Improvement tasks" description="Allow improvement work for PortOS and managed apps." value={formData.improvementEnabled ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.improvementEnabled} onChange={(value) => setFormData((current) => ({ ...current, improvementEnabled: value }))} />+ <ConfigRow label="Proactive discovery" description="Create tasks from mission goals when capacity is available." value={formData.proactiveMode ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.proactiveMode} onChange={(value) => setFormData((current) => ({ ...current, proactiveMode: value }))} />+ <ConfigRow label="Idle app review" description="Look for app improvements when user work is idle." value={formData.idleReviewEnabled ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.idleReviewEnabled} onChange={(value) => setFormData((current) => ({ ...current, idleReviewEnabled: value }))} />+ <ConfigRow label="Idle review priority" description="Priority assigned to newly generated idle-review tasks." value={PRIORITY_OPTIONS.find((option) => option.value === formData.idleReviewPriority)?.label} editing={editing} type="select" inputValue={formData.idleReviewPriority} options={PRIORITY_OPTIONS} onChange={(value) => setFormData((current) => ({ ...current, idleReviewPriority: value }))} />+ <ConfigRow label="Scheduled agent jobs" description="Enable the global scheduler in addition to each job's own switch." value={formData.autonomousJobsEnabled ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.autonomousJobsEnabled} onChange={(value) => setFormData((current) => ({ ...current, autonomousJobsEnabled: value }))} />+ <ConfigRow label="App review cooldown" description="Minimum time before CoS reviews the same app again." value={`${formData.appReviewCooldownMinutes} min`} editing={editing} type="number" inputValue={formData.appReviewCooldownMinutes} min={0} suffix="minutes" onChange={(value) => setFormData((current) => ({ ...current, appReviewCooldownMinutes: value }))} />+ <ConfigRow label="Auto-approve investigations" description="Admit failure-loop and failure-storm investigations unattended." value={formData.autoApproveInvestigations ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.autoApproveInvestigations} onChange={(value) => setFormData((current) => ({ ...current, autoApproveInvestigations: value }))} />+ </div>+ </section>++ <section className="space-y-3" aria-labelledby="appearance-heading">+ <div id="appearance-heading">+ <SectionHeading icon={Palette} title="Appearance" description="Set the default avatar and whether active work may choose a matching style." />+ </div>+ <div className="grid gap-3 sm:grid-cols-2">+ <ConfigRow label="Default avatar" description="Visual style used by the CoS panel." value={AVATAR_STYLE_LABELS[formData.avatarStyle] || formData.avatarStyle} editing={editing} type="select" inputValue={formData.avatarStyle} options={Object.entries(AVATAR_STYLE_LABELS).map(([value, label]) => ({ value, label }))} onChange={(value) => setFormData((current) => ({ ...current, avatarStyle: value }))} />+ <ConfigRow label="Dynamic avatar" description="Switch style based on task type, provider, or priority." value={formData.dynamicAvatar ? 'Enabled' : 'Disabled'} editing={editing} type="checkbox" inputValue={formData.dynamicAvatar} onChange={(value) => setFormData((current) => ({ ...current, dynamicAvatar: value }))} />+ </div>+ </section>++ <section className="space-y-3" aria-labelledby="embeddings-heading">+ <div id="embeddings-heading">+ <SectionHeading icon={Database} title="Memory embeddings" description="Provider and model used to index CoS memory for semantic retrieval." />+ </div>+ <div className="rounded-lg border border-port-border bg-port-card p-4"><ProviderModelSelectorproviders={providers}- selectedProviderId={- providers?.some((p) => p.id === embeddingProviderId)- ? embeddingProviderId- : providers?.some((p) => p.id === hookProviderId)- ? hookProviderId- : ''- }+ selectedProviderId={providers?.some((provider) => provider.id === embeddingProviderId)+ ? embeddingProviderId+ : providers?.some((provider) => provider.id === hookProviderId) ? hookProviderId : ''}selectedModel={embeddingModel || hookModel}availableModels={availableModels}- onProviderChange={async (id) => {+ onProviderChange={(id) => {setEmbeddingProviderId(id);setProviderHook(id);setEmbeddingModel('');- await api.updateCosConfig({ embeddingProviderId: id, embeddingModel: '' });- toast.success('Embedding provider updated');- onUpdate();+ return api.updateCosConfig({ embeddingProviderId: id, embeddingModel: '' })+ .then(() => {+ toast.success('Embedding provider updated');+ onUpdate();+ });}}- onModelChange={async (m) => {- setEmbeddingModel(m);- setModelHook(m);- await api.updateCosConfig({ embeddingModel: m });- toast.success('Embedding model updated');- onUpdate();+ onModelChange={(model) => {+ setEmbeddingModel(model);+ setModelHook(model);+ return api.updateCosConfig({ embeddingModel: model })+ .then(() => {+ toast.success('Embedding model updated');+ onUpdate();+ });}}- label="Embedding Provider"+ label="Embedding provider"/></div>- </div>+ </section>- {/* MCP Servers */}- <div>- <h4 className="text-sm font-medium text-gray-400 mb-2">MCP Servers</h4>- <div className="bg-port-card border border-port-border rounded-lg p-4">- {config?.mcpServers?.map((mcp, idx) => (- <div key={idx} className="flex items-center gap-2 text-sm">- <span className="text-port-accent font-mono">{mcp.name}</span>- <span className="text-gray-500">:</span>- <span className="text-gray-400">{mcp.command} {mcp.args?.join(' ')}</span>- </div>- )) || <span className="text-gray-500">No MCP servers configured</span>}+ <section className="space-y-3" aria-labelledby="advanced-heading">+ <div id="advanced-heading">+ <SectionHeading icon={Server} title="Advanced" description="Read-only runtime wiring managed by the installation and repository." /></div>- </div>-- {/* Task Files */}- <div>- <h4 className="text-sm font-medium text-gray-400 mb-2">Task Files</h4>- <div className="bg-port-card border border-port-border rounded-lg p-4 space-y-2">- <div className="flex items-center gap-2 text-sm">- <FileText size={14} className="text-gray-500" />- <span className="text-gray-400">User Tasks:</span>- <span className="text-white font-mono">{config?.userTasksFile || 'TASKS.md'}</span>+ <div className="grid gap-3 md:grid-cols-2">+ <div className="rounded-lg border border-port-border bg-port-card p-4">+ <h5 className="text-sm font-medium text-port-text">MCP servers</h5>+ <div className="mt-3 space-y-2">+ {config?.mcpServers?.length ? config.mcpServers.map((mcp) => (+ <div key={mcp.name} className="rounded-md bg-port-bg px-3 py-2 text-xs">+ <span className="font-mono font-medium text-port-accent">{mcp.name}</span>+ <span className="ml-2 break-all text-port-text-muted">{mcp.command} {mcp.args?.join(' ')}</span>+ </div>+ )) : <span className="text-xs text-port-text-muted">No MCP servers configured</span>}+ </div></div>- <div className="flex items-center gap-2 text-sm">- <FileText size={14} className="text-gray-500" />- <span className="text-gray-400">System Tasks:</span>- <span className="text-white font-mono">{config?.cosTasksFile || 'COS-TASKS.md'}</span>+ <div className="rounded-lg border border-port-border bg-port-card p-4">+ <h5 className="text-sm font-medium text-port-text">Task files</h5>+ <div className="mt-3 space-y-2 text-xs">+ <div className="flex items-center gap-2 rounded-md bg-port-bg px-3 py-2">+ <FileText size={14} className="text-port-text-muted" />+ <span className="text-port-text-muted">User</span>+ <span className="ml-auto font-mono text-port-text">{config?.userTasksFile || 'TASKS.md'}</span>+ </div>+ <div className="flex items-center gap-2 rounded-md bg-port-bg px-3 py-2">+ <FileText size={14} className="text-port-text-muted" />+ <span className="text-port-text-muted">System</span>+ <span className="ml-auto font-mono text-port-text">{config?.cosTasksFile || 'COS-TASKS.md'}</span>+ </div>+ </div></div></div>- </div>+ </section></div>);}diff --git a/client/src/components/cos/tabs/ConfigTab.test.jsx b/client/src/components/cos/tabs/ConfigTab.test.jsxindex 235214f309..e369baaee6 100644--- a/client/src/components/cos/tabs/ConfigTab.test.jsx+++ b/client/src/components/cos/tabs/ConfigTab.test.jsx@@ -1,5 +1,6 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { MemoryRouter } from 'react-router';// Regression coverage for #2519 — failed CoS config calls must NOT flash a// success toast, must keep the user in edit mode, and must revert optimistic@@ -7,6 +8,7 @@ import { fireEvent, render, screen, waitFor, within } from '@testing-library/reaconst api = vi.hoisted(() => ({updateCosConfig: vi.fn(),getCosBudgetUsage: vi.fn(),+ getPersistentMind: vi.fn(),}));const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn() }));const providerHook = vi.hoisted(() => ({@@ -22,7 +24,7 @@ vi.mock('../../../services/api', () => api);vi.mock('../../../services/apiLocalLlm', () => localLlm);vi.mock('../../ui/Toast', () => ({ default: toast }));// The provider/model selector hook fetches providers over the network — stub it-// so the test exercises only the config-save / level-change handlers.+// so the test exercises only the config screen's own behavior.vi.mock('../../../hooks/useProviderModels', () => ({default: () => ({providers: [{ id: 'codex', name: 'Codex', models: ['gpt-5'], defaultModel: 'gpt-5' }],@@ -41,25 +43,50 @@ const config = {maxConcurrentAgents: 3,maxConcurrentAgentsPerProject: 2,maxProcessMemoryMb: 2048,+ maxTotalProcesses: 50,+ alwaysOn: false,autoStart: false,improvementEnabled: true,proactiveMode: true,idleReviewEnabled: true,- immediateExecution: true,};+const renderConfig = (props = {}) => render(+ <MemoryRouter>+ <ConfigTab+ config={config}+ onUpdate={vi.fn()}+ onEvaluate={vi.fn()}+ avatarStyle="svg"+ {...props}+ />+ </MemoryRouter>,+);+beforeEach(() => {vi.clearAllMocks();api.getCosBudgetUsage.mockResolvedValue({ usage: {} });localLlm.getLocalLlmStatus.mockResolvedValue({ ollama: { models: [] }, lmstudio: { models: [] } });localLlm.getToolUseModels.mockResolvedValue({ models: [] });+ api.getPersistentMind.mockResolvedValue({+ state: {+ enabled: true,+ started: true,+ status: 'waiting',+ queuedMessageCount: 2,+ lastCompletedAt: null,+ lastError: null,+ pauseReason: null,+ },+ profile: { enabled: true, providerId: 'codex', model: 'gpt-5' },+ });});describe('ConfigTab handleSave', () => {it('keeps the editor open and does not toast success when the save fails', async () => {api.updateCosConfig.mockRejectedValue(new Error('network down'));const onUpdate = vi.fn();- render(<ConfigTab config={config} onUpdate={onUpdate} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);+ renderConfig({ onUpdate });fireEvent.click(screen.getByRole('button', { name: /Edit/i }));fireEvent.click(screen.getByRole('button', { name: /Save/i }));@@ -74,7 +101,7 @@ describe('ConfigTab handleSave', () => {it('closes the editor and toasts success when the save resolves', async () => {api.updateCosConfig.mockResolvedValue({ success: true });const onUpdate = vi.fn();- render(<ConfigTab config={config} onUpdate={onUpdate} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);+ renderConfig({ onUpdate });fireEvent.click(screen.getByRole('button', { name: /Edit/i }));fireEvent.click(screen.getByRole('button', { name: /Save/i }));@@ -86,12 +113,33 @@ describe('ConfigTab handleSave', () => {// Editor closed — the Edit button is back.expect(screen.getByRole('button', { name: /Edit/i })).toBeInTheDocument();});++ it('saves the newly exposed scheduler and health controls together', async () => {+ api.updateCosConfig.mockResolvedValue({ success: true });+ renderConfig();+ await screen.findByText('Waiting for the next wake');++ fireEvent.click(screen.getByRole('button', { name: /Edit settings/i }));+ fireEvent.change(screen.getByRole('spinbutton', { name: 'Process count alert' }), { target: { value: '64' } });+ fireEvent.change(screen.getByRole('spinbutton', { name: 'App review cooldown' }), { target: { value: '45' } });+ fireEvent.click(screen.getByRole('checkbox', { name: /Scheduled agent jobs/i }));+ fireEvent.click(screen.getByRole('button', { name: /Save settings/i }));++ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(+ expect.objectContaining({+ maxTotalProcesses: 64,+ appReviewCooldownMs: 2_700_000,+ autonomousJobsEnabled: false,+ }),+ { silent: true },+ ));+ });});describe('persistent mind profile', () => {it('starts disabled and saving its toggle sends a default-safe profile without starting a mind', async () => {api.updateCosConfig.mockResolvedValue({ success: true });- render(<ConfigTab config={config} onUpdate={vi.fn()} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);+ renderConfig();const toggle = screen.getByRole('checkbox', { name: 'Enable persistent mind profile' });expect(toggle).not.toBeChecked();@@ -108,21 +156,21 @@ describe('persistent mind profile', () => {});describe('Default Avatar Style dropdown', () => {- it('disables default avatar style dropdown when not editing', async () => {- render(<ConfigTab config={{ ...config, avatarStyle: 'svg' }} onUpdate={vi.fn()} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);- await waitFor(() => expect(screen.getByRole('combobox', { name: 'Default Avatar Style' })).toBeDisabled());+ it('shows the saved avatar style as text when not editing', async () => {+ renderConfig({ config: { ...config, avatarStyle: 'svg' } });+ await screen.findByText('Waiting for the next wake');- const select = screen.getByRole('combobox', { name: 'Default Avatar Style' });- expect(select).toHaveValue('svg');+ expect(screen.queryByRole('combobox', { name: 'Default avatar' })).not.toBeInTheDocument();+ expect(screen.getByText('Digital (SVG)')).toBeInTheDocument();});it('stages dropdown selection locally without triggering immediate save call', async () => {- render(<ConfigTab config={{ ...config, avatarStyle: 'svg' }} onUpdate={vi.fn()} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);- await waitFor(() => expect(screen.getByRole('combobox', { name: 'Default Avatar Style' })).toBeDisabled());+ renderConfig({ config: { ...config, avatarStyle: 'svg' } });+ await screen.findByText('Waiting for the next wake');fireEvent.click(screen.getByRole('button', { name: /Edit/i }));- const select = screen.getByRole('combobox', { name: 'Default Avatar Style' });+ const select = screen.getByRole('combobox', { name: 'Default avatar' });expect(select).toBeEnabled();fireEvent.change(select, { target: { value: 'cyber' } });@@ -134,12 +182,11 @@ describe('Default Avatar Style dropdown', () => {it('includes staged avatarStyle in updateCosConfig payload on Save click', async () => {api.updateCosConfig.mockResolvedValue({ success: true });const onUpdate = vi.fn();- render(<ConfigTab config={{ ...config, avatarStyle: 'svg' }} onUpdate={onUpdate} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);- await waitFor(() => expect(screen.getByRole('combobox', { name: 'Default Avatar Style' })).toBeDisabled());+ renderConfig({ config: { ...config, avatarStyle: 'svg' }, onUpdate });fireEvent.click(screen.getByRole('button', { name: /Edit/i }));- const select = screen.getByRole('combobox', { name: 'Default Avatar Style' });+ const select = screen.getByRole('combobox', { name: 'Default avatar' });fireEvent.change(select, { target: { value: 'cyber' } });fireEvent.click(screen.getByRole('button', { name: /Save/i }));@@ -153,91 +200,57 @@ describe('Default Avatar Style dropdown', () => {});it('reverts staged avatarStyle dropdown selection when Cancel is clicked', async () => {- render(<ConfigTab config={{ ...config, avatarStyle: 'svg' }} onUpdate={vi.fn()} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);- await waitFor(() => expect(screen.getByRole('combobox', { name: 'Default Avatar Style' })).toBeDisabled());+ renderConfig({ config: { ...config, avatarStyle: 'svg' } });+ await screen.findByText('Waiting for the next wake');fireEvent.click(screen.getByRole('button', { name: /Edit/i }));- const select = screen.getByRole('combobox', { name: 'Default Avatar Style' });+ const select = screen.getByRole('combobox', { name: 'Default avatar' });fireEvent.change(select, { target: { value: 'cyber' } });expect(select).toHaveValue('cyber');fireEvent.click(screen.getByRole('button', { name: /Cancel/i }));expect(screen.getByRole('button', { name: /Edit/i })).toBeInTheDocument();- const selectAfterCancel = screen.getByRole('combobox', { name: 'Default Avatar Style' });- expect(selectAfterCancel).toBeDisabled();- expect(selectAfterCancel).toHaveValue('svg');+ expect(screen.queryByRole('combobox', { name: 'Default avatar' })).not.toBeInTheDocument();+ expect(screen.getByText('Digital (SVG)')).toBeInTheDocument();});});-describe('ConfigTab handleLevelChange', () => {- // Reads the non-editing value span rendered next to a ConfigRow label.- const rowValue = (label) => within(screen.getByText(label).closest('div')).getByText;-- it('does not toast success when the autonomy level change fails', async () => {- api.updateCosConfig.mockRejectedValue(new Error('boom'));- render(<ConfigTab config={config} onUpdate={vi.fn()} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);+describe('persistent mind status', () => {+ it('shows the live supervisor state and links to the full mind workspace', async () => {+ renderConfig();- fireEvent.click(screen.getByRole('button', { name: 'Standby' }));-- await waitFor(() => expect(toast.error).toHaveBeenCalledWith('boom'));- expect(toast.success).not.toHaveBeenCalled();+ expect(await screen.findByText('Waiting for the next wake')).toBeInTheDocument();+ expect(screen.getByText('Started')).toBeInTheDocument();+ expect(screen.getByLabelText('Queued persistent mind messages')).toHaveTextContent('2');+ expect(screen.getByRole('link', { name: /Open mind/i })).toHaveAttribute('href', '/cos/mind');});- it('reverts the optimistic form params when the level change fails', async () => {- api.updateCosConfig.mockRejectedValue(new Error('boom'));- render(<ConfigTab config={config} onUpdate={vi.fn()} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);-- // Baseline: Max Concurrent Agents shows the config value (3).- expect(rowValue('Max Concurrent Agents')('3')).toBeInTheDocument();-- // Standby sets maxConcurrentAgents: 1 optimistically; on failure it must revert- // back to 3 (without the revert this row would be stuck showing 1).- fireEvent.click(screen.getByRole('button', { name: 'Standby' }));+ it('does not expose the retired global autonomy presets', async () => {+ renderConfig();- await waitFor(() => expect(toast.error).toHaveBeenCalledWith('boom'));- expect(rowValue('Max Concurrent Agents')('3')).toBeInTheDocument();+ await screen.findByText('Waiting for the next wake');+ expect(screen.queryByRole('button', { name: 'Standby' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'YOLO' })).not.toBeInTheDocument();+ expect(screen.getByText('Automation guardrails')).toBeInTheDocument();});+});- it('keeps the optimistic params and toasts the label (silently) after the change resolves', async () => {+describe('boot startup compatibility', () => {+ it('shows alwaysOn as the boot setting and clears the legacy alias when saving it off', async () => {api.updateCosConfig.mockResolvedValue({ success: true });- render(<ConfigTab config={config} onUpdate={vi.fn()} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);+ renderConfig({ config: { ...config, alwaysOn: true, autoStart: true } });- fireEvent.click(screen.getByRole('button', { name: 'Standby' }));+ fireEvent.click(screen.getByRole('button', { name: /Edit settings/i }));+ const toggle = screen.getByRole('checkbox', { name: /Start on server boot/i });+ expect(toggle).toBeChecked();+ fireEvent.click(toggle);+ fireEvent.click(screen.getByRole('button', { name: /Save settings/i }));- await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Autonomy level set to Standby'));- // Optimistic value persisted (Standby → maxConcurrentAgents: 1).- expect(rowValue('Max Concurrent Agents')('1')).toBeInTheDocument();- // The PUT must pass { silent: true } so the custom catch is the only error toast.- expect(api.updateCosConfig).toHaveBeenCalledWith(- expect.objectContaining({ maxConcurrentAgents: 1 }),+ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(+ expect.objectContaining({ alwaysOn: false, autoStart: false }),{ silent: true },- );- });-- it('does not clobber a newer successful preset when an earlier request fails late', async () => {- // Standby's PUT stays pending; YOLO's resolves first. When Standby then- // rejects, its rollback must NOT restore stale values over YOLO's now-- // persisted preset — only keys still holding Standby's optimistic value revert.- let rejectStandby;- api.updateCosConfig.mockImplementation((params) => {- if (params.maxConcurrentAgents === 1) {- return new Promise((_, reject) => { rejectStandby = () => reject(new Error('boom')); });- }- return Promise.resolve({ success: true });- });- render(<ConfigTab config={config} onUpdate={vi.fn()} onEvaluate={vi.fn()} avatarStyle="svg" setAvatarStyle={vi.fn()} />);-- fireEvent.click(screen.getByRole('button', { name: 'Standby' })); // optimistic → 1 (pending)- fireEvent.click(screen.getByRole('button', { name: 'YOLO' })); // optimistic → 5 (resolves)-- await waitFor(() => expect(toast.success).toHaveBeenCalledWith('Autonomy level set to YOLO'));- expect(rowValue('Max Concurrent Agents')('5')).toBeInTheDocument();-- rejectStandby();- await waitFor(() => expect(toast.error).toHaveBeenCalledWith('boom'));- // YOLO's value survives — the stale Standby rollback must not reset it to 3.- expect(rowValue('Max Concurrent Agents')('5')).toBeInTheDocument();+ ));});});diff --git a/client/src/pages/ChiefOfStaff.test.jsx b/client/src/pages/ChiefOfStaff.test.jsxindex 82845fa89e..9798af404b 100644--- a/client/src/pages/ChiefOfStaff.test.jsx+++ b/client/src/pages/ChiefOfStaff.test.jsx@@ -15,6 +15,7 @@ const api = vi.hoisted(() => ({getCosLearningSummary: vi.fn(),getCosActionableInsights: vi.fn(),getCosBudgetUsage: vi.fn(),+ getPersistentMind: vi.fn(),forceCosEvaluate: vi.fn(),pauseCos: vi.fn(),resumeCos: vi.fn(),@@ -71,7 +72,6 @@ const config = {improvementEnabled: true,proactiveMode: true,idleReviewEnabled: true,- immediateExecution: true,};beforeEach(() => {@@ -89,6 +89,10 @@ beforeEach(() => {api.getCosLearning.mockResolvedValue(null);api.getProviderStatuses.mockResolvedValue({ providers: {} });api.getCosBudgetUsage.mockResolvedValue({ usage: {} });+ api.getPersistentMind.mockResolvedValue({+ state: { enabled: false, started: false, status: 'disabled', queuedMessageCount: 0 },+ profile: { enabled: false, providerId: null, model: null },+ });api.pauseCos.mockResolvedValue({ success: true, pausedAt: '2026-01-01T00:00:00.000Z' });api.resumeCos.mockResolvedValue({ success: true });api.getCosLearningDurations.mockResolvedValue(null);diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.mdindex 77debd727f..d039d6acb1 100644--- a/docs/features/chief-of-staff.md+++ b/docs/features/chief-of-staff.md@@ -80,11 +80,16 @@ The `selectModelForTask` function routes tasks to appropriate model tiers:| maxConcurrentAgents | 3 | Max parallel agents (global) || maxConcurrentAgentsPerProject | 2 | Max parallel agents per project || maxProcessMemoryMb | 2048 | Memory alert threshold |-| autoStart | false | Start on server boot |-| selfImprovementEnabled | true | Allow self-analysis |+| maxTotalProcesses | 50 | Process-count alert threshold |+| alwaysOn | true | Start on server boot (`autoStart` is a legacy compatibility alias) |+| improvementEnabled | true | Allow improvement work for PortOS and managed apps || proactiveMode | true | Always find work when idle |-| comprehensiveAppImprovement | true | Apply full analysis to managed apps |-| avatarStyle | svg | CoS UI avatar style: `svg`, `cyber`, `sigil`, or `ascii` |+| idleReviewEnabled | true | Review managed apps while user work is idle |+| autonomousJobsEnabled | true | Enable the global scheduled-agent-job runner |+| domainAutonomy | execute per domain | Off, dry-run, or execute policy for each automatic-work domain |+| domainBudgets | unlimited | Optional daily action and runtime caps per domain |+| persistentMindProfile.enabled | false | Configure a persistent-mind profile without starting it |+| avatarStyle | svg | Default CoS UI avatar style |## API Endpointsdiff --git a/scripts/migrations/303-retire-cos-autonomy-presets.js b/scripts/migrations/303-retire-cos-autonomy-presets.jsnew file mode 100644index 0000000000..38c45125b6--- /dev/null+++ b/scripts/migrations/303-retire-cos-autonomy-presets.js@@ -0,0 +1,41 @@+/** Remove retired global CoS preset fields while preserving per-job autonomy. */++import { readFile } from 'fs/promises';+import { join } from 'path';+import { atomicWrite } from '../../server/lib/fileUtils.js';++export const RETIRED_COS_CONFIG_KEYS = [+ 'autonomyLevel',+ 'comprehensiveAppImprovement',+ 'immediateExecution',+];++export default {+ async up({ rootDir }) {+ const statePath = join(rootDir, 'data', 'cos', 'state.json');+ const raw = await readFile(statePath, 'utf8').catch((error) => {+ if (error.code === 'ENOENT') return null;+ throw error;+ });+ if (raw == null) return { updated: 0, reason: 'no-state' };++ let state;+ try {+ state = JSON.parse(raw);+ } catch {+ return { updated: 0, reason: 'invalid-state' };+ }+ if (!state || typeof state !== 'object' || Array.isArray(state)+ || !state.config || typeof state.config !== 'object' || Array.isArray(state.config)) {+ return { updated: 0, reason: 'invalid-state' };+ }++ const removed = RETIRED_COS_CONFIG_KEYS.filter((key) => Object.hasOwn(state.config, key));+ if (removed.length === 0) return { updated: 0, reason: 'already-applied' };++ for (const key of removed) delete state.config[key];+ await atomicWrite(statePath, state);+ console.log(`🧹 migration 303: retired ${removed.length} obsolete CoS config field(s)`);+ return { updated: 1, removed };+ },+};diff --git a/scripts/migrations/303-retire-cos-autonomy-presets.test.js b/scripts/migrations/303-retire-cos-autonomy-presets.test.jsnew file mode 100644index 0000000000..4e6fd63619--- /dev/null+++ b/scripts/migrations/303-retire-cos-autonomy-presets.test.js@@ -0,0 +1,53 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import migration, { RETIRED_COS_CONFIG_KEYS } from './303-retire-cos-autonomy-presets.js';++const readJson = (path) => JSON.parse(readFileSync(path, 'utf8'));++describe('migration 303 — retire CoS autonomy presets', () => {+ let rootDir;+ let statePath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-303-cos-config-'));+ mkdirSync(join(rootDir, 'data', 'cos'), { recursive: true });+ statePath = join(rootDir, 'data', 'cos', 'state.json');+ });++ afterEach(() => rmSync(rootDir, { recursive: true, force: true }));++ it('removes only retired global fields and preserves runtime and per-job data', async () => {+ writeFileSync(statePath, JSON.stringify({+ config: {+ maxConcurrentAgents: 4,+ domainAutonomy: { cos: 'dry-run' },+ autonomyLevel: 'manager',+ comprehensiveAppImprovement: true,+ immediateExecution: true,+ },+ persistentMind: { status: 'waiting' },+ jobs: [{ id: 'job-1', autonomyLevel: 'manager' }],+ }));++ await expect(migration.up({ rootDir })).resolves.toEqual({+ updated: 1,+ removed: RETIRED_COS_CONFIG_KEYS,+ });+ expect(readJson(statePath)).toEqual({+ config: { maxConcurrentAgents: 4, domainAutonomy: { cos: 'dry-run' } },+ persistentMind: { status: 'waiting' },+ jobs: [{ id: 'job-1', autonomyLevel: 'manager' }],+ });+ });++ it('is idempotent and leaves malformed state untouched', async () => {+ writeFileSync(statePath, JSON.stringify({ config: { maxConcurrentAgents: 3 } }));+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'already-applied' });++ writeFileSync(statePath, '{broken');+ await expect(migration.up({ rootDir })).resolves.toEqual({ updated: 0, reason: 'invalid-state' });+ expect(readFileSync(statePath, 'utf8')).toBe('{broken');+ });+});diff --git a/server/routes/cos.test.js b/server/routes/cos.test.jsindex 3fcdf41349..54016bd9a6 100644--- a/server/routes/cos.test.js+++ b/server/routes/cos.test.js@@ -249,6 +249,19 @@ describe('CoS Routes', () => {expect(response.status).toBe(200);expect(cos.updateConfig).toHaveBeenCalledWith(updates);});++ it.each([+ ['autonomyLevel', 'manager'],+ ['comprehensiveAppImprovement', true],+ ['immediateExecution', true],+ ])('rejects the retired %s config field', async (field, value) => {+ const response = await request(app)+ .put('/api/cos/config')+ .send({ [field]: value });++ expect(response.status).toBe(400);+ expect(cos.updateConfig).not.toHaveBeenCalled();+ });});describe('GET /api/cos/tasks', () => {diff --git a/server/routes/cosStatusRoutes.js b/server/routes/cosStatusRoutes.jsindex 0276f8c948..6b3981b4a1 100644--- a/server/routes/cosStatusRoutes.js+++ b/server/routes/cosStatusRoutes.js@@ -46,11 +46,8 @@ export const cosConfigSchema = z.object({appReviewCooldownMs: z.number().int().min(0).optional(),idleReviewEnabled: z.boolean().optional(),idleReviewPriority: z.enum(['LOW', 'MEDIUM', 'HIGH', 'CRITICAL']).optional(),- comprehensiveAppImprovement: z.boolean().optional(),- immediateExecution: z.boolean().optional(),proactiveMode: z.boolean().optional(),autonomousJobsEnabled: z.boolean().optional(),- autonomyLevel: z.enum(['standby', 'assistant', 'manager', 'yolo']).optional(),autoApproveInvestigations: z.boolean().optional(),// A durable reasoning route for the persistent mind. It is separate from// `alwaysOn`: saving or enabling this profile never starts background work.diff --git a/server/services/cosState.js b/server/services/cosState.jsindex 9bc7087a72..448df49b39 100644--- a/server/services/cosState.js+++ b/server/services/cosState.js@@ -57,11 +57,8 @@ export const DEFAULT_CONFIG = {appReviewCooldownMs: 1800000,idleReviewEnabled: true,idleReviewPriority: 'MEDIUM',- comprehensiveAppImprovement: true,- immediateExecution: true,proactiveMode: true,autonomousJobsEnabled: true,- autonomyLevel: 'standby',// Investigation tasks normally hold only failure loops for a human. This// opt-in also admits those loop/storm investigations unattended.autoApproveInvestigations: false,@@ -225,6 +222,13 @@ export async function loadState() {// from re-emitting a key the strict PUT schema would now reject on a full// round-trip, and purges it from disk on the next saveState.delete persistedConfig.evaluationIntervalMs;+ // The global four-level autonomy preset was only a UI shortcut that rewrote+ // independent capacity/work-generation fields. Domain guardrails now own the+ // actual off/dry-run/execute policy, so do not keep re-emitting this inert key+ // from upgraded state files. Per-job autonomyLevel remains a separate contract.+ delete persistedConfig.autonomyLevel;+ delete persistedConfig.comprehensiveAppImprovement;+ delete persistedConfig.immediateExecution;stateCache = {...DEFAULT_STATE,