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([issue-711]): per-domain autonomy guardrails (off | dry-run | execute)
Adam Eivy531342a0d0ca
diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 334fd3cefa..cfa85d9a4b 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -166,6 +166,30 @@ export const MEMORY_TYPE_COLORS = {context: 'bg-gray-500/20 text-gray-400 border-gray-500/30'};+// Per-domain autonomy guardrails (#711). Mirrors server/lib/domainAutonomy.js —+// each domain is independently set to off | dry-run | execute. Default is+// `execute` (historical behavior). Keep this list in sync with the server.+export const AUTONOMY_DOMAINS = [+ { id: 'brain', label: 'Brain auto-classify', description: 'Auto-classify captured thoughts and file them.' },+ { id: 'memory', label: 'Memory auto-extract', description: 'Auto-store high-confidence memories from agent runs.' },+ { id: 'cos', label: 'CoS auto-run', description: 'Auto-spawn autonomous (non-user) tasks without approval.' },+ { id: 'messages', label: 'Messages auto-send', description: 'Auto-forward notifications to outbound channels (Telegram).' }+];++export const DOMAIN_AUTONOMY_MODES = [+ { id: 'off', label: 'Off', description: 'Never act automatically — leave it for manual action.' },+ { id: 'dry-run', label: 'Dry-run', description: 'Plan the action and surface it, but don\'t commit the side effect.' },+ { id: 'execute', label: 'Execute', description: 'Act automatically (default).' }+];++export const DEFAULT_DOMAIN_MODE = 'execute';++// Resolve a domain's mode from config, tolerating absent/partial config.+export const getDomainMode = (config, domainId) => {+ const candidate = config?.domainAutonomy?.[domainId];+ return DOMAIN_AUTONOMY_MODES.some(m => m.id === candidate) ? candidate : DEFAULT_DOMAIN_MODE;+};+// Autonomy level presets for CoS behaviorexport const AUTONOMY_LEVELS = [{diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsxindex e21dcb4faa..1f5433da60 100644--- a/client/src/components/cos/tabs/ConfigTab.jsx+++ b/client/src/components/cos/tabs/ConfigTab.jsx@@ -3,7 +3,7 @@ import { Settings, Activity, CheckCircle, FileText } from 'lucide-react';import toast from '../../ui/Toast';import * as api from '../../../services/api';import ConfigRow from './ConfigRow';-import { AUTONOMY_LEVELS, detectAutonomyLevel, formatInterval, AVATAR_STYLE_LABELS } from '../constants';+import { AUTONOMY_LEVELS, detectAutonomyLevel, formatInterval, AVATAR_STYLE_LABELS, AUTONOMY_DOMAINS, DOMAIN_AUTONOMY_MODES, getDomainMode } from '../constants';import ProviderModelSelector from '../../ProviderModelSelector';import useProviderModels from '../../../hooks/useProviderModels';@@ -131,6 +131,64 @@ function AutonomyControl({ config, onLevelChange }) {);}+// 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-green-500/30 bg-green-500/10 text-green-500 hover:bg-green-500/20',+ active: 'ring-2 ring-green-600 border-green-600 bg-green-500 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 }) {+ 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)}+ 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>+ </div>+ );+ })}+ </div>+ </div>+ );+}+export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, setAvatarStyle, evalCountdown }) {const { providers, availableModels, setSelectedProviderId: setProviderHook, setSelectedModel: setModelHook, selectedProviderId: hookProviderId, selectedModel: hookModel } = useProviderModels();const [embeddingProviderId, setEmbeddingProviderId] = useState(config?.embeddingProviderId || 'lmstudio');@@ -169,6 +227,12 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, sonUpdate();};+ const handleDomainChange = async (domainId, mode, modeLabel) => {+ await api.updateCosConfig({ domainAutonomy: { [domainId]: mode } }).catch(err => toast.error(err.message));+ toast.success(`${domainId} autonomy set to ${modeLabel}`);+ onUpdate();+ };+const handleSave = async () => {await api.updateCosConfig(formData).catch(err => toast.error(err.message));toast.success('Configuration updated');@@ -212,6 +276,9 @@ export default function ConfigTab({ config, onUpdate, onEvaluate, avatarStyle, s{/* Autonomy Level Control */}<AutonomyControl config={config} onLevelChange={handleLevelChange} />+ {/* Per-domain Autonomy Guardrails */}+ <DomainAutonomyControl config={config} onDomainChange={handleDomainChange} />+<div className="bg-port-card border border-port-border rounded-lg divide-y divide-port-border"><ConfigRowlabel="Evaluation Interval"diff --git a/server/lib/README.md b/server/lib/README.mdindex a6d9edc418..30b19e7b55 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -196,6 +196,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub|---|---|| `asyncMutex.js` | Promise-based async mutex. || `authGate.js` | Express + Socket.IO middleware that gates `/api/*` and `/data/*` behind the password set in `settings.secrets.auth`. No-op when auth is off; emits 401 `AUTH_REQUIRED` (or plain text for `/data/*`) when on and the request has no valid session token. |+| `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)` + `isDomainOff/DryRun/Execute`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). || `errorHandler.js` | `ServerError` + `asyncHandler` middleware. || `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. || `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |diff --git a/server/lib/domainAutonomy.js b/server/lib/domainAutonomy.jsnew file mode 100644index 0000000000..bc20d68276--- /dev/null+++ b/server/lib/domainAutonomy.js@@ -0,0 +1,90 @@+/**+ * Per-domain autonomy guardrails (pure helpers).+ *+ * Splits PortOS's single global autonomy posture into independent per-domain+ * knobs. Each domain is one of three modes:+ *+ * - `off` — never act automatically; leave the work for explicit user action.+ * - `dry-run` — compute what WOULD happen and surface it, but don't commit the+ * side effect (don't file, don't store-as-active, don't spawn, don't send).+ * - `execute` — act automatically (the historical default behavior).+ *+ * The default for every domain is `execute`, which exactly reproduces pre-#711+ * behavior — so an install with no stored `domainAutonomy` config needs no+ * migration; the absent-key path resolves to `execute`.+ *+ * These helpers are side-effect-free: callers pass in the CoS config (or a raw+ * domainAutonomy map) and read back a normalized mode. The execution-point+ * gating (brain.js, memoryExtractor.js, cos.js, telegram.js) lives at each call+ * site; this module only owns the vocabulary and normalization.+ */++export const DOMAIN_MODES = ['off', 'dry-run', 'execute'];++export const DEFAULT_DOMAIN_MODE = 'execute';++// The four domains the issue (#711) carves the global posture into. `id` is the+// stored key; `label`/`description` drive the settings UI. Keep this list as the+// single source of truth — the client mirrors it for rendering.+export const AUTONOMY_DOMAINS = [+ {+ id: 'brain',+ label: 'Brain auto-classify',+ description: 'Automatically classify captured thoughts and file them to a destination.'+ },+ {+ id: 'memory',+ label: 'Memory auto-extract',+ description: 'Automatically store high-confidence memories extracted from agent runs.'+ },+ {+ id: 'cos',+ label: 'CoS auto-run',+ description: 'Automatically spawn autonomous (non-user) tasks without approval.'+ },+ {+ id: 'messages',+ label: 'Messages auto-send',+ description: 'Automatically forward notifications to outbound channels (e.g. Telegram).'+ }+];++export const DOMAIN_IDS = AUTONOMY_DOMAINS.map((d) => d.id);++const isValidMode = (mode) => DOMAIN_MODES.includes(mode);++/**+ * Coerce a raw (possibly hand-edited / legacy / partial) domainAutonomy map into+ * a complete, valid `{ [domainId]: mode }` object. Unknown keys are dropped;+ * missing or invalid values fall back to `execute`.+ *+ * @param {unknown} raw+ * @returns {Record<string, string>}+ */+export function normalizeDomainAutonomy(raw) {+ const source = raw && typeof raw === 'object' && !Array.isArray(raw) ? raw : {};+ const normalized = {};+ for (const id of DOMAIN_IDS) {+ const candidate = source[id];+ normalized[id] = isValidMode(candidate) ? candidate : DEFAULT_DOMAIN_MODE;+ }+ return normalized;+}++/**+ * Read a single domain's mode from a CoS config object. Tolerates a missing+ * `config`, a missing `domainAutonomy`, and an unknown/invalid stored value —+ * all resolve to `execute` so absent config reproduces historical behavior.+ *+ * @param {object|null|undefined} config - CoS config (has optional `domainAutonomy`)+ * @param {string} domainId - one of DOMAIN_IDS+ * @returns {'off'|'dry-run'|'execute'}+ */+export function getDomainMode(config, domainId) {+ const candidate = config?.domainAutonomy?.[domainId];+ return isValidMode(candidate) ? candidate : DEFAULT_DOMAIN_MODE;+}++export const isDomainOff = (config, domainId) => getDomainMode(config, domainId) === 'off';+export const isDomainDryRun = (config, domainId) => getDomainMode(config, domainId) === 'dry-run';+export const isDomainExecute = (config, domainId) => getDomainMode(config, domainId) === 'execute';diff --git a/server/lib/domainAutonomy.test.js b/server/lib/domainAutonomy.test.jsnew file mode 100644index 0000000000..81d2853cf4--- /dev/null+++ b/server/lib/domainAutonomy.test.js@@ -0,0 +1,91 @@+import { describe, it, expect } from 'vitest';+import {+ DOMAIN_MODES,+ DEFAULT_DOMAIN_MODE,+ AUTONOMY_DOMAINS,+ DOMAIN_IDS,+ normalizeDomainAutonomy,+ getDomainMode,+ isDomainOff,+ isDomainDryRun,+ isDomainExecute+} from './domainAutonomy.js';++describe('domainAutonomy constants', () => {+ it('exposes the three modes with execute as default', () => {+ expect(DOMAIN_MODES).toEqual(['off', 'dry-run', 'execute']);+ expect(DEFAULT_DOMAIN_MODE).toBe('execute');+ });++ it('lists the four domains with unique ids', () => {+ expect(DOMAIN_IDS).toEqual(['brain', 'memory', 'cos', 'messages']);+ expect(new Set(DOMAIN_IDS).size).toBe(DOMAIN_IDS.length);+ for (const d of AUTONOMY_DOMAINS) {+ expect(d.id).toBeTruthy();+ expect(d.label).toBeTruthy();+ expect(d.description).toBeTruthy();+ }+ });+});++describe('normalizeDomainAutonomy', () => {+ it('fills every domain with execute when given an empty/garbage value', () => {+ for (const raw of [undefined, null, {}, [], 'nope', 42]) {+ const result = normalizeDomainAutonomy(raw);+ expect(Object.keys(result).sort()).toEqual([...DOMAIN_IDS].sort());+ for (const id of DOMAIN_IDS) expect(result[id]).toBe('execute');+ }+ });++ it('keeps valid modes and drops unknown keys', () => {+ const result = normalizeDomainAutonomy({ brain: 'off', memory: 'dry-run', bogus: 'execute' });+ expect(result.brain).toBe('off');+ expect(result.memory).toBe('dry-run');+ expect(result.cos).toBe('execute'); // unspecified → default+ expect(result.messages).toBe('execute');+ expect(result.bogus).toBeUndefined();+ });++ it('coerces invalid mode values to execute', () => {+ const result = normalizeDomainAutonomy({ brain: 'sometimes', cos: '' });+ expect(result.brain).toBe('execute');+ expect(result.cos).toBe('execute');+ });+});++describe('getDomainMode', () => {+ it('resolves execute for absent config / domainAutonomy', () => {+ expect(getDomainMode(undefined, 'brain')).toBe('execute');+ expect(getDomainMode(null, 'brain')).toBe('execute');+ expect(getDomainMode({}, 'brain')).toBe('execute');+ expect(getDomainMode({ domainAutonomy: {} }, 'brain')).toBe('execute');+ });++ it('reads a stored valid mode', () => {+ const config = { domainAutonomy: { brain: 'off', messages: 'dry-run' } };+ expect(getDomainMode(config, 'brain')).toBe('off');+ expect(getDomainMode(config, 'messages')).toBe('dry-run');+ expect(getDomainMode(config, 'cos')).toBe('execute');+ });++ it('falls back to execute for an invalid stored value', () => {+ expect(getDomainMode({ domainAutonomy: { brain: 'haywire' } }, 'brain')).toBe('execute');+ });+});++describe('mode predicates', () => {+ const config = { domainAutonomy: { brain: 'off', memory: 'dry-run', cos: 'execute' } };+ it('isDomainOff', () => {+ expect(isDomainOff(config, 'brain')).toBe(true);+ expect(isDomainOff(config, 'memory')).toBe(false);+ });+ it('isDomainDryRun', () => {+ expect(isDomainDryRun(config, 'memory')).toBe(true);+ expect(isDomainDryRun(config, 'cos')).toBe(false);+ });+ it('isDomainExecute (incl. default for unset/absent)', () => {+ expect(isDomainExecute(config, 'cos')).toBe(true);+ expect(isDomainExecute(config, 'messages')).toBe(true); // unset → execute+ expect(isDomainExecute(config, 'brain')).toBe(false);+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 2e7d9e30fb..b0f26f0fc6 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -163,6 +163,7 @@ export * from './timezone.js';// === General utilities ===export * from './asyncMutex.js';export * from './authGate.js';+export * from './domainAutonomy.js';export * from './errorHandler.js';export * from './mapWithConcurrency.js';export * from './objects.js';diff --git a/server/routes/cosStatusRoutes.js b/server/routes/cosStatusRoutes.jsindex 6ab105f87d..67c9141843 100644--- a/server/routes/cosStatusRoutes.js+++ b/server/routes/cosStatusRoutes.js@@ -9,6 +9,7 @@ import { reinitialize as reinitializeEmbeddings } from '../services/memoryEmbeddimport { asyncHandler } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { z } from 'zod';+import { DOMAIN_IDS, DOMAIN_MODES } from '../lib/domainAutonomy.js';const router = Router();@@ -42,6 +43,11 @@ export const cosConfigSchema = z.object({proactiveMode: z.boolean().optional(),autonomousJobsEnabled: z.boolean().optional(),autonomyLevel: z.enum(['standby', 'assistant', 'manager', 'yolo']).optional(),+ // Per-domain autonomy guardrails (#711): partial map of domainId → mode.+ // Partial is fine — updateConfig() merges it over the stored map.+ domainAutonomy: z.object(+ Object.fromEntries(DOMAIN_IDS.map((id) => [id, z.enum(DOMAIN_MODES).optional()]))+ ).strict().optional(),rehabilitationGracePeriodDays: z.number().int().min(1).optional(),completedAgentRetentionMs: z.number().int().min(0).optional(),embeddingProviderId: z.string().optional(),diff --git a/server/services/brain.js b/server/services/brain.jsindex 36ee6f73be..922d55580c 100644--- a/server/services/brain.js+++ b/server/services/brain.js@@ -15,6 +15,7 @@ import { buildPrompt } from './promptService.js';import { validate } from '../lib/validation.js';import { safeJSONParse } from '../lib/fileUtils.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';+import { getDomainAutonomyMode } from './cosState.js';import {classifierOutputSchema,digestOutputSchema,@@ -134,7 +135,13 @@ export async function captureThought(text, providerOverride, modelOverride) {const provider = providerOverride || meta.defaultProvider;const model = modelOverride || meta.defaultModel;- // Create initial inbox log entry+ // Per-domain autonomy gate: `off` captures the thought but skips auto-classify+ // entirely (it lands in the inbox for manual review); `dry-run` classifies and+ // surfaces the suggestion but doesn't auto-file it.+ const mode = await getDomainAutonomyMode('brain');++ // Create initial inbox log entry. When auto-classify is off the entry goes+ // straight to needs_review rather than the transient classifying state.const inboxEntry = await storage.createInboxLog({capturedText: text,source: 'brain_ui',@@ -143,19 +150,29 @@ export async function captureThought(text, providerOverride, modelOverride) {modelId: model,promptTemplateId: 'brain-classifier'},- status: 'classifying'+ status: mode === 'off' ? 'needs_review' : 'classifying'});- console.log(`🧠 Thought captured, classifying in background: ${inboxEntry.id}`);+ if (mode === 'off') {+ console.log(`🧠 Thought captured, auto-classify is OFF — left for manual review: ${inboxEntry.id}`);+ return {+ inboxLog: inboxEntry,+ message: 'Thought captured! Auto-classify is off — review it in the inbox.'+ };+ }++ console.log(`🧠 Thought captured, classifying in background${mode === 'dry-run' ? ' (dry-run, no auto-file)' : ''}: ${inboxEntry.id}`);// Run AI classification in background (don't await)// Pass resolved provider/model so callAI uses brain's configured provider, not the system active one- classifyInBackground(inboxEntry.id, text, meta, provider, model)+ classifyInBackground(inboxEntry.id, text, meta, provider, model, mode).catch(err => console.error(`❌ Background classification failed for ${inboxEntry.id}: ${err.message}`));return {inboxLog: inboxEntry,- message: 'Thought captured! AI is classifying...'+ message: mode === 'dry-run'+ ? 'Thought captured! AI is suggesting a classification (dry-run — confirm to file).'+ : 'Thought captured! AI is classifying...'};}@@ -163,7 +180,7 @@ export async function captureThought(text, providerOverride, modelOverride) {* Background AI classification for a captured thought.* Updates the inbox entry and emits a brain:classified event when done.*/-async function classifyInBackground(entryId, text, meta, providerOverride, modelOverride) {+async function classifyInBackground(entryId, text, meta, providerOverride, modelOverride, mode = 'execute') {let classification = null;let aiError = null;@@ -239,6 +256,26 @@ async function classifyInBackground(entryId, text, meta, providerOverride, modelreturn;}+ // Dry-run: a confident classification was produced, but the auto-file side+ // effect is withheld. Surface the suggestion as needs_review so the user can+ // confirm filing it from the inbox.+ if (mode === 'dry-run') {+ await storage.updateInboxLog(entryId, {+ ai: aiMeta,+ classification,+ status: 'needs_review'+ });+ console.log(`🧠 [dry-run] Classified ${entryId} → ${classification.destination} (not filed; awaiting confirmation)`);+ brainEvents.emit('classified', {+ entryId,+ status: 'needs_review',+ destination: classification.destination,+ title: classification.title,+ dryRun: true+ });+ return;+ }+// File to appropriate destinationconst filedRecord = await fileToDestination(classification.destination, classification.extracted, classification.title);diff --git a/server/services/brain.test.js b/server/services/brain.test.jsindex 1cbe15bd7a..1db16d4415 100644--- a/server/services/brain.test.js+++ b/server/services/brain.test.js@@ -76,13 +76,18 @@ vi.mock('../lib/validation.js', () => ({validate: vi.fn()}));-// Mock fileUtils+// Mock fileUtils. PATHS / atomicWrite / ensureDirs are consumed transitively by+// cosState.js (pulled in via brain.js's per-domain autonomy gate) — keep them+// stubbed so the mock stays complete.vi.mock('../lib/fileUtils.js', () => ({tryReadFile: vi.fn().mockResolvedValue(null),safeJSONParse: vi.fn((str, defaultVal) => {if (!str) return defaultVal;try { return JSON.parse(str); } catch { return defaultVal; }- })+ }),+ PATHS: { data: '/tmp/portos-test', cos: '/tmp/portos-test/cos', reports: '/tmp/portos-test/reports', scripts: '/tmp/portos-test/scripts', root: '/tmp/portos-test' },+ atomicWrite: vi.fn().mockResolvedValue(undefined),+ ensureDirs: vi.fn().mockResolvedValue(undefined)}));// Mock the central LLM handler — brain.js used to spawn child_processdiff --git a/server/services/cos.js b/server/services/cos.jsindex 0974d1cd82..acc44dda42 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -27,6 +27,7 @@ import { recordJobExecution } from './autonomousJobs.js';import { safeJSONParse } from '../lib/fileUtils.js';import { addNotification, NOTIFICATION_TYPES } from './notifications.js';import { getUserTimezone, todayInTimezone } from '../lib/timezone.js';+import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';// Shared state management (extracted to avoid circular deps)import { loadState, saveState, withStateLock, ensureDirectories, isImprovementEnabled, AGENTS_DIR, REPORTS_DIR, SCRIPTS_DIR, ROOT_DIR, isDaemonRunning, setDaemonRunning } from './cosState.js';@@ -147,7 +148,18 @@ export async function getConfig() {export async function updateConfig(updates) {const config = await withStateLock(async () => {const state = await loadState();+ // domainAutonomy is a partial-friendly map: a PATCH that names only one+ // domain must merge over the others rather than replace the whole object.+ // Capture the prior map BEFORE the spread clobbers it, then normalize the+ // merge so an unknown/invalid stored value resolves to the `execute` default.+ const priorDomainAutonomy = state.config.domainAutonomy;state.config = { ...state.config, ...updates };+ if (updates.domainAutonomy !== undefined) {+ state.config.domainAutonomy = normalizeDomainAutonomy({+ ...priorDomainAutonomy,+ ...updates.domainAutonomy+ });+ }await saveState(state);return state.config;});@@ -728,12 +740,21 @@ async function dequeueNextTask() {trackSpawn(userTask);}- // Priority 2: Auto-approved system tasks+ // Priority 2: Auto-approved system tasks — gated by the CoS auto-run domain.+ // `off`/`dry-run` both stop the unattended spawn; `dry-run` logs what would+ // have run so the user can see the plan without it executing.const cosTaskData = await getCosTasks();const autoApproved = cosTaskData.autoApproved || [];+ const cosAutonomyMode = getDomainMode(state.config, 'cos');for (const task of autoApproved) {if (spawned >= availableSlots) break;+ if (cosAutonomyMode !== 'execute') {+ if (cosAutonomyMode === 'dry-run') {+ emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });+ }+ continue;+ }if (await blockIfExceedsMaxSpawns(task, 'internal')) continue;// Skip improvement tasks whose type was disabled after queuingconst analysisType = task.metadata?.analysisType || task.metadata?.selfImprovementType;diff --git a/server/services/cosState.js b/server/services/cosState.jsindex a914338039..29afc06f37 100644--- a/server/services/cosState.js+++ b/server/services/cosState.js@@ -9,6 +9,7 @@ import { existsSync } from 'fs';import { join, dirname } from 'path';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';import { ensureDirs, safeJSONParse, PATHS, atomicWrite } from '../lib/fileUtils.js';+import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';export const STATE_FILE = join(PATHS.cos, 'state.json');export const AGENTS_DIR = join(PATHS.cos, 'agents');@@ -56,6 +57,10 @@ export const DEFAULT_CONFIG = {proactiveMode: true,autonomousJobsEnabled: true,autonomyLevel: 'standby',+ // 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`.+ domainAutonomy: normalizeDomainAutonomy({}),rehabilitationGracePeriodDays: 7,completedAgentRetentionMs: 86400000,embeddingProviderId: 'lmstudio',@@ -183,6 +188,14 @@ export async function saveState(state) {await atomicWrite(STATE_FILE, state);}+// Resolve a single domain's autonomy mode (off | dry-run | execute) without+// importing cos.js (which would create circular deps). Domains gate their+// automatic behavior off this; an absent/invalid value resolves to `execute`.+export async function getDomainAutonomyMode(domainId) {+ const state = await loadState();+ return getDomainMode(state.config, domainId);+}+// Daemon state accessors — used by modules that need to check daemon status// without importing cos.js (which would create circular deps)let _daemonRunning = false;diff --git a/server/services/memoryExtractor.js b/server/services/memoryExtractor.jsindex 3e74457157..c760a35b03 100644--- a/server/services/memoryExtractor.js+++ b/server/services/memoryExtractor.js@@ -10,6 +10,7 @@ import { generateMemoryEmbedding } from './memoryEmbeddings.js';import { cosEvents } from './cosEvents.js';import * as notifications from './notifications.js';import { classifyMemories, isAvailable as isClassifierAvailable } from './memoryClassifier.js';+import { getDomainAutonomyMode } from './cosState.js';const DEDUP_SIMILARITY_THRESHOLD = 0.82;@@ -201,6 +202,15 @@ async function findExistingDuplicate(embedding, content, pendingMemories) {* Uses LLM-based classification when available, falls back to pattern matching.*/export async function extractAndStoreMemories(agentId, taskId, output, task = null) {+ // Per-domain autonomy gate: `off` skips memory extraction entirely; `dry-run`+ // routes even high-confidence memories to pending approval (nothing stores as+ // active without a human confirm); `execute` is the historical behavior.+ const mode = await getDomainAutonomyMode('memory');+ if (mode === 'off') {+ console.log(`🧠 Memory auto-extract is OFF — skipping extraction for agent ${agentId}`);+ return { created: 0, pendingApproval: 0, memories: [], pendingMemories: [], skipped: 'domain-off' };+ }+const allMemories = [];let usedLLM = false;@@ -295,13 +305,21 @@ export async function extractAndStoreMemories(agentId, taskId, output, task = nu}, embedding);}+ // In dry-run, high-confidence memories that would auto-store as active are+ // instead routed to pending approval — nothing enters active memory without a+ // human confirm, but the extraction work is still surfaced for review.const created = [];+ const pendingMemories = [];for (const mem of highConfidence) {- const memory = await dedupAndCreate(mem);- if (memory) created.push(memory);+ if (mode === 'dry-run') {+ const memory = await dedupAndCreate(mem, { status: 'pending_approval' });+ if (memory) pendingMemories.push(memory);+ } else {+ const memory = await dedupAndCreate(mem);+ if (memory) created.push(memory);+ }}- const pendingMemories = [];for (const mem of mediumConfidence) {const memory = await dedupAndCreate(mem, { status: 'pending_approval' });if (memory) pendingMemories.push(memory);diff --git a/server/services/telegram.js b/server/services/telegram.jsindex 8689fbf9fe..bb89a1ad6f 100644--- a/server/services/telegram.js+++ b/server/services/telegram.js@@ -10,6 +10,7 @@ import { join } from 'path';import { v4 as uuidv4 } from '../lib/uuid.js';import { getSettings } from './settings.js';import { notificationEvents, NOTIFICATION_TYPES, getNotifications } from './notifications.js';+import { getDomainAutonomyMode } from './cosState.js';import { approveMemory, rejectMemory, peekMemory } from './memoryBackend.js';import { ensureDir, PATHS, readJSONFile, formatDuration, atomicWrite } from '../lib/fileUtils.js';import { getActiveAgents } from './subAgentSpawner.js';@@ -370,6 +371,16 @@ async function handleCallbackQuery(query) {* Forward a notification to Telegram*/async function forwardNotification(notification) {+ // Per-domain autonomy gate: `off` suppresses outbound forwarding; `dry-run`+ // logs what would have been sent without actually messaging the channel.+ const mode = await getDomainAutonomyMode('messages');+ if (mode !== 'execute') {+ if (mode === 'dry-run') {+ console.log(`📨 [dry-run] Messages auto-send would forward notification: ${notification.type} — "${notification.title}"`);+ }+ return;+ }+// Use cached forwardTypes to avoid disk I/O on every notificationif (Array.isArray(cachedForwardTypes) && cachedForwardTypes.length > 0) {if (!cachedForwardTypes.includes(notification.type)) return;