Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-711]): address claude+codex review — gate all autonomous spawn paths + bridge + toast
Adam Eivyb9dedff486a8
diff --git a/client/src/components/cos/tabs/ConfigTab.jsx b/client/src/components/cos/tabs/ConfigTab.jsxindex 1f5433da60..06baf33f86 100644--- a/client/src/components/cos/tabs/ConfigTab.jsx+++ b/client/src/components/cos/tabs/ConfigTab.jsx@@ -172,7 +172,7 @@ function DomainAutonomyControl({ config, onDomainChange }) {return (<buttonkey={mode.id}- onClick={() => onDomainChange(domain.id, mode.id, mode.label)}+ 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}`}>@@ -227,10 +227,16 @@ 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 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 handleSave = async () => {diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex ab9f7641dc..f3f72cb3d0 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -45,9 +45,10 @@ export const pauseCos = (reason) => request('/cos/pause', {});export const resumeCos = () => request('/cos/resume', { method: 'POST' });export const getCosConfig = () => request('/cos/config');-export const updateCosConfig = (config) => request('/cos/config', {+export const updateCosConfig = (config, options = {}) => request('/cos/config', {method: 'PUT',- body: JSON.stringify(config)+ body: JSON.stringify(config),+ ...options});export const getCosTasks = (options) => request('/cos/tasks', options);export const addCosTask = (task) => request('/cos/tasks', {diff --git a/server/services/cos.js b/server/services/cos.jsindex acc44dda42..a3c82578f4 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -775,8 +775,11 @@ async function dequeueNextTask() {const hasPendingUserTasks = pendingUserTasks.length > 0;- // Priority 3: Mission-driven proactive tasks- if (spawned < availableSlots && !hasPendingUserTasks && state.config.proactiveMode) {+ // Priority 3: Mission-driven proactive tasks. These are speculative autonomous+ // spawns — when CoS auto-run isn't `execute`, skip generating them entirely+ // (off and dry-run both withhold autonomous spawns; only the concrete already-+ // queued auto-approved tasks above are surfaced for dry-run).+ if (spawned < availableSlots && !hasPendingUserTasks && state.config.proactiveMode && cosAutonomyMode === 'execute') {const missionTasks = await generateMissionTasks({ maxTasks: availableSlots - spawned }).catch(err => {emitLog('debug', `Mission task generation failed: ${err.message}`);return [];@@ -802,8 +805,9 @@ async function dequeueNextTask() {}}- // Priority 4: Idle review task (only when completely idle)- if (spawned === 0 && state.config.idleReviewEnabled && !hasPendingUserTasks) {+ // Priority 4: Idle review task (only when completely idle) — also an autonomous+ // spawn, so gated by the CoS auto-run domain.+ if (spawned === 0 && state.config.idleReviewEnabled && !hasPendingUserTasks && cosAutonomyMode === 'execute') {const freshCosTasks = await getCosTasks();const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;if (pendingSystemTasks === 0) {diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 37af1fa043..fce21e1248 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -655,6 +655,22 @@ describe('cos.js source — priority + capacity invariants', () => {expect(evalFn).toMatch(/tasksToSpawn\.length\s*===\s*0\s*&&\s*state\.config\.idleReviewEnabled/);});+ it('CoS auto-run domain gate (#711) fences autonomous spawns in BOTH engines', () => {+ // Per-domain autonomy: the `cos` guardrail must gate every AUTOMATIC internal+ // spawn path — not just the auto-approved loop. Both spawn engines+ // (dequeueNextTask in cos.js, evaluateTasks in cosTaskGenerator.js) must read+ // the cos mode and fence their mission / idle / auto-approved blocks on it,+ // or "off"/"dry-run" leaks autonomous agents through the un-gated engine.+ const dequeueFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function dequeueNextTask'));+ const evalFn = extractFnBody(GEN_SRC, GEN_SRC.indexOf('export async function evaluateTasks'));++ for (const [name, fnBody] of [['dequeueNextTask', dequeueFn], ['evaluateTasks', evalFn]]) {+ expect(fnBody, `${name} must resolve the cos autonomy mode`).toMatch(/getDomainMode\(\s*state\.config\s*,\s*['"]cos['"]\s*\)/);+ // The mission/idle blocks must be fenced on execute so off/dry-run skip them.+ expect(fnBody, `${name} must fence autonomous spawns on cosAutonomyMode === 'execute'`).toMatch(/cosAutonomyMode\s*===\s*['"]execute['"]/);+ }+ });+it('both on-demand loops dedupe markAppReviewStarted per app via reviewStartedApps set', () => {// Multiple on-demand requests targeting the same app should mark its// activity record review-started only once per cycle — without the guard,diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 58682c780e..15e3c2a22b 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -25,6 +25,7 @@ import { join } from 'path';import { sanitizeTaskMetadata, PIPELINE_BEHAVIOR_FLAGS, MAX_TOTAL_SPAWNS, normalizeReviewers } from '../lib/validation.js';import { parsePlanItems, extractAllIds, findInProgressIds, pickFirstAvailable, diagnoseUnpickablePlan } from '../lib/planIds.js';import { loadState, saveState, withStateLock, isImprovementEnabled, isDaemonRunning } from './cosState.js';+import { getDomainMode } from '../lib/domainAutonomy.js';import { cosEvents, emitLog } from './cosEvents.js';import { addTask, updateTask, getAllTasks, getCosTasks, firstLine, PRIORITY_VALUES } from './cosTaskStore.js';import { recordDecision, DECISION_TYPES } from './decisionLog.js';@@ -242,6 +243,12 @@ export async function evaluateTasks(options) {// Track per-project counts including tasks we're about to spawn in this batchconst spawnProjectCounts = { ...agentsByProject };+ // Per-domain CoS auto-run gate. Off/dry-run withhold all AUTOMATIC internal+ // spawns (auto-approved system tasks, mission, feature-agent, idle-review);+ // user and on-demand tasks are unaffected. dry-run logs the concrete already-+ // queued auto-approved tasks it would have spawned without emitting them.+ const cosAutonomyMode = getDomainMode(state.config, 'cos');+// Helper: check if a task can spawn (within both global and per-project limits)const canSpawnTask = (task) => {if (tasksToSpawn.length >= availableSlots) return false;@@ -345,8 +352,16 @@ export async function evaluateTasks(options) {trackSpawn(userTask);}- // Priority 2: Auto-approved system tasks (if slots available)- if (tasksToSpawn.length < availableSlots && cosTaskData.exists) {+ // Priority 2: Auto-approved system tasks (if slots available) — gated by the+ // CoS auto-run domain. off/dry-run withhold the unattended spawn; dry-run logs+ // what would have run so the user can see the plan without it executing.+ if (tasksToSpawn.length < availableSlots && cosTaskData.exists && cosAutonomyMode !== 'execute') {+ if (cosAutonomyMode === 'dry-run') {+ for (const task of (cosTaskData.autoApproved || [])) {+ emitLog('info', `[dry-run] CoS auto-run would spawn system task: ${task.id}`, { taskId: task.id, domainAutonomy: 'cos' });+ }+ }+ } else if (tasksToSpawn.length < availableSlots && cosTaskData.exists) {const autoApproved = cosTaskData.autoApproved || [];for (const task of autoApproved) {if (tasksToSpawn.length >= availableSlots) break;@@ -391,13 +406,15 @@ export async function evaluateTasks(options) {// Background: Queue eligible self-improvement tasks as system tasks// Only queue if there are NO pending user tasks (user tasks always take priority)- // Skip on initial startup to avoid auto-spawning agents on fresh installs- if (state.config.idleReviewEnabled && !hasPendingUserTasks && !initialStartup) {+ // Skip on initial startup to avoid auto-spawning agents on fresh installs.+ // Also skip when CoS auto-run isn't `execute` — queueing creates autonomous work.+ if (state.config.idleReviewEnabled && !hasPendingUserTasks && !initialStartup && cosAutonomyMode === 'execute') {await queueEligibleImprovementTasks(state, cosTaskData);}- // Priority 3: Mission-driven proactive tasks (if no user tasks)- if (tasksToSpawn.length < availableSlots && !hasPendingUserTasks && state.config.proactiveMode) {+ // Priority 3: Mission-driven proactive tasks (if no user tasks). Autonomous —+ // gated by the CoS auto-run domain (off/dry-run skip generation entirely).+ if (tasksToSpawn.length < availableSlots && !hasPendingUserTasks && state.config.proactiveMode && cosAutonomyMode === 'execute') {const missionTasks = await generateMissionTasks({ maxTasks: availableSlots - tasksToSpawn.length }).catch(err => {emitLog('debug', `Mission task generation failed: ${err.message}`);return [];@@ -431,8 +448,9 @@ export async function evaluateTasks(options) {// which caused duplicate agent spawns on startup when both paths fired// for the same past-due job within seconds of each other.- // Priority 3.6: Feature Agents (after autonomous jobs, yield to user tasks)- if (tasksToSpawn.length < availableSlots && !hasPendingUserTasks) {+ // Priority 3.6: Feature Agents (after autonomous jobs, yield to user tasks).+ // Autonomous — gated by the CoS auto-run domain.+ if (tasksToSpawn.length < availableSlots && !hasPendingUserTasks && cosAutonomyMode === 'execute') {const { getDueFeatureAgents, generateTaskFromFeatureAgent, setCurrentAgent } = await import('./featureAgents.js');const dueAgents = await getDueFeatureAgents().catch(err => {emitLog('debug', `Feature agents check failed: ${err.message}`);@@ -454,7 +472,7 @@ export async function evaluateTasks(options) {// 1. Nothing to spawn// 2. No pending user tasks (even on cooldown)// 3. No system tasks queued- if (tasksToSpawn.length === 0 && state.config.idleReviewEnabled && !hasPendingUserTasks) {+ if (tasksToSpawn.length === 0 && state.config.idleReviewEnabled && !hasPendingUserTasks && cosAutonomyMode === 'execute') {const freshCosTasks = await getCosTasks();const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;if (pendingSystemTasks === 0) {diff --git a/server/services/telegramBridge.js b/server/services/telegramBridge.jsindex b050ed53ee..833b0b57b7 100644--- a/server/services/telegramBridge.js+++ b/server/services/telegramBridge.js@@ -13,6 +13,7 @@ import { join } from 'path';import { homedir } from 'os';import { tryReadFile } from '../lib/fileUtils.js';import { notificationEvents, NOTIFICATION_TYPES } from './notifications.js';+import { getDomainAutonomyMode } from './cosState.js';const CHANNELS_DIR = join(homedir(), '.claude', 'channels', 'telegram');const ENV_FILE = join(CHANNELS_DIR, '.env');@@ -222,6 +223,16 @@ export function updateCachedForwardTypes(forwardTypes) {* Forward a notification to Telegram via HTTP API*/async function forwardNotification(notification) {+ // Per-domain autonomy gate (mirrors telegram.js): `off` suppresses outbound+ // forwarding; `dry-run` logs what would have been sent without messaging.+ 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;+ }+if (Array.isArray(cachedForwardTypes) && cachedForwardTypes.length > 0) {if (!cachedForwardTypes.includes(notification.type)) return;}diff --git a/server/services/telegramBridge.test.js b/server/services/telegramBridge.test.jsindex 87c55593be..d845d42911 100644--- a/server/services/telegramBridge.test.js+++ b/server/services/telegramBridge.test.js@@ -10,13 +10,25 @@ const fileStore = new Map();vi.mock('../lib/fileUtils.js', () => ({tryReadFile: vi.fn(async (path) => (fileStore.has(path) ? fileStore.get(path) : null)),- // Stubs to satisfy notifications.js (the real module imports these at load).- PATHS: { data: '/mock/data' },+ // Stubs to satisfy notifications.js and cosState.js (the latter is pulled in+ // by the bridge's per-domain messages gate; it needs PATHS.cos + ensureDirs).+ PATHS: { data: '/mock/data', cos: '/mock/data/cos', reports: '/mock/data/reports', scripts: '/mock/data/scripts', root: '/mock/data' },ensureDir: vi.fn().mockResolvedValue(undefined),+ ensureDirs: vi.fn().mockResolvedValue(undefined),+ safeJSONParse: vi.fn((str, defaultVal) => { if (!str) return defaultVal; try { return JSON.parse(str); } catch { return defaultVal; } }),readJSONFile: vi.fn(async (_path, defaultValue = null) => defaultValue),atomicWrite: vi.fn().mockResolvedValue(undefined)}));+// The bridge's per-domain "messages" gate reads getDomainAutonomyMode from+// cosState. Mock it with a mutable mode so we can exercise off/dry-run without+// a real state.json. Default 'execute' keeps the pre-existing forwarding tests+// behaving as before.+let mockMessagesMode = 'execute';+vi.mock('./cosState.js', () => ({+ getDomainAutonomyMode: vi.fn(async () => mockMessagesMode)+}));+// We import the real notifications module so the bridge can subscribe to the// event emitter — that's the spot where forwardNotification is exercised// without poking at any private internal.@@ -86,6 +98,7 @@ describe('telegramBridge service', () => {// Reset module-level state and unsubscribe from the EventEmitter.await cleanup();updateCachedForwardTypes(null);+ mockMessagesMode = 'execute';vi.useRealTimers();vi.restoreAllMocks();vi.unstubAllGlobals();@@ -284,5 +297,29 @@ describe('telegramBridge service', () => {await flush();expect(fetchSpy.mock.calls.filter(([url]) => url.endsWith('/sendMessage'))).toHaveLength(1);});++ it('suppresses forwarding when the messages domain is off or dry-run (#711)', async () => {+ for (const mode of ['off', 'dry-run']) {+ mockMessagesMode = mode;+ seedCredentials();+ const fetchSpy = mockTelegramFetch();+ vi.stubGlobal('fetch', fetchSpy);+ await init();+ fetchSpy.mockClear();++ notificationEvents.emit('added', {+ type: NOTIFICATION_TYPES.HEALTH_ISSUE,+ title: 'Should not send',+ priority: PRIORITY_LEVELS.HIGH+ });+ await flush();++ expect(+ fetchSpy.mock.calls.filter(([url]) => url.endsWith('/sendMessage')),+ `messages mode "${mode}" must not forward to Telegram`+ ).toHaveLength(0);+ await cleanup();+ }+ });});});