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
refactor: import CoS task and agent operations from the modules that declare them (#12988)
[._.]/ Adam Eivydae95de8bd0e
diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 5122ec60bd..5c72e25c04 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -50,6 +50,20 @@ const NARROWED = ['reads the local-LLM concurrency cap from its leaf without loading the prompt runner'],['services/cos.js', 'services/promptRunner.js','reads the local-LLM concurrency cap from its leaf without loading the prompt runner'],+ ['services/agentFinalization.js', 'services/promptRunner.js',+ 'writes task state through the task store without loading the CoS daemon graph'],+ ['services/agentFinalization.js', 'services/cosTaskGenerator.js',+ 'writes task state through the task store without loading the CoS daemon graph'],+ ['services/investigationTaskProducer.js', 'services/cos.js',+ 'queues investigation tasks through the task store, not the CoS daemon'],+ ['services/repoIntake.js', 'services/cos.js',+ 'queues intake tasks through the task store, not the CoS daemon'],+ ['services/askPromote.js', 'services/cos.js',+ 'queues promoted tasks through the task store, not the CoS daemon'],+ ['routes/gsd.js', 'services/cos.js',+ 'queues GSD tasks through the task store, not the CoS daemon'],+ ['routes/apps/agents.js', 'services/cos.js',+ 'lists agents from the declaring agent modules, not the CoS daemon'],['services/imageGen/prepareParams.js', 'services/imageGen/index.js','reads cleaner request policy without loading execution backends'],['services/codeReview.js', 'lib/validation.js',diff --git a/server/routes/apps/agents.js b/server/routes/apps/agents.jsindex 4eefb76454..a487a8a911 100644--- a/server/routes/apps/agents.js+++ b/server/routes/apps/agents.js@@ -5,7 +5,8 @@*/import { Router } from 'express';-import * as cos from '../../services/cos.js';+import { getAgentDates, getAgentsByDate } from '../../services/cosAgentIndex.js';+import { getAgents } from '../../services/cosAgentLifecycle.js';import { asyncHandler } from '../../lib/errorHandler.js';import { toAgentListItems } from '../../lib/cosAgentListProjection.js';import { parsePagination } from '../../lib/validation.js';@@ -18,19 +19,19 @@ router.get('/:id/agents', loadApp, asyncHandler(async (req, res) => {const app = req.loadedApp;const { limit } = parsePagination(req.query, { defaultLimit: 50, maxLimit: 500 });- const runningAgents = await cos.getAgents().catch(() => []);+ const runningAgents = await getAgents().catch(() => []);const appRunning = runningAgents.filter(a =>a.metadata?.app === app.id || a.metadata?.taskApp === app.id);// Scan last 14 days of agent history for this app- const dates = await cos.getAgentDates().catch(() => []);+ const dates = await getAgentDates().catch(() => []);const recentDates = dates.slice(0, 14);const historyAgents = [];for (const { date } of recentDates) {if (historyAgents.length >= limit) break;- const dayAgents = await cos.getAgentsByDate(date).catch(() => []);+ const dayAgents = await getAgentsByDate(date).catch(() => []);const appAgents = dayAgents.filter(a =>a.metadata?.app === app.id || a.metadata?.taskApp === app.id);diff --git a/server/routes/apps/agents.test.js b/server/routes/apps/agents.test.jsindex e70324cc82..73fcd53b20 100644--- a/server/routes/apps/agents.test.js+++ b/server/routes/apps/agents.test.js@@ -6,14 +6,17 @@ import agentRoutes from './agents.js';vi.mock('../../services/apps.js', () => ({getAppById: vi.fn(),}));-vi.mock('../../services/cos.js', () => ({+vi.mock('../../services/cosAgentLifecycle.js', () => ({getAgents: vi.fn(),+}));+vi.mock('../../services/cosAgentIndex.js', () => ({getAgentDates: vi.fn(),getAgentsByDate: vi.fn(),}));import * as appsService from '../../services/apps.js';-import * as cos from '../../services/cos.js';+import { getAgentDates, getAgentsByDate } from '../../services/cosAgentIndex.js';+import { getAgents } from '../../services/cosAgentLifecycle.js';const APP = { id: 'app-001', name: 'Widget' };@@ -33,9 +36,9 @@ describe('GET /api/apps/:id/agents', () => {app.use('/api/apps', agentRoutes);vi.clearAllMocks();appsService.getAppById.mockResolvedValue(APP);- cos.getAgents.mockResolvedValue([]);- cos.getAgentDates.mockResolvedValue([]);- cos.getAgentsByDate.mockResolvedValue([]);+ getAgents.mockResolvedValue([]);+ getAgentDates.mockResolvedValue([]);+ getAgentsByDate.mockResolvedValue([]);});// This response carries up to 500 records; shipping each one's transcript and@@ -44,9 +47,9 @@ describe('GET /api/apps/:id/agents', () => {// never reuses the text, so the bounded copy is all it needs.it('projects the combined list: no transcripts, bounded descriptions', async () => {const long = 'Refactor the queue. '.repeat(5000);- cos.getAgents.mockResolvedValue([agentFor('agent-running', { status: 'running' })]);- cos.getAgentDates.mockResolvedValue([{ date: '2026-07-13', count: 1 }]);- cos.getAgentsByDate.mockResolvedValue([+ getAgents.mockResolvedValue([agentFor('agent-running', { status: 'running' })]);+ getAgentDates.mockResolvedValue([{ date: '2026-07-13', count: 1 }]);+ getAgentsByDate.mockResolvedValue([agentFor('agent-done', { metadata: { taskApp: APP.id, taskDescription: long } }),]);diff --git a/server/routes/apps/launchVideos.js b/server/routes/apps/launchVideos.jsindex 00caa7b5a3..7370ba0e41 100644--- a/server/routes/apps/launchVideos.js+++ b/server/routes/apps/launchVideos.js@@ -103,10 +103,11 @@ router.post('/:id/launch-videos/publish', loadApp, asyncHandler(async (req, res)if (dirname(source) !== root || !(await stat(source).catch(missingVideoSource)).isFile()) {throw new ServerError('Launch video source is invalid', { status: 400 });}- const cos = await import('../../services/cos.js');- if (!cos.isRunning()) throw new ServerError('Start CoS before publishing a launch video', { status: 409 });+ const { isRunning } = await import('../../services/cos.js');+ const { addTask } = await import('../../services/cosTaskStore.js');+ if (!isRunning()) throw new ServerError('Start CoS before publishing a launch video', { status: 409 });const { getInstanceId } = await import('../../services/instanceIdentity.js');- const task = await cos.addTask({+ const task = await addTask({description: 'Publish launch video to README', app: app.id, priority: 'MEDIUM',targetInstanceId: await getInstanceId(), useWorktree: true, openPR: true,prCompletion: 'review-then-merge', provider, model, effort,@@ -128,8 +129,9 @@ router.post('/:id/launch-videos', loadApp, asyncHandler(async (req, res) => {if (!/^[a-zA-Z0-9_-]{1,128}$/.test(app.id) || !app.repoPath || !await pathExists(app.repoPath)) {throw new ServerError('App repository is unavailable', { status: 400 });}- const cos = await import('../../services/cos.js');- if (!cos.isRunning()) throw new ServerError('Start CoS before making a launch video', { status: 409 });+ const { isRunning } = await import('../../services/cos.js');+ const { addTask } = await import('../../services/cosTaskStore.js');+ if (!isRunning()) throw new ServerError('Start CoS before making a launch video', { status: 409 });if (options.generateMusic && options.musicTrack) throw new ServerError('Choose generated music or a library track, not both', { status: 400 });if (options.motionSkills) {// The prompt names only skills that are actually installed for the agent.@@ -257,7 +259,7 @@ router.post('/:id/launch-videos', loadApp, asyncHandler(async (req, res) => {// Motion, camera, sound and native moves only: the app's own palette and fonts stay authoritative (#10254).// A revision keeps its source take's look, so it takes no new grammar.const grammarPrompt = styleGrammarId && !sourceVideoId ? `\n${renderFilmStyleGrammarPrompt(styleGrammarId, { parts: LAUNCH_VIDEO_GRAMMAR_PARTS })}\nTreat this film style grammar as the medium's motion, camera and sound rulebook; motionStyle still picks the film's structure, and the app's palette and fonts win over any colour or type it implies.` : '';- return cos.addTask({+ return addTask({description: 'Make launch video', app: app.id, priority: 'MEDIUM', targetInstanceId,useWorktree: false, openPR: false, noCodeOutput: true,provider, model, effort,diff --git a/server/routes/apps/launchVideos.test.js b/server/routes/apps/launchVideos.test.jsindex ce8f02d1c8..fdf3a1ec7d 100644--- a/server/routes/apps/launchVideos.test.js+++ b/server/routes/apps/launchVideos.test.js@@ -9,7 +9,8 @@ import express from 'express';import { request } from '../../lib/testHelper.js';import { errorMiddleware } from '../../lib/errorHandler.js';import { getAppById } from '../../services/apps.js';-import { addTask, isRunning } from '../../services/cos.js';+import { addTask } from '../../services/cosTaskStore.js';+import { isRunning } from '../../services/cos.js';import { loadHistory } from '../../services/videoGen/history.js';import { detectMotionSkills } from '../../lib/motionSkills.js';import { resolveMusicTrackPath } from '../../services/pipeline/audioMux.js';@@ -21,7 +22,8 @@ const ffmpeg = await findFfmpeg();vi.mock('../../lib/fileUtils.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('portos-launch-publish-') }));afterAll(cleanupTempDataRoots);vi.mock('../../services/apps.js', () => ({ getAppById: vi.fn() }));-vi.mock('../../services/cos.js', () => ({ addTask: vi.fn(), isRunning: vi.fn() }));+vi.mock('../../services/cosTaskStore.js', () => ({ addTask: vi.fn() }));+vi.mock('../../services/cos.js', () => ({ isRunning: vi.fn() }));vi.mock('../../services/instanceIdentity.js', () => ({ getInstanceId: async () => 'example-instance' }));vi.mock('../../services/pipeline/audioMux.js', () => ({ resolveMusicTrackPath: vi.fn(async () => null) }));vi.mock('../../lib/beatGrid.js', () => ({ getBeatGrid: vi.fn(async () => null) }));diff --git a/server/routes/apps/pullRequests.test.js b/server/routes/apps/pullRequests.test.jsindex 0ed9637d5b..20cf7d7c9d 100644--- a/server/routes/apps/pullRequests.test.js+++ b/server/routes/apps/pullRequests.test.js@@ -13,7 +13,8 @@ vi.mock('../../services/appPullRequestMerge.js', async (importOriginal) => ({...(await importOriginal()),mergeAppPullRequest: vi.fn(),}));-vi.mock('../../services/cos.js', () => ({+vi.mock('../../services/cos.js', () => ({}));+vi.mock('../../services/cosTaskStore.js', () => ({getAllTasks: vi.fn(),}));vi.mock('../../services/codeReview.js', () => ({@@ -39,7 +40,7 @@ vi.mock('../../services/taskSchedule.js', () => ({import * as appsService from '../../services/apps.js';import { listAppPullRequests } from '../../services/appPullRequests.js';import { mergeAppPullRequest } from '../../services/appPullRequestMerge.js';-import { getAllTasks } from '../../services/cos.js';+import { getAllTasks } from '../../services/cosTaskStore.js';import { resolveReviewLoopOptions } from '../../services/codeReview.js';import { spawnReviewLoopFollowUp } from '../../services/agentWorktreeCleanup.js';import { listExternalOpenPullRequests, resolvePrReviewerTargetScope } from '../../services/prReviewerSecurity.js';diff --git a/server/routes/apps/viteTls.js b/server/routes/apps/viteTls.jsindex 0464d84ff8..00c1fea0c2 100644--- a/server/routes/apps/viteTls.js+++ b/server/routes/apps/viteTls.js@@ -12,7 +12,8 @@ import { join } from 'path';import { PATHS, atomicWrite } from '../../lib/fileUtils.js';import * as appsService from '../../services/apps.js';import { PORTOS_APP_ID } from '../../services/apps.js';-import * as cos from '../../services/cos.js';+import { addTask } from '../../services/cosTaskStore.js';+import { isRunning } from '../../services/cos.js';import { z } from 'zod';import { validateRequest } from '../../lib/validation.js';import { asyncHandler, ServerError } from '../../lib/errorHandler.js';@@ -118,14 +119,14 @@ router.post('/:id/fix-vite-hosts', loadApp, asyncHandler(async (req, res) => {const config = await findViteConfig(app.repoPath, { extraDirs });if (mode === 'ai') {- if (!cos.isRunning()) {+ if (!isRunning()) {throw new ServerError('CoS is not running — start it to use AI remediation, or use the automatic fix.',{ status: 409, code: 'COS_NOT_RUNNING' });}const where = config ? config.path : `${app.repoPath} (no vite.config found — create one)`;- const task = await cos.addTask({+ const task = await addTask({description: `Allow the Tailscale host in ${app.name}'s Vite config so its Dev UI loads`,priority: 'MEDIUM',app: app.id,diff --git a/server/routes/apps/viteTls.test.js b/server/routes/apps/viteTls.test.jsindex d9df0261ba..da9a321210 100644--- a/server/routes/apps/viteTls.test.js+++ b/server/routes/apps/viteTls.test.js@@ -12,12 +12,15 @@ vi.mock('../../services/apps.js', () => ({}));vi.mock('../../services/cos.js', () => ({- isRunning: vi.fn().mockReturnValue(true),+ isRunning: vi.fn().mockReturnValue(true)+}));+vi.mock('../../services/cosTaskStore.js', () => ({addTask: vi.fn().mockResolvedValue({ id: 'task-vite-1' })}));import * as appsService from '../../services/apps.js';-import * as cos from '../../services/cos.js';+import { addTask } from '../../services/cosTaskStore.js';+import { isRunning } from '../../services/cos.js';import { writeFileSync, readFileSync, mkdirSync, rmSync } from 'fs';import { join } from 'path';import { tmpdir } from 'os';@@ -31,8 +34,8 @@ describe('Apps Vite Dev-UI host guard', () => {app.use(express.json());app.use('/api/apps', viteTlsRoutes);vi.clearAllMocks();- cos.isRunning.mockReturnValue(true);- cos.addTask.mockResolvedValue({ id: 'task-vite-1' });+ isRunning.mockReturnValue(true);+ addTask.mockResolvedValue({ id: 'task-vite-1' });repoDir = join(tmpdir(), `vite-host-${Math.random().toString(36).slice(2)}`);mkdirSync(repoDir, { recursive: true });});@@ -109,7 +112,7 @@ describe('Apps Vite Dev-UI host guard', () => {it('ai mode queues a CoS task targeting the app', async () => {appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });- cos.isRunning.mockReturnValue(true);+ isRunning.mockReturnValue(true);const response = await request(app).post('/api/apps/app-001/fix-vite-hosts')@@ -117,7 +120,7 @@ describe('Apps Vite Dev-UI host guard', () => {expect(response.status).toBe(200);expect(response.body.taskId).toBe('task-vite-1');- expect(cos.addTask).toHaveBeenCalledWith(+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({ app: 'app-001', approvalRequired: true }),'internal');@@ -126,7 +129,7 @@ describe('Apps Vite Dev-UI host guard', () => {it('ai mode returns 409 when CoS is not running', async () => {appsService.getAppById.mockResolvedValue({ id: 'app-001', name: 'A', repoPath: repoDir });- cos.isRunning.mockReturnValue(false);+ isRunning.mockReturnValue(false);const response = await request(app).post('/api/apps/app-001/fix-vite-hosts')diff --git a/server/routes/ask.test.js b/server/routes/ask.test.jsindex d3d83946bc..d019cb0b46 100644--- a/server/routes/ask.test.js+++ b/server/routes/ask.test.js@@ -29,7 +29,7 @@ vi.mock('../services/brain.js', () => ({captureThought: vi.fn(),}));-vi.mock('../services/cos.js', () => ({+vi.mock('../services/cosTaskStore.js', () => ({addTask: vi.fn(),}));@@ -40,7 +40,7 @@ vi.mock('../services/identity.js', () => ({const convs = await import('../services/askConversations.js');const svc = await import('../services/askService.js');const brainService = await import('../services/brain.js');-const cosService = await import('../services/cos.js');+const { addTask } = await import('../services/cosTaskStore.js');const identityService = await import('../services/identity.js');const { default: routes } = await import('./ask.js');@@ -149,7 +149,7 @@ describe('POST /api/ask/:id/turns/:turnId/promote', () => {it('promotes an assistant turn to a CoS task with priority and source context', async () => {convs.getConversation.mockResolvedValue(fullConv);convs.setPromoted.mockResolvedValue({ ...fullConv, promoted: true });- cosService.addTask.mockResolvedValue({ id: 'task-1', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-1', status: 'pending' });const res = await request(makeApp()).post(`/api/ask/${convId}/turns/a1/promote`)@@ -158,7 +158,7 @@ describe('POST /api/ask/:id/turns/:turnId/promote', () => {expect(res.status).toBe(200);expect(res.body.target).toBe('task');expect(res.body.ref).toEqual({ type: 'task', id: 'task-1' });- expect(cosService.addTask).toHaveBeenCalledWith(+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({description: 'Block 30 minutes for deep work after lunch.',priority: 'HIGH',@@ -175,21 +175,21 @@ describe('POST /api/ask/:id/turns/:turnId/promote', () => {turns: [{ id: 'a1', role: 'assistant', content: longContent }],});convs.setPromoted.mockResolvedValue({ ...fullConv, promoted: true });- cosService.addTask.mockResolvedValue({ id: 'task-2' });+ addTask.mockResolvedValue({ id: 'task-2' });const res = await request(makeApp()).post(`/api/ask/${convId}/turns/a1/promote`).send({ target: 'task' });expect(res.status).toBe(200);- const description = cosService.addTask.mock.calls[0][0].description;+ const description = addTask.mock.calls[0][0].description;expect(description.length).toBeLessThanOrEqual(280);expect(description.endsWith('…')).toBe(true);});it('returns 409 when the promoted task is a duplicate', async () => {convs.getConversation.mockResolvedValue(fullConv);- cosService.addTask.mockResolvedValue({ id: 'task-existing', duplicate: true, status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-existing', duplicate: true, status: 'pending' });const res = await request(makeApp()).post(`/api/ask/${convId}/turns/a1/promote`)diff --git a/server/routes/brainLinks.test.js b/server/routes/brainLinks.test.jsindex 285546fe5f..71306b5f2b 100644--- a/server/routes/brainLinks.test.js+++ b/server/routes/brainLinks.test.js@@ -39,7 +39,7 @@ vi.mock('../services/repoCloner.js', async () => {return { isDerivedClonePath: actual.isDerivedClonePath, pullRepo: vi.fn() };});-vi.mock('../services/cos.js', () => ({ addTask: vi.fn() }));+vi.mock('../services/cosTaskStore.js', () => ({ addTask: vi.fn() }));vi.mock('../services/repoIntake.js', () => ({queueMalwareScan: vi.fn(),diff --git a/server/routes/capabilities.test.js b/server/routes/capabilities.test.jsindex 57569ae83d..e18930640c 100644--- a/server/routes/capabilities.test.js+++ b/server/routes/capabilities.test.js@@ -29,7 +29,7 @@ vi.mock('../services/messageAccounts.js', () => ({vi.mock('../services/memoryBackend.js', () => ({countMemories: vi.fn(async () => 7),}));-vi.mock('../services/cos.js', () => ({+vi.mock('../services/cosState.js', () => ({getConfig: vi.fn(async () => ({ embeddingProviderId: 'lmstudio' })),}));vi.mock('../services/voice/config.js', () => ({diff --git a/server/routes/cos.test.js b/server/routes/cos.test.jsindex cb5780c4c2..653923eeed 100644--- a/server/routes/cos.test.js+++ b/server/routes/cos.test.js@@ -33,8 +33,15 @@ vi.mock('../services/cos.js', () => ({stop: vi.fn(),pause: vi.fn(),resume: vi.fn(),- getConfig: vi.fn(),updateConfig: vi.fn(),+ listScripts: vi.fn(),+ getScript: vi.fn(),+ forceSpawnTask: vi.fn()+}));+vi.mock('../services/cosState.js', () => ({+ getConfig: vi.fn()+}));+vi.mock('../services/cosTaskStore.js', () => ({getAllTasks: vi.fn(),getUserTasks: vi.fn(),getCosTasks: vi.fn(),@@ -44,22 +51,36 @@ vi.mock('../services/cos.js', () => ({// Read by the DELETE route so the ledger row keeps the task's description.getTaskById: vi.fn(async () => null),deleteTask: vi.fn(),- approveTask: vi.fn(),- evaluateTasks: vi.fn(),+ approveTask: vi.fn()+}));+vi.mock('../services/cosTaskGenerator.js', () => ({+ evaluateTasks: vi.fn()+}));+vi.mock('../services/cosHealthMonitor.js', () => ({getHealthStatus: vi.fn(),- runHealthCheck: vi.fn(),+ runHealthCheck: vi.fn()+}));+vi.mock('../services/cosAgentLifecycle.js', () => ({cleanupZombieAgents: vi.fn(),getAgents: vi.fn(),+ getAgent: vi.fn(),+ deleteAgent: vi.fn(),+ sendBtwToAgent: vi.fn()+}));+vi.mock('../services/cosAgentIndex.js', () => ({getAgentDates: vi.fn(),getAgentsByDate: vi.fn(),- getCompletedAgentPage: vi.fn(),+ getCompletedAgentPage: vi.fn()+}));+vi.mock('../services/cosAgentFeedback.js', () => ({getPendingAgentFeedback: vi.fn(),- getAgent: vi.fn(),- deleteAgent: vi.fn(),- clearCompletedAgents: vi.fn(),submitAgentFeedback: vi.fn(),- sendBtwToAgent: vi.fn(),- getFeedbackStats: vi.fn(),+ getFeedbackStats: vi.fn()+}));+vi.mock('../services/cosAgentArchive.js', () => ({+ clearCompletedAgents: vi.fn()+}));+vi.mock('../services/cosReports.js', () => ({listReports: vi.fn(),getTodayReport: vi.fn(),getReport: vi.fn(),@@ -67,9 +88,6 @@ vi.mock('../services/cos.js', () => ({listBriefings: vi.fn(),getLatestBriefing: vi.fn(),getBriefing: vi.fn(),- listScripts: vi.fn(),- getScript: vi.fn(),- forceSpawnTask: vi.fn(),getTodayActivity: vi.fn(),getWhileAwayActivity: vi.fn(),getRecentTasks: vi.fn()@@ -138,7 +156,16 @@ vi.mock('../services/codeReview.js', () => ({}));// Import mocked modules-import * as cos from '../services/cos.js';+import { addTask, approveTask, deleteTask, reorderTasks, updateTask } from '../services/cosTaskStore.js';+import { cleanupZombieAgents, deleteAgent, getAgent, getAgents, sendBtwToAgent } from '../services/cosAgentLifecycle.js';+import { clearCompletedAgents } from '../services/cosAgentArchive.js';+import { evaluateTasks } from '../services/cosTaskGenerator.js';+import { generateReport, getBriefing, getLatestBriefing, getReport, getTodayActivity, getTodayReport, getWhileAwayActivity, listBriefings, listReports } from '../services/cosReports.js';+import { getAgentDates, getAgentsByDate, getCompletedAgentPage } from '../services/cosAgentIndex.js';+import { getConfig } from '../services/cosState.js';+import { getFeedbackStats, getPendingAgentFeedback, submitAgentFeedback } from '../services/cosAgentFeedback.js';+import { getHealthStatus, runHealthCheck } from '../services/cosHealthMonitor.js';+import { getScript, getStatus, listScripts, pause, resume, start, stop, updateConfig } from '../services/cos.js';import * as agentOrchestrator from '../services/agentOrchestrator.js';import * as appActivity from '../services/appActivity.js';import * as claudeChangelog from '../services/claudeChangelog.js';@@ -160,7 +187,7 @@ describe('CoS Routes', () => {// Reset all mocksvi.clearAllMocks();// GET /tasks settles its payload against the live agent list (#spawn window).- cos.getAgents.mockResolvedValue([]);+ getAgents.mockResolvedValue([]);});describe('GET /api/cos', () => {@@ -172,7 +199,7 @@ describe('CoS Routes', () => {config: {},stats: {}};- cos.getStatus.mockResolvedValue(mockStatus);+ getStatus.mockResolvedValue(mockStatus);const response = await request(app).get('/api/cos');@@ -184,31 +211,31 @@ describe('CoS Routes', () => {describe('POST /api/cos/start', () => {it('should start CoS daemon', async () => {- cos.start.mockResolvedValue({ success: true });+ start.mockResolvedValue({ success: true });const response = await request(app).post('/api/cos/start');expect(response.status).toBe(200);expect(response.body.success).toBe(true);- expect(cos.start).toHaveBeenCalled();+ expect(start).toHaveBeenCalled();});});describe('POST /api/cos/stop', () => {it('should stop CoS daemon', async () => {- cos.stop.mockResolvedValue({ success: true });+ stop.mockResolvedValue({ success: true });const response = await request(app).post('/api/cos/stop');expect(response.status).toBe(200);expect(response.body.success).toBe(true);- expect(cos.stop).toHaveBeenCalled();+ expect(stop).toHaveBeenCalled();});});describe('POST /api/cos/pause', () => {it('should pause CoS daemon with reason', async () => {- cos.pause.mockResolvedValue({ success: true, pausedAt: '2024-01-15T10:00:00Z' });+ pause.mockResolvedValue({ success: true, pausedAt: '2024-01-15T10:00:00Z' });const response = await request(app).post('/api/cos/pause')@@ -216,13 +243,13 @@ describe('CoS Routes', () => {expect(response.status).toBe(200);expect(response.body.success).toBe(true);- expect(cos.pause).toHaveBeenCalledWith('User requested pause');+ expect(pause).toHaveBeenCalledWith('User requested pause');});});describe('POST /api/cos/resume', () => {it('should resume CoS daemon', async () => {- cos.resume.mockResolvedValue({ success: true });+ resume.mockResolvedValue({ success: true });const response = await request(app).post('/api/cos/resume');@@ -236,7 +263,7 @@ describe('CoS Routes', () => {const mockConfig = {maxConcurrentAgents: 3};- cos.getConfig.mockResolvedValue(mockConfig);+ getConfig.mockResolvedValue(mockConfig);const response = await request(app).get('/api/cos/config');@@ -248,40 +275,40 @@ describe('CoS Routes', () => {describe('PUT /api/cos/config', () => {it('should update configuration', async () => {const updates = { maxConcurrentAgents: 5 };- cos.updateConfig.mockResolvedValue({ ...updates });+ updateConfig.mockResolvedValue({ ...updates });const response = await request(app).put('/api/cos/config').send(updates);expect(response.status).toBe(200);- expect(cos.updateConfig).toHaveBeenCalledWith(updates);+ expect(updateConfig).toHaveBeenCalledWith(updates);});it('accepts the investigation auto-approval setting', async () => {const updates = { autoApproveInvestigations: true };- cos.updateConfig.mockResolvedValue(updates);+ updateConfig.mockResolvedValue(updates);const response = await request(app).put('/api/cos/config').send(updates);expect(response.status).toBe(200);- expect(cos.updateConfig).toHaveBeenCalledWith(updates);+ expect(updateConfig).toHaveBeenCalledWith(updates);});it('validates machine-local maintainer intent without granting other capabilities', async () => {const updates = { persistentMindMaintainer: { enabled: true, appIds: ['example-app'], intervalMinutes: 60 } };- cos.updateConfig.mockResolvedValue(updates);+ updateConfig.mockResolvedValue(updates);expect((await request(app).put('/api/cos/config').send(updates)).status).toBe(200);- expect(cos.updateConfig).toHaveBeenCalledWith(updates);+ expect(updateConfig).toHaveBeenCalledWith(updates);expect((await request(app).put('/api/cos/config').send({ persistentMindMaintainer: { intervalMinutes: 0 } })).status).toBe(400);expect((await request(app).put('/api/cos/config').send({ persistentMindMaintainer: { createTasks: true } })).status).toBe(400);});it('validates the persistent mind wake cadence', async () => {const updates = { persistentMindProfile: { wakeIntervalMinutes: 60 } };- cos.updateConfig.mockResolvedValue(updates);+ updateConfig.mockResolvedValue(updates);const accepted = await request(app).put('/api/cos/config').send(updates);const rejected = await request(app).put('/api/cos/config').send({@@ -289,7 +316,7 @@ describe('CoS Routes', () => {});expect(accepted.status).toBe(200);- expect(cos.updateConfig).toHaveBeenCalledWith(updates);+ expect(updateConfig).toHaveBeenCalledWith(updates);expect(rejected.status).toBe(400);});@@ -299,13 +326,13 @@ describe('CoS Routes', () => {['immediateExecution', true],['proactiveMode', false],])('accepts but ignores the retired %s config field for older clients', async (field, value) => {- cos.updateConfig.mockResolvedValue({ maxConcurrentAgents: 5 });+ updateConfig.mockResolvedValue({ maxConcurrentAgents: 5 });const response = await request(app).put('/api/cos/config').send({ [field]: value, maxConcurrentAgents: 5 });expect(response.status).toBe(200);- expect(cos.updateConfig).toHaveBeenCalledWith({ maxConcurrentAgents: 5 });+ expect(updateConfig).toHaveBeenCalledWith({ maxConcurrentAgents: 5 });});});@@ -315,7 +342,7 @@ describe('CoS Routes', () => {description: 'Test task',priority: 'HIGH'};- cos.addTask.mockResolvedValue({+ addTask.mockResolvedValue({id: 'task-001',...taskData,status: 'pending'@@ -327,7 +354,7 @@ describe('CoS Routes', () => {expect(response.status).toBe(200);expect(response.body.id).toBe('task-001');- expect(cos.addTask).toHaveBeenCalledWith(+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({ description: 'Test task' }),'user');@@ -350,14 +377,14 @@ describe('CoS Routes', () => {{ filename: 'b-456.png', originalName: 'photo-two.png', path: '/data/cos/attachments/b-456.png', size: 200, mimeType: 'image/png' },]};- cos.addTask.mockResolvedValue({ id: 'task-002', ...taskData, status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-002', ...taskData, status: 'pending' });const response = await request(app).post('/api/cos/tasks').send(taskData);expect(response.status).toBe(200);- expect(cos.addTask).toHaveBeenCalledWith(+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({screenshots: taskData.screenshots,attachments: taskData.attachments,@@ -370,14 +397,14 @@ describe('CoS Routes', () => {describe('POST /api/cos/tasks/reorder', () => {it('should reorder tasks', async () => {const taskIds = ['task-002', 'task-001', 'task-003'];- cos.reorderTasks.mockResolvedValue({ success: true, order: taskIds });+ reorderTasks.mockResolvedValue({ success: true, order: taskIds });const response = await request(app).post('/api/cos/tasks/reorder').send({ taskIds });expect(response.status).toBe(200);- expect(cos.reorderTasks).toHaveBeenCalledWith(taskIds);+ expect(reorderTasks).toHaveBeenCalledWith(taskIds);});it('should return 400 if taskIds is missing', async () => {@@ -400,25 +427,25 @@ describe('CoS Routes', () => {describe('PUT /api/cos/tasks/:id', () => {it('should update a task', async () => {const updates = { status: 'completed' };- cos.updateTask.mockResolvedValue({ id: 'task-001', ...updates });+ updateTask.mockResolvedValue({ id: 'task-001', ...updates });const response = await request(app).put('/api/cos/tasks/task-001').send(updates);expect(response.status).toBe(200);- expect(cos.updateTask).toHaveBeenCalledWith('task-001', expect.objectContaining({ status: 'completed' }), 'user');+ expect(updateTask).toHaveBeenCalledWith('task-001', expect.objectContaining({ status: 'completed' }), 'user');});it('should update an internal task in the internal queue', async () => {- cos.updateTask.mockResolvedValue({ id: 'sys-001', model: 'gpt-5.6-terra' });+ updateTask.mockResolvedValue({ id: 'sys-001', model: 'gpt-5.6-terra' });const response = await request(app).put('/api/cos/tasks/sys-001').send({ model: 'gpt-5.6-terra', type: 'internal' });expect(response.status).toBe(200);- expect(cos.updateTask).toHaveBeenCalledWith(+ expect(updateTask).toHaveBeenCalledWith('sys-001',expect.objectContaining({ model: 'gpt-5.6-terra' }),'internal'@@ -426,7 +453,7 @@ describe('CoS Routes', () => {});it('should return 404 if task not found', async () => {- cos.updateTask.mockResolvedValue({ error: 'Task not found' });+ updateTask.mockResolvedValue({ error: 'Task not found' });const response = await request(app).put('/api/cos/tasks/task-999')@@ -436,14 +463,14 @@ describe('CoS Routes', () => {});it('should set blocker metadata when marking as blocked', async () => {- cos.updateTask.mockResolvedValue({ id: 'task-001', status: 'blocked' });+ updateTask.mockResolvedValue({ id: 'task-001', status: 'blocked' });const response = await request(app).put('/api/cos/tasks/task-001').send({ status: 'blocked', blockedReason: 'Waiting for API access' });expect(response.status).toBe(200);- expect(cos.updateTask).toHaveBeenCalledWith(+ expect(updateTask).toHaveBeenCalledWith('task-001',expect.objectContaining({status: 'blocked',@@ -454,14 +481,14 @@ describe('CoS Routes', () => {});it('should not send metadata when changing status to pending (service handles cleanup)', async () => {- cos.updateTask.mockResolvedValue({ id: 'task-001', status: 'pending' });+ updateTask.mockResolvedValue({ id: 'task-001', status: 'pending' });const response = await request(app).put('/api/cos/tasks/task-001').send({ status: 'pending' });expect(response.status).toBe(200);- const callArgs = cos.updateTask.mock.calls[0][1];+ const callArgs = updateTask.mock.calls[0][1];expect(callArgs.status).toBe('pending');expect(callArgs.metadata).toBeUndefined();});@@ -469,16 +496,16 @@ describe('CoS Routes', () => {describe('DELETE /api/cos/tasks/:id', () => {it('should delete a task', async () => {- cos.deleteTask.mockResolvedValue({ success: true, taskId: 'task-001' });+ deleteTask.mockResolvedValue({ success: true, taskId: 'task-001' });const response = await request(app).delete('/api/cos/tasks/task-001');expect(response.status).toBe(200);- expect(cos.deleteTask).toHaveBeenCalledWith('task-001', 'user');+ expect(deleteTask).toHaveBeenCalledWith('task-001', 'user');});it('should return 404 if task not found', async () => {- cos.deleteTask.mockResolvedValue({ error: 'Task not found' });+ deleteTask.mockResolvedValue({ error: 'Task not found' });const response = await request(app).delete('/api/cos/tasks/task-999');@@ -488,16 +515,16 @@ describe('CoS Routes', () => {describe('POST /api/cos/tasks/:id/approve', () => {it('should approve a task', async () => {- cos.approveTask.mockResolvedValue({ id: 'sys-001', autoApproved: true });+ approveTask.mockResolvedValue({ id: 'sys-001', autoApproved: true });const response = await request(app).post('/api/cos/tasks/sys-001/approve');expect(response.status).toBe(200);- expect(cos.approveTask).toHaveBeenCalledWith('sys-001');+ expect(approveTask).toHaveBeenCalledWith('sys-001');});it('should return 400 if task does not require approval', async () => {- cos.approveTask.mockResolvedValue({ error: 'Task does not require approval' });+ approveTask.mockResolvedValue({ error: 'Task does not require approval' });const response = await request(app).post('/api/cos/tasks/task-001/approve');@@ -507,21 +534,21 @@ describe('CoS Routes', () => {describe('POST /api/cos/evaluate', () => {it('should trigger task evaluation', async () => {- cos.evaluateTasks.mockResolvedValue();+ evaluateTasks.mockResolvedValue();const response = await request(app).post('/api/cos/evaluate');expect(response.status).toBe(200);expect(response.body.success).toBe(true);- expect(cos.evaluateTasks).toHaveBeenCalled();+ expect(evaluateTasks).toHaveBeenCalled();});});describe('GET /api/cos/agents', () => {it('should return state-resident agents without waiting for zombie cleanup', async () => {let releaseCleanup;- cos.cleanupZombieAgents.mockReturnValue(new Promise((resolve) => { releaseCleanup = resolve; }));- cos.getAgents.mockResolvedValue([+ cleanupZombieAgents.mockReturnValue(new Promise((resolve) => { releaseCleanup = resolve; }));+ getAgents.mockResolvedValue([{ id: 'agent-001', status: 'running' },{ id: 'agent-002', status: 'completed' }]);@@ -530,7 +557,7 @@ describe('CoS Routes', () => {expect(response.status).toBe(200);expect(response.body).toHaveLength(2);- expect(cos.cleanupZombieAgents).toHaveBeenCalled();+ expect(cleanupZombieAgents).toHaveBeenCalled();releaseCleanup({ cleaned: [], count: 0 });});});@@ -538,7 +565,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/agents listing projection', () => {it('strips the transcript and bounds a pasted-prompt description', async () => {const long = 'Refactor the queue. '.repeat(5000);- cos.getAgents.mockResolvedValue([+ getAgents.mockResolvedValue([{ id: 'agent-001', status: 'completed', output: ['a', 'b'], metadata: { taskDescription: long, model: 'opus' } }]);@@ -552,7 +579,7 @@ describe('CoS Routes', () => {});it('leaves a normal description unflagged so the client never hydrates for nothing', async () => {- cos.getAgents.mockResolvedValue([+ getAgents.mockResolvedValue([{ id: 'agent-001', status: 'running', metadata: { taskDescription: 'Fix the thing' } }]);@@ -565,7 +592,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/agents/history', () => {it('should return available date buckets', async () => {- cos.getAgentDates.mockResolvedValue([+ getAgentDates.mockResolvedValue([{ date: '2026-02-25', count: 5 },{ date: '2026-02-24', count: 3 }]);@@ -576,22 +603,22 @@ describe('CoS Routes', () => {expect(response.body.dates).toHaveLength(2);expect(response.body.dates[0]).toEqual({ date: '2026-02-25', count: 5 });expect(response.body).not.toHaveProperty('latest');- expect(cos.getAgentsByDate).not.toHaveBeenCalled();+ expect(getAgentsByDate).not.toHaveBeenCalled();});it('?hydrate=1 also returns the newest bucket, so the tab needs one round trip', async () => {- cos.getAgentDates.mockResolvedValue([+ getAgentDates.mockResolvedValue([{ date: '2026-02-25', count: 5 },{ date: '2026-02-24', count: 3 }]);- cos.getAgentsByDate.mockResolvedValue([+ getAgentsByDate.mockResolvedValue([{ id: 'agent-001', status: 'completed', output: ['a'], metadata: { taskDescription: 'Short' } }]);const response = await request(app).get('/api/cos/agents/history?hydrate=1');expect(response.status).toBe(200);- expect(cos.getAgentsByDate).toHaveBeenCalledWith('2026-02-25');+ expect(getAgentsByDate).toHaveBeenCalledWith('2026-02-25');expect(response.body.latest.date).toBe('2026-02-25');expect(response.body.latest.agents).toHaveLength(1);// The hydrated bucket goes through the same listing projection.@@ -599,19 +626,19 @@ describe('CoS Routes', () => {});it('hydrates to null on an install with no archived runs', async () => {- cos.getAgentDates.mockResolvedValue([]);+ getAgentDates.mockResolvedValue([]);const response = await request(app).get('/api/cos/agents/history?hydrate=1');expect(response.status).toBe(200);expect(response.body.latest).toBeNull();- expect(cos.getAgentsByDate).not.toHaveBeenCalled();+ expect(getAgentsByDate).not.toHaveBeenCalled();});});describe('GET /api/cos/agents/history/:date', () => {it('should return agents for a valid date', async () => {- cos.getAgentsByDate.mockResolvedValue([+ getAgentsByDate.mockResolvedValue([{ id: 'agent-001', status: 'completed' }]);@@ -619,7 +646,7 @@ describe('CoS Routes', () => {expect(response.status).toBe(200);expect(response.body).toHaveLength(1);- expect(cos.getAgentsByDate).toHaveBeenCalledWith('2026-02-25');+ expect(getAgentsByDate).toHaveBeenCalledWith('2026-02-25');});it('should return 400 for invalid date format', async () => {@@ -637,7 +664,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/agents/:id', () => {it('should return agent by ID', async () => {- cos.getAgent.mockResolvedValue({ id: 'agent-001', status: 'running' });+ getAgent.mockResolvedValue({ id: 'agent-001', status: 'running' });const response = await request(app).get('/api/cos/agents/agent-001');@@ -646,7 +673,7 @@ describe('CoS Routes', () => {});it('should return 404 if agent not found', async () => {- cos.getAgent.mockResolvedValue(null);+ getAgent.mockResolvedValue(null);const response = await request(app).get('/api/cos/agents/agent-999');@@ -781,16 +808,16 @@ describe('CoS Routes', () => {describe('DELETE /api/cos/agents/:id', () => {it('should delete an agent', async () => {- cos.deleteAgent.mockResolvedValue({ success: true, agentId: 'agent-001' });+ deleteAgent.mockResolvedValue({ success: true, agentId: 'agent-001' });const response = await request(app).delete('/api/cos/agents/agent-001');expect(response.status).toBe(200);- expect(cos.deleteAgent).toHaveBeenCalledWith('agent-001');+ expect(deleteAgent).toHaveBeenCalledWith('agent-001');});it('should return 404 if agent not found', async () => {- cos.deleteAgent.mockRejectedValue(new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' }));+ deleteAgent.mockRejectedValue(new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' }));const response = await request(app).delete('/api/cos/agents/agent-999');@@ -800,7 +827,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/health', () => {it('should return health status', async () => {- cos.getHealthStatus.mockResolvedValue({+ getHealthStatus.mockResolvedValue({lastCheck: '2024-01-15T10:00:00Z',issues: []});@@ -814,7 +841,7 @@ describe('CoS Routes', () => {describe('POST /api/cos/health/check', () => {it('should force health check', async () => {- cos.runHealthCheck.mockResolvedValue({+ runHealthCheck.mockResolvedValue({metrics: {},issues: []});@@ -822,13 +849,13 @@ describe('CoS Routes', () => {const response = await request(app).post('/api/cos/health/check');expect(response.status).toBe(200);- expect(cos.runHealthCheck).toHaveBeenCalled();+ expect(runHealthCheck).toHaveBeenCalled();});});describe('GET /api/cos/reports', () => {it('should list all reports', async () => {- cos.listReports.mockResolvedValue(['2024-01-15', '2024-01-14']);+ listReports.mockResolvedValue(['2024-01-15', '2024-01-14']);const response = await request(app).get('/api/cos/reports');@@ -839,7 +866,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/reports/today', () => {it('should return today report', async () => {- cos.getTodayReport.mockResolvedValue({+ getTodayReport.mockResolvedValue({date: '2024-01-15',summary: { tasksCompleted: 5 }});@@ -853,7 +880,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/reports/:date', () => {it('should return report by date', async () => {- cos.getReport.mockResolvedValue({+ getReport.mockResolvedValue({date: '2024-01-14',summary: {}});@@ -864,7 +891,7 @@ describe('CoS Routes', () => {});it('should return 404 if report not found', async () => {- cos.getReport.mockResolvedValue(null);+ getReport.mockResolvedValue(null);const response = await request(app).get('/api/cos/reports/1999-01-01');@@ -875,7 +902,7 @@ describe('CoS Routes', () => {const response = await request(app).get('/api/cos/reports/not-a-date');expect(response.status).toBe(400);- expect(cos.getReport).not.toHaveBeenCalled();+ expect(getReport).not.toHaveBeenCalled();});});@@ -915,7 +942,7 @@ describe('CoS Routes', () => {'scan'])('should create a task from slashdo command %s', async (command) => {getAppById.mockResolvedValue({ id: 'my-app', name: 'MyApp', type: 'web', repoPath: '/repo' });- cos.addTask.mockResolvedValue({ id: `task-sd-${command}`, status: 'pending' });+ addTask.mockResolvedValue({ id: `task-sd-${command}`, status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo')@@ -927,7 +954,7 @@ describe('CoS Routes', () => {// the invocation + inline the body once the provider is known — it no// longer eagerly loads the body or hardcodes `/do:` into the description// (both assumed a Claude host that can type slash commands).- const [taskData] = cos.addTask.mock.calls.at(-1);+ const [taskData] = addTask.mock.calls.at(-1);expect(taskData.slashdoCommand).toBe(command);expect(taskData.context).toBeUndefined();expect(taskData.description).not.toContain('/do:');@@ -946,7 +973,7 @@ describe('CoS Routes', () => {expect(response.status).toBe(400);expect(response.body.code).toBe('UNSUPPORTED_PLAN_ONLY_TRACKER');- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});// #3636: the catalog posture's `worktreeChangesExpected` must reach the task,@@ -964,14 +991,14 @@ describe('CoS Routes', () => {['depfree', true]])('threads the catalog deliverable posture — %s ⇒ worktreeChangesExpected %s', async (command, expected) => {getAppById.mockResolvedValue({ id: 'my-app', name: 'MyApp', type: 'web', repoPath: '/repo' });- cos.addTask.mockResolvedValue({ id: `task-wce-${command}`, status: 'pending' });+ addTask.mockResolvedValue({ id: `task-wce-${command}`, status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo').send({ command, app: 'my-app' });expect(response.status).toBe(200);- expect(cos.addTask.mock.calls.at(-1)[0].worktreeChangesExpected).toBe(expected);+ expect(addTask.mock.calls.at(-1)[0].worktreeChangesExpected).toBe(expected);});// The run drawer's removal bar reaches the bundled command as its own flag;@@ -985,14 +1012,14 @@ describe('CoS Routes', () => {['better', 'extreme', undefined]])('forwards the depfree removal bar as a command flag — %s + %s ⇒ %s', async (command, depfreeMode, slashdoArgs) => {getAppById.mockResolvedValue({ id: 'my-app', name: 'MyApp', type: 'web', repoPath: '/repo' });- cos.addTask.mockResolvedValue({ id: 'task-depfree-mode', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-depfree-mode', status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo').send({ command, app: 'my-app', ...(depfreeMode ? { depfreeMode } : {}) });expect(response.status).toBe(200);- const [taskData] = cos.addTask.mock.calls.at(-1);+ const [taskData] = addTask.mock.calls.at(-1);expect(taskData.slashdoArgs).toBe(slashdoArgs);expect(taskData.description.includes('mode)')).toBe(slashdoArgs !== undefined);});@@ -1003,19 +1030,19 @@ describe('CoS Routes', () => {.post('/api/cos/tasks/slashdo').send({ command: 'depfree', app: 'my-app', depfreeMode: 'zero' });expect(response.status).toBe(400);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('queues the SwiftUI audit for a Swift app', async () => {getAppById.mockResolvedValue({ id: 'my-ios', name: 'MyPhone', type: 'ios-native', repoPath: '/repo' });- cos.addTask.mockResolvedValue({ id: 'task-sd-swift', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-sd-swift', status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo').send({ command: 'better-swift', app: 'my-ios' });expect(response.status).toBe(200);- expect(cos.addTask.mock.calls.at(-1)[0].slashdoCommand).toBe('better-swift');+ expect(addTask.mock.calls.at(-1)[0].slashdoCommand).toBe('better-swift');});// The panel only offers the applicable one of better / better-swift, but the@@ -1033,7 +1060,7 @@ describe('CoS Routes', () => {expect(response.status).toBe(400);expect(response.body.code).toBe('WORKFLOW_APP_TYPE_MISMATCH');- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('404s an unknown app for every command, not just next', async () => {@@ -1044,7 +1071,7 @@ describe('CoS Routes', () => {.send({ command: 'push', app: 'ghost-app' });expect(response.status).toBe(404);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});// The Issues tab's Replan button: `replan` + a pinned issue is a per-issue@@ -1061,7 +1088,7 @@ describe('CoS Routes', () => {target: '42',taskMetadata: { useWorktree: false, openPR: false, noCodeOutput: true, worktreeChangesExpected: false }});- cos.addTask.mockResolvedValue({ id: 'task-replan-42', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-replan-42', status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo')@@ -1072,7 +1099,7 @@ describe('CoS Routes', () => {expect.objectContaining({ id: 'my-app' }),expect.objectContaining({ target: '42', overrideContext: 'focus on the migration' }));- const [taskData] = cos.addTask.mock.calls.at(-1);+ const [taskData] = addTask.mock.calls.at(-1);expect(taskData.prompt).toBe('REPLAN ISSUE PROMPT');// Same reason `next` carries none: the assembled prompt IS the task prompt.expect(taskData.slashdoCommand).toBeUndefined();@@ -1088,7 +1115,7 @@ describe('CoS Routes', () => {it('leaves an untargeted replan on the bundled backlog-audit workflow', async () => {getAppById.mockResolvedValue({ id: 'my-app', name: 'MyApp', type: 'web', repoPath: '/repo' });- cos.addTask.mockResolvedValue({ id: 'task-replan-all', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-replan-all', status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo')@@ -1096,7 +1123,7 @@ describe('CoS Routes', () => {expect(response.status).toBe(200);expect(buildIssueReplanTask).not.toHaveBeenCalled();- expect(cos.addTask.mock.calls.at(-1)[0].slashdoCommand).toBe('replan');+ expect(addTask.mock.calls.at(-1)[0].slashdoCommand).toBe('replan');});it('surfaces the builder\'s tracker rejection instead of queuing a run with nothing to comment on', async () => {@@ -1111,7 +1138,7 @@ describe('CoS Routes', () => {expect(response.status).toBe(400);expect(response.body.code).toBe('UNSUPPORTED_REPLAN_TRACKER');- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('does not queue a manual claim when contributor-label cleanup fails', async () => {@@ -1121,7 +1148,7 @@ describe('CoS Routes', () => {const response = await request(app).post('/api/cos/tasks/slashdo').send({ command: 'next', app: 'my-app', target: '42' });expect(response.status).toBe(502);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('routes /do:next through the app Work Tracker instead of the raw command', async () => {@@ -1133,7 +1160,7 @@ describe('CoS Routes', () => {prompt: 'CLAIM ISSUE PROMPT',taskMetadata: { useWorktree: false, openPR: false }});- cos.addTask.mockResolvedValue({ id: 'task-sd-next', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-sd-next', status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo')@@ -1144,7 +1171,7 @@ describe('CoS Routes', () => {expect(buildClaimWorkTask).toHaveBeenCalledWith(expect.objectContaining({ id: 'my-app' }), expect.any(Object));// The raw do:next body must NOT be inlined for the next command.expect(loadSlashdoCommand).not.toHaveBeenCalledWith('next');- const [taskData] = cos.addTask.mock.calls.at(-1);+ const [taskData] = addTask.mock.calls.at(-1);// The claim body is the agent PROMPT, not the one-line human note (#4153).expect(taskData.prompt).toBe('CLAIM ISSUE PROMPT');expect(taskData.context).toBeUndefined();@@ -1182,14 +1209,14 @@ describe('CoS Routes', () => {swarmCount: 6}});- cos.addTask.mockResolvedValue({ id: 'task-sd-next-reviewers', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-sd-next-reviewers', status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo').send({ command: 'next', app: 'my-app' });expect(response.status).toBe(200);- const [taskData] = cos.addTask.mock.calls.at(-1);+ const [taskData] = addTask.mock.calls.at(-1);expect(taskData).toMatchObject({reviewers: ['codex', 'claude'],usernames: ['alice'],@@ -1217,14 +1244,14 @@ describe('CoS Routes', () => {prompt: 'CLAIM ISSUE PROMPT',taskMetadata: { useWorktree: false, openPR: false, worktreeChangesExpected: false }});- cos.addTask.mockResolvedValue({ id: 'task-sd-next-wce', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-sd-next-wce', status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo').send({ command: 'next', app: 'my-app' });expect(response.status).toBe(200);- expect(cos.addTask.mock.calls.at(-1)[0].worktreeChangesExpected).toBe(false);+ expect(addTask.mock.calls.at(-1)[0].worktreeChangesExpected).toBe(false);});// …and when the claim flow says nothing, the catalog's commit-shaped default@@ -1238,14 +1265,14 @@ describe('CoS Routes', () => {prompt: 'CLAIM PLAN PROMPT',taskMetadata: { useWorktree: false, openPR: false }});- cos.addTask.mockResolvedValue({ id: 'task-sd-next-default', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-sd-next-default', status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo').send({ command: 'next', app: 'my-app' });expect(response.status).toBe(200);- expect(cos.addTask.mock.calls.at(-1)[0].worktreeChangesExpected).toBe(true);+ expect(addTask.mock.calls.at(-1)[0].worktreeChangesExpected).toBe(true);});it('threads the run drawer settings — target/author-filter/reviewers into the claim prompt, provider/model/effort/simplify onto the task', async () => {@@ -1258,7 +1285,7 @@ describe('CoS Routes', () => {taskMetadata: { useWorktree: false, openPR: false },target: '412'});- cos.addTask.mockResolvedValue({ id: 'task-sd-target', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-sd-target', status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo')@@ -1278,7 +1305,7 @@ describe('CoS Routes', () => {expect(response.status).toBe(200);expect(prepareAppIssueClaim).toHaveBeenCalledWith(expect.objectContaining({ id: 'my-app' }), '412', 'github');- expect(prepareAppIssueClaim.mock.invocationCallOrder[0]).toBeLessThan(cos.addTask.mock.invocationCallOrder[0]);+ expect(prepareAppIssueClaim.mock.invocationCallOrder[0]).toBeLessThan(addTask.mock.invocationCallOrder[0]);expect(buildClaimWorkTask).toHaveBeenCalledWith(expect.objectContaining({ id: 'my-app' }),{@@ -1299,7 +1326,7 @@ describe('CoS Routes', () => {reviewerMaxRounds: { codex: 2, ollama: 1 }});- const [taskData] = cos.addTask.mock.calls.at(-1);+ const [taskData] = addTask.mock.calls.at(-1);expect(taskData.provider).toBe('claude-cli');expect(taskData.model).toBe('claude-opus-5');expect(taskData.effort).toBe('high');@@ -1322,7 +1349,7 @@ describe('CoS Routes', () => {taskMetadata: { useWorktree: false, openPR: false, prCompletion: 'merge-on-green' },target: '412'});- cos.addTask.mockResolvedValue({ id: 'task-sd-mog', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-sd-mog', status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo')@@ -1337,7 +1364,7 @@ describe('CoS Routes', () => {expect.objectContaining({ id: 'my-app' }),expect.objectContaining({ prCompletion: 'merge-on-green' }));- const [taskData] = cos.addTask.mock.calls.at(-1);+ const [taskData] = addTask.mock.calls.at(-1);expect(taskData.prCompletion).toBe('merge-on-green');});@@ -1402,7 +1429,7 @@ describe('CoS Routes', () => {it('should return 409 for duplicate task', async () => {getAppById.mockResolvedValue({ id: 'my-app', name: 'MyApp', type: 'web', repoPath: '/repo' });- cos.addTask.mockResolvedValue({ duplicate: true, status: 'pending' });+ addTask.mockResolvedValue({ duplicate: true, status: 'pending' });const response = await request(app).post('/api/cos/tasks/slashdo')@@ -1421,7 +1448,7 @@ describe('CoS Routes', () => {getAppById.mockResolvedValue(jiraApp);getTaskPrompt.mockResolvedValue(TEMPLATE);getCodeReviewDefaults.mockResolvedValue({ reviewers: ['claude'] });- cos.addTask.mockResolvedValue({ id: 'task-jira-1', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-jira-1', status: 'pending' });const response = await request(app).post('/api/cos/tasks/jira-ticket')@@ -1431,7 +1458,7 @@ describe('CoS Routes', () => {expect(response.body.id).toBe('task-jira-1');expect(getTaskPrompt).toHaveBeenCalledWith('claim-issue-jira');- const [taskData, taskType] = cos.addTask.mock.calls.at(-1);+ const [taskData, taskType] = addTask.mock.calls.at(-1);expect(taskType).toBe('user');// Placeholders substituted, ticket constraint appended.expect(taskData.prompt).toContain('Work MyApp at /repo (app my-app); reviewers: claude.');@@ -1449,14 +1476,14 @@ describe('CoS Routes', () => {getAppById.mockResolvedValue(jiraApp);getTaskPrompt.mockResolvedValue(TEMPLATE);getCodeReviewDefaults.mockResolvedValue(null);- cos.addTask.mockResolvedValue({ id: 'task-jira-2', status: 'pending' });+ addTask.mockResolvedValue({ id: 'task-jira-2', status: 'pending' });const response = await request(app).post('/api/cos/tasks/jira-ticket').send({ app: 'my-app', ticketKey: 'proj-7' });expect(response.status).toBe(200);- const [taskData] = cos.addTask.mock.calls.at(-1);+ const [taskData] = addTask.mock.calls.at(-1);expect(taskData.description).toContain('PROJ-7');expect(taskData.prompt).toContain('PROJ-7');});@@ -1469,7 +1496,7 @@ describe('CoS Routes', () => {.send({ app: 'ghost', ticketKey: 'PROJ-1' });expect(response.status).toBe(404);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('returns 400 when JIRA is not enabled for the app', async () => {@@ -1480,7 +1507,7 @@ describe('CoS Routes', () => {.send({ app: 'my-app', ticketKey: 'PROJ-1' });expect(response.status).toBe(400);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('returns 400 for a malformed ticket key', async () => {@@ -1496,7 +1523,7 @@ describe('CoS Routes', () => {getAppById.mockResolvedValue(jiraApp);getTaskPrompt.mockResolvedValue(TEMPLATE);getCodeReviewDefaults.mockResolvedValue(null);- cos.addTask.mockResolvedValue({ duplicate: true, status: 'pending' });+ addTask.mockResolvedValue({ duplicate: true, status: 'pending' });const response = await request(app).post('/api/cos/tasks/jira-ticket')@@ -1508,7 +1535,7 @@ describe('CoS Routes', () => {describe('POST /api/cos/tasks (duplicate)', () => {it('should return 409 for duplicate task', async () => {- cos.addTask.mockResolvedValue({ duplicate: true, status: 'running' });+ addTask.mockResolvedValue({ duplicate: true, status: 'running' });const response = await request(app).post('/api/cos/tasks')@@ -1524,7 +1551,7 @@ describe('CoS Routes', () => {describe('DELETE /api/cos/agents/completed', () => {it('should clear completed agents', async () => {- cos.clearCompletedAgents.mockResolvedValue({ cleared: 3 });+ clearCompletedAgents.mockResolvedValue({ cleared: 3 });const response = await request(app).delete('/api/cos/agents/completed');@@ -1535,7 +1562,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/agents/feedback/pending', () => {it('returns the durable count and the reconciled eligible agent projection', async () => {- cos.getPendingAgentFeedback.mockResolvedValue({+ getPendingAgentFeedback.mockResolvedValue({count: 1,agents: [{ id: 'agent-001', status: 'completed', metadata: { taskType: 'user' } }],unavailable: [{ agentId: 'agent-old', availability: 'unavailable', unavailableReason: 'deleted' }],@@ -1552,14 +1579,14 @@ describe('CoS Routes', () => {describe('POST /api/cos/agents/:id/feedback', () => {it('should submit positive feedback', async () => {- cos.submitAgentFeedback.mockResolvedValue({ success: true });+ submitAgentFeedback.mockResolvedValue({ success: true });const response = await request(app).post('/api/cos/agents/agent-001/feedback').send({ rating: 'positive', comment: 'Great work' });expect(response.status).toBe(200);- expect(cos.submitAgentFeedback).toHaveBeenCalledWith('agent-001', { rating: 'positive', comment: 'Great work' });+ expect(submitAgentFeedback).toHaveBeenCalledWith('agent-001', { rating: 'positive', comment: 'Great work' });});it('should return 400 for invalid rating', async () => {@@ -1571,7 +1598,7 @@ describe('CoS Routes', () => {});it('should return 404 if agent not found', async () => {- cos.submitAgentFeedback.mockRejectedValue(new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' }));+ submitAgentFeedback.mockRejectedValue(new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' }));const response = await request(app).post('/api/cos/agents/agent-999/feedback')@@ -1581,7 +1608,7 @@ describe('CoS Routes', () => {});it('should return 400 (INVALID_STATE) when the agent is not completed', async () => {- cos.submitAgentFeedback.mockRejectedValue(new ServerError('Can only submit feedback for completed agents', { status: 400, code: 'INVALID_STATE' }));+ submitAgentFeedback.mockRejectedValue(new ServerError('Can only submit feedback for completed agents', { status: 400, code: 'INVALID_STATE' }));const response = await request(app).post('/api/cos/agents/agent-001/feedback')@@ -1594,14 +1621,14 @@ describe('CoS Routes', () => {describe('POST /api/cos/agents/:id/btw', () => {it('should send btw message to agent', async () => {- cos.sendBtwToAgent.mockResolvedValue({ success: true });+ sendBtwToAgent.mockResolvedValue({ success: true });const response = await request(app).post('/api/cos/agents/agent-001/btw').send({ message: 'Additional context here' });expect(response.status).toBe(200);- expect(cos.sendBtwToAgent).toHaveBeenCalledWith('agent-001', 'Additional context here');+ expect(sendBtwToAgent).toHaveBeenCalledWith('agent-001', 'Additional context here');});it('should return 400 for empty message', async () => {@@ -1629,7 +1656,7 @@ describe('CoS Routes', () => {});it('should return 404 if agent not found', async () => {- cos.sendBtwToAgent.mockRejectedValue(new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' }));+ sendBtwToAgent.mockRejectedValue(new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' }));const response = await request(app).post('/api/cos/agents/agent-999/btw')@@ -1639,7 +1666,7 @@ describe('CoS Routes', () => {});it('should return 400 (INVALID_STATE) when BTW is unsupported for the agent', async () => {- cos.sendBtwToAgent.mockRejectedValue(new ServerError('Agent is not running', { status: 400, code: 'INVALID_STATE' }));+ sendBtwToAgent.mockRejectedValue(new ServerError('Agent is not running', { status: 400, code: 'INVALID_STATE' }));const response = await request(app).post('/api/cos/agents/agent-001/btw')@@ -1652,7 +1679,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/feedback/stats', () => {it('should return feedback statistics', async () => {- cos.getFeedbackStats.mockResolvedValue({ total: 10, positive: 7, negative: 2, neutral: 1 });+ getFeedbackStats.mockResolvedValue({ total: 10, positive: 7, negative: 2, neutral: 1 });const response = await request(app).get('/api/cos/feedback/stats');@@ -1667,14 +1694,14 @@ describe('CoS Routes', () => {describe('POST /api/cos/reports/generate', () => {it('should generate a report', async () => {- cos.generateReport.mockResolvedValue({ date: '2026-02-25', summary: {} });+ generateReport.mockResolvedValue({ date: '2026-02-25', summary: {} });const response = await request(app).post('/api/cos/reports/generate').send({ date: '2026-02-25' });expect(response.status).toBe(200);- expect(cos.generateReport).toHaveBeenCalledWith('2026-02-25');+ expect(generateReport).toHaveBeenCalledWith('2026-02-25');});it('should reject a date that is not a bare YYYY-MM-DD day', async () => {@@ -1685,13 +1712,13 @@ describe('CoS Routes', () => {.send({ date: '2026-02-25T00:00:00.000Z' });expect(response.status).toBe(400);- expect(cos.generateReport).not.toHaveBeenCalled();+ expect(generateReport).not.toHaveBeenCalled();});});describe('GET /api/cos/briefings', () => {it('should list all briefings', async () => {- cos.listBriefings.mockResolvedValue(['2026-02-25', '2026-02-24']);+ listBriefings.mockResolvedValue(['2026-02-25', '2026-02-24']);const response = await request(app).get('/api/cos/briefings');@@ -1702,7 +1729,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/briefings/latest', () => {it('should return latest briefing', async () => {- cos.getLatestBriefing.mockResolvedValue({ date: '2026-02-25', content: 'Latest' });+ getLatestBriefing.mockResolvedValue({ date: '2026-02-25', content: 'Latest' });const response = await request(app).get('/api/cos/briefings/latest');@@ -1713,7 +1740,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/briefings/:date', () => {it('should return briefing by date', async () => {- cos.getBriefing.mockResolvedValue({ date: '2026-02-24', content: 'Briefing' });+ getBriefing.mockResolvedValue({ date: '2026-02-24', content: 'Briefing' });const response = await request(app).get('/api/cos/briefings/2026-02-24');@@ -1721,7 +1748,7 @@ describe('CoS Routes', () => {});it('should return 404 if briefing not found', async () => {- cos.getBriefing.mockResolvedValue(null);+ getBriefing.mockResolvedValue(null);const response = await request(app).get('/api/cos/briefings/1999-01-01');@@ -1732,7 +1759,7 @@ describe('CoS Routes', () => {const response = await request(app).get('/api/cos/briefings/not-a-date');expect(response.status).toBe(400);- expect(cos.getBriefing).not.toHaveBeenCalled();+ expect(getBriefing).not.toHaveBeenCalled();});});@@ -1759,7 +1786,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/scripts', () => {it('should list scripts', async () => {- cos.listScripts.mockResolvedValue([{ name: 'backup.sh' }]);+ listScripts.mockResolvedValue([{ name: 'backup.sh' }]);const response = await request(app).get('/api/cos/scripts');@@ -1770,7 +1797,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/scripts/:name', () => {it('should return script content', async () => {- cos.getScript.mockResolvedValue({ name: 'backup.sh', content: '#!/bin/bash' });+ getScript.mockResolvedValue({ name: 'backup.sh', content: '#!/bin/bash' });const response = await request(app).get('/api/cos/scripts/backup.sh');@@ -1779,7 +1806,7 @@ describe('CoS Routes', () => {});it('should return 404 if script not found', async () => {- cos.getScript.mockResolvedValue(null);+ getScript.mockResolvedValue(null);const response = await request(app).get('/api/cos/scripts/missing.sh');@@ -1789,7 +1816,7 @@ describe('CoS Routes', () => {describe('GET /api/cos/activity/today', () => {it('should return today activity summary', async () => {- cos.getTodayActivity.mockResolvedValue({ stats: { completed: 5 } });+ getTodayActivity.mockResolvedValue({ stats: { completed: 5 } });const response = await request(app).get('/api/cos/activity/today');@@ -1800,42 +1827,42 @@ describe('CoS Routes', () => {describe('GET /api/cos/activity/while-away', () => {it('passes a valid ISO since through to the service', async () => {- cos.getWhileAwayActivity.mockResolvedValue({ stats: { completed: 3 } });+ getWhileAwayActivity.mockResolvedValue({ stats: { completed: 3 } });const since = '2026-06-01T00:00:00.000Z';const response = await request(app).get(`/api/cos/activity/while-away?since=${encodeURIComponent(since)}`);expect(response.status).toBe(200);expect(response.body.stats.completed).toBe(3);- expect(cos.getWhileAwayActivity).toHaveBeenCalledWith(since);+ expect(getWhileAwayActivity).toHaveBeenCalledWith(since);});it('tolerates a garbage since (200 + service fallback, not 400)', async () => {- cos.getWhileAwayActivity.mockResolvedValue({ stats: { completed: 0 } });+ getWhileAwayActivity.mockResolvedValue({ stats: { completed: 0 } });const response = await request(app).get('/api/cos/activity/while-away?since=not-a-date');expect(response.status).toBe(200);// Malformed value is dropped to undefined so the service applies its// own 24h fallback rather than the route 400-ing the dashboard card.- expect(cos.getWhileAwayActivity).toHaveBeenCalledWith(undefined);+ expect(getWhileAwayActivity).toHaveBeenCalledWith(undefined);});it('works with no since param', async () => {- cos.getWhileAwayActivity.mockResolvedValue({ stats: { completed: 1 } });+ getWhileAwayActivity.mockResolvedValue({ stats: { completed: 1 } });const response = await request(app).get('/api/cos/activity/while-away');expect(response.status).toBe(200);- expect(cos.getWhileAwayActivity).toHaveBeenCalledWith(undefined);+ expect(getWhileAwayActivity).toHaveBeenCalledWith(undefined);});});describe('CoS scoped collections', () => {it('scopes live agents and validates completed page bounds without changing legacy lists', async () => {- cos.getAgents.mockResolvedValue([{ id: 'running', status: 'running' }, { id: 'done', status: 'completed' }]);+ getAgents.mockResolvedValue([{ id: 'running', status: 'running' }, { id: 'done', status: 'completed' }]);expect((await request(app).get('/api/cos/agents?active=1')).body.map(agent => agent.id)).toEqual(['running']);expect((await request(app).get('/api/cos/agents')).body).toHaveLength(2);- cos.getCompletedAgentPage.mockResolvedValue({ items: [{ id: 'done', output: ['private transcript'], metadata: { taskSummary: 'x'.repeat(100000), simplifySummary: 'y'.repeat(100000) } }], total: 1, nextCursor: null });+ getCompletedAgentPage.mockResolvedValue({ items: [{ id: 'done', output: ['private transcript'], metadata: { taskSummary: 'x'.repeat(100000), simplifySummary: 'y'.repeat(100000) } }], total: 1, nextCursor: null });const page = await request(app).get('/api/cos/agents/completed?limit=25');expect(page.body).toMatchObject({ items: [{ id: 'done', metadata: { taskSummaryTruncated: true, simplifySummaryTruncated: true } }], total: 1, nextCursor: null });expect(page.body.items[0]).not.toHaveProperty('output');diff --git a/server/routes/cosAgentRoutes.admissionQueue.test.js b/server/routes/cosAgentRoutes.admissionQueue.test.jsindex 3260c59f38..69cc8e7bb4 100644--- a/server/routes/cosAgentRoutes.admissionQueue.test.js+++ b/server/routes/cosAgentRoutes.admissionQueue.test.js@@ -5,7 +5,11 @@ import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';const fixture = vi.hoisted(() => ({ state: null, disk: null, queue: null, enqueued: null, read: null, origin: null, save: null }));-vi.mock('../services/cos.js', () => ({}));+vi.mock('../services/cosAgentArchive.js', () => ({}));+vi.mock('../services/cosAgentFeedback.js', () => ({}));+vi.mock('../services/cosAgentIndex.js', () => ({}));+vi.mock('../services/cosAgentLifecycle.js', () => ({}));+vi.mock('../services/cosHealthMonitor.js', () => ({}));vi.mock('../services/agentOrchestrator.js', () => ({}));vi.mock('../services/cosState.js', () => ({withStateLock: (fn) => { const result = fixture.queue(fn); fixture.enqueued?.(); return result; },diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.jsindex 295be779bb..82edc21e14 100644--- a/server/routes/cosAgentRoutes.js+++ b/server/routes/cosAgentRoutes.js@@ -4,8 +4,12 @@import { Router } from 'express';import { z } from 'zod';-import * as cos from '../services/cos.js';-// Lifecycle transitions go through the facade (#3450), not the `cos.js` barrel.+import { cleanupZombieAgents, deleteAgent, getAgent, getAgentPrompt, getAgents, sendBtwToAgent } from '../services/cosAgentLifecycle.js';+import { clearCompletedAgents } from '../services/cosAgentArchive.js';+import { getAgentDates, getAgentsByDate, getCompletedAgentPage } from '../services/cosAgentIndex.js';+import { getFeedbackStats, getPendingAgentFeedback, getPendingAgentFeedbackCount, getPendingAgentFeedbackPage, submitAgentFeedback } from '../services/cosAgentFeedback.js';+import { getHealthStatus, runHealthCheck } from '../services/cosHealthMonitor.js';+// Lifecycle transitions go through the facade (#3450).import * as agentOrchestrator from '../services/agentOrchestrator.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { toAgentListItems } from '../lib/cosAgentListProjection.js';@@ -81,13 +85,13 @@ const agentQuerySchema = z.object({// GET /api/cos/health - Get health statusrouter.get('/health', asyncHandler(async (req, res) => {- const health = await cos.getHealthStatus();+ const health = await getHealthStatus();res.json(health);}));// POST /api/cos/health/check - Force health checkrouter.post('/health/check', asyncHandler(async (req, res) => {- const result = await cos.runHealthCheck();+ const result = await runHealthCheck();res.json(result);}));@@ -100,11 +104,11 @@ router.get('/agents', asyncHandler(async (req, res) => {// The state listing is still useful while that repair runs, so keep cleanup// off the response critical path and let it complete independently; the next// normal refresh will see any repaired records.- void cos.cleanupZombieAgents().catch((err) => {+ void cleanupZombieAgents().catch((err) => {console.error(`🧹 Background zombie cleanup failed: ${err.message}`);});const { active } = validateRequest(z.object({ active: z.literal('1').optional() }), req.query);- const agents = await cos.getAgents();+ const agents = await getAgents();res.json(toAgentListItems(active ? agents.filter(agent => agent.status !== 'completed') : agents));}));@@ -115,7 +119,7 @@ const completedQuerySchema = z.object({});router.get('/agents/completed', asyncHandler(async (req, res) => {const query = validateRequest(completedQuerySchema, req.query);- const page = await cos.getCompletedAgentPage({ ...query, liveAgents: await cos.getAgents() });+ const page = await getCompletedAgentPage({ ...query, liveAgents: await getAgents() });res.json({ ...page, items: toAgentListItems(page.items) });}));@@ -131,14 +135,14 @@ const historyQuerySchema = z.object({ hydrate: z.literal('1').optional() });router.get('/agents/history', asyncHandler(async (req, res) => {const { hydrate } = validateRequest(historyQuerySchema, req.query);- const dates = await cos.getAgentDates();+ const dates = await getAgentDates();if (!hydrate) return res.json({ dates });// `latest: null` is the answer for an install with no archived runs at all —// distinct from a bucket that read back empty, which the client must not// mistake for "not hydrated" and re-request.const latestDate = dates[0]?.date;const latest = latestDate- ? { date: latestDate, agents: toAgentListItems(await cos.getAgentsByDate(latestDate)) }+ ? { date: latestDate, agents: toAgentListItems(await getAgentsByDate(latestDate)) }: null;res.json({ dates, latest });}));@@ -149,7 +153,7 @@ router.get('/agents/history/:date', asyncHandler(async (req, res) => {if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) {throw new ServerError('Invalid date format (expected YYYY-MM-DD)', { status: 400, code: 'VALIDATION_ERROR' });}- const agents = await cos.getAgentsByDate(date);+ const agents = await getAgentsByDate(date);res.json(toAgentListItems(agents));}));@@ -167,12 +171,12 @@ router.get('/agents/feedback/pending', asyncHandler(async (req, res) => {limit: z.coerce.number().int().min(1).max(100).optional(),cursor: z.string().max(512).optional(),}), req.query);- if (countOnly) return res.json({ count: await cos.getPendingAgentFeedbackCount() });+ if (countOnly) return res.json({ count: await getPendingAgentFeedbackCount() });if (limit) {- const page = await cos.getPendingAgentFeedbackPage({ limit, cursor });+ const page = await getPendingAgentFeedbackPage({ limit, cursor });return res.json({ ...page, items: toAgentListItems(page.items) });}- const pending = await cos.getPendingAgentFeedback({ includeUnavailable: true });+ const pending = await getPendingAgentFeedback({ includeUnavailable: true });res.json({count: pending.count,agents: toAgentListItems(pending.agents),@@ -183,7 +187,7 @@ router.get('/agents/feedback/pending', asyncHandler(async (req, res) => {// GET /api/cos/agents/:id - Get agent by ID (transcript hydrated as a capped tail)router.get('/agents/:id', asyncHandler(async (req, res) => {const { lines } = validateRequest(agentQuerySchema, req.query);- const agent = await cos.getAgent(req.params.id, lines ? { limit: lines } : {});+ const agent = await getAgent(req.params.id, lines ? { limit: lines } : {});if (!agent) {throw new ServerError('Agent not found', { status: 404, code: 'NOT_FOUND' });}@@ -194,7 +198,7 @@ router.get('/agents/:id', asyncHandler(async (req, res) => {// The service throws a ServerError (404) when the agent or prompt file is// missing — asyncHandler renders the standard envelope.router.get('/agents/:id/prompt', asyncHandler(async (req, res) => {- const result = await cos.getAgentPrompt(req.params.id);+ const result = await getAgentPrompt(req.params.id);res.json(result);}));@@ -252,14 +256,14 @@ router.get('/agents/:id/stats', asyncHandler(async (req, res) => {// DELETE /api/cos/agents/completed - Clear completed agents (must be before :id route)router.delete('/agents/completed', asyncHandler(async (req, res) => {- const result = await cos.clearCompletedAgents();+ const result = await clearCompletedAgents();res.json(result);}));// DELETE /api/cos/agents/:id - Delete a single agent// The service throws a ServerError (404) when the agent doesn't exist.router.delete('/agents/:id', asyncHandler(async (req, res) => {- const result = await cos.deleteAgent(req.params.id);+ const result = await deleteAgent(req.params.id);res.json(result);}));@@ -269,7 +273,7 @@ router.post('/agents/:id/feedback', asyncHandler(async (req, res) => {// The service throws a ServerError — 404 when the agent is missing, 400// (INVALID_STATE) when it isn't completed — so no result-shape mapping here.- const result = await cos.submitAgentFeedback(req.params.id, { rating, comment });+ const result = await submitAgentFeedback(req.params.id, { rating, comment });res.json(result);}));@@ -280,13 +284,13 @@ router.post('/agents/:id/btw', asyncHandler(async (req, res) => {// The service throws a ServerError — 404 when the agent is missing, 400// (INVALID_STATE) for the not-running / not-a-Claude-TUI refusals — so no// result-shape string-matching here.- const result = await cos.sendBtwToAgent(req.params.id, message);+ const result = await sendBtwToAgent(req.params.id, message);res.json(result);}));// GET /api/cos/feedback/stats - Get feedback statisticsrouter.get('/feedback/stats', asyncHandler(async (req, res) => {- const stats = await cos.getFeedbackStats();+ const stats = await getFeedbackStats();res.json(stats);}));diff --git a/server/routes/cosAgentRoutes.mergeAdmission.test.js b/server/routes/cosAgentRoutes.mergeAdmission.test.jsindex e6e9e8f86e..a83c9ec381 100644--- a/server/routes/cosAgentRoutes.mergeAdmission.test.js+++ b/server/routes/cosAgentRoutes.mergeAdmission.test.js@@ -6,7 +6,11 @@ import { errorMiddleware } from '../lib/errorHandler.js';const claimMergeAdmission = vi.hoisted(() => vi.fn(async ({ outcome }) => ({ admitted: false, released: true, outcome })));const handoffPendingMerge = vi.hoisted(() => vi.fn(async () => ({ queued: false, reason: 'handoff-owner-unverified', retryable: false })));vi.mock('../services/cosMergeHandoff.js', () => ({ handoffPendingMerge }));-vi.mock('../services/cos.js', () => ({}));+vi.mock('../services/cosAgentArchive.js', () => ({}));+vi.mock('../services/cosAgentFeedback.js', () => ({}));+vi.mock('../services/cosAgentIndex.js', () => ({}));+vi.mock('../services/cosAgentLifecycle.js', () => ({}));+vi.mock('../services/cosHealthMonitor.js', () => ({}));vi.mock('../services/agentOrchestrator.js', () => ({}));vi.mock('../services/cosMergeAdmission.js', async (importOriginal) => ({MERGE_ADMISSION_OUTCOMES: (await importOriginal()).MERGE_ADMISSION_OUTCOMES,diff --git a/server/routes/cosAgentRoutes.ownershipResponse.test.js b/server/routes/cosAgentRoutes.ownershipResponse.test.jsindex 0aa9dc6e95..e42b836cba 100644--- a/server/routes/cosAgentRoutes.ownershipResponse.test.js+++ b/server/routes/cosAgentRoutes.ownershipResponse.test.js@@ -14,7 +14,11 @@ vi.mock('../lib/checkoutRetirementAdmission.js', () => ({return work();},}));-vi.mock('../services/cos.js', () => ({}));+vi.mock('../services/cosAgentArchive.js', () => ({}));+vi.mock('../services/cosAgentFeedback.js', () => ({}));+vi.mock('../services/cosAgentIndex.js', () => ({}));+vi.mock('../services/cosAgentLifecycle.js', () => ({}));+vi.mock('../services/cosHealthMonitor.js', () => ({}));vi.mock('../services/agentOrchestrator.js', () => ({}));vi.mock('../services/apps.js', () => ({ getAppById: async () => ({ repoPath: '/synthetic/repo' }) }));vi.mock('../services/cosState.js', () => ({diff --git a/server/routes/cosInsightRoutes.js b/server/routes/cosInsightRoutes.jsindex ff6e7d794a..8d25ff0ca0 100644--- a/server/routes/cosInsightRoutes.js+++ b/server/routes/cosInsightRoutes.js@@ -4,7 +4,11 @@import { Router } from 'express';import { z } from 'zod';-import * as cos from '../services/cos.js';+import { getAgents } from '../services/cosAgentLifecycle.js';+import { getAllTasks } from '../services/cosTaskStore.js';+import { getHealthStatus, runHealthCheck } from '../services/cosHealthMonitor.js';+import { getPendingAgentFeedbackCount } from '../services/cosAgentFeedback.js';+import { getRecentTasks, getTodayActivity } from '../services/cosReports.js';import * as taskLearning from '../services/taskLearning.js';import { getActivityCalendar } from '../services/cosActivityCalendar.js';import * as goalProgress from '../services/goalProgress.js';@@ -30,14 +34,14 @@ router.get('/activity-calendar', asyncHandler(async (req, res) => {router.get('/actionable-insights', asyncHandler(async (req, res) => {const { cachedHealth } = validateRequest(z.object({ cachedHealth: z.literal('1').optional() }), req.query);const [tasksData, learningSummary, healthCheck, notificationsModule, pendingFeedbackCount, leftoverFindings, agents] = await Promise.all([- cos.getAllTasks().catch(err => { console.error(`❌ Failed to load tasks: ${err.message}`); return { user: null, cos: null }; }),+ getAllTasks().catch(err => { console.error(`❌ Failed to load tasks: ${err.message}`); return { user: null, cos: null }; }),taskLearning.getLearningInsights().catch(err => { console.error(`❌ Failed to load learning insights: ${err.message}`); return null; }),- (cachedHealth ? cos.getHealthStatus() : cos.runHealthCheck()).catch(err => { console.error(`❌ Failed to run health check: ${err.message}`); return null; }),+ (cachedHealth ? getHealthStatus() : runHealthCheck()).catch(err => { console.error(`❌ Failed to run health check: ${err.message}`); return null; }),import('../services/notifications.js').catch(err => { console.error(`❌ Failed to load notifications: ${err.message}`); return null; }),- cos.getPendingAgentFeedbackCount().catch(err => { console.error(`❌ Failed to load pending agent feedback: ${err.message}`); return 0; }),+ getPendingAgentFeedbackCount().catch(err => { console.error(`❌ Failed to load pending agent feedback: ${err.message}`); return 0; }),detectIdleLeftoverBranches().catch(err => { console.error(`❌ Failed to detect leftover branches: ${err.message}`); return []; }),// Settles the pending list against live agents — see lib/cosSpawnWindow.js.- cos.getAgents().catch(err => { console.error(`❌ Failed to load agents: ${err.message}`); return []; })+ getAgents().catch(err => { console.error(`❌ Failed to load agents: ${err.message}`); return []; })]);const runningAgents = runningAgentsByTaskId(agents);@@ -221,7 +225,7 @@ router.get('/actionable-insights', asyncHandler(async (req, res) => {// GET /api/cos/recent-tasks - Get recent completed tasks for dashboard widgetrouter.get('/recent-tasks', asyncHandler(async (req, res) => {const { limit } = parsePagination(req.query, { defaultLimit: 10, maxLimit: 500 });- const recentTasks = await cos.getRecentTasks(limit);+ const recentTasks = await getRecentTasks(limit);res.json(recentTasks);}));@@ -229,12 +233,12 @@ router.get('/recent-tasks', asyncHandler(async (req, res) => {// Combines today's activity and queue counts into one efficient call.router.get('/quick-summary', asyncHandler(async (req, res) => {const [todayActivity, tasksData, agents] = await Promise.all([- cos.getTodayActivity(),- cos.getAllTasks(),+ getTodayActivity(),+ getAllTasks(),// The dashboard widget renders this queue total beside its own "N agents// running" line, so a raw pending count showed the one task already being// worked on both — see lib/cosSpawnWindow.js.- cos.getAgents().catch(() => [])+ getAgents().catch(() => [])]);const runningAgents = runningAgentsByTaskId(agents);diff --git a/server/routes/cosInsightRoutes.test.js b/server/routes/cosInsightRoutes.test.jsindex 6ef0426e0e..4db0a69916 100644--- a/server/routes/cosInsightRoutes.test.js+++ b/server/routes/cosInsightRoutes.test.js@@ -3,12 +3,20 @@ import express from 'express';import { request } from '../lib/testHelper.js';import insightRoutes from './cosInsightRoutes.js';-vi.mock('../services/cos.js', () => ({- getAllTasks: vi.fn(),- getAgents: vi.fn(async () => []),+vi.mock('../services/cosTaskStore.js', () => ({+ getAllTasks: vi.fn()+}));+vi.mock('../services/cosAgentLifecycle.js', () => ({+ getAgents: vi.fn(async () => [])+}));+vi.mock('../services/cosHealthMonitor.js', () => ({runHealthCheck: vi.fn(),- getHealthStatus: vi.fn(),- getPendingAgentFeedbackCount: vi.fn(),+ getHealthStatus: vi.fn()+}));+vi.mock('../services/cosAgentFeedback.js', () => ({+ getPendingAgentFeedbackCount: vi.fn()+}));+vi.mock('../services/cosReports.js', () => ({getTodayActivity: vi.fn(),getRecentTasks: vi.fn()}));@@ -39,7 +47,11 @@ vi.mock('../services/notifications.js', () => ({getNotifications: vi.fn().mockResolvedValue([])}));-import * as cos from '../services/cos.js';+import { getAgents } from '../services/cosAgentLifecycle.js';+import { getAllTasks } from '../services/cosTaskStore.js';+import { getHealthStatus, runHealthCheck } from '../services/cosHealthMonitor.js';+import { getPendingAgentFeedbackCount } from '../services/cosAgentFeedback.js';+import { getRecentTasks, getTodayActivity } from '../services/cosReports.js';import * as taskLearning from '../services/taskLearning.js';import { getActivityCalendar } from '../services/cosActivityCalendar.js';import * as goalProgress from '../services/goalProgress.js';@@ -54,7 +66,7 @@ describe('CoS Insight Routes', () => {app.use(express.json());app.use('/api/cos', insightRoutes);vi.clearAllMocks();- cos.getPendingAgentFeedbackCount.mockResolvedValue(0);+ getPendingAgentFeedbackCount.mockResolvedValue(0);// clearAllMocks keeps implementations, so a per-test override would leak// into later tests — restore the default empty notification list here.notifications.getNotifications.mockResolvedValue([]);@@ -96,25 +108,25 @@ describe('CoS Insight Routes', () => {describe('GET /api/cos/actionable-insights', () => {it('refreshes event-driven insights from persisted health without running process repair', async () => {- cos.getAllTasks.mockResolvedValue({ user: null, cos: null });+ getAllTasks.mockResolvedValue({ user: null, cos: null });taskLearning.getLearningInsights.mockResolvedValue(null);- cos.getHealthStatus.mockResolvedValue({ issues: [] });+ getHealthStatus.mockResolvedValue({ issues: [] });const response = await request(app).get('/api/cos/actionable-insights?cachedHealth=1');expect(response.status).toBe(200);- expect(cos.getHealthStatus).toHaveBeenCalledTimes(1);- expect(cos.runHealthCheck).not.toHaveBeenCalled();+ expect(getHealthStatus).toHaveBeenCalledTimes(1);+ expect(runHealthCheck).not.toHaveBeenCalled();expect(response.body.insights).toEqual([]);expect(response.body.unavailableSources).toEqual([]);});it('should return actionable insights sorted by priority', async () => {- cos.getAllTasks.mockResolvedValue({+ getAllTasks.mockResolvedValue({user: { grouped: { pending: [{ id: 't1', description: 'Task' }], blocked: [] } },cos: { awaitingApproval: [{ id: 'a1', description: 'Approve me' }], grouped: { pending: [], blocked: [] } }});taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });- cos.runHealthCheck.mockResolvedValue({ issues: [] });- cos.getPendingAgentFeedbackCount.mockResolvedValue(2);+ runHealthCheck.mockResolvedValue({ issues: [] });+ getPendingAgentFeedbackCount.mockResolvedValue(2);const response = await request(app).get('/api/cos/actionable-insights');@@ -134,13 +146,13 @@ describe('CoS Insight Routes', () => {});it('surfaces leftover idle branches as a Run Now insight card', async () => {- cos.getAllTasks.mockResolvedValue({+ getAllTasks.mockResolvedValue({user: { grouped: { pending: [], blocked: [] } },cos: { awaitingApproval: [], grouped: { pending: [], blocked: [] } }});taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });- cos.runHealthCheck.mockResolvedValue({ issues: [] });- cos.getPendingAgentFeedbackCount.mockResolvedValue(0);+ runHealthCheck.mockResolvedValue({ issues: [] });+ getPendingAgentFeedbackCount.mockResolvedValue(0);detectIdleLeftoverBranches.mockResolvedValueOnce([{appId: 'app-acme', appName: 'Acme', leftoverCount: 3, states: { NEEDS_PR: 3 },branches: ['claim/one'], lastUserReconcileAt: null, agentsIdle: true,@@ -168,13 +180,13 @@ describe('CoS Insight Routes', () => {// no way to know which app to run branch-reconcile for — the card now names// every app and carries the per-app rows the banner runs from.it('names each app holding leftover branches in the multi-app card', async () => {- cos.getAllTasks.mockResolvedValue({+ getAllTasks.mockResolvedValue({user: { grouped: { pending: [], blocked: [] } },cos: { awaitingApproval: [], grouped: { pending: [], blocked: [] } }});taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });- cos.runHealthCheck.mockResolvedValue({ issues: [] });- cos.getPendingAgentFeedbackCount.mockResolvedValue(0);+ runHealthCheck.mockResolvedValue({ issues: [] });+ getPendingAgentFeedbackCount.mockResolvedValue(0);detectIdleLeftoverBranches.mockResolvedValueOnce([{ appId: 'app-acme', appName: 'Acme', leftoverCount: 4, states: { NEEDS_PR: 4 }, branches: [], lastUserReconcileAt: null, agentsIdle: true },{ appId: 'app-beta', appName: 'Beta', leftoverCount: 1, states: { WIP: 1 }, branches: [], lastUserReconcileAt: '2026-08-28T10:00:00.000Z', agentsIdle: true },@@ -192,10 +204,10 @@ describe('CoS Insight Routes', () => {// writes, so a PM2 process that failed to auto-restart banner'd at the same// muted `medium` priority as a memory warning.it('raises the health insight to critical for an error-type issue', async () => {- cos.getAllTasks.mockResolvedValue({ user: null, cos: null });+ getAllTasks.mockResolvedValue({ user: null, cos: null });taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });- cos.getPendingAgentFeedbackCount.mockResolvedValue(0);- cos.runHealthCheck.mockResolvedValue({+ getPendingAgentFeedbackCount.mockResolvedValue(0);+ runHealthCheck.mockResolvedValue({issues: [{ type: 'warning', category: 'memory', message: 'High memory usage in: example-app (900MB)' },{ type: 'error', category: 'processes', message: 'example-app failed to auto-restart' }@@ -216,10 +228,10 @@ describe('CoS Insight Routes', () => {});it('keeps a warning-only health check at medium priority', async () => {- cos.getAllTasks.mockResolvedValue({ user: null, cos: null });+ getAllTasks.mockResolvedValue({ user: null, cos: null });taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [] });- cos.getPendingAgentFeedbackCount.mockResolvedValue(0);- cos.runHealthCheck.mockResolvedValue({+ getPendingAgentFeedbackCount.mockResolvedValue(0);+ runHealthCheck.mockResolvedValue({issues: [{ type: 'warning', category: 'memory', message: 'High memory usage in: example-app (900MB)' }]});@@ -239,14 +251,14 @@ describe('CoS Insight Routes', () => {// `slice(0, 5)` entirely. Only reachable now that a health issue can// actually be `critical`.it('sorts a critical insight first and keeps it within the top-5 slice', async () => {- cos.getAllTasks.mockResolvedValue({+ getAllTasks.mockResolvedValue({user: { grouped: { pending: [], blocked: [{ id: 'b1', description: 'Blocked task' }] } },cos: { awaitingApproval: [{ id: 'a1', description: 'Approve me' }], grouped: { pending: [], blocked: [] } }});taskLearning.getLearningInsights.mockResolvedValue({ skippedTypes: [{ type: 'flaky' }] });- cos.getPendingAgentFeedbackCount.mockResolvedValue(2);+ getPendingAgentFeedbackCount.mockResolvedValue(2);notifications.getNotifications.mockResolvedValue([{ type: 'briefing_ready' }]);- cos.runHealthCheck.mockResolvedValue({+ runHealthCheck.mockResolvedValue({issues: [{ type: 'error', category: 'processes', message: 'example-app failed to auto-restart' }]});@@ -260,9 +272,9 @@ describe('CoS Insight Routes', () => {});it('keeps health observation failure visible when parallel calls fail', async () => {- cos.getAllTasks.mockRejectedValue(new Error('fail'));+ getAllTasks.mockRejectedValue(new Error('fail'));taskLearning.getLearningInsights.mockRejectedValue(new Error('fail'));- cos.runHealthCheck.mockRejectedValue(new Error('fail'));+ runHealthCheck.mockRejectedValue(new Error('fail'));const response = await request(app).get('/api/cos/actionable-insights');@@ -274,10 +286,10 @@ describe('CoS Insight Routes', () => {});it.each(['', '?cachedHealth=1'])('retains other insights while health is unavailable on %s', async query => {- cos.getAllTasks.mockResolvedValue({ user: null, cos: { awaitingApproval: [{ id: 'a1', description: 'Example approval' }] } });+ getAllTasks.mockResolvedValue({ user: null, cos: { awaitingApproval: [{ id: 'a1', description: 'Example approval' }] } });taskLearning.getLearningInsights.mockResolvedValue(null);- cos.runHealthCheck.mockRejectedValue(new Error('private failure details'));- cos.getHealthStatus.mockRejectedValue(new Error('private failure details'));+ runHealthCheck.mockRejectedValue(new Error('private failure details'));+ getHealthStatus.mockRejectedValue(new Error('private failure details'));const response = await request(app).get(`/api/cos/actionable-insights${query}`);@@ -285,33 +297,33 @@ describe('CoS Insight Routes', () => {expect(response.body.insights.map(i => i.type)).toEqual(['approval', 'health-unavailable']);expect(response.body.unavailableSources).toEqual([{ source: 'health', code: 'HEALTH_UNAVAILABLE' }]);expect(JSON.stringify(response.body)).not.toContain('private failure details');- if (query) expect(cos.runHealthCheck).not.toHaveBeenCalled();+ if (query) expect(runHealthCheck).not.toHaveBeenCalled();});});describe('GET /api/cos/recent-tasks', () => {it('should return recent tasks with default limit', async () => {- cos.getRecentTasks.mockResolvedValue([{ id: 't1' }]);+ getRecentTasks.mockResolvedValue([{ id: 't1' }]);const response = await request(app).get('/api/cos/recent-tasks');expect(response.status).toBe(200);- expect(cos.getRecentTasks).toHaveBeenCalledWith(10);+ expect(getRecentTasks).toHaveBeenCalledWith(10);});it('should respect custom limit', async () => {- cos.getRecentTasks.mockResolvedValue([]);+ getRecentTasks.mockResolvedValue([]);const response = await request(app).get('/api/cos/recent-tasks?limit=5');expect(response.status).toBe(200);- expect(cos.getRecentTasks).toHaveBeenCalledWith(5);+ expect(getRecentTasks).toHaveBeenCalledWith(5);});});describe('GET /api/cos/quick-summary', () => {it('should return combined dashboard summary', async () => {- cos.getTodayActivity.mockResolvedValue({+ getTodayActivity.mockResolvedValue({stats: { completed: 3, succeeded: 2, failed: 1, running: 0, successRate: 67 },time: { combined: '2h 30m' },isRunning: true,@@ -319,7 +331,7 @@ describe('CoS Insight Routes', () => {lastEvaluation: Date.now(),accomplishments: ['Fixed bug']});- cos.getAllTasks.mockResolvedValue({+ getAllTasks.mockResolvedValue({user: { grouped: { pending: [] } },cos: { awaitingApproval: [], grouped: { pending: [] } }});@@ -339,18 +351,18 @@ describe('CoS Insight Routes', () => {it('does not count a task its agent is already running as queued', async () => {// The dashboard widget renders this payload's queue total beside its own// "N agents running" line, so the one task being worked read as BOTH.- cos.getTodayActivity.mockResolvedValue({+ getTodayActivity.mockResolvedValue({stats: { completed: 0, succeeded: 0, failed: 0, running: 1, successRate: 0 },time: { combined: '0s' },isRunning: true,isPaused: false,lastEvaluation: Date.now()});- cos.getAllTasks.mockResolvedValue({+ getAllTasks.mockResolvedValue({user: { grouped: { pending: [{ id: 'user/42', status: 'pending' }] } },cos: { awaitingApproval: [], grouped: { pending: [] } }});- cos.getAgents.mockResolvedValue([{ id: 'agent-1', taskId: 'user/42', status: 'running', startedAt: new Date().toISOString() }]);+ getAgents.mockResolvedValue([{ id: 'agent-1', taskId: 'user/42', status: 'running', startedAt: new Date().toISOString() }]);const response = await request(app).get('/api/cos/quick-summary');diff --git a/server/routes/cosJobRoutes.js b/server/routes/cosJobRoutes.jsindex d13d5d3957..24444c43af 100644--- a/server/routes/cosJobRoutes.js+++ b/server/routes/cosJobRoutes.js@@ -3,7 +3,8 @@*/import { Router } from 'express';-import * as cos from '../services/cos.js';+import { addTask, reviveBlockedTask } from '../services/cosTaskStore.js';+import { forceSpawnTask } from '../services/cos.js';import * as autonomousJobs from '../services/autonomousJobs.js';import { checkJobGate, hasGate, getRegisteredGates } from '../services/jobGates.js';import { computeNextJobRun } from '../services/autonomousJobs/scheduler.js';@@ -220,7 +221,7 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {// metadata. addTask maps these top-level keys back onto metadata; without// them an app-scoped job triggered manually would run in the PortOS root// (the scheduled path emits the full task object via task:ready and is unaffected).- const taskResult = await cos.addTask({+ const taskResult = await addTask({// The generator's own field projection — the app scope, the git-workflow// options, the provider/model/effort pins, the job:spawned markers and the// no-change-success contract — so a manual trigger queues exactly what the@@ -246,7 +247,7 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {// with a fresh retry budget (#2614) instead of silently pointing the user// at a task that will never run; an active twin is surfaced as-is.if (taskResult.status === 'blocked') {- await cos.reviveBlockedTask(taskResult.id, { priority: task.priority, metadata: task.metadata }, 'internal');+ await reviveBlockedTask(taskResult.id, { priority: task.priority, metadata: task.metadata }, 'internal');res.json({ success: true, type: 'agent', status: 'queued', taskId: taskResult.id, revived: true });return;}@@ -267,7 +268,7 @@ router.post('/jobs/:id/trigger', asyncHandler(async (req, res) => {// leave this freshly-created task pending until a later evaluation or manual// start. Keep the task queued when the spawn cannot proceed (for example, no// capacity), but report the actionable reason instead of claiming it started.- const spawnResult = await cos.forceSpawnTask(taskResult.id);+ const spawnResult = await forceSpawnTask(taskResult.id);if (spawnResult?.error) {res.json({success: false,diff --git a/server/routes/cosJobRoutes.test.js b/server/routes/cosJobRoutes.test.jsindex e2bf3e7ebc..3aaa78e2c2 100644--- a/server/routes/cosJobRoutes.test.js+++ b/server/routes/cosJobRoutes.test.js@@ -4,8 +4,10 @@ import { request } from '../lib/testHelper.js';import { errorMiddleware } from '../lib/errorHandler.js';import jobRoutes from './cosJobRoutes.js';+vi.mock('../services/cosTaskStore.js', () => ({+ addTask: vi.fn()+}));vi.mock('../services/cos.js', () => ({- addTask: vi.fn(),forceSpawnTask: vi.fn()}));@@ -46,7 +48,8 @@ vi.mock('../services/userTimezone.js', () => ({getUserTimezone: vi.fn(),}));-import * as cos from '../services/cos.js';+import { addTask } from '../services/cosTaskStore.js';+import { forceSpawnTask } from '../services/cos.js';import * as autonomousJobs from '../services/autonomousJobs.js';import { checkJobGate, hasGate, getRegisteredGates } from '../services/jobGates.js';import { parseCronToNextRun } from '../services/eventScheduler.js';@@ -520,8 +523,8 @@ describe('CoS Job Routes', () => {autonomousJobs.isShellJob.mockReturnValue(false);autonomousJobs.isScriptJob.mockReturnValue(false);autonomousJobs.generateTaskFromJob.mockResolvedValue({ description: 'Review', priority: 'MEDIUM' });- cos.addTask.mockResolvedValue({ id: 'task-1' });- cos.forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-1' });+ addTask.mockResolvedValue({ id: 'task-1' });+ forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-1' });const response = await request(app).post('/api/cos/jobs/j1/trigger');@@ -530,7 +533,7 @@ describe('CoS Job Routes', () => {expect(response.body.status).toBe('queued');expect(response.body.started).toBe(true);expect(response.body.taskId).toBe('task-1');- expect(cos.forceSpawnTask).toHaveBeenCalledWith('task-1');+ expect(forceSpawnTask).toHaveBeenCalledWith('task-1');});it('re-aims one run with the request body values without touching the stored job', async () => {@@ -548,8 +551,8 @@ describe('CoS Job Routes', () => {autonomousJobs.isShellJob.mockReturnValue(false);autonomousJobs.isScriptJob.mockReturnValue(false);autonomousJobs.generateTaskFromJob.mockResolvedValue({ description: 'Review', priority: 'MEDIUM' });- cos.addTask.mockResolvedValue({ id: 'task-1' });- cos.forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-1' });+ addTask.mockResolvedValue({ id: 'task-1' });+ forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-1' });const response = await request(app).post('/api/cos/jobs/j1/trigger')@@ -580,8 +583,8 @@ describe('CoS Job Routes', () => {autonomousJobs.isShellJob.mockReturnValue(false);autonomousJobs.isScriptJob.mockReturnValue(false);autonomousJobs.generateTaskFromJob.mockResolvedValue({ description: 'Review', priority: 'MEDIUM' });- cos.addTask.mockResolvedValue({ id: 'task-1' });- cos.forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-1' });+ addTask.mockResolvedValue({ id: 'task-1' });+ forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-1' });await request(app).post('/api/cos/jobs/j1/trigger').send({ formValues: { subject: 'One-off subject' } });@@ -589,7 +592,7 @@ describe('CoS Job Routes', () => {// configuration rides at the end of the prompt where that key never// reaches it — so without the changed value named here, aiming this job// somewhere else while the first run is still queued is silently dropped.- expect(cos.addTask).toHaveBeenCalledWith(+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({ description: expect.stringContaining('Review — Subject: One-off subject') }),'internal',expect.anything()@@ -607,14 +610,14 @@ describe('CoS Job Routes', () => {autonomousJobs.isShellJob.mockReturnValue(false);autonomousJobs.isScriptJob.mockReturnValue(false);autonomousJobs.generateTaskFromJob.mockResolvedValue({ description: 'Review', priority: 'MEDIUM' });- cos.addTask.mockResolvedValue({ id: 'task-1' });- cos.forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-1' });+ addTask.mockResolvedValue({ id: 'task-1' });+ forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-1' });await request(app).post('/api/cos/jobs/j1/trigger').send({ formValues: { subject: 'Saved subject' } });// Re-running a job as saved is the SAME piece of work, so it must keep the// plain description and stay dedupable against the run already queued.- expect(cos.addTask).toHaveBeenCalledWith(+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({ description: 'Review' }),'internal',expect.anything()@@ -654,13 +657,13 @@ describe('CoS Job Routes', () => {prompt: 'Review\n\n## Preloaded task data\nSnapshot'}});- cos.addTask.mockResolvedValue({ id: 'task-2' });- cos.forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-2' });+ addTask.mockResolvedValue({ id: 'task-2' });+ forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-2' });const response = await request(app).post('/api/cos/jobs/j1/trigger');expect(response.status).toBe(200);- expect(cos.addTask).toHaveBeenCalledWith(+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({app: 'app-xyz',useWorktree: true,@@ -676,7 +679,7 @@ describe('CoS Job Routes', () => {'internal',{ suppressDequeue: true });- expect(cos.forceSpawnTask).toHaveBeenCalledWith('task-2');+ expect(forceSpawnTask).toHaveBeenCalledWith('task-2');});it('should preserve the no-change success contract when Run now queues an agent job', async () => {@@ -694,12 +697,12 @@ describe('CoS Job Routes', () => {noChangeSuccess: true,}});- cos.addTask.mockResolvedValue({ id: 'task-no-change' });+ addTask.mockResolvedValue({ id: 'task-no-change' });const response = await request(app).post('/api/cos/jobs/j1/trigger');expect(response.status).toBe(200);- expect(cos.addTask).toHaveBeenCalledWith(+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({ autonomousJob: true, jobId: 'j1', noChangeSuccess: true }),'internal',{ suppressDequeue: true }@@ -715,18 +718,18 @@ describe('CoS Job Routes', () => {priority: 'MEDIUM',metadata: { provider: 'anthropic', model: 'claude-opus-4-8', effort: 'high' }});- cos.addTask.mockResolvedValue({ id: 'task-3' });- cos.forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-3' });+ addTask.mockResolvedValue({ id: 'task-3' });+ forceSpawnTask.mockResolvedValue({ success: true, taskId: 'task-3' });const response = await request(app).post('/api/cos/jobs/j1/trigger');expect(response.status).toBe(200);- expect(cos.addTask).toHaveBeenCalledWith(+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({ provider: 'anthropic', model: 'claude-opus-4-8', effort: 'high' }),'internal',{ suppressDequeue: true });- expect(cos.forceSpawnTask).toHaveBeenCalledWith('task-3');+ expect(forceSpawnTask).toHaveBeenCalledWith('task-3');});it('reports a direct-spawn failure while retaining the queued task', async () => {@@ -734,8 +737,8 @@ describe('CoS Job Routes', () => {autonomousJobs.isShellJob.mockReturnValue(false);autonomousJobs.isScriptJob.mockReturnValue(false);autonomousJobs.generateTaskFromJob.mockResolvedValue({ description: 'Review', priority: 'MEDIUM' });- cos.addTask.mockResolvedValue({ id: 'task-4' });- cos.forceSpawnTask.mockResolvedValue({ error: 'No available agent slots (1/1)' });+ addTask.mockResolvedValue({ id: 'task-4' });+ forceSpawnTask.mockResolvedValue({ error: 'No available agent slots (1/1)' });const response = await request(app).post('/api/cos/jobs/j1/trigger');@@ -762,7 +765,7 @@ describe('CoS Job Routes', () => {autonomousJobs.isShellJob.mockReturnValue(false);autonomousJobs.isScriptJob.mockReturnValue(false);autonomousJobs.generateTaskFromJob.mockResolvedValue({ description: 'Review', priority: 'MEDIUM' });- cos.addTask.mockResolvedValue(null);+ addTask.mockResolvedValue(null);const response = await request(app).post('/api/cos/jobs/j1/trigger');diff --git a/server/routes/cosReportRoutes.js b/server/routes/cosReportRoutes.jsindex 8b760f42b8..d48daf2ba5 100644--- a/server/routes/cosReportRoutes.js+++ b/server/routes/cosReportRoutes.js@@ -4,7 +4,8 @@import { Router } from 'express';import { z } from 'zod';-import * as cos from '../services/cos.js';+import { generateReport, getBriefing, getLatestBriefing, getReport, getTodayActivity, getTodayReport, getWhileAwayActivity, listBriefings, listReports } from '../services/cosReports.js';+import { getScript, listScripts } from '../services/cos.js';import * as appActivity from '../services/appActivity.js';import * as claudeChangelog from '../services/claudeChangelog.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';@@ -38,20 +39,20 @@ const whileAwayQuerySchema = z.object({// GET /api/cos/reports - List all reportsrouter.get('/reports', asyncHandler(async (req, res) => {- const reports = await cos.listReports();+ const reports = await listReports();res.json(reports);}));// GET /api/cos/reports/today - Get today's reportrouter.get('/reports/today', asyncHandler(async (req, res) => {- const report = await cos.getTodayReport();+ const report = await getTodayReport();res.json(report);}));// GET /api/cos/reports/:date - Get report by daterouter.get('/reports/:date', asyncHandler(async (req, res) => {const { date } = validateRequest(dateParamSchema, req.params);- const report = await cos.getReport(date);+ const report = await getReport(date);if (!report) {throw new ServerError('Report not found', { status: 404, code: 'NOT_FOUND' });}@@ -61,26 +62,26 @@ router.get('/reports/:date', asyncHandler(async (req, res) => {// POST /api/cos/reports/generate - Generate report for daterouter.post('/reports/generate', asyncHandler(async (req, res) => {const { date } = validateRequest(generateReportSchema, req.body);- const report = await cos.generateReport(date);+ const report = await generateReport(date);res.json(report);}));// GET /api/cos/briefings - List all briefingsrouter.get('/briefings', asyncHandler(async (req, res) => {- const briefings = await cos.listBriefings();+ const briefings = await listBriefings();res.json({ briefings });}));// GET /api/cos/briefings/latest - Get latest briefingrouter.get('/briefings/latest', asyncHandler(async (req, res) => {- const briefing = await cos.getLatestBriefing();+ const briefing = await getLatestBriefing();res.json(briefing);}));// GET /api/cos/briefings/:date - Get briefing by daterouter.get('/briefings/:date', asyncHandler(async (req, res) => {const { date } = validateRequest(dateParamSchema, req.params);- const briefing = await cos.getBriefing(date);+ const briefing = await getBriefing(date);if (!briefing) {throw new ServerError('Briefing not found', { status: 404, code: 'NOT_FOUND' });}@@ -101,13 +102,13 @@ router.get('/claude-changelog/cached', asyncHandler(async (req, res) => {// GET /api/cos/scripts - List generated scriptsrouter.get('/scripts', asyncHandler(async (req, res) => {- const scripts = await cos.listScripts();+ const scripts = await listScripts();res.json(scripts);}));// GET /api/cos/scripts/:name - Get script contentrouter.get('/scripts/:name', asyncHandler(async (req, res) => {- const script = await cos.getScript(req.params.name);+ const script = await getScript(req.params.name);if (!script) {throw new ServerError('Script not found', { status: 404, code: 'NOT_FOUND' });}@@ -138,7 +139,7 @@ router.post('/app-activity/:appId/clear-cooldown', asyncHandler(async (req, res)// GET /api/cos/activity/today - Get today's activity summaryrouter.get('/activity/today', asyncHandler(async (req, res) => {- const activity = await cos.getTodayActivity();+ const activity = await getTodayActivity();res.json(activity);}));@@ -146,7 +147,7 @@ router.get('/activity/today', asyncHandler(async (req, res) => {// client's last-visit marker). Powers the "While You Were Away" dashboard card.router.get('/activity/while-away', asyncHandler(async (req, res) => {const { since } = validateRequest(whileAwayQuerySchema, req.query);- const activity = await cos.getWhileAwayActivity(since);+ const activity = await getWhileAwayActivity(since);res.json(activity);}));diff --git a/server/routes/cosStatusRoutes.js b/server/routes/cosStatusRoutes.jsindex 6281caffd3..5efe64fcc7 100644--- a/server/routes/cosStatusRoutes.js+++ b/server/routes/cosStatusRoutes.js@@ -4,7 +4,8 @@ import { persistentMindMaintainerSchema } from '../lib/persistentMindMaintainer.*/import { Router } from 'express';-import * as cos from '../services/cos.js';+import { getConfig } from '../services/cosState.js';+import { getStatus, pause, resume, start, stop, updateConfig } from '../services/cos.js';import { getAllDomainUsageToday } from '../services/domainUsage.js';import { reinitialize as reinitializeEmbeddings } from '../services/memoryEmbeddings.js';import { asyncHandler } from '../lib/errorHandler.js';@@ -121,38 +122,38 @@ export const cosConfigSchema = z.object({// GET /api/cos - Get CoS statusrouter.get('/', asyncHandler(async (req, res) => {- const status = await cos.getStatus();+ const status = await getStatus();res.json(status);}));// POST /api/cos/start - Start CoS daemonrouter.post('/start', asyncHandler(async (req, res) => {- const result = await cos.start();+ const result = await start();res.json(result);}));// POST /api/cos/stop - Stop CoS daemonrouter.post('/stop', asyncHandler(async (req, res) => {- const result = await cos.stop();+ const result = await stop();res.json(result);}));// POST /api/cos/pause - Pause CoS daemon (stays running but skips evaluations)router.post('/pause', asyncHandler(async (req, res) => {const { reason } = validateRequest(pauseSchema, req.body);- const result = await cos.pause(reason);+ const result = await pause(reason);res.json(result);}));// POST /api/cos/resume - Resume CoS daemon from pauserouter.post('/resume', asyncHandler(async (req, res) => {- const result = await cos.resume();+ const result = await resume();res.json(result);}));// GET /api/cos/config - Get configurationrouter.get('/config', asyncHandler(async (req, res) => {- const config = await cos.getConfig();+ const config = await getConfig();res.json(config);}));@@ -166,7 +167,7 @@ router.get('/budget-usage', asyncHandler(async (req, res) => {// PUT /api/cos/config - Update configurationrouter.put('/config', asyncHandler(async (req, res) => {const validated = validateRequest(cosConfigSchema, req.body);- const config = await cos.updateConfig(validated);+ const config = await updateConfig(validated);if (validated.embeddingProviderId !== undefined || validated.embeddingModel !== undefined) {reinitializeEmbeddings();}diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.jsindex 27130146bb..a6bf77fc6c 100644--- a/server/routes/cosTaskRoutes.js+++ b/server/routes/cosTaskRoutes.js@@ -6,7 +6,10 @@ import { Router } from 'express';import { z } from 'zod';import { existsSync } from 'fs';import { isRepo, notGitRepoMessage } from '../services/git.js';-import * as cos from '../services/cos.js';+import { addTask, approveTask, challengeTask, deleteTask, findTaskWithSource, getAllTasks, getCosTasks, getTaskById, getTaskView, getUserTasks, reorderTasks, resolveTaskChallenge, resolveTaskChallengeWithRecheck, updateTask } from '../services/cosTaskStore.js';+import { evaluateTasks } from '../services/cosTaskGenerator.js';+import { forceSpawnTask } from '../services/cos.js';+import { getAgents } from '../services/cosAgentLifecycle.js';import { enhanceTaskPrompt } from '../services/taskEnhancer.js';import { buildClaimWorkTask, buildIssueReplanTask, buildJiraTicketTask } from '../services/cosTaskClaimWork.js';import { getAppById, getAppWorkTracker, PORTOS_APP_ID } from '../services/apps.js';@@ -163,7 +166,7 @@ const router = Router();// too. Settling HERE rather than in `getAllTasks()` keeps the dispatch readers// (task generation, retry revival, dedup) on the raw truth they need, while// every API consumer gets an honest queue depth without knowing the window-// exists. The bounded views (`cos.getTaskView`) select from the parsed snapshot+// exists. The bounded views (`getTaskView`) select from the parsed snapshot// before cloning; only `view=full` pays for the whole store.//// With no params it returns a bounded `{ user, cos }` projection: all non-completed@@ -192,13 +195,13 @@ router.get('/tasks', asyncHandler(async (req, res) => {});// The bounded views select inside the store BEFORE cloning, so a queue refresh// never copies archived prompt bodies (#9677). Settlement runs on the selection.- const agentsPromise = cos.getAgents().catch(() => []);+ const agentsPromise = getAgents().catch(() => []);if (query.view === 'completed') {const { limit } = validateRequest(z.object({ limit: z.coerce.number().int().min(1).max(100).default(25) }), req.query);- return res.json(await cos.getTaskView({ kind: 'completed', source: query.source, cursor: query.cursor, limit }));+ return res.json(await getTaskView({ kind: 'completed', source: query.source, cursor: query.cursor, limit }));}if (query.view === 'queue') {- const [view, agents] = await Promise.all([cos.getTaskView({ kind: 'queue', selected: query.selected }), agentsPromise]);+ const [view, agents] = await Promise.all([getTaskView({ kind: 'queue', selected: query.selected }), agentsPromise]);const tasks = settleView(view, runningAgentsByTaskId(agents));// `tasks` stays whole (open queue + the selected historical task); the derived// lists shrink to id/status summaries.@@ -212,18 +215,18 @@ router.get('/tasks', asyncHandler(async (req, res) => {}if (!isPaginationRequested(req.query)) {if (query.view === 'full') {- const [allTasks, agents] = await Promise.all([cos.getAllTasks(), agentsPromise]);+ const [allTasks, agents] = await Promise.all([getAllTasks(), agentsPromise]);return res.json(settleView(allTasks, runningAgentsByTaskId(agents)));}// Bare form: bounded projection. Every non-completed task stays whole; the// completed history (96% of the bytes on a long-lived install, and once// more inside `grouped`) shrinks to the first `view=completed` page plus// `completedCount`. `view=full` is the raw-store escape hatch.- const [view, agents] = await Promise.all([cos.getTaskView({ kind: 'bare' }), agentsPromise]);+ const [view, agents] = await Promise.all([getTaskView({ kind: 'bare' }), agentsPromise]);return res.json(settleView(view, runningAgentsByTaskId(agents)));}const { limit, offset } = parsePagination(req.query, { defaultLimit: 50, maxLimit: 500 });- const [view, agents] = await Promise.all([cos.getTaskView({ kind: 'window', offset, limit }), agentsPromise]);+ const [view, agents] = await Promise.all([getTaskView({ kind: 'window', offset, limit }), agentsPromise]);const runningAgents = runningAgentsByTaskId(agents);const { totals } = view;res.json({@@ -235,13 +238,13 @@ router.get('/tasks', asyncHandler(async (req, res) => {// GET /api/cos/tasks/user - Get user tasksrouter.get('/tasks/user', asyncHandler(async (req, res) => {- const tasks = await cos.getUserTasks();+ const tasks = await getUserTasks();res.json(tasks);}));// GET /api/cos/tasks/internal - Get CoS internal tasksrouter.get('/tasks/internal', asyncHandler(async (req, res) => {- const tasks = await cos.getCosTasks();+ const tasks = await getCosTasks();res.json(tasks);}));@@ -250,7 +253,7 @@ router.get('/tasks/internal', asyncHandler(async (req, res) => {// holds, instead of re-reading the whole queue per click (#12032). Registered// after the literal /tasks/user and /tasks/internal routes so those still win.router.get('/tasks/:id', asyncHandler(async (req, res) => {- const found = await cos.findTaskWithSource(req.params.id);+ const found = await findTaskWithSource(req.params.id);if (!found) throw new ServerError('Task not found', { status: 404, code: 'NOT_FOUND' });res.json(found);}));@@ -259,7 +262,7 @@ router.get('/tasks/:id', asyncHandler(async (req, res) => {router.post('/tasks/reorder', asyncHandler(async (req, res) => {const { taskIds } = validateRequest(cosTaskReorderBodySchema, req.body);- const result = await cos.reorderTasks(taskIds);+ const result = await reorderTasks(taskIds);res.json(result);}));@@ -440,7 +443,7 @@ router.post('/tasks/slashdo', asyncHandler(async (req, res) => {simplify: simplify === true,reviewLoop: false};- const result = await cos.addTask(planTask ? { ...taskData, prompt: planTask.prompt } : taskData, 'user');+ const result = await addTask(planTask ? { ...taskData, prompt: planTask.prompt } : taskData, 'user');if (result?.duplicate) {throw new ServerError(`A task with this description is already ${result.status}`, { status: 409, code: 'DUPLICATE_TASK' });@@ -479,7 +482,7 @@ router.post('/tasks/jira-ticket', asyncHandler(async (req, res) => {simplify: false,reviewLoop: false,};- const result = await cos.addTask(taskData, 'user');+ const result = await addTask(taskData, 'user');if (result?.duplicate) {throw new ServerError(`A task for ${key} is already ${result.status}`, { status: 409, code: 'DUPLICATE_TASK' });@@ -517,7 +520,7 @@ router.post('/tasks', asyncHandler(async (req, res) => {{ ...preparedTask, fingerprint: clientInvestigationFingerprint(preparedTask) },{ taskType: type, delivery })).task- : await cos.addTask(preparedTask, type);+ : await addTask(preparedTask, type);if (result?.duplicate) {throw new ServerError(`A task with this description is already ${result.status}`, { status: 409, code: 'DUPLICATE_TASK' });@@ -569,7 +572,7 @@ router.put('/tasks/:id', asyncHandler(async (req, res) => {updates.metadata = { ...updates.metadata, blocker: blockedReason };}- const result = await cos.updateTask(id, updates, type);+ const result = await updateTask(id, updates, type);if (result?.error) {throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });}@@ -599,8 +602,8 @@ router.delete('/tasks/:id', asyncHandler(async (req, res) => {// only handle on what was thrown away would be an opaque task id.// `.catch` because this read only supplies a LABEL — a task file that will not// parse must not turn a working delete into a 500.- const doomed = await cos.getTaskById(id).catch(() => null);- const result = await cos.deleteTask(id, type);+ const doomed = await getTaskById(id).catch(() => null);+ const result = await deleteTask(id, type);if (result?.error) {throw new ServerError(result.error, { status: 404, code: 'NOT_FOUND' });}@@ -621,7 +624,7 @@ router.delete('/tasks/:id', asyncHandler(async (req, res) => {router.post('/tasks/:id/approve', asyncHandler(async (req, res) => {const { id } = req.params;- const result = await cos.approveTask(id);+ const result = await approveTask(id);if (result?.error) {throw new ServerError(result.error, { status: 400, code: 'BAD_REQUEST' });}@@ -644,7 +647,7 @@ router.post('/tasks/:id/approve', asyncHandler(async (req, res) => {router.post('/tasks/:id/challenge', asyncHandler(async (req, res) => {const { id } = req.params;const { reason, evidence, reviewer } = validateRequest(challengeTaskSchema, req.body);- const result = await cos.challengeTask(id, { reason, evidence, reviewer });+ const result = await challengeTask(id, { reason, evidence, reviewer });if (result?.error) {const status = (result.code === 'CHALLENGE_EXHAUSTED' || result.code === 'CHALLENGE_BUDGET_EXHAUSTED' || result.code === 'CANNOT_CHALLENGE_COMPLETED') ? 409: result.code === 'NOT_FOUND' ? 404 : 400;@@ -662,8 +665,8 @@ router.post('/tasks/:id/challenge/resolve', asyncHandler(async (req, res) => {const { id } = req.params;const { outcome, recheck, note, resolvedBy } = validateRequest(resolveChallengeSchema, req.body);const result = recheck- ? await cos.resolveTaskChallengeWithRecheck(id, { recheck, resolvedBy })- : await cos.resolveTaskChallenge(id, { outcome, note, resolvedBy });+ ? await resolveTaskChallengeWithRecheck(id, { recheck, resolvedBy })+ : await resolveTaskChallenge(id, { outcome, note, resolvedBy });if (result?.error) {const status = result.code === 'NOT_FOUND' ? 404: result.code === 'NOT_CHALLENGED' ? 409@@ -688,13 +691,13 @@ router.post('/goal-fidelity/false-positive', asyncHandler(async (req, res) => {// POST /api/cos/evaluate - Force task evaluationrouter.post('/evaluate', asyncHandler(async (req, res) => {- await cos.evaluateTasks();+ await evaluateTasks();res.json({ success: true, message: 'Evaluation triggered' });}));// POST /api/cos/tasks/:id/spawn - Force-spawn a pending taskrouter.post('/tasks/:id/spawn', asyncHandler(async (req, res) => {- const result = await cos.forceSpawnTask(req.params.id);+ const result = await forceSpawnTask(req.params.id);if (result.error) {const message = String(result.error);let status = 400;diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.jsindex 11847000ea..38330dff4a 100644--- a/server/routes/cosTaskRoutes.test.js+++ b/server/routes/cosTaskRoutes.test.js@@ -40,12 +40,11 @@ vi.mock('../lib/fileUtils.js', async () => {return makePathsProxy(actual, { dataRoot: tempRoot });});-vi.mock('../services/cos.js', () => ({+vi.mock('../services/cosTaskStore.js', () => ({addTask: vi.fn(),updateTask: vi.fn(),getAllTasks: vi.fn(),getTaskView: vi.fn(),- getAgents: vi.fn(),getUserTasks: vi.fn(),getCosTasks: vi.fn(),getTaskById: vi.fn(),@@ -56,8 +55,15 @@ vi.mock('../services/cos.js', () => ({challengeTask: vi.fn(),resolveTaskChallenge: vi.fn(),resolveTaskChallengeWithRecheck: vi.fn(),- evaluateTasks: vi.fn(),reviveBlockedTask: vi.fn(),+}));+vi.mock('../services/cosAgentLifecycle.js', () => ({+ getAgents: vi.fn(),+}));+vi.mock('../services/cosTaskGenerator.js', () => ({+ evaluateTasks: vi.fn(),+}));+vi.mock('../services/cos.js', () => ({forceSpawnTask: vi.fn(),}));vi.mock('../services/taskEnhancer.js', () => ({ enhanceTaskPrompt: vi.fn() }));@@ -71,7 +77,9 @@ vi.mock('../services/instances.js', () => ({ getAssignableInstances: vi.fn() }))vi.mock('../services/managedAppRepositories.js', () => ({ resolveManagedAppIssueTarget: vi.fn() }));vi.mock('../services/goalFidelityCalibration.js', () => ({ reportGoalFidelityFalsePositive: vi.fn() }));-import * as cos from '../services/cos.js';+import { addTask, approveTask, deleteTask, findTaskWithSource, getAllTasks, getTaskById, getTaskView, getUserTasks, updateTask } from '../services/cosTaskStore.js';+import { forceSpawnTask } from '../services/cos.js';+import { getAgents } from '../services/cosAgentLifecycle.js';import { getAssignableInstances } from '../services/instances.js';import { getAppById, getAppWorkTracker } from '../services/apps.js';import { resolveManagedAppIssueTarget } from '../services/managedAppRepositories.js';@@ -102,12 +110,12 @@ beforeEach(() => {{ instanceId: SELF, name: 'workstation', isSelf: true },{ instanceId: PEER, name: 'render-box', isSelf: false },]);- cos.addTask.mockImplementation(async (taskData) => ({ id: 'task-1', ...taskData }));- cos.getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });- cos.getAgents.mockResolvedValue([]);+ addTask.mockImplementation(async (taskData) => ({ id: 'task-1', ...taskData }));+ getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } });+ getAgents.mockResolvedValue([]);// The producer's storm counter is module state shared across this file's cases.__resetInvestigationCircuit();- cos.updateTask.mockResolvedValue({ id: 'task-1' });+ updateTask.mockResolvedValue({ id: 'task-1' });getAppById.mockResolvedValue({ id: 'portos-default', name: 'PortOS', repoPath: '/example/portos' });resolveManagedAppIssueTarget.mockResolvedValue({role: 'upstream',@@ -128,39 +136,39 @@ describe('CoS task collection selectors', () => {expect(res.status).toBe(400);expect(res.body.code).toBe('VALIDATION_ERROR');- expect(cos.addTask).not.toHaveBeenCalled();- expect(cos.updateTask).not.toHaveBeenCalled();- expect(cos.deleteTask).not.toHaveBeenCalled();- expect(cos.getTaskById).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();+ expect(updateTask).not.toHaveBeenCalled();+ expect(deleteTask).not.toHaveBeenCalled();+ expect(getTaskById).not.toHaveBeenCalled();expect(await listUserActions()).toEqual([]);});it('deletes from the explicitly selected internal collection', async () => {- cos.getTaskById.mockResolvedValue({ id: 'sys-example', description: 'Example task' });- cos.deleteTask.mockResolvedValue({ success: true, taskId: 'sys-example' });+ getTaskById.mockResolvedValue({ id: 'sys-example', description: 'Example task' });+ deleteTask.mockResolvedValue({ success: true, taskId: 'sys-example' });const res = await request(buildApp()).delete('/api/cos/tasks/sys-example?type=internal');expect(res.status).toBe(200);- expect(cos.deleteTask).toHaveBeenCalledWith('sys-example', 'internal');+ expect(deleteTask).toHaveBeenCalledWith('sys-example', 'internal');});});describe('GET /api/cos/tasks/:id', () => {it('returns the task as stored with its source queue', async () => {const task = { id: 'task-old', description: 'Example archived task', status: 'completed', taskType: 'documentation' };- cos.findTaskWithSource.mockResolvedValue({ task, source: 'user' });+ findTaskWithSource.mockResolvedValue({ task, source: 'user' });const res = await request(buildApp()).get('/api/cos/tasks/task-old');expect(res.status).toBe(200);expect(res.body).toEqual({ task, source: 'user' });- expect(cos.findTaskWithSource).toHaveBeenCalledWith('task-old');+ expect(findTaskWithSource).toHaveBeenCalledWith('task-old');});it('is a 404 for an unknown id and never shadows the literal list routes', async () => {- cos.findTaskWithSource.mockResolvedValue(null);- cos.getUserTasks.mockResolvedValue({ tasks: [] });+ findTaskWithSource.mockResolvedValue(null);+ getUserTasks.mockResolvedValue({ tasks: [] });const missing = await request(buildApp()).get('/api/cos/tasks/no-such-task');expect(missing.status).toBe(404);@@ -168,7 +176,7 @@ describe('GET /api/cos/tasks/:id', () => {const list = await request(buildApp()).get('/api/cos/tasks/user');expect(list.status).toBe(200);- expect(cos.findTaskWithSource).toHaveBeenCalledTimes(1);+ expect(findTaskWithSource).toHaveBeenCalledTimes(1);});});@@ -177,8 +185,8 @@ describe('CoS task responses after action-ledger failures', () => {const ledgerPath = join(tempRoot, 'user-action-events.json');mkdirSync(ledgerPath);const log = vi.spyOn(console, 'error').mockImplementation(() => {});- cos.getTaskById.mockResolvedValue({ id: 'task-1', description: 'Example task' });- cos.deleteTask.mockResolvedValue({ success: true, taskId: 'task-1' });+ getTaskById.mockResolvedValue({ id: 'task-1', description: 'Example task' });+ deleteTask.mockResolvedValue({ success: true, taskId: 'task-1' });try {const url = method === 'post' ? '/api/cos/tasks' : '/api/cos/tasks/task-1';@@ -199,21 +207,21 @@ describe('POST /api/cos/tasks — managed app completion defaults', () => {getAppById.mockResolvedValue({ id: 'example-app', defaultPrCompletion: policy });const res = await request(buildApp()).post('/api/cos/tasks').send({ description: 'Example fix', app: 'example-app', useWorktree: true });expect(res.status).toBe(200);- expect(cos.addTask.mock.calls[0][0].prCompletion).toBe(policy ?? 'review-then-merge');+ expect(addTask.mock.calls[0][0].prCompletion).toBe(policy ?? 'review-then-merge');});it.each(['draft', 'leave-open'])('preserves explicit %s over app automatic merge', async policy => {getAppById.mockResolvedValue({ id: 'example-app', defaultPrCompletion: 'review-then-merge' });const res = await request(buildApp()).post('/api/cos/tasks').send({ description: 'Example fix', app: 'example-app', openPR: true, prCompletion: policy });expect(res.status).toBe(200);- expect(cos.addTask.mock.calls[0][0].prCompletion).toBe(policy);+ expect(addTask.mock.calls[0][0].prCompletion).toBe(policy);});it('does not add a PR completion policy when the caller explicitly disables PR creation', async () => {getAppById.mockResolvedValue({ id: 'example-app', defaultPrCompletion: 'review-then-merge' });const res = await request(buildApp()).post('/api/cos/tasks').send({ description: 'Example fix', app: 'example-app', useWorktree: true, openPR: false });expect(res.status).toBe(200);- expect(cos.addTask.mock.calls[0][0]).not.toHaveProperty('prCompletion');+ expect(addTask.mock.calls[0][0]).not.toHaveProperty('prCompletion');});});@@ -223,7 +231,7 @@ describe('POST /api/cos/tasks — targetInstanceId (#4520)', () => {.post('/api/cos/tasks').send({ description: 'render the shot', targetInstanceId: PEER });expect(res.status).toBe(200);- expect(cos.addTask).toHaveBeenCalledWith(expect.objectContaining({ targetInstanceId: PEER }), 'user');+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({ targetInstanceId: PEER }), 'user');});it('rejects a pin naming an instance this install does not know', async () => {@@ -231,14 +239,14 @@ describe('POST /api/cos/tasks — targetInstanceId (#4520)', () => {.post('/api/cos/tasks').send({ description: 'render the shot', targetInstanceId: 'ghost-instance-id' });expect(res.status).toBe(400);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('creates an unpinned task without consulting the registry', async () => {const res = await request(buildApp()).post('/api/cos/tasks').send({ description: 'anywhere' });expect(res.status).toBe(200);expect(getAssignableInstances).not.toHaveBeenCalled();- expect(cos.addTask.mock.calls[0][0].targetInstanceId).toBeUndefined();+ expect(addTask.mock.calls[0][0].targetInstanceId).toBeUndefined();});});@@ -250,7 +258,7 @@ describe('CoS task routes — orchestration profiles (#5992)', () => {.post('/api/cos/tasks').send({ description: 'refactor the resolver', orchestrationMode: 'orchestrated', orchestrationProfile: PROFILE });expect(res.status).toBe(200);- expect(cos.addTask).toHaveBeenCalledWith(+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({ orchestrationMode: 'orchestrated', orchestrationProfile: PROFILE }),'user');@@ -261,7 +269,7 @@ describe('CoS task routes — orchestration profiles (#5992)', () => {.post('/api/cos/tasks').send({ description: 'x', orchestrationProfile: { saboteur: { model: 'evil' } } });expect(res.status).toBe(400);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('rejects an effort rung outside the supported ladder', async () => {@@ -275,19 +283,19 @@ describe('CoS task routes — orchestration profiles (#5992)', () => {const app = buildApp();const flip = await request(app).put('/api/cos/tasks/task-1').send({ orchestrationMode: 'orchestrated' });expect(flip.status).toBe(200);- expect(cos.updateTask.mock.calls[0][1]).toHaveProperty('orchestrationMode', 'orchestrated');+ expect(updateTask.mock.calls[0][1]).toHaveProperty('orchestrationMode', 'orchestrated');- cos.updateTask.mockClear();+ updateTask.mockClear();const clear = await request(app).put('/api/cos/tasks/task-1').send({ orchestrationMode: '' });expect(clear.status).toBe(200);- expect(cos.updateTask.mock.calls[0][1]).toHaveProperty('orchestrationMode', null);+ expect(updateTask.mock.calls[0][1]).toHaveProperty('orchestrationMode', null);});it('leaves the pins untouched when the patch omits them', async () => {const res = await request(buildApp()).put('/api/cos/tasks/task-1').send({ description: 'new title' });expect(res.status).toBe(200);- expect(cos.updateTask.mock.calls[0][1]).not.toHaveProperty('orchestrationMode');- expect(cos.updateTask.mock.calls[0][1]).not.toHaveProperty('orchestrationProfile');+ expect(updateTask.mock.calls[0][1]).not.toHaveProperty('orchestrationMode');+ expect(updateTask.mock.calls[0][1]).not.toHaveProperty('orchestrationProfile');});});@@ -300,7 +308,7 @@ describe('POST /api/cos/tasks — client-queued investigations (#6043)', () => {.send({ description: INSTALL_FAILURE, isInvestigation: true });expect(res.status).toBe(200);- expect(cos.addTask).toHaveBeenCalledWith(expect.objectContaining({+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({description: INSTALL_FAILURE,// Recognized by isInvestigationTask() — which is also the meta-cascade// guard, so a failure of THIS task cannot file an investigation of itself.@@ -315,7 +323,7 @@ describe('POST /api/cos/tasks — client-queued investigations (#6043)', () => {.post('/api/cos/tasks').send({ description: INSTALL_FAILURE, isInvestigation: true });- expect(cos.addTask).toHaveBeenCalledWith(expect.objectContaining({+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({useWorktree: true,openPR: true,prCompletion: 'review-then-merge',@@ -332,7 +340,7 @@ describe('POST /api/cos/tasks — client-queued investigations (#6043)', () => {investigationFingerprint: 'auth-error:provider-failure:Example CLI',});- const filed = cos.addTask.mock.calls[0][0];+ const filed = addTask.mock.calls[0][0];expect(filed.investigationFingerprint).toBe(clientInvestigationFingerprint({ description: INSTALL_FAILURE }));expect(filed.investigationFingerprint).not.toBe('auth-error:provider-failure:Example CLI');});@@ -342,7 +350,7 @@ describe('POST /api/cos/tasks — client-queued investigations (#6043)', () => {await request(app).post('/api/cos/tasks').send({ description: INSTALL_FAILURE, isInvestigation: true });await request(app).post('/api/cos/tasks').send({ description: 'Fix Other Runtime installer failure', isInvestigation: true });- const [first, second] = cos.addTask.mock.calls.map(call => call[0].investigationFingerprint);+ const [first, second] = addTask.mock.calls.map(call => call[0].investigationFingerprint);expect(first).not.toBe(second);expect(clientInvestigationFingerprint({ description: INSTALL_FAILURE })).toBe(first);});@@ -358,12 +366,12 @@ describe('POST /api/cos/tasks — client-queued investigations (#6043)', () => {expect(res.status).toBe(400);expect(res.body.code).toBe('NOT_A_GIT_REPO');expect(res.body.error).toContain('Example App is not a git repository');- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('leaves an ordinary task untouched by the investigation path', async () => {await request(buildApp()).post('/api/cos/tasks').send({ description: 'Render the opening shot' });- const filed = cos.addTask.mock.calls[0][0];+ const filed = addTask.mock.calls[0][0];expect(filed).not.toHaveProperty('isInvestigation');expect(filed).not.toHaveProperty('investigationFingerprint');});@@ -384,7 +392,7 @@ describe('POST /api/cos/tasks — client-queued investigations (#6043)', () => {});it('still reports the store duplicate as a 409 so the button can say the task already exists', async () => {- cos.addTask.mockResolvedValue({ id: 'task-1', status: 'pending', duplicate: true });+ addTask.mockResolvedValue({ id: 'task-1', status: 'pending', duplicate: true });const res = await request(buildApp()).post('/api/cos/tasks').send({ description: INSTALL_FAILURE, isInvestigation: true });@@ -403,7 +411,7 @@ describe('POST /api/cos/tasks — plan-only tracker gate', () => {expect(res.status).toBe(400);expect(res.body.code).toBe('UNSUPPORTED_PLAN_ONLY_TRACKER');- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('allows issue-only planning for a GitLab tracker', async () => {@@ -414,7 +422,7 @@ describe('POST /api/cos/tasks — plan-only tracker gate', () => {.send({ description: 'plan the change', app: 'gitlab-app', planOnly: true });expect(res.status).toBe(200);- expect(cos.addTask).toHaveBeenCalledWith(expect.objectContaining({ planOnly: true }), 'user');+ expect(addTask).toHaveBeenCalledWith(expect.objectContaining({ planOnly: true }), 'user');});it('pins plan-only GitHub commands to the detected upstream repository', async () => {@@ -429,8 +437,8 @@ describe('POST /api/cos/tasks — plan-only tracker gate', () => {expect.objectContaining({ repoPath: '/example/portos' }),'upstream',);- expect(cos.addTask.mock.calls[0][0].prompt).toContain('github.com/example-org/example-app');- expect(cos.addTask.mock.calls[0][0].prompt).toContain('canonical upstream');+ expect(addTask.mock.calls[0][0].prompt).toContain('github.com/example-org/example-app');+ expect(addTask.mock.calls[0][0].prompt).toContain('canonical upstream');});it('honors a deliberate origin target for a plan-only task', async () => {@@ -445,12 +453,12 @@ describe('POST /api/cos/tasks — plan-only tracker gate', () => {expect(res.status).toBe(200);expect(resolveManagedAppIssueTarget).toHaveBeenCalledWith(expect.anything(), 'origin');- expect(cos.addTask.mock.calls[0][0].prompt).toContain('configured origin');+ expect(addTask.mock.calls[0][0].prompt).toContain('configured origin');});});describe('PUT /api/cos/tasks/:id — targetInstanceId (#4520)', () => {- const metadataOf = () => cos.updateTask.mock.calls[0][1].metadata;+ const metadataOf = () => updateTask.mock.calls[0][1].metadata;it('re-pins a task to a known instance', async () => {const res = await request(buildApp()).put('/api/cos/tasks/task-1').send({ targetInstanceId: PEER });@@ -473,13 +481,13 @@ describe('PUT /api/cos/tasks/:id — targetInstanceId (#4520)', () => {it('leaves the pin untouched when the field is absent from the patch', async () => {const res = await request(buildApp()).put('/api/cos/tasks/task-1').send({ description: 'new title' });expect(res.status).toBe(200);- expect(cos.updateTask.mock.calls[0][1].metadata).toBeUndefined();+ expect(updateTask.mock.calls[0][1].metadata).toBeUndefined();});it('rejects a re-pin to an unknown instance without writing anything', async () => {const res = await request(buildApp()).put('/api/cos/tasks/task-1').send({ targetInstanceId: 'ghost-instance-id' });expect(res.status).toBe(400);- expect(cos.updateTask).not.toHaveBeenCalled();+ expect(updateTask).not.toHaveBeenCalled();});it('keeps the blocked reason alongside a pin change rather than overwriting it', async () => {@@ -540,7 +548,7 @@ describe('CoS task routes write operator-action rows (#5594)', () => {});it('records nothing when the create is refused as a duplicate', async () => {- cos.addTask.mockResolvedValueOnce({ id: 'task-1', duplicate: true, status: 'pending' });+ addTask.mockResolvedValueOnce({ id: 'task-1', duplicate: true, status: 'pending' });const res = await request(buildApp()).post('/api/cos/tasks').send({ description: 'Render the opening shot' });expect(res.status).toBe(409);expect(await listUserActions()).toEqual([]);@@ -560,8 +568,8 @@ describe('CoS task routes write operator-action rows (#5594)', () => {});it('records cos.task.delete with the description the task had before it was removed', async () => {- cos.getTaskById.mockResolvedValue({ id: 'task-1', description: 'Render the opening shot' });- cos.deleteTask.mockResolvedValue({ success: true, taskId: 'task-1' });+ getTaskById.mockResolvedValue({ id: 'task-1', description: 'Render the opening shot' });+ deleteTask.mockResolvedValue({ success: true, taskId: 'task-1' });const res = await request(buildApp()).delete('/api/cos/tasks/task-1');@@ -572,8 +580,8 @@ describe('CoS task routes write operator-action rows (#5594)', () => {});it('records cos.task.approve and cos.task.spawn', async () => {- cos.approveTask.mockResolvedValue({ id: 'sys-1', description: 'Nightly sweep' });- cos.forceSpawnTask.mockResolvedValue({ success: true });+ approveTask.mockResolvedValue({ id: 'sys-1', description: 'Nightly sweep' });+ forceSpawnTask.mockResolvedValue({ success: true });expect((await request(buildApp()).post('/api/cos/tasks/sys-1/approve')).status).toBe(200);expect((await request(buildApp()).post('/api/cos/tasks/sys-1/spawn')).status).toBe(200);@@ -585,7 +593,7 @@ describe('CoS task routes write operator-action rows (#5594)', () => {});it('records nothing when the mutation itself failed', async () => {- cos.updateTask.mockResolvedValueOnce({ error: 'Task not found' });+ updateTask.mockResolvedValueOnce({ error: 'Task not found' });expect((await request(buildApp()).put('/api/cos/tasks/ghost').send({ priority: 'HIGH' })).status).toBe(404);expect(await listUserActions()).toEqual([]);});@@ -605,12 +613,12 @@ describe('GET /api/cos/tasks — the spawn window (lib/cosSpawnWindow.js)', () =const store = () => ({ user: source(), cos: { tasks: [], grouped: { pending: [], in_progress: [] } } });beforeEach(() => {- cos.getAllTasks.mockResolvedValue(store());- cos.getTaskView.mockResolvedValue(store());+ getAllTasks.mockResolvedValue(store());+ getTaskView.mockResolvedValue(store());});it('regroups a task its agent already holds and stamps it spawning', async () => {- cos.getAgents.mockResolvedValue([live('user/42')]);+ getAgents.mockResolvedValue([live('user/42')]);const res = await request(buildApp()).get('/api/cos/tasks');@@ -625,7 +633,7 @@ describe('GET /api/cos/tasks — the spawn window (lib/cosSpawnWindow.js)', () =it('leaves the queue alone when the agent list cannot be read', async () => {// Over-reporting the queue is the safe direction: a failed probe may not be// what hides a task the user is waiting on.- cos.getAgents.mockRejectedValue(new Error('state unreadable'));+ getAgents.mockRejectedValue(new Error('state unreadable'));const res = await request(buildApp()).get('/api/cos/tasks');@@ -646,21 +654,21 @@ describe('GET /api/cos/tasks — bounded view routing (#9677)', () => {const empty = { tasks: [], grouped: {}, exists: false };it('bare view reads the bounded reader, never the raw store, and settles the selection', async () => {- cos.getTaskView.mockResolvedValue({ user: { ...open(), completedCount: 40, completedNextCursor: 'user/09' }, cos: empty });- cos.getAgents.mockResolvedValue([live('user/1')]);+ getTaskView.mockResolvedValue({ user: { ...open(), completedCount: 40, completedNextCursor: 'user/09' }, cos: empty });+ getAgents.mockResolvedValue([live('user/1')]);const res = await request(buildApp()).get('/api/cos/tasks');- expect(cos.getTaskView).toHaveBeenCalledWith({ kind: 'bare' });- expect(cos.getAllTasks).not.toHaveBeenCalled();+ expect(getTaskView).toHaveBeenCalledWith({ kind: 'bare' });+ expect(getAllTasks).not.toHaveBeenCalled();expect(res.body.user).toMatchObject({ completedCount: 40, completedNextCursor: 'user/09' });expect(res.body.user.grouped.in_progress.map(t => t.id)).toEqual(['user/1']);});it('queue view summarizes the derived lists and forwards the selected id', async () => {- cos.getTaskView.mockResolvedValue({ user: { ...open(), completedCount: 9,+ getTaskView.mockResolvedValue({ user: { ...open(), completedCount: 9,grouped: { pending: [{ id: 'user/1', status: 'pending', description: 'x' }], completed: [{ id: 'user/old', status: 'completed', description: 'y' }] } }, cos: empty });- cos.getAgents.mockResolvedValue([live('user/1')]);+ getAgents.mockResolvedValue([live('user/1')]);const res = await request(buildApp()).get('/api/cos/tasks?view=queue&selected=user/old');- expect(cos.getTaskView).toHaveBeenCalledWith({ kind: 'queue', selected: 'user/old' });+ expect(getTaskView).toHaveBeenCalledWith({ kind: 'queue', selected: 'user/old' });expect(res.body.user.completedCount).toBe(9);expect(res.body.user.grouped).toEqual({pending: [], in_progress: [{ id: 'user/1', status: 'pending', spawning: true }],@@ -669,29 +677,29 @@ describe('GET /api/cos/tasks — bounded view routing (#9677)', () => {});it('completed view validates the page size and passes source/cursor through', async () => {- cos.getTaskView.mockResolvedValue({ items: [], total: 0, nextCursor: null });+ getTaskView.mockResolvedValue({ items: [], total: 0, nextCursor: null });const res = await request(buildApp()).get('/api/cos/tasks?view=completed&source=internal&cursor=c9&limit=10');expect(res.body).toEqual({ items: [], total: 0, nextCursor: null });- expect(cos.getTaskView).toHaveBeenCalledWith({ kind: 'completed', source: 'internal', cursor: 'c9', limit: 10 });+ expect(getTaskView).toHaveBeenCalledWith({ kind: 'completed', source: 'internal', cursor: 'c9', limit: 10 });expect((await request(buildApp()).get('/api/cos/tasks?view=completed&limit=101')).status).toBe(400);});it('limit/offset keeps the legacy shape with true totals and settles the window', async () => {- cos.getTaskView.mockResolvedValue({ user: { file: 'TASKS.md', exists: true, type: 'user', tasks: [{ id: 'user/1', status: 'pending' }] },+ getTaskView.mockResolvedValue({ user: { file: 'TASKS.md', exists: true, type: 'user', tasks: [{ id: 'user/1', status: 'pending' }] },cos: { file: 'COS.md', exists: true, type: 'internal', tasks: [] }, totals: { user: 7, cos: 3 } });- cos.getAgents.mockResolvedValue([live('user/1')]);+ getAgents.mockResolvedValue([live('user/1')]);const res = await request(buildApp()).get('/api/cos/tasks?limit=1&offset=2');- expect(cos.getTaskView).toHaveBeenCalledWith({ kind: 'window', offset: 2, limit: 1 });+ expect(getTaskView).toHaveBeenCalledWith({ kind: 'window', offset: 2, limit: 1 });expect(res.body.pagination).toEqual({ limit: 1, offset: 2, userTotal: 7, cosTotal: 3, total: 10 });expect(res.body.user.tasks[0]).toMatchObject({ id: 'user/1', spawning: true });expect(res.body.user.grouped).toBeUndefined();});it('view=full stays the raw store, settled', async () => {- cos.getAllTasks.mockResolvedValue({ user: open(), cos: empty });- cos.getAgents.mockResolvedValue([live('user/1')]);+ getAllTasks.mockResolvedValue({ user: open(), cos: empty });+ getAgents.mockResolvedValue([live('user/1')]);const res = await request(buildApp()).get('/api/cos/tasks?view=full');- expect(cos.getTaskView).not.toHaveBeenCalled();+ expect(getTaskView).not.toHaveBeenCalled();expect(res.body.user.tasks[0]).toMatchObject({ id: 'user/1', spawning: true });});});@@ -770,15 +778,15 @@ describe('host-control gate on CoS task queueing (#8716)', () => {expect(res.status).toBe(403);expect(res.body.code).toBe('HOST_CONTROL_FORBIDDEN');}- expect(cos.addTask).not.toHaveBeenCalled();- expect(cos.forceSpawnTask).not.toHaveBeenCalled();- expect(cos.approveTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();+ expect(forceSpawnTask).not.toHaveBeenCalled();+ expect(approveTask).not.toHaveBeenCalled();});it('keeps a local password-free caller able to queue a task', async () => {const res = await request(buildGatedApp('127.0.0.1')).post('/api/cos/tasks').send({ description: 'local work' });expect(res.status).toBe(200);- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);});it('with a password set, Basic credentials are refused and an operator session is not', async () => {@@ -790,12 +798,12 @@ describe('host-control gate on CoS task queueing (#8716)', () => {.send({ description: 'peer work' });expect(basic.status).toBe(403);expect(basic.body.code).toBe('HOST_CONTROL_FORBIDDEN');- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();const session = await request(remote).post('/api/cos/tasks').set('Authorization', `Bearer ${token}`).send({ description: 'operator work' });expect(session.status).toBe(200);- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);});});diff --git a/server/routes/gsd.js b/server/routes/gsd.jsindex 3548630530..5ed331dd85 100644--- a/server/routes/gsd.js+++ b/server/routes/gsd.js@@ -14,7 +14,7 @@ import { atomicWrite } from '../lib/fileUtils.js'import { documentUpdateSchema, validateRequest } from '../lib/validation.js'import * as gsdService from '../services/gsdService.js'import { resolveGsdPath } from '../services/gsdPaths.js'-import { addTask } from '../services/cos.js'+import { addTask } from '../services/cosTaskStore.js'import { getActiveApps } from '../services/apps.js'import * as git from '../services/git.js'diff --git a/server/routes/gsd.test.js b/server/routes/gsd.test.jsindex 0448fdfa14..99eb6230a5 100644--- a/server/routes/gsd.test.js+++ b/server/routes/gsd.test.js@@ -37,7 +37,7 @@ vi.mock('../services/apps.js', () => ({getActiveApps: vi.fn(async () => mocks.activeApps),}));-vi.mock('../services/cos.js', () => ({+vi.mock('../services/cosTaskStore.js', () => ({addTask: mocks.addTask,}));diff --git a/server/routes/health.test.js b/server/routes/health.test.jsindex 4853e12883..892f7fc93d 100644--- a/server/routes/health.test.js+++ b/server/routes/health.test.js@@ -6,7 +6,9 @@ import express from 'express';import { request } from '../lib/testHelper.js';import systemHealthRoutes from './systemHealth.js';import { listProcesses, listProcessesStrict } from '../services/pm2.js';-import { getStatus, getPendingTaskIds, getAgents } from '../services/cos.js';+import { getStatus } from '../services/cos.js';+import { getPendingTaskIds } from '../services/cosTaskStore.js';+import { getAgents } from '../services/cosAgentLifecycle.js';import { getSelf } from '../services/instanceIdentity.js';import { isAuthEnabled } from '../services/auth.js';import { checkGhHealth } from '../services/github.js';@@ -64,8 +66,12 @@ vi.mock('../services/appProcessStatus.js', () => ({}));vi.mock('../services/cos.js', () => ({- getStatus: vi.fn().mockResolvedValue(null),- getPendingTaskIds: vi.fn().mockResolvedValue([]),+ getStatus: vi.fn().mockResolvedValue(null)+}));+vi.mock('../services/cosTaskStore.js', () => ({+ getPendingTaskIds: vi.fn().mockResolvedValue([])+}));+vi.mock('../services/cosAgentLifecycle.js', () => ({getAgents: vi.fn().mockResolvedValue([])}));diff --git a/server/routes/hostControlRunsVoice.test.js b/server/routes/hostControlRunsVoice.test.jsindex 35b4d00fd3..65a819ad76 100644--- a/server/routes/hostControlRunsVoice.test.js+++ b/server/routes/hostControlRunsVoice.test.js@@ -26,11 +26,13 @@ vi.mock('../services/pm2.js', () => ({listProcesses: vi.fn(async () => [{ name: 'example-api', status: 'online' }]),restartApp: vi.fn(async () => {}),}));-vi.mock('../services/cos.js', () => ({+vi.mock('../services/cosTaskStore.js', () => ({addTask: vi.fn(async () => ({ id: 'example-task' })),- isRunning: () => true,reviveBlockedTask: vi.fn(),}));+vi.mock('../services/cos.js', () => ({+ isRunning: () => true,+}));vi.mock('../services/providers.js', () => ({getActiveProvider: vi.fn(async () => ({ id: 'example-cli', type: 'cli', enabled: true })),getProviderById: vi.fn(), getAllProviders: vi.fn(),@@ -78,7 +80,7 @@ import { registerVoiceHandlers } from '../sockets/voice.js';import { dispatchTool } from '../services/voice/tools.js';import { streamChat } from '../services/voice/llm.js';import { restartApp } from '../services/pm2.js';-import { addTask } from '../services/cos.js';+import { addTask } from '../services/cosTaskStore.js';import { captureThought } from '../services/brain.js';import { generateImage } from '../services/imageGen/index.js';diff --git a/server/routes/imageVideoModels.js b/server/routes/imageVideoModels.jsindex 9418b13ca5..594429d182 100644--- a/server/routes/imageVideoModels.js+++ b/server/routes/imageVideoModels.js@@ -123,7 +123,7 @@ const supportRequestSchema = z.object({}).strict();router.post('/support-request', asyncHandler(async (req, res) => {const { kind, request } = validateRequest(supportRequestSchema, req.body);- const { addTask } = await import('../services/cos.js');+ const { addTask } = await import('../services/cosTaskStore.js');const task = await addTask({description: `Add ${kind} generation support: ${request.split('\n')[0].slice(0, 160)}`,prompt: `Investigate and implement ${kind} generation model or method support in PortOS.diff --git a/server/routes/imageVideoModels.store.test.js b/server/routes/imageVideoModels.store.test.jsindex 74315dab60..424ba74143 100644--- a/server/routes/imageVideoModels.store.test.js+++ b/server/routes/imageVideoModels.store.test.js@@ -7,7 +7,7 @@ import { errorMiddleware } from '../lib/errorHandler.js';import { request } from '../lib/testHelper.js';vi.mock('../services/modelManifest.js', () => ({ recordModelUninstall: vi.fn(async () => true) }));-vi.mock('../services/cos.js', () => ({ addTask: vi.fn() }));+vi.mock('../services/cosTaskStore.js', () => ({ addTask: vi.fn() }));vi.mock('../services/mediaModelInstall.js', () => ({ addModelFromHuggingface: vi.fn() }));const { default: routes } = await import('./imageVideoModels.js');diff --git a/server/routes/imageVideoModels.test.js b/server/routes/imageVideoModels.test.jsindex 044c20ae34..d3a1c4a792 100644--- a/server/routes/imageVideoModels.test.js+++ b/server/routes/imageVideoModels.test.js@@ -33,7 +33,7 @@ vi.mock('../lib/huggingfaceModel.js', () => ({searchHuggingfaceModels: vi.fn(async (query) => [{ id: `org/${query}`, likes: 1, downloads: 2, pipeline_tag: 'text-to-image' }]),}));-vi.mock('../services/cos.js', () => ({ addTask: vi.fn(async () => ({ id: 'task-support', status: 'pending' })) }));+vi.mock('../services/cosTaskStore.js', () => ({ addTask: vi.fn(async () => ({ id: 'task-support', status: 'pending' })) }));vi.mock('../services/mediaModelInstall.js', () => ({addModelFromHuggingface: vi.fn(async (input) => ({@@ -173,7 +173,7 @@ describe('DELETE /custom/:id', () => {describe('catalog availability and support requests', () => {it('validates availability and queues explicit implementation work', async () => {- const { addTask } = await import('../services/cos.js');+ const { addTask } = await import('../services/cosTaskStore.js');const invalid = await request(makeApp()).patch('/api/image-video/models/registry/dev/availability').send({ enabled: 'false' });expect(invalid.status).toBe(400);const saved = await request(makeApp()).patch('/api/image-video/models/registry/dev/availability').send({ enabled: false });diff --git a/server/routes/systemActivity.test.js b/server/routes/systemActivity.test.jsindex 328bf38131..7aadf7505d 100644--- a/server/routes/systemActivity.test.js+++ b/server/routes/systemActivity.test.js@@ -7,7 +7,9 @@ vi.mock('../lib/cudaCapability.js', () => ({ getCudaCapability: async () => ({ svi.mock('../services/mediaJobQueue/index.js', () => ({ listJobs: () => [], getRunningJob: () => null }));vi.mock('../services/imageTo3d/models.js', () => ({ listGeneratingModelSummaries: async () => [] }));vi.mock('../services/ollamaManager.js', () => ({ getLoadedModels: deps.loaded, getLastLoadedModelsError: deps.loadedError }));-vi.mock('../services/cos.js', () => ({ getPendingTaskIds: async () => [], getAgents: async () => [] }));+vi.mock('../services/cos.js', () => ({}));+vi.mock('../services/cosTaskStore.js', () => ({ getPendingTaskIds: async () => [] }));+vi.mock('../services/cosAgentLifecycle.js', () => ({ getAgents: async () => [] }));vi.mock('../services/cosState.js', () => ({ readPersistentMindStateForSafetyCheck: async () => ({ trusted: true }) }));vi.mock('../services/appOperations.js', () => ({ listActiveAppOperations: () => [] }));vi.mock('../services/updateChecker.js', () => ({ isUpdateInProgress: () => false }));diff --git a/server/services/activeProcessing.js b/server/services/activeProcessing.jsindex 33c1e14461..3b30b18175 100644--- a/server/services/activeProcessing.js+++ b/server/services/activeProcessing.js@@ -9,7 +9,9 @@ import { listActiveAppOperations } from './appOperations.js';import { readPersistentMindStateForSafetyCheck } from './cosState.js';import { isUpdateInProgress } from './updateChecker.js';import { listActiveRenders } from './renderActivity.js';-import * as cos from './cos.js';+import { getAgents } from './cosAgentLifecycle.js';+import { getPendingTaskIds } from './cosTaskStore.js';+import { getStatus } from './cos.js';// Lazy — NOT a static top-level import. `services/runner.js` and// `services/backup.js` both drag heavy subtrees (provider CLI spawning;@@ -134,10 +136,10 @@ export async function getSystemActivity({ includeOllama = false } = {}) {// building. Both of these degrade to the value that unlocks a restart, so// neither may be manufactured from a failed read.listGeneratingModelSummaries().catch(() => null),- cos.getPendingTaskIds().catch(() => null),+ getPendingTaskIds().catch(() => null),// `null` = the read FAILED, distinct from `[]` = read fine, no agents. The// counts degrade differently for the two, so they must stay separable.- cos.getAgents().catch(() => null),+ getAgents().catch(() => null),// Same contract one layer down: the reader reports `trusted: false` rather// than an empty mind, so an unreadable state cannot read as an idle one.readPersistentMindStateForSafetyCheck().catch(() => ({ trusted: false, persistentMind: null })),@@ -153,7 +155,7 @@ export async function getSystemActivity({ includeOllama = false } = {}) {importBackup().then((m) => m.isBackupInProgress()).catch(() => true),includeOllama ? getOllamaTelemetry() : null,]);- const cosStatus = agents === null ? await cos.getStatus().catch(() => null) : null;+ const cosStatus = agents === null ? await getStatus().catch(() => null) : null;const slices = {jobs: jobs.map(sanitizeJob),// `null` survives to the verdict as a blocker; the widget's owndiff --git a/server/services/activeProcessing.test.js b/server/services/activeProcessing.test.jsindex 8c9dc93f1c..7d3aa98d52 100644--- a/server/services/activeProcessing.test.js+++ b/server/services/activeProcessing.test.js@@ -9,7 +9,9 @@ vi.mock('./mediaJobQueue/index.js', () => ({ listJobs: deps.jobs, getRunningJob:vi.mock('./mediaJobQueue/sanitizeJob.js', () => ({ sanitizeJob: (job) => ({ id: job.id, kind: job.kind, status: job.status, params: { musicStudio: job.params.musicStudio } }) }));vi.mock('./imageTo3d/models.js', () => ({ listGeneratingModelSummaries: deps.models }));vi.mock('./ollamaManager.js', () => ({ getLoadedModels: deps.loaded, getLastLoadedModelsError: () => null }));-vi.mock('./cos.js', () => ({ getPendingTaskIds: deps.tasks, getStatus: deps.status, getAgents: deps.agents }));+vi.mock('./cosTaskStore.js', () => ({ getPendingTaskIds: deps.tasks }));+vi.mock('./cos.js', () => ({ getStatus: deps.status }));+vi.mock('./cosAgentLifecycle.js', () => ({ getAgents: deps.agents }));vi.mock('./cosState.js', () => ({ readPersistentMindStateForSafetyCheck: deps.mind }));vi.mock('./appOperations.js', () => ({ listActiveAppOperations: deps.operations }));vi.mock('./updateChecker.js', () => ({ isUpdateInProgress: deps.updating }));diff --git a/server/services/agentCompletion.js b/server/services/agentCompletion.jsindex b2ec6a302b..b0d1b5d20a 100644--- a/server/services/agentCompletion.js+++ b/server/services/agentCompletion.js@@ -7,17 +7,9 @@ import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';*/import { updateAgent } from './cosAgentLifecycle.js';-// `getConfig` comes from cosState.js, NOT cos.js, and that asymmetry with the-// other cos.js getConfig importers is load-bearing — do not "fix" it for-// consistency. This module sits on a cycle (cos.js → agentState.js →-// agentOrchestrator.js → agentManagement.js → agentFinalization.js → here), and-// pointing this import back at cos.js while cos.js re-exports getConfig from-// cosState.js leaves cos.js's own re-exported bindings uninitialized at import-// time — `firstLine is not a function` in cos.test.js, verified.-//-// agentCompletion.test.js's getConfig stub therefore has to name cosState.js-// too — pointed at cos.js it intercepts nothing, and the suite silently-// exercises the real loadState() against the running install's config.+// agentCompletion.test.js's getConfig stub must name cosState.js: that is the+// declaring module, and a stub on any other specifier intercepts nothing (the+// suite would silently read the running install's config).import { getConfig } from './cosState.js';import { startAppCooldown, markAppReviewCompleted } from './appActivity.js';import { emitLog } from './cosEvents.js';diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex 617c19814e..e164648f11 100644--- a/server/services/agentCompletionCleanup.js+++ b/server/services/agentCompletionCleanup.js@@ -32,7 +32,8 @@ import { join, relative, resolve, sep } from 'path';import { unlink, rm } from 'fs/promises';import { emitLog } from './cosEvents.js';import { updateAgent } from './cosAgentLifecycle.js';-import { updateTask, addTask, reviveBlockedTask, checkStagePrecondition } from './cos.js';+import { updateTask, addTask, reviveBlockedTask } from './cosTaskStore.js';+import { checkStagePrecondition } from './cosTaskGenerator.js';import { PIPELINE_STAGE_BEHAVIOR_FLAGS, normalizeReviewers } from '../lib/validation.js';import { PATHS, rmGuarded, tryReadFile } from '../lib/fileUtils.js';import { DONE_SENTINEL_NAME, doneSentinelName, doneSentinelPath as resolveDoneSentinelPath } from '../lib/agentSentinel.js';@@ -315,7 +316,7 @@ export async function runAgentCompletionCleanup({ agentId, task, agent, effectiv// Fetch agent state once for JIRA, plan-question, and the resume pointer. Its// worktree fields are stamped once at registerAgent and never mutated, so passing// it to the release spares a re-read that would re-split the whole output.txt.- const { getAgent: getAgentState } = await import('./cos.js');+ const { getAgent: getAgentState } = await import('./cosAgentLifecycle.js');const agentState = await getAgentState(agentId).catch(() => null);try {@@ -580,7 +581,7 @@ async function completeWorktreeCleanup({ agentId, task, effectiveSuccess, prOwneasync function reportWorktreeCleanupWarnings({ agentId, task, cleanupWarnings }) {if (cleanupWarnings?.length > 0) {- const { getAgent: getAgentForResult } = await import('./cos.js');+ const { getAgent: getAgentForResult } = await import('./cosAgentLifecycle.js');const currentAgent = await getAgentForResult(agentId).catch(() => null);await updateAgent(agentId, { result: { ...currentAgent?.result, warnings: cleanupWarnings } });@@ -620,7 +621,7 @@ async function reportWorktreeCleanupWarnings({ agentId, task, cleanupWarnings })export async function runSpawnerCompletionCleanup({ agentId, task, success: effectiveSuccess, prOwnership, prClaimVerified = false, branchProvenEmpty = false, outputBuffer }) {let agentState = null;try {- const { getAgent } = await import('./cos.js');+ const { getAgent } = await import('./cosAgentLifecycle.js');agentState = await getAgent(agentId).catch(() => null);await runCompletionCleanupSteps({agentId, task, agentState, effectiveSuccess, prOwnership,diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex 5afa6ebf0f..0e68bc6cc8 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -13,13 +13,18 @@ import { mkdtemp, writeFile, readFile, rm } from 'node:fs/promises';import { tmpdir } from 'node:os';import { join } from 'node:path';+vi.mock('./cos.js', () => ({}));vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));-vi.mock('./cosAgentLifecycle.js', () => ({ updateAgent: vi.fn() }));-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({updateTask: vi.fn().mockResolvedValue({}),addTask: vi.fn().mockResolvedValue({}),reviveBlockedTask: vi.fn().mockResolvedValue({}),+}));+vi.mock('./cosTaskGenerator.js', () => ({checkStagePrecondition: vi.fn().mockReturnValue({ passed: true }),+}));+vi.mock('./cosAgentLifecycle.js', () => ({+ updateAgent: vi.fn(),getAgent: vi.fn().mockResolvedValue(null),}));vi.mock('./jira.js', () => ({ getInstances: vi.fn(), addComment: vi.fn() }));@@ -40,7 +45,9 @@ vi.mock('./creativeDirector/completionHook.js', () => ({ handleCreativeDirectorCvi.mock('./taskPromptService.js', () => ({ getStagePrompt: vi.fn().mockResolvedValue('do stage work in {appName}') }));import { handlePipelineProgression, runAgentCompletionCleanup, runSpawnerCompletionCleanup, removeCompletionSentinel } from './agentCompletionCleanup.js';-import { updateTask, addTask, reviveBlockedTask, getAgent, checkStagePrecondition } from './cos.js';+import { updateTask, addTask, reviveBlockedTask } from './cosTaskStore.js';+import { getAgent } from './cosAgentLifecycle.js';+import { checkStagePrecondition } from './cosTaskGenerator.js';import { emitLog } from './cosEvents.js';import { cleanupAgentWorktree, releaseRetryHold, spawnMergeRecoveryTask } from './agentWorktreeCleanup.js';import { resolveReviewLoopOptions } from './codeReview.js';diff --git a/server/services/agentCompletionRouting.test.js b/server/services/agentCompletionRouting.test.jsindex 71967538bc..a93ce57911 100644--- a/server/services/agentCompletionRouting.test.js+++ b/server/services/agentCompletionRouting.test.js@@ -22,19 +22,22 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-vi.mock('./cos.js', () => ({+vi.mock('./cosState.js', () => ({getConfig: vi.fn().mockResolvedValue({}),+}));++vi.mock('./cosTaskStore.js', () => ({updateTask: vi.fn().mockResolvedValue(true),getTaskById: vi.fn().mockResolvedValue(null),- getAgentRecord: vi.fn().mockResolvedValue(null),- // The recovery path reaches for this via `await import('./cos.js')`.- getAgent: vi.fn().mockResolvedValue(null),}));vi.mock('./cosAgentLifecycle.js', () => ({registerAgent: vi.fn().mockResolvedValue(undefined),updateAgent: vi.fn().mockResolvedValue(undefined),completeAgent: vi.fn().mockResolvedValue(undefined),+ getAgentRecord: vi.fn().mockResolvedValue(null),+ // The recovery path reaches for this via `await import('./cosAgentLifecycle.js')`.+ getAgent: vi.fn().mockResolvedValue(null),}));vi.mock('./agentFinalization.js', () => ({@@ -65,8 +68,8 @@ vi.mock('./agentCompletionCleanup.js', () => ({import { handleAgentCompletion } from './agentLifecycle.js';import { runnerAgents, completingAgents, pausedAgents } from './agentState.js';-import { completeAgent } from './cosAgentLifecycle.js';-import { getAgent, getAgentRecord, getTaskById, updateTask } from './cos.js';+import { completeAgent, getAgent, getAgentRecord } from './cosAgentLifecycle.js';+import { getTaskById, updateTask } from './cosTaskStore.js';import { retireDeadAgent } from './agentFinalization.js';import { handleOrphanedTask } from './agentManagement.js';diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.jsindex 2056d4a619..12b289a2b9 100644--- a/server/services/agentErrorAnalysis.js+++ b/server/services/agentErrorAnalysis.js@@ -10,7 +10,7 @@ import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';*/import { emitLog } from './cosEvents.js';-import { addTask, updateTask } from './cos.js';+import { addTask, updateTask } from './cosTaskStore.js';import { cosEvents } from './cosEvents.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';import { redactOutput } from '../lib/commandSecurity.js';diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.jsindex 7204a06593..ef989627df 100644--- a/server/services/agentErrorAnalysis.test.js+++ b/server/services/agentErrorAnalysis.test.js@@ -3,7 +3,7 @@ import { describe, expect, it, vi, beforeEach } from 'vitest';// maybeCreateInvestigationTask → createInvestigationTask → addTask does real// store I/O; stub it so the skip-vs-create gate can be asserted in isolation.// getAllTasks feeds the fingerprint dedup scan (#2615).-vi.mock('./cos.js', () => ({ addTask: vi.fn(), updateTask: vi.fn(), getAllTasks: vi.fn() }));+vi.mock('./cosTaskStore.js', () => ({ addTask: vi.fn(), updateTask: vi.fn(), getAllTasks: vi.fn() }));import {analyzeAgentFailure,@@ -33,7 +33,7 @@ import { PII_PATTERNS } from '../lib/piiRedactionPatterns.js';import { detectImmediateFallbackSignal } from '../lib/aiToolkit/errorDetection.js';import { API_ACCESS_ERROR_CATEGORIES } from './agentErrorAnalysis.js';import { ENVIRONMENTAL_ERROR_CATEGORIES } from './taskLearning/metrics.js';-import { addTask, updateTask, getAllTasks } from './cos.js';+import { addTask, updateTask, getAllTasks } from './cosTaskStore.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';import { groupTasksByStatus, getAutoApprovedTasks, getAwaitingApprovalTasks } from '../lib/taskParser.js';diff --git a/server/services/agentFinalization.goalFidelity.test.js b/server/services/agentFinalization.goalFidelity.test.jsindex 3265e88a40..59a3be7d8d 100644--- a/server/services/agentFinalization.goalFidelity.test.js+++ b/server/services/agentFinalization.goalFidelity.test.js@@ -43,7 +43,7 @@ vi.mock('./cosAgentLifecycle.js', () => ({}));const updateTaskMock = vi.fn(async () => ({}));-vi.mock('./cos.js', () => ({ updateTask: (...args) => updateTaskMock(...args) }));+vi.mock('./cosTaskStore.js', () => ({ updateTask: (...args) => updateTaskMock(...args) }));vi.mock('./providers.js', () => ({ getActiveProvider: vi.fn(async () => null) }));vi.mock('./providerStatus.js', () => ({markProviderUsageLimit: vi.fn(async () => null),diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 0680b18b25..70e04dddea 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -31,7 +31,7 @@ import { cosEvents, emitLog } from './cosEvents.js';// import, which puts it inside the facade's closure, so the facade is out of// reach here.import { getAgent, getAgentRecord, updateAgent, completeAgent } from './cosAgentLifecycle.js';-import { updateTask } from './cos.js';+import { updateTask } from './cosTaskStore.js';import { isExpectedUnpersistedMiss } from '../lib/autonomousJobTask.js';import { getActiveProvider } from './providers.js';import { markProviderUsageLimit, markProviderUnavailable } from './providerStatus.js';diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.jsindex 9fe57eb26c..cde2556e38 100644--- a/server/services/agentFinalization.outputHooks.test.js+++ b/server/services/agentFinalization.outputHooks.test.js@@ -54,7 +54,7 @@ import {} from './agentFinalization.js';-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({updateTask: vi.fn(async () => ({})),addTask: vi.fn(async () => ({ id: 'investigation-test' })),}));@@ -77,7 +77,7 @@ vi.mock('./taskSchedule.js', () => ({recordTaskTypeSuccess: vi.fn(async () => null),recordRecommendedAudits: vi.fn(async () => null),}));-import { updateTask, addTask } from './cos.js';+import { updateTask, addTask } from './cosTaskStore.js';import { completeAgentRun } from './agentRunTracking.js';import { processAgentCompletion } from './agentCompletion.js';import { MAX_TASK_RETRIES, resolveFailedTaskUpdate } from './agentErrorAnalysis.js';diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.jsindex ad3b84d423..766c045d0b 100644--- a/server/services/agentFinalization.prVerification.test.js+++ b/server/services/agentFinalization.prVerification.test.js@@ -59,7 +59,7 @@ vi.mock('./cosAgentLifecycle.js', () => ({}));const updateTaskMock = vi.fn(async () => ({}));-vi.mock('./cos.js', () => ({ updateTask: (...args) => updateTaskMock(...args) }));+vi.mock('./cosTaskStore.js', () => ({ updateTask: (...args) => updateTaskMock(...args) }));vi.mock('./providers.js', () => ({ getActiveProvider: vi.fn(async () => null) }));vi.mock('./providerStatus.js', () => ({markProviderUsageLimit: vi.fn(async () => null),diff --git a/server/services/agentFinalization.primaryCheckoutDrift.test.js b/server/services/agentFinalization.primaryCheckoutDrift.test.jsindex 397cdef87c..e4bd53078e 100644--- a/server/services/agentFinalization.primaryCheckoutDrift.test.js+++ b/server/services/agentFinalization.primaryCheckoutDrift.test.js@@ -47,7 +47,7 @@ vi.mock('./cosAgentLifecycle.js', () => ({}));const updateTaskMock = vi.fn(async () => ({}));-vi.mock('./cos.js', () => ({ updateTask: (...args) => updateTaskMock(...args) }));+vi.mock('./cosTaskStore.js', () => ({ updateTask: (...args) => updateTaskMock(...args) }));vi.mock('./providers.js', () => ({ getActiveProvider: vi.fn(async () => null) }));vi.mock('./providerStatus.js', () => ({markProviderUsageLimit: vi.fn(async () => null),diff --git a/server/services/agentFinalization.providerBench.test.js b/server/services/agentFinalization.providerBench.test.jsindex 42ea820ded..ca3a94645b 100644--- a/server/services/agentFinalization.providerBench.test.js+++ b/server/services/agentFinalization.providerBench.test.js@@ -45,7 +45,7 @@ vi.mock('./cosAgentLifecycle.js', () => ({updateAgent: vi.fn(async () => null),completeAgent: vi.fn(async () => null),}));-vi.mock('./cos.js', () => ({ updateTask: vi.fn(async () => ({})) }));+vi.mock('./cosTaskStore.js', () => ({ updateTask: vi.fn(async () => ({})) }));const getActiveProviderMock = vi.fn(async () => null);vi.mock('./providers.js', () => ({ getActiveProvider: (...a) => getActiveProviderMock(...a) }));diff --git a/server/services/agentFinalization.retireDeadAgent.test.js b/server/services/agentFinalization.retireDeadAgent.test.jsindex 848a950b94..8a17e0840f 100644--- a/server/services/agentFinalization.retireDeadAgent.test.js+++ b/server/services/agentFinalization.retireDeadAgent.test.js@@ -25,7 +25,7 @@ vi.mock('./agentCompletionCleanup.js', () => ({removeCompletionSentinel: vi.fn(async () => undefined),}));vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn(async () => null) }));-vi.mock('./cos.js', () => ({ updateTask: vi.fn(async () => ({})), addTask: vi.fn(async () => ({ id: 'investigation-test' })) }));+vi.mock('./cosTaskStore.js', () => ({ updateTask: vi.fn(async () => ({})), addTask: vi.fn(async () => ({ id: 'investigation-test' })) }));vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn(), cosEvents: { emit: vi.fn(), on: vi.fn() } }));vi.mock('./taskTypeHooks.js', () => ({canRunTaskOutputHookWithoutPayload: vi.fn(() => true),diff --git a/server/services/agentImportCycles.test.js b/server/services/agentImportCycles.test.jsindex 0c9a81346a..b2128700fb 100644--- a/server/services/agentImportCycles.test.js+++ b/server/services/agentImportCycles.test.js@@ -316,13 +316,9 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {.toContain('requestAgentTermination');// A FORWARDER is any module that re-exports its way to a declaring module, at- // any depth: `cos.js` is one hop (`export { … } from './cosAgentLifecycle.js'`).- // It used to be two, through the `cosAgents.js` barrel that sat between them;- // that barrel is retired (#3450), leaving `cos.js`'s agent re-export block as- // the last forwarder. Walking the re-export edges instead of listing the- // barrels means a NEW barrel is covered the day it is written. Asserted- // rather than merely computed, so collapsing this last one has to come here- // and say so.+ // any depth. None remain: `cosAgents.js` was retired in #3450 and `cos.js`'s+ // agent re-export block was the last one. Walking the re-export edges rather+ // than listing barrels means a NEW barrel is covered the day it is written.const reexportEdges = (file) => [...readFileSync(join(SERVICES_DIR, file), 'utf-8').matchAll(/export\s*(?:\*|\{[^}]*\})\s*(?:as\s+\w+\s*)?from\s*['"]([^'"]+)['"]/g)@@ -342,8 +338,8 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {}}}- expect([...forwarders].sort(), 'the set of barrels still forwarding a transition changed — intended?')- .toEqual(['cos.js']);+ expect([...forwarders].sort(), 'a barrel forwards a transition again — import the declaring module instead')+ .toEqual([]);// Production sources only. A test mirrors whatever its subject imports (a// mock pointed at a module the subject no longer imports silently stops@@ -441,9 +437,8 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {});it('keeps cos.js out of every static import cycle (#5684)', () => {- // cos.js re-exports cosState/cosTaskStore for backward compat with- // `import * as cos`. Two leaf services used to reach THROUGH that barrel for- // one symbol each (memoryEmbeddings -> getConfig, character -> the task data),+ // cos.js used to re-export cosState/cosTaskStore. Two leaf services reached+ // THROUGH that barrel for one symbol each (memoryEmbeddings -> getConfig, character -> the task data),// and because cos.js transitively reaches the CoS tool registry -> voice// tools -> askService -> both of those leaves, each one-symbol forward closed// a 7-module ring. Both now import the DECLARING module, which is the samediff --git a/server/services/agentLifecycle.blockAndBail.test.js b/server/services/agentLifecycle.blockAndBail.test.jsindex ad569cd2c7..cab3fbd01e 100644--- a/server/services/agentLifecycle.blockAndBail.test.js+++ b/server/services/agentLifecycle.blockAndBail.test.js@@ -63,6 +63,7 @@ vi.mock('./cosAgentLifecycle.js', () => ({registerAgent: vi.fn().mockResolvedValue(undefined),updateAgent: vi.fn().mockResolvedValue(undefined),completeAgent: vi.fn().mockResolvedValue(undefined),+ getAgentRecord: vi.fn().mockResolvedValue(null),}));vi.mock('./agentRunTracking.js', () => ({createAgentRun: vi.fn().mockResolvedValue(undefined),@@ -78,11 +79,13 @@ vi.mock('./cosEvents.js', () => ({emitLog: vi.fn(),cosEvents: { emit: vi.fn(), on: vi.fn() },}));-vi.mock('./cos.js', () => ({+vi.mock('./cosState.js', async importOriginal => ({+ ...(await importOriginal()),getConfig: vi.fn().mockResolvedValue({}),+}));+vi.mock('./cosTaskStore.js', () => ({updateTask: vi.fn().mockResolvedValue(undefined),getTaskById: vi.fn().mockResolvedValue(null),- getAgentRecord: vi.fn().mockResolvedValue(null),}));vi.mock('./forgeAuth.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));vi.mock('./agentCliSpawning.js', () => ({@@ -156,7 +159,8 @@ import { registerAgent } from './cosAgentLifecycle.js';import { createAgentRun } from './agentRunTracking.js';import { buildCliSpawnConfig, isTuiProvider } from './agentCliSpawning.js';import { spawnAgentViaRunner } from './cosRunnerClient.js';-import { getConfig, updateTask } from './cos.js';+import { getConfig } from './cosState.js';+import { updateTask } from './cosTaskStore.js';import { cosEvents, emitLog } from './cosEvents.js';import { releaseAppReviewMarker } from './appActivity.js';import { acquire, release } from './executionLanes.js';diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 489901dd66..86698d1f7d 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -31,8 +31,8 @@ import { join } from 'path';import { readFile } from 'fs/promises';import { existsSync } from 'fs';import { cosEvents, emitLog } from './cosEvents.js';-import { updateAgent, completeAgent } from './cosAgentLifecycle.js';-import { getTaskById, updateTask, getAgentRecord } from './cos.js';+import { updateAgent, completeAgent, getAgent, getAgentRecord } from './cosAgentLifecycle.js';+import { getTaskById, updateTask } from './cosTaskStore.js';import { spawnAgentViaRunner, getRunnerHealth, classifyRunnerSpawnFailure, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } from './cosRunnerClient.js';import { isInternalTaskId } from '../lib/taskParser.js';import { PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';@@ -436,10 +436,7 @@ export async function extractPipelineOutputSummary(task, workspacePath, outputBu* one name.*/async function completeUntrackedAgentFromCosState(agentId, exitCode, success, duration, { interruptedStartup = null } = {}) {- // Dynamic import: `cos.js` imports back into this cluster, so a static import- // of the transcript-hydrating `getAgent` here would close an import cycle.- const { getAgent: getAgentState } = await import('./cos.js');- const cosAgent = await getAgentState(agentId).catch(() => null);+ const cosAgent = await getAgent(agentId).catch(() => null);if (!cosAgent) {console.log(`⚠️ Received completion for unknown agent: ${agentId} (not in cos state)`);return;diff --git a/server/services/agentLifecycle.postureGate.test.js b/server/services/agentLifecycle.postureGate.test.jsindex 731de8a286..aa12e581c8 100644--- a/server/services/agentLifecycle.postureGate.test.js+++ b/server/services/agentLifecycle.postureGate.test.js@@ -63,6 +63,7 @@ vi.mock('./cosAgentLifecycle.js', () => ({registerAgent: vi.fn().mockResolvedValue(undefined),updateAgent: vi.fn().mockResolvedValue(undefined),completeAgent: vi.fn().mockResolvedValue(undefined),+ getAgentRecord: vi.fn().mockResolvedValue(null),}));vi.mock('./agentRunTracking.js', () => ({createAgentRun: vi.fn().mockResolvedValue(undefined),@@ -78,11 +79,13 @@ vi.mock('./cosEvents.js', () => ({emitLog: vi.fn(),cosEvents: { emit: vi.fn(), on: vi.fn() },}));-vi.mock('./cos.js', () => ({+vi.mock('./cosState.js', async importOriginal => ({+ ...(await importOriginal()),getConfig: vi.fn().mockResolvedValue({}),+}));+vi.mock('./cosTaskStore.js', () => ({updateTask: vi.fn().mockResolvedValue(undefined),getTaskById: vi.fn().mockResolvedValue(null),- getAgentRecord: vi.fn().mockResolvedValue(null),}));vi.mock('./forgeAuth.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));vi.mock('./agentCliSpawning.js', () => ({@@ -158,7 +161,7 @@ import { registerAgent } from './cosAgentLifecycle.js';import { createAgentRun } from './agentRunTracking.js';import { buildCliSpawnConfig, isTuiProvider, spawnDirectly } from './agentCliSpawning.js';import { spawnAgentViaRunner } from './cosRunnerClient.js';-import { updateTask } from './cos.js';+import { updateTask } from './cosTaskStore.js';import { spawningTasks, runnerAgents, setUseRunner } from './agentState.js';// The provider every install actually runs its CoS agents on, and the one named@@ -222,7 +225,7 @@ afterAll(() => rmSync(TEMP_ROOT, { recursive: true, force: true }));describe('spawn setup failure after the worktree exists', () => {it('blocks private setup errors and releases the lane without publishing source details', async () => {- const { getConfig } = await import('./cos.js');+ const { getConfig } = await import('./cosState.js');const { release } = await import('./executionLanes.js');const { emitLog } = await import('./cosEvents.js');const { registerAgent } = await import('./cosAgentLifecycle.js');diff --git a/server/services/agentLifecycle.recoveredAudit.test.js b/server/services/agentLifecycle.recoveredAudit.test.jsindex c1c3175cc2..3029e849d2 100644--- a/server/services/agentLifecycle.recoveredAudit.test.js+++ b/server/services/agentLifecycle.recoveredAudit.test.js@@ -34,14 +34,13 @@ vi.mock('./cosAgentLifecycle.js', async importOriginal => ({Object.assign(fixture.records.get(id), { status: 'completed', result });}),}));-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({getAllTasks: vi.fn(async () => ({ user: { grouped: {} }, cos: { grouped: { active: fixture.tasks } } })),- getAgent: vi.fn(async id => fixture.records.get(id)),- getAgentRecord: vi.fn(async id => fixture.records.get(id)),getTaskById: vi.fn(async id => fixture.tasks.find(t => t.id === id)),updateTask: vi.fn(async (id, update) => Object.assign(fixture.tasks.find(t => t.id === id), update)),- addTask: vi.fn(), reviveBlockedTask: vi.fn(), checkStagePrecondition: vi.fn(),+ addTask: vi.fn(), reviveBlockedTask: vi.fn(),}));+vi.mock('./cosTaskGenerator.js', () => ({ checkStagePrecondition: vi.fn() }));vi.mock('./agentWorktreeCleanup.js', () => ({cleanupAgentWorktree: vi.fn(async id => {fixture.trace.push('cleanup');diff --git a/server/services/agentLifecycle.spawnViaRunner.test.js b/server/services/agentLifecycle.spawnViaRunner.test.jsindex 9a6f1dd103..c00833a3b1 100644--- a/server/services/agentLifecycle.spawnViaRunner.test.js+++ b/server/services/agentLifecycle.spawnViaRunner.test.js@@ -41,6 +41,8 @@ vi.mock('./cosAgentLifecycle.js', () => ({registerAgent: vi.fn().mockResolvedValue(undefined),updateAgent: vi.fn().mockResolvedValue(undefined),completeAgent: vi.fn().mockResolvedValue(undefined),+ getAgentRecord: vi.fn().mockResolvedValue(null),+ getAgent: vi.fn().mockResolvedValue(null),}));vi.mock('./agentRunTracking.js', () => ({@@ -61,12 +63,12 @@ vi.mock('./cosEvents.js', () => ({cosEvents: { emit: vi.fn(), on: vi.fn() },}));-vi.mock('./cos.js', () => ({+vi.mock('./cosState.js', () => ({getConfig: vi.fn().mockResolvedValue({}),+}));+vi.mock('./cosTaskStore.js', () => ({updateTask: vi.fn().mockResolvedValue(undefined),getTaskById: vi.fn().mockResolvedValue(null),- getAgentRecord: vi.fn().mockResolvedValue(null),- getAgent: vi.fn().mockResolvedValue(null),}));vi.mock('./forgeAuth.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));@@ -132,7 +134,8 @@ import { spawnAgentViaRunner, RUNNER_SPAWN_REFUSED, RUNNER_SPAWN_AMBIGUOUS } froimport { completeAgent, updateAgent } from './cosAgentLifecycle.js';import { completeAgentRun } from './agentRunTracking.js';import { finalizeAgent, releaseAgentLane, retireDeadAgent } from './agentFinalization.js';-import { getAgent, getAgentRecord, getTaskById } from './cos.js';+import { getAgent, getAgentRecord } from './cosAgentLifecycle.js';+import { getTaskById } from './cosTaskStore.js';import { release } from './executionLanes.js';import { releaseRetryHold } from './agentWorktreeCleanup.js';import { analyzeAgentFailure } from './agentErrorAnalysis.js';diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex c39c178e31..81e671af4c 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -474,7 +474,7 @@ describe('self-update spawn gate — funnel coverage (#4124)', () => {const body = trackedCompletionPreamble();expect(body).toMatch(/const persistedAgent = await getAgentRecord\(agentId\)/);// Imported unaliased, so `getAgent` can't be smuggled back in under this name.- expect(AGENT_LIFECYCLE_SRC).toMatch(/import \{[^}]*\bgetAgentRecord\b[^}]*\} from '\.\/cos\.js'/);+ expect(AGENT_LIFECYCLE_SRC).toMatch(/import \{[^}]*\bgetAgentRecord\b[^}]*\} from '\.\/cosAgentLifecycle\.js'/);expect(AGENT_LIFECYCLE_SRC).not.toMatch(/getAgent as getAgentRecord/);// Exactly one read for the whole tracked path.const reads = AGENT_LIFECYCLE_SRC.match(/await getAgentRecord\(agentId\)/g) || [];diff --git a/server/services/agentManagement.claimResume.test.js b/server/services/agentManagement.claimResume.test.jsindex 44db82adde..3c81baa399 100644--- a/server/services/agentManagement.claimResume.test.js+++ b/server/services/agentManagement.claimResume.test.js@@ -13,6 +13,7 @@ vi.mock('./cosState.js', () => ({saveState: async state => { f.state = state; f.disk = structuredClone(state); },readAgentsStateForSafetyCheck: async () => ({ trusted: true, agents: structuredClone(f.disk.agents) }),readMergeAdmissionStateForSafetyCheck: async () => ({ trusted: true, ...structuredClone(f.disk) }),+ getConfig: async () => ({}),}));vi.mock('./cosAgentLifecycle.js', () => ({getAgentRecord: vi.fn(async id => f.state.agents[id]),@@ -26,8 +27,7 @@ vi.mock('./cosAgentLifecycle.js', () => ({updateAgent: vi.fn(), isLiveAgentRecord: agent => agent?.status === 'running',AGENT_RECORD_UNREADABLE: Symbol('unreadable'),}));-vi.mock('./cos.js', () => ({- getConfig: async () => ({}),+vi.mock('./cosTaskStore.js', () => ({getTaskById: vi.fn(async id => f.tasks[id] || null),reviveBlockedTask: vi.fn(async (id, patch) => {f.tasks[id] = { ...f.tasks[id], status: 'pending', metadata: { ...f.tasks[id].metadata, ...patch.metadata } };@@ -39,8 +39,11 @@ vi.mock('./cos.js', () => ({status: 'pending', metadata: { ...metadata, ...Object.fromEntries(Object.entries(input).filter(([k, v]) => k !== 'description' && v !== undefined)) } };return f.tasks.replacement;}),- forceSpawnTask: vi.fn(), evaluateTasks: vi.fn(),}));+vi.mock('./cos.js', () => ({+ forceSpawnTask: vi.fn(),+}));+vi.mock('./cosTaskGenerator.js', () => ({ evaluateTasks: vi.fn() }));vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn(), cosEvents: { emit: vi.fn() } }));vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent: vi.fn() }));vi.mock('./agentRunTracking.js', () => ({ createAgentRun: async () => ({ runId: 'run-new' }), completeAgentRun: vi.fn() }));@@ -108,7 +111,8 @@ vi.mock('./creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettleimport { resumeAgent } from './agentManagement.js';import { dispatchAgentRun } from './agentSpawnDispatch.js';-import { forceSpawnTask, addTask, getTaskById } from './cos.js';+import { forceSpawnTask } from './cos.js';+import { addTask, getTaskById } from './cosTaskStore.js';import { completeAgent, updateAgent } from './cosAgentLifecycle.js';import { spawnDirectly } from './agentCliSpawning.js';import { setUseRunner } from './agentState.js';diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex d8bf7f6b0b..0da3834d09 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -22,7 +22,9 @@ import { emitLog } from './cosEvents.js';// that declares it; a barrel would be a third answer to "where does completeAgent// live", which is the thing this sequencing keeps removing.import { completeAgent, updateAgent, getAgents, getAgentRecord, AGENT_RECORD_UNREADABLE, isLiveAgentRecord, readAgentRecordOrUnreadable } from './cosAgentLifecycle.js';-import { updateTask, addTask, getTaskById, reviveBlockedTask, evaluateTasks, forceSpawnTask } from './cos.js';+import { updateTask, addTask, getTaskById, reviveBlockedTask } from './cosTaskStore.js';+import { evaluateTasks } from './cosTaskGenerator.js';+import { forceSpawnTask } from './cos.js';import { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS, pauseMetadata, isAgentPausedTask, isResumablePausedTask, registerPauseReleaseAdapter } from '../lib/taskPauseHold.js';import { terminateAgentViaRunner, killAgentViaRunner, pauseAgentViaRunner, getAgentStatsFromRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';import { runnerEntryShieldsRunningRecord } from '../lib/runnerAgentLiveness.js';@@ -1169,12 +1171,6 @@ export function cleanupOrphanedAgents() {}async function runCleanupOrphanedAgents() {- // Was `await import('./cos.js')` destructuring all four of these (#3450). The- // deferral bought nothing — this module already imports `./cos.js` statically- // at the top, so the module was loaded either way — while routing two agent- // functions through the `cos.js` re-export block, i.e. reaching a transition- // through a barrel. `completeAgent`/`getAgents` now come from the module that- // declares them and `evaluateTasks` joined the existing static `cos.js` import.const agents = await getAgents();let cleanedCount = 0;const orphanedTaskIds = [];diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex f667f48ccc..2366696fbf 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -44,13 +44,17 @@ const AGENT_MANAGEMENT_SRC = normalizeEol(readFileSync(join(__dirname, 'agentManconst { appendRunEvent } = vi.hoisted(() => ({ appendRunEvent: vi.fn(async () => ({ appended: true })) }));vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent }));-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({updateTask: vi.fn().mockResolvedValue(true),addTask: vi.fn().mockResolvedValue({ id: 'sys-mocked' }),getTaskById: vi.fn(),getAllTasks: vi.fn(),- reviveBlockedTask: vi.fn().mockResolvedValue(true),- evaluateTasks: vi.fn().mockResolvedValue(undefined),+ reviveBlockedTask: vi.fn().mockResolvedValue(true)+}));+vi.mock('./cosTaskGenerator.js', () => ({+ evaluateTasks: vi.fn().mockResolvedValue(undefined)+}));+vi.mock('./cos.js', () => ({forceSpawnTask: vi.fn().mockResolvedValue({ success: true })}));@@ -163,7 +167,8 @@ import { getAgents, updateAgent, getAgentRecord, readAgentRecordOrUnreadable, AGimport { updateRun, getProject } from './creativeDirector/local.js';import { advanceAfterPlanStepSettled } from './creativeDirector/planAdvance.js';import { advanceAfterSceneSettled } from './creativeDirector/completionHook.js';-import { updateTask, addTask, getTaskById, getAllTasks, reviveBlockedTask, forceSpawnTask } from './cos.js';+import { updateTask, addTask, getTaskById, getAllTasks, reviveBlockedTask } from './cosTaskStore.js';+import { forceSpawnTask } from './cos.js';import { pauseAgentViaRunner, terminateAgentViaRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';diff --git a/server/services/agentOrchestrator.js b/server/services/agentOrchestrator.jsindex 01d8e7946f..1eb6061cf4 100644--- a/server/services/agentOrchestrator.js+++ b/server/services/agentOrchestrator.js@@ -124,9 +124,9 @@* unchanged, and the two test files that only ever exercised one of them are* renamed to sit beside it (`cosAgentLifecycle.test.js`, `cosAgentIndex.merge.test.js`).*- * Remaining: `cos.js`'s agent re-export block (`export { … } from` the four- * modules above, ~20 names) is the last partial view of the cluster. It is a- * wide surface with many `vi.mock`ed importers and wants its own PR.+ * `cos.js`'s agent re-export block was the last partial view of the cluster and is+ * gone (#12988): `cos.js` declares only the daemon, and callers import each+ * function from the module that declares it.*/// Process/runner layer — owns the live agent maps and the OS-level signals.diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.jsindex 74f3e2bc73..91786d8774 100644--- a/server/services/agentRepoStateVerification.js+++ b/server/services/agentRepoStateVerification.js@@ -34,7 +34,7 @@ import { sameRetirementCheckout } from '../lib/reconcileRetirementEvidence.js';import { readLocalBranchPresence, readCheckoutPathPresence, inspectOpenDeliveryRepair } from './repoCleanupObservation.js';import { join, resolve } from 'path';import { emitLog } from './cosEvents.js';-import { addTask } from './cos.js';+import { addTask } from './cosTaskStore.js';import * as git from './git.js';import { listWorktrees } from './worktreeManager.js';import { listRemoteHeads, driveToMerge } from './branchReconcile.js';diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.jsindex 72a3e3fe0e..c3310ffb30 100644--- a/server/services/agentRepoStateVerification.test.js+++ b/server/services/agentRepoStateVerification.test.js@@ -27,18 +27,19 @@ vi.mock('../lib/gitRemote.js', () => ({ getOriginInfo: vi.fn(async () => ({ hostvi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: vi.fn(async () => ({})) }));vi.mock('./heldCheckoutReview.js', () => ({ readRetirementForgeEvidence: vi.fn(async () => ({ prHead: '1'.repeat(40), defaultHead: '2'.repeat(40) })) }));vi.mock('./completedCheckoutEvidence.js', () => ({ readCompletedCheckoutIdentity: vi.fn() }));+vi.mock('./cos.js', () => ({}));vi.mock('./cosAgentLifecycle.js', () => ({ reserveRepoCleanupRecovery: vi.fn(async () => ({ admitted: true, attempt: 1 })), recordRepoCleanupRecovery: vi.fn(async () => true), recordCleanupOutcome: vi.fn(async () => true), updateAgent: vi.fn().mockResolvedValue({}), recordRepoStateRecovery: vi.fn().mockResolvedValue(true), recordRepoStateVerification: vi.fn().mockResolvedValue(true) }));vi.mock('./cosClaimOwnership.js', () => ({ readClaimOwnershipAgents: vi.fn().mockResolvedValue([]) }));-vi.mock('./cosTaskStore.js', () => ({ getTaskById: vi.fn().mockResolvedValue(null) }));vi.mock('./taskSchedule.js', () => ({ recordBranchReconcileOutcome: vi.fn().mockResolvedValue({}) }));vi.mock('./heldCheckoutRecovery.js', () => ({retireInventoriedCheckout: vi.fn(async () => ({ ok: true, archiveDir: '/private/archive', branchDeleted: true })),prepareInventoriedCheckoutRetirement: vi.fn().mockResolvedValue({ ok: true, review: { digest: 'a'.repeat(64) } }),}));vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({addTask: vi.fn().mockResolvedValue({ id: 'task-recovery-1' }),getAllTasks: vi.fn().mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } }),+ getTaskById: vi.fn().mockResolvedValue(null),}));vi.mock('./prWatcher.js', () => ({ readPendingMergePrs: vi.fn().mockReturnValue([]) }));vi.mock('./worktreeManager.js', () => ({ listWorktrees: vi.fn().mockResolvedValue([]) }));@@ -80,7 +81,7 @@ import { readBranchCompletionPolicies } from './branchCompletionPolicy.js';import { getTaskById } from './cosTaskStore.js';import { recordBranchReconcileOutcome } from './taskSchedule.js';import { prepareInventoriedCheckoutRetirement, retireInventoriedCheckout } from './heldCheckoutRecovery.js';-import { addTask, getAllTasks } from './cos.js';+import { addTask, getAllTasks } from './cosTaskStore.js';import { ensureTaskThread } from './brainTaskThreads.js';import { listWorktrees } from './worktreeManager.js';import { listRemoteHeads, cleanupMerged } from './branchReconcile.js';diff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.jsindex eb08c0c629..7257b1eda4 100644--- a/server/services/agentRunnerSync.js+++ b/server/services/agentRunnerSync.js@@ -73,7 +73,7 @@ export async function syncRunnerAgents() {console.log(`🔄 Syncing ${agents.length} running agents from CoS Runner`);// Get all tasks to find task data for each agent- const { getAllTasks } = await import('./cos.js');+ const { getAllTasks } = await import('./cosTaskStore.js');const allTasksData = await getAllTasks().catch(() => ({ user: {}, cos: {} }));// Build a task lookup map from all task sources, tagging each with its taskTypediff --git a/server/services/agentRunnerSync.test.js b/server/services/agentRunnerSync.test.jsindex 656d2a2b6a..5572464777 100644--- a/server/services/agentRunnerSync.test.js+++ b/server/services/agentRunnerSync.test.js@@ -8,6 +8,7 @@ const recoveredPty = {kill: vi.fn(),};+vi.mock('./cos.js', () => ({}));vi.mock('./cosRunnerClient.js', () => ({getActiveAgentsFromRunner: vi.fn(),terminateAgentViaRunner: vi.fn(async () => ({ success: true, terminated: true })),@@ -24,7 +25,7 @@ vi.mock('./shell.js', () => ({unregisterExternalSession: vi.fn(),}));-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({getAllTasks: vi.fn().mockResolvedValue({user: { grouped: { active: [{ id: 'task-1', description: 'Example task' }] } },cos: { grouped: {} },diff --git a/server/services/agentSpawnDispatch.dispatching.test.js b/server/services/agentSpawnDispatch.dispatching.test.jsindex 0d230b5b17..c3878f0209 100644--- a/server/services/agentSpawnDispatch.dispatching.test.js+++ b/server/services/agentSpawnDispatch.dispatching.test.js@@ -9,7 +9,9 @@ vi.mock('../lib/checkoutRetirementAdmission.js', () => ({ withCheckoutPublicatiof.publicationActive = true;try { return await work(); } finally { f.publicationActive = false; }}) }));-vi.mock('./cos.js', () => ({ getConfig: async () => ({}), updateTask: vi.fn(async () => f.updateResult) }));+vi.mock('./cos.js', () => ({}));+vi.mock('./cosState.js', () => ({ getConfig: async () => ({}) }));+vi.mock('./cosTaskStore.js', () => ({ updateTask: vi.fn(async () => f.updateResult) }));vi.mock('./cosAgentLifecycle.js', () => ({registerAgent: vi.fn(() => f.registerGate),updateAgent: vi.fn(),@@ -55,7 +57,7 @@ import { dispatchAgentRun } from './agentSpawnDispatch.js';import { getActiveAgentIds, protectedAgentIds, setUseRunner } from './agentState.js';import { spawnDirectly } from './agentCliSpawning.js';import { prepareAgentWorkspace } from './agentWorkspacePrep.js';-import { updateTask } from './cos.js';+import { updateTask } from './cosTaskStore.js';import { registerAgent } from './cosAgentLifecycle.js';import { withCheckoutPublication } from '../lib/checkoutRetirementAdmission.js';diff --git a/server/services/agentSpawnDispatch.js b/server/services/agentSpawnDispatch.jsindex 161e230064..51c0e1d4e6 100644--- a/server/services/agentSpawnDispatch.js+++ b/server/services/agentSpawnDispatch.js@@ -1,7 +1,8 @@import { withBackupAssetPublication } from '../lib/backupSnapshotBoundary.js';import { join } from 'path';import { existsSync } from 'fs';-import { getConfig, updateTask } from './cos.js';+import { getConfig } from './cosState.js';+import { updateTask } from './cosTaskStore.js';import { isExpectedUnpersistedMiss } from '../lib/autonomousJobTask.js';import { isPrivateSecurityTask } from '../lib/privateSecurityPolicy.js';import { PROVIDER_CONFIG_BLOCKED_CATEGORY } from '../lib/taskBlockCategories.js';diff --git a/server/services/agentSpawnPreparation.js b/server/services/agentSpawnPreparation.jsindex 0f1d900337..91cb1a0316 100644--- a/server/services/agentSpawnPreparation.js+++ b/server/services/agentSpawnPreparation.js@@ -1,7 +1,7 @@import { cosEvents, emitLog } from './cosEvents.js';import { loadState } from './cosState.js';import { hasActiveTaskOwner } from './agentState.js';-import { getTaskById, updateTask } from './cos.js';+import { getTaskById, updateTask } from './cosTaskStore.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';import { isInternalTaskId } from '../lib/taskParser.js';import { isRetryHeld } from '../lib/taskRetryHold.js';diff --git a/server/services/agentSpawnPreparation.test.js b/server/services/agentSpawnPreparation.test.jsindex 6f616ef2c5..b174d436ea 100644--- a/server/services/agentSpawnPreparation.test.js+++ b/server/services/agentSpawnPreparation.test.js@@ -6,7 +6,7 @@ const hasActiveTaskOwner = vi.hoisted(() => vi.fn());vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn(), on: vi.fn() }, emitLog: vi.fn() }));vi.mock('./cosState.js', () => ({ loadState }));vi.mock('./agentState.js', () => ({ hasActiveTaskOwner }));-vi.mock('./cos.js', () => ({ getTaskById: vi.fn(), updateTask: vi.fn() }));+vi.mock('./cosTaskStore.js', () => ({ getTaskById: vi.fn(), updateTask: vi.fn() }));vi.mock('./toolStateMachine.js', () => ({createToolExecution: vi.fn(), startExecution: vi.fn(), completeExecution: vi.fn(), errorExecution: vi.fn(),}));@@ -17,7 +17,7 @@ vi.mock('./appActivity.js', () => ({ releaseAppReviewMarker: vi.fn() }));import { prepareAgentSpawn, createAgentSpawnContext } from './agentSpawnPreparation.js';import { cosEvents, emitLog } from './cosEvents.js';-import { updateTask } from './cos.js';+import { updateTask } from './cosTaskStore.js';import { release } from './executionLanes.js';import { releaseAppReviewMarker } from './appActivity.js';diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex 8812414f22..6962630625 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -40,7 +40,7 @@ vi.mock('./providerStatus.js', () => ({markProviderRateLimited: vi.fn().mockResolvedValue(undefined)}));-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({updateTask: vi.fn().mockResolvedValue(undefined)}));diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex 7e2436a875..0d1f7b37de 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -30,7 +30,7 @@ import { basename, join, resolve } from 'path';import { existsSync } from 'fs';import { execGit } from '../lib/execGit.js';import { emitLog } from './cosEvents.js';-import { updateTask, addTask } from './cos.js';+import { updateTask, addTask } from './cosTaskStore.js';import { getAppById } from './apps.js';import { isTruthyMeta, isFalsyMeta, protectedAgentIds } from './agentState.js';import { PATHS, ensureDir } from '../lib/fileUtils.js';@@ -115,7 +115,7 @@ async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName,// Fail CLOSED on an unreadable agent list: an empty protected set would read as// "nothing is running", which is the one wrong answer here — it would move a// live run's directory. The caller's timed pause is the safe outcome instead.- const { getAgents } = await import('./cos.js');+ const { getAgents } = await import('./cosAgentLifecycle.js');const agents = await getAgents().catch(err => {emitLog('warn', `🌳 Skipping worktree adoption for task ${taskId} — could not read the agent list: ${err.message}`, { taskId });return null;@@ -170,7 +170,7 @@ async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName,* @returns {Promise<boolean>} true when the holder was released*/async function releaseOwnerlessForeignHolderForTask({ workspacePath, branchName, agentId, taskId }) {- const { getAgents } = await import('./cos.js');+ const { getAgents } = await import('./cosAgentLifecycle.js');const agents = await getAgents().catch(() => null);if (!Array.isArray(agents)) return false;const activeIds = protectedAgentIds(agents);@@ -404,7 +404,7 @@ async function prepareRequestedWorktree({* Read-only: nothing here rebases, commits, pushes, moves or removes.*/async function admitClaimContinuation({ task, agentId, sourceWorkspace, claimWorkspace }) {- const { getAgents } = await import('./cos.js');+ const { getAgents } = await import('./cosAgentLifecycle.js');const [agents, worktrees] = await Promise.all([getAgents().catch(() => null),listWorktrees(sourceWorkspace).catch(() => null),diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.jsindex 9a36eeac29..31c43082ef 100644--- a/server/services/agentWorkspacePrep.test.js+++ b/server/services/agentWorkspacePrep.test.js@@ -12,6 +12,7 @@import { describe, it, expect, beforeEach, vi } from 'vitest';const recoveryCheck = vi.hoisted(() => vi.fn(async () => null));+vi.mock('./cos.js', () => ({}));vi.mock('./cosMergeHandoff.js', () => ({ validateCleanupReviewTarget: (...args) => recoveryCheck(...args) }));const publication = vi.hoisted(() => ({ active: false, refuse: false }));vi.mock('../lib/checkoutRetirementAdmission.js', () => ({ withCheckoutPublication: vi.fn(async (_repo, work) => {@@ -23,9 +24,11 @@ vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));vi.mock('../lib/execGit.js', () => ({execGit: vi.fn().mockImplementation(async args => ({ stdout: args.includes('--is-inside-work-tree') ? 'true' : '', stderr: '', exitCode: 0 })),}));-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({updateTask: vi.fn().mockResolvedValue({}),addTask: vi.fn().mockResolvedValue({}),+}));+vi.mock('./cosAgentLifecycle.js', () => ({getAgents: vi.fn().mockResolvedValue([]),}));vi.mock('./apps.js', () => ({ getAppById: vi.fn().mockResolvedValue(null) }));@@ -88,7 +91,8 @@ vi.mock('fs', async (importOriginal) => {import { prepareAgentWorkspace, resolveTaskExistingBranch } from './agentWorkspacePrep.js';import { claimContinuationWorkspace } from '../lib/claimContinuation.js';-import { updateTask, addTask, getAgents } from './cos.js';+import { updateTask, addTask } from './cosTaskStore.js';+import { getAgents } from './cosAgentLifecycle.js';import { emitLog } from './cosEvents.js';import { ensureLatest, isRepo, fetchOrigin, createBranch } from './git.js';import { getAppDataForTask } from './agentAppWorkspace.js';diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 9c5f972fef..9fb6fd43bd 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -16,7 +16,9 @@ import { existsSync } from 'fs';import { PORTOS_APP_ID } from '../lib/appIdentity.js';import { join } from 'path';import { emitLog } from './cosEvents.js';-import { addTask, forceSpawnTask, getAgents, updateTask } from './cos.js';+import { addTask, updateTask } from './cosTaskStore.js';+import { forceSpawnTask } from './cos.js';+import { getAgents } from './cosAgentLifecycle.js';import * as git from './git.js';import { resolveTaskHookType } from './taskTypeHooks.js';import { removeWorktree, classifyWorktreeDirt, listWorktrees } from './worktreeManager.js';@@ -130,7 +132,7 @@ async function auditRepoState(agentId, success, originalTask, warnings) {const { verifyAgentRepoState } = await import('./agentRepoStateVerification.js');// `getAgentRecord`, not `getAgent` — the audit reads three worktree metadata// fields and has no use for the run's whole output.txt.- const { getAgentRecord } = await import('./cos.js');+ const { getAgentRecord } = await import('./cosAgentLifecycle.js');const agentState = await getAgentRecord(agentId).catch(() => null);if (publicationHolds.has(agentId) || ['running', 'blocked'].includes(agentState?.metadata?.publicationValidation?.status)) return;await verifyAgentRepoState({@@ -150,7 +152,7 @@ async function auditRepoState(agentId, success, originalTask, warnings) {*/async function auditMergeGate(agentId, originalTask) {const { auditClaimMergeGate } = await import('./mergeGateAudit.js');- const { getAgentRecord } = await import('./cos.js');+ const { getAgentRecord } = await import('./cosAgentLifecycle.js');const agentState = await getAgentRecord(agentId).catch(() => null);if (!agentState) return;await auditClaimMergeGate({ agentId, task: originalTask, agentState });@@ -191,7 +193,7 @@ export function resolveWorktreeDisposition({ isWorktree, success, prCreation, di}async function worktreeCleanupContext(agentId, options) {- const { getAgent } = await import('./cos.js');+ const { getAgent } = await import('./cosAgentLifecycle.js');const agentState = await getAgent(agentId).catch(() => null);const metadata = agentState?.metadata;if (!metadata?.isWorktree || metadata.isPersistentWorktree) return { isWorktree: false };@@ -317,7 +319,7 @@ async function openWorktreePullRequest(context) {emitLog('info', `🌳 Opening PR for worktree agent ${agentId} branch ${worktreeBranch}`, { agentId, branchName: worktreeBranch });if (context.originalTask?.metadata?.app === PORTOS_APP_ID) {- const { updateAgent } = await import('./cos.js');+ const { updateAgent } = await import('./cosAgentLifecycle.js');try {publicationHolds.set(agentId, { status: 'running' });await updateAgent(agentId, { metadata: { publicationValidation: { status: 'running', startedAt: new Date().toISOString() } } });@@ -979,7 +981,8 @@ export async function releaseRetryHold({ agentId, task, success, agentMetadata }if (!agentId || !task?.id) return {};if (success && !isLegacyDeepAudit(task.metadata)) return {};- const { getTaskById, getAgentRecord } = await import('./cos.js');+ const { getTaskById } = await import('./cosTaskStore.js');+ const { getAgentRecord } = await import('./cosAgentLifecycle.js');const persisted = await getTaskById(task.id).catch(err => {emitLog('warn', `Skipping resume pointer for task ${task.id} — status unreadable: ${err.message}`, { taskId: task.id, agentId });return null;@@ -1358,7 +1361,7 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p}async function resumeReviewLoopCoordinator(taskId, prUrl, prBranch, reviewTarget = null) {- const { getTaskById } = await import('./cos.js');+ const { getTaskById } = await import('./cosTaskStore.js');const task = await getTaskById(taskId);if (!task || task.taskType !== 'internal' || !isTruthyMeta(task.metadata?.reviewLoopFollowUp)|| task.metadata.reviewLoopPRUrl !== prUrl || task.metadata.reviewLoopPRBranch !== prBranch) {diff --git a/server/services/agentWorktreeCleanup.repoStateAudit.test.js b/server/services/agentWorktreeCleanup.repoStateAudit.test.jsindex 5ffb0024e0..4323c1b16b 100644--- a/server/services/agentWorktreeCleanup.repoStateAudit.test.js+++ b/server/services/agentWorktreeCleanup.repoStateAudit.test.js@@ -11,13 +11,16 @@import { describe, it, expect, beforeEach, vi } from 'vitest';+vi.mock('./cos.js', () => ({}));vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({addTask: vi.fn().mockResolvedValue({}),updateTask: vi.fn().mockResolvedValue({}),+ getTaskById: vi.fn().mockResolvedValue(null),+}));+vi.mock('./cosAgentLifecycle.js', () => ({getAgent: vi.fn().mockResolvedValue(null),getAgentRecord: vi.fn().mockResolvedValue(null),- getTaskById: vi.fn().mockResolvedValue(null),}));vi.mock('./git.js', () => ({getDefaultBranch: vi.fn().mockResolvedValue('main'),@@ -43,7 +46,8 @@ vi.mock('./agentRepoStateVerification.js', () => ({import { probePrForBranch } from './prProbe.js';import { cleanupAgentWorktree, spawnMergeRecoveryTask } from './agentWorktreeCleanup.js';import { verifyAgentRepoState } from './agentRepoStateVerification.js';-import { getAgent, getAgentRecord, addTask } from './cos.js';+import { getAgent, getAgentRecord } from './cosAgentLifecycle.js';+import { addTask } from './cosTaskStore.js';import { removeWorktree } from './worktreeManager.js';const worktreeAgent = {diff --git a/server/services/askPromote.js b/server/services/askPromote.jsindex 33345e1bfe..b5dd39f564 100644--- a/server/services/askPromote.js+++ b/server/services/askPromote.js@@ -16,7 +16,7 @@import { ServerError } from '../lib/errorHandler.js';import * as convs from './askConversations.js';import * as brainService from './brain.js';-import * as cosService from './cos.js';+import { addTask } from './cosTaskStore.js';import * as identityService from './identity.js';// Cap promoted task descriptions so a long assistant answer doesn't bloat@@ -66,7 +66,7 @@ export async function promoteTurnContent({ conversationId, turn, target, prioritconst description = content.length <= TASK_DESCRIPTION_MAX? content: `${content.slice(0, TASK_DESCRIPTION_MAX - 1)}…`;- const result = await cosService.addTask({+ const result = await addTask({description,priority,context: `Promoted from Ask Yourself conversation ${conversationId}`,diff --git a/server/services/askPromote.test.js b/server/services/askPromote.test.jsindex 4ad90005bd..b46f2d6ba0 100644--- a/server/services/askPromote.test.js+++ b/server/services/askPromote.test.js@@ -9,7 +9,7 @@ const identityService = { addProgressEntry: vi.fn() };vi.mock('./askConversations.js', () => convs);vi.mock('./brain.js', () => brainService);-vi.mock('./cos.js', () => cosService);+vi.mock('./cosTaskStore.js', () => cosService);vi.mock('./identity.js', () => identityService);const { latestAssistantTurn, promoteLatestAssistantTurn, promoteTurnById } = await import('./askPromote.js');diff --git a/server/services/autoFixer.test.js b/server/services/autoFixer.test.jsindex 522e1bfc2e..15b0731890 100644--- a/server/services/autoFixer.test.js+++ b/server/services/autoFixer.test.js@@ -10,12 +10,14 @@ import { ERROR_CATEGORIES } from '../lib/aiToolkit/errorDetection.js';// branches, and `getAllTasks` feeds the shared investigation-approval policy// (reached via agentErrorAnalysis) an empty backlog — no prior investigation and// no storm, i.e. the ordinary unattended case.-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({addTask: vi.fn().mockResolvedValue({ id: 'task-1' }),- isRunning: vi.fn().mockReturnValue(true),updateTask: vi.fn().mockResolvedValue(true),getAllTasks: vi.fn().mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } }),}));+vi.mock('./cos.js', () => ({+ isRunning: vi.fn().mockReturnValue(true),+}));// installState reaches out to git/fs; stub it so the stale-deployed-build// branch is driven from the test rather than from this checkout's real HEAD.@@ -26,7 +28,8 @@ vi.mock('./installState.js', () => ({const installState = await import('./installState.js');-const cos = await import('./cos.js');+const { addTask, getAllTasks } = await import('./cosTaskStore.js');+const { isRunning } = await import('./cos.js');const {noteFallbackHandled,initAutoFixer,@@ -44,7 +47,7 @@ initAutoFixer();// Tasks handed to the durable store (addTask's first argument).function filedTasks() {- return cos.addTask.mock.calls.map(([task]) => task);+ return addTask.mock.calls.map(([task]) => task);}function emitProviderFailure({ provider = 'Primary CLI', model = 'm-1', runId = 'run-1' } = {}) {@@ -67,8 +70,8 @@ function emitProviderFailure({ provider = 'Primary CLI', model = 'm-1', runId =describe('autoFixer — defer + noteFallbackHandled', () => {beforeEach(() => {vi.useFakeTimers();- cos.addTask.mockClear();- cos.isRunning.mockReturnValue(true);+ addTask.mockClear();+ isRunning.mockReturnValue(true);_resetAutoFixerForTests();});@@ -84,12 +87,12 @@ describe('autoFixer — defer + noteFallbackHandled', () => {await vi.advanceTimersByTimeAsync(0);// Task is NOT created right away — it's deferred.- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();// After the defer window elapses, the task is created.await vi.advanceTimersByTimeAsync(5500);- expect(cos.addTask).toHaveBeenCalledTimes(1);- expect(cos.addTask.mock.calls[0][0]).toMatchObject({+ expect(addTask).toHaveBeenCalledTimes(1);+ expect(addTask.mock.calls[0][0]).toMatchObject({description: 'Investigate AI provider failure: Primary CLI (m-1)',});});@@ -144,7 +147,7 @@ describe('autoFixer — defer + noteFallbackHandled', () => {context: expect.objectContaining({ timeoutOrigin: 'caller-budget', runtimeBudgetMs: 120000 }),}));await vi.advanceTimersByTimeAsync(6000);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();} finally { errorEvents.off('error', observed); }});@@ -155,10 +158,10 @@ describe('autoFixer — defer + noteFallbackHandled', () => {errorEvents.emit('error', budget);await escalateProviderFailure(budget);await vi.advanceTimersByTimeAsync(6000);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();emitProviderFailure({ provider: 'Example API', model: 'm-1', runId: 'fault-run' });await vi.advanceTimersByTimeAsync(6000);- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);});it('never creates an investigation task for a content/safety refusal', async () => {@@ -178,7 +181,7 @@ describe('autoFixer — defer + noteFallbackHandled', () => {},});await vi.advanceTimersByTimeAsync(6000);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('suppresses the task for a SLOW fallback that finishes after the defer window', async () => {@@ -194,12 +197,12 @@ describe('autoFixer — defer + noteFallbackHandled', () => {// The backstop window elapses with the fallback still running — no task.await vi.advanceTimersByTimeAsync(6000);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();// Fallback finally succeeds ~25s later — still no task.noteFallbackHandled({ provider: 'Ollama', model: 'command-r' });await vi.advanceTimersByTimeAsync(25000);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('suppresses the task even when noteFallbackStarted races ahead of the error event', async () => {@@ -209,7 +212,7 @@ describe('autoFixer — defer + noteFallbackHandled', () => {noteFallbackStarted({ provider: 'Ollama', model: 'command-r' });emitProviderFailure({ provider: 'Ollama', model: 'command-r' });await vi.advanceTimersByTimeAsync(6000);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('noteFallbackFailed releases suppression so a later identical failure can raise a task', async () => {@@ -220,7 +223,7 @@ describe('autoFixer — defer + noteFallbackHandled', () => {// A fresh failure with no fallback in flight now schedules + fires a task.emitProviderFailure({ provider: 'Ollama', model: 'command-r' });await vi.advanceTimersByTimeAsync(6000);- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);});it('cancels the deferred task when noteFallbackHandled fires within the window', async () => {@@ -233,7 +236,7 @@ describe('autoFixer — defer + noteFallbackHandled', () => {// Advancing past the defer window must NOT trigger task creation.await vi.advanceTimersByTimeAsync(10000);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('returns false when noteFallbackHandled has no matching deferred task', async () => {@@ -251,7 +254,7 @@ describe('autoFixer — defer + noteFallbackHandled', () => {expect(noteFallbackHandled({ provider: 'Other CLI', model: 'm-1' })).toBe(false);await vi.advanceTimersByTimeAsync(5500);- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);});it('allows a future failure of the same provider to raise a new task after suppression (no 60s dedupe lockout)', async () => {@@ -259,30 +262,30 @@ describe('autoFixer — defer + noteFallbackHandled', () => {await vi.advanceTimersByTimeAsync(0);noteFallbackHandled({ provider: 'Primary CLI', model: 'm-1' });await vi.advanceTimersByTimeAsync(10000);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();// Same provider fails again later — must NOT be suppressed by the// dedupe map (which would otherwise hold the key for 60s).emitProviderFailure({ provider: 'Primary CLI', model: 'm-1', runId: 'r-2' });await vi.advanceTimersByTimeAsync(0);await vi.advanceTimersByTimeAsync(5500);- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);});it('files a durable investigation task when CoS is not running', async () => {- cos.isRunning.mockReturnValue(false);+ isRunning.mockReturnValue(false);emitProviderFailure({ provider: 'Primary CLI', model: 'm-1' });await vi.advanceTimersByTimeAsync(5500);- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);expect(filedTasks()[0].description).toContain('Investigate AI provider failure: Primary CLI (m-1)');expect(filedTasks()[0].isInvestigation).toBe(true);// A repeat inside the dedupe window files nothing new.emitProviderFailure({ provider: 'Primary CLI', model: 'm-1', runId: 'run-2' });await vi.advanceTimersByTimeAsync(5500);- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);});// The body built by buildAIProviderErrorContext has always fallen back to@@ -290,7 +293,7 @@ describe('autoFixer — defer + noteFallbackHandled', () => {// no attribution filed a task literally called// "Investigate AI provider failure: undefined (undefined)".it('never titles a task with a literal undefined provider or model', async () => {- cos.isRunning.mockReturnValue(false);+ isRunning.mockReturnValue(false);// Emitted raw, not through emitProviderFailure — that helper defaults// provider/model, which is exactly the attribution this case lacks.@@ -313,7 +316,7 @@ describe('autoFixer — defer + noteFallbackHandled', () => {// Simulate addTask rejecting (e.g. PLAN.md write error). Without the// dedupe-clear in the catch arm, the next identical failure would be// suppressed for 60s even though no investigation task ever landed.- cos.addTask.mockRejectedValueOnce(new Error('plan write failed'));+ addTask.mockRejectedValueOnce(new Error('plan write failed'));emitProviderFailure({ provider: 'Primary CLI', model: 'm-1', runId: 'r-1' });await vi.advanceTimersByTimeAsync(0);@@ -322,13 +325,13 @@ describe('autoFixer — defer + noteFallbackHandled', () => {await vi.advanceTimersByTimeAsync(0);// First attempt: addTask threw, so no task was created.- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);// Second identical failure within the 60s dedupe window must NOT be// suppressed — the stale dedupe entry should have been cleared.emitProviderFailure({ provider: 'Primary CLI', model: 'm-1', runId: 'r-2' });await vi.advanceTimersByTimeAsync(5500);- expect(cos.addTask).toHaveBeenCalledTimes(2);+ expect(addTask).toHaveBeenCalledTimes(2);});it('does NOT collide on hyphenated provider/model pairs (uses an unambiguous separator)', async () => {@@ -340,7 +343,7 @@ describe('autoFixer — defer + noteFallbackHandled', () => {await vi.advanceTimersByTimeAsync(5500);// Both distinct failures must schedule their own investigation task.- expect(cos.addTask).toHaveBeenCalledTimes(2);+ expect(addTask).toHaveBeenCalledTimes(2);});it('dedupes within the defer window — a second identical failure does not double-schedule', async () => {@@ -351,7 +354,7 @@ describe('autoFixer — defer + noteFallbackHandled', () => {// Only the first failure schedules a task; the second is dropped by// either isDuplicateError or the deferredTasks.has guard.- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);});});@@ -369,8 +372,8 @@ function emitCriticalError(overrides = {}) {describe('autoFixer — generic critical-error auto-fix path', () => {beforeEach(() => {vi.useFakeTimers();- cos.addTask.mockClear();- cos.isRunning.mockReturnValue(true);+ addTask.mockClear();+ isRunning.mockReturnValue(true);_resetAutoFixerForTests();});@@ -383,8 +386,8 @@ describe('autoFixer — generic critical-error auto-fix path', () => {emitCriticalError({ message: 'Cannot read properties of undefined', stack: 'Error: boom\n at foo (file.js:1:1)' });await vi.advanceTimersByTimeAsync(0);- expect(cos.addTask).toHaveBeenCalledTimes(1);- expect(cos.addTask.mock.calls[0][0]).toMatchObject({+ expect(addTask).toHaveBeenCalledTimes(1);+ expect(addTask.mock.calls[0][0]).toMatchObject({description: 'Fix critical error: Cannot read properties of undefined',approvalRequired: false,approvalReason: null,@@ -395,15 +398,15 @@ describe('autoFixer — generic critical-error auto-fix path', () => {emitCriticalError({ code: 'SOME_ERROR', message: 'recoverable-ish failure', severity: 'error' });await vi.advanceTimersByTimeAsync(0);- expect(cos.addTask).toHaveBeenCalledTimes(1);- expect(cos.addTask.mock.calls[0][0]).toMatchObject({ approvalRequired: false });+ expect(addTask).toHaveBeenCalledTimes(1);+ expect(addTask.mock.calls[0][0]).toMatchObject({ approvalRequired: false });});it('stamps the fingerprint the loop policy reads, so a repeat of the same cause is recognizable', async () => {emitCriticalError({ code: 'SOME_ERROR', message: 'first time', severity: 'error' });await vi.advanceTimersByTimeAsync(0);- expect(cos.addTask.mock.calls[0][0]).toMatchObject({+ expect(addTask.mock.calls[0][0]).toMatchObject({isInvestigation: true,investigationFingerprint: 'unknown:critical-error:SOME_ERROR',});@@ -413,7 +416,7 @@ describe('autoFixer — generic critical-error auto-fix path', () => {// A prior investigation carrying the fingerprint the production path above// actually writes, settled an hour ago — the fix did not hold, so another// unattended agent would just repeat it.- cos.getAllTasks.mockResolvedValueOnce({+ getAllTasks.mockResolvedValueOnce({user: { tasks: [] },cos: {tasks: [{@@ -431,27 +434,27 @@ describe('autoFixer — generic critical-error auto-fix path', () => {emitCriticalError({ code: 'SOME_ERROR', message: 'the same failure, again', severity: 'error' });await vi.advanceTimersByTimeAsync(0);- expect(cos.addTask).toHaveBeenCalledTimes(1);- expect(cos.addTask.mock.calls[0][0]).toMatchObject({+ expect(addTask).toHaveBeenCalledTimes(1);+ expect(addTask.mock.calls[0][0]).toMatchObject({approvalRequired: true,approvalReason: 'investigation-loop:repeat-fingerprint',});- expect(cos.addTask.mock.calls[0][0].description).toContain('Why this is held for you');+ expect(addTask.mock.calls[0][0].description).toContain('Why this is held for you');});it('does not fire for a non-critical error that is not marked auto-fixable', async () => {emitCriticalError({ code: 'VALIDATION_ERROR', message: 'bad input', severity: 'error', canAutoFix: false });await vi.advanceTimersByTimeAsync(0);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('does not fire when CoS is not running', async () => {- cos.isRunning.mockReturnValue(false);+ isRunning.mockReturnValue(false);emitCriticalError();await vi.advanceTimersByTimeAsync(0);- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();});it('dedupes identical critical errors within the window', async () => {@@ -459,15 +462,15 @@ describe('autoFixer — generic critical-error auto-fix path', () => {emitCriticalError();await vi.advanceTimersByTimeAsync(0);- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);});});describe('autoFixer — circuit breaker (guardrail #3)', () => {beforeEach(() => {vi.useFakeTimers();- cos.addTask.mockClear();- cos.isRunning.mockReturnValue(true);+ addTask.mockClear();+ isRunning.mockReturnValue(true);_resetAutoFixerForTests();});@@ -487,12 +490,12 @@ describe('autoFixer — circuit breaker (guardrail #3)', () => {await vi.advanceTimersByTimeAsync(5500); // let the deferred task fireawait vi.advanceTimersByTimeAsync(DEDUPE_GAP_MS - 5500); // clear the dedupe window}- expect(cos.addTask).toHaveBeenCalledTimes(3);+ expect(addTask).toHaveBeenCalledTimes(3);// 4th failure within the same hour trips the circuit — no task scheduled.emitProviderFailure({ provider: 'Ollama', model: 'command-r', runId: 'r-4' });await vi.advanceTimersByTimeAsync(6000);- expect(cos.addTask).toHaveBeenCalledTimes(3);+ expect(addTask).toHaveBeenCalledTimes(3);});it('AI-provider path: the circuit auto-closes once failures age out of the 1h window', async () => {@@ -502,7 +505,7 @@ describe('autoFixer — circuit breaker (guardrail #3)', () => {await vi.advanceTimersByTimeAsync(DEDUPE_GAP_MS - 5500);}// 3 tasks (4th suppressed by the open circuit).- expect(cos.addTask).toHaveBeenCalledTimes(3);+ expect(addTask).toHaveBeenCalledTimes(3);// Let the whole failure burst age past the rolling 1h window.await vi.advanceTimersByTimeAsync(60 * 60 * 1000 + 1000);@@ -510,7 +513,7 @@ describe('autoFixer — circuit breaker (guardrail #3)', () => {// A fresh failure now raises a task again — the circuit auto-closed.emitProviderFailure({ provider: 'Ollama', model: 'command-r', runId: 'r-late' });await vi.advanceTimersByTimeAsync(5500);- expect(cos.addTask).toHaveBeenCalledTimes(4);+ expect(addTask).toHaveBeenCalledTimes(4);});it('AI-provider path: the circuit is per-resource — a different provider is unaffected', async () => {@@ -519,12 +522,12 @@ describe('autoFixer — circuit breaker (guardrail #3)', () => {await vi.advanceTimersByTimeAsync(5500);await vi.advanceTimersByTimeAsync(DEDUPE_GAP_MS - 5500);}- expect(cos.addTask).toHaveBeenCalledTimes(3); // Ollama circuit open+ expect(addTask).toHaveBeenCalledTimes(3); // Ollama circuit open// A distinct provider/model still gets its investigation task.emitProviderFailure({ provider: 'LM Studio', model: 'qwen', runId: 'b-0' });await vi.advanceTimersByTimeAsync(5500);- expect(cos.addTask).toHaveBeenCalledTimes(4);+ expect(addTask).toHaveBeenCalledTimes(4);});it('AI-provider path: fallback-recovered failures do NOT count toward the circuit', async () => {@@ -540,13 +543,13 @@ describe('autoFixer — circuit breaker (guardrail #3)', () => {noteFallbackHandled({ provider: 'Ollama', model: 'command-r' }); // success — clears dedupe/in-flightawait vi.advanceTimersByTimeAsync(DEDUPE_GAP_MS);}- expect(cos.addTask).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();// A genuine unrecovered failure now STILL raises a task — the circuit never// opened because recovered failures were never counted.emitProviderFailure({ provider: 'Ollama', model: 'command-r', runId: 'real' });await vi.advanceTimersByTimeAsync(5500);- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);});it('generic critical-error path: suppresses the fix task once the same error fires >3 times within the hour', async () => {@@ -555,11 +558,11 @@ describe('autoFixer — circuit breaker (guardrail #3)', () => {await vi.advanceTimersByTimeAsync(0);await vi.advanceTimersByTimeAsync(DEDUPE_GAP_MS);}- expect(cos.addTask).toHaveBeenCalledTimes(3);+ expect(addTask).toHaveBeenCalledTimes(3);emitCriticalError({ message: 'recurring boom' });await vi.advanceTimersByTimeAsync(0);- expect(cos.addTask).toHaveBeenCalledTimes(3); // circuit open — suppressed+ expect(addTask).toHaveBeenCalledTimes(3); // circuit open — suppressed});});@@ -651,8 +654,8 @@ describe('autoFixer — structured per-attempt diagnostics (issue #2328)', () =>describe('autoFixer — diagnostics ride on the created task record (issue #2328)', () => {beforeEach(() => {vi.useFakeTimers();- cos.addTask.mockClear();- cos.isRunning.mockReturnValue(true);+ addTask.mockClear();+ isRunning.mockReturnValue(true);_resetAutoFixerForTests();});@@ -677,8 +680,8 @@ describe('autoFixer — diagnostics ride on the created task record (issue #2328});await vi.advanceTimersByTimeAsync(5500);- expect(cos.addTask).toHaveBeenCalledTimes(1);- const taskArg = cos.addTask.mock.calls[0][0];+ expect(addTask).toHaveBeenCalledTimes(1);+ const taskArg = addTask.mock.calls[0][0];expect(taskArg.diagnostics).toMatchObject({triggerEvent: 'AI_PROVIDER_EXECUTION_FAILED',target: 'Claude Code CLI (claude-opus-4-8)',@@ -706,7 +709,7 @@ describe('autoFixer — diagnostics ride on the created task record (issue #2328});it('attaches diagnostics to the filed task when CoS is not running', async () => {- cos.isRunning.mockReturnValue(false);+ isRunning.mockReturnValue(false);emitProviderFailure({ provider: 'LM Studio', model: 'qwen', runId: 'p-1' });await vi.advanceTimersByTimeAsync(5500);@@ -723,8 +726,8 @@ describe('autoFixer — diagnostics ride on the created task record (issue #2328emitCriticalError({ code: 'UNCAUGHT_EXCEPTION', message: 'Cannot read properties of undefined' });await vi.advanceTimersByTimeAsync(0);- expect(cos.addTask).toHaveBeenCalledTimes(1);- expect(cos.addTask.mock.calls[0][0].diagnostics).toMatchObject({+ expect(addTask).toHaveBeenCalledTimes(1);+ expect(addTask.mock.calls[0][0].diagnostics).toMatchObject({triggerEvent: 'UNCAUGHT_EXCEPTION',target: 'UNCAUGHT_EXCEPTION',tier: FIX_TIERS.ESCALATE,@@ -734,8 +737,8 @@ describe('autoFixer — diagnostics ride on the created task record (issue #2328describe('autoFixer — escalateProviderFailure (explicit Tier-4, issue #2342)', () => {beforeEach(() => {- cos.addTask.mockClear();- cos.isRunning.mockReturnValue(true);+ addTask.mockClear();+ isRunning.mockReturnValue(true);_resetAutoFixerForTests();});afterEach(() => {@@ -754,12 +757,12 @@ describe('autoFixer — escalateProviderFailure (explicit Tier-4, issue #2342)',it('creates an investigation task immediately (no defer window)', async () => {const task = await escalateProviderFailure(providerError());- expect(cos.addTask).toHaveBeenCalledTimes(1);- expect(cos.addTask.mock.calls[0][0]).toMatchObject({+ expect(addTask).toHaveBeenCalledTimes(1);+ expect(addTask.mock.calls[0][0]).toMatchObject({description: 'Investigate AI provider failure: Primary API (primary-model)',});// Diagnostics still ride on the escalated task (tier-classified from category).- expect(cos.addTask.mock.calls[0][0].diagnostics).toMatchObject({+ expect(addTask.mock.calls[0][0].diagnostics).toMatchObject({category: 'model-not-found',tier: FIX_TIERS.CONFIG_ENV,});@@ -774,7 +777,7 @@ describe('autoFixer — escalateProviderFailure (explicit Tier-4, issue #2342)',]);// Only the first escalation creates a task; the rest are deduped within the// window (returns null).- expect(cos.addTask).toHaveBeenCalledTimes(1);+ expect(addTask).toHaveBeenCalledTimes(1);expect(results.filter(Boolean)).toHaveLength(1);});@@ -787,11 +790,11 @@ describe('autoFixer — escalateProviderFailure (explicit Tier-4, issue #2342)',await escalateProviderFailure(providerError('Ollama', 'command-r'));await vi.advanceTimersByTimeAsync(61000);}- expect(cos.addTask).toHaveBeenCalledTimes(3);+ expect(addTask).toHaveBeenCalledTimes(3);// 4th distinct escalation (still within the 1h circuit window) trips it.const suppressed = await escalateProviderFailure(providerError('Ollama', 'command-r'));expect(suppressed).toBeNull();- expect(cos.addTask).toHaveBeenCalledTimes(3);+ expect(addTask).toHaveBeenCalledTimes(3);} finally {vi.useRealTimers();}@@ -800,13 +803,13 @@ describe('autoFixer — escalateProviderFailure (explicit Tier-4, issue #2342)',describe('autoFixer — escalateProviderFailure dedupe clears on task-creation failure (#2342)', () => {beforeEach(() => {- cos.addTask.mockReset();- cos.isRunning.mockReturnValue(true);+ addTask.mockReset();+ isRunning.mockReturnValue(true);_resetAutoFixerForTests();});afterEach(() => {- cos.addTask.mockReset();- cos.addTask.mockResolvedValue({ id: 'task-1' });+ addTask.mockReset();+ addTask.mockResolvedValue({ id: 'task-1' });_resetAutoFixerForTests();});@@ -818,16 +821,16 @@ describe('autoFixer — escalateProviderFailure dedupe clears on task-creation fcontext: { provider: 'Ollama', providerId: 'ollama', model: 'command-r', errorDetails: 'model gone', errorAnalysis: { category: 'model-not-found' } },};// First escalation: addTask rejects → dedupe marker must be cleared.- cos.addTask.mockRejectedValueOnce(new Error('plan write failed'));+ addTask.mockRejectedValueOnce(new Error('plan write failed'));const first = await (await import('./autoFixer.js')).escalateProviderFailure(err);expect(first).toBeNull();// Second identical escalation within the window must NOT be deduped — it// creates the task the failed first attempt never did.- cos.addTask.mockResolvedValueOnce({ id: 'task-ok' });+ addTask.mockResolvedValueOnce({ id: 'task-ok' });const second = await (await import('./autoFixer.js')).escalateProviderFailure(err);expect(second).toBeTruthy();- expect(cos.addTask).toHaveBeenCalledTimes(2);+ expect(addTask).toHaveBeenCalledTimes(2);});});@@ -839,8 +842,8 @@ describe('autoFixer — escalateProviderFailure dedupe clears on task-creation fdescribe('autoFixer — stale deployed build in the investigation body', () => {beforeEach(() => {vi.useFakeTimers();- cos.addTask.mockClear();- cos.isRunning.mockReturnValue(false);+ addTask.mockClear();+ isRunning.mockReturnValue(false);installState.getBootCommit.mockReturnValue(null);installState.getInstallState.mockClear();installState.getInstallState.mockResolvedValue(null);diff --git a/server/services/autonomousJobs/layeredIntelligenceHooks.js b/server/services/autonomousJobs/layeredIntelligenceHooks.jsindex 190682e255..2c3a9ec3b2 100644--- a/server/services/autonomousJobs/layeredIntelligenceHooks.js+++ b/server/services/autonomousJobs/layeredIntelligenceHooks.js@@ -533,7 +533,7 @@ export function isTaskOutputPayload(payload) {}async function defaultEnqueueHandoff(taskData) {- const { addTask } = await import('../cos.js')+ const { addTask } = await import('../cosTaskStore.js')return addTask(taskData, 'internal')}diff --git a/server/services/branchCompletionPolicy.test.js b/server/services/branchCompletionPolicy.test.jsindex 06cde01714..ea3d5a08cb 100644--- a/server/services/branchCompletionPolicy.test.js+++ b/server/services/branchCompletionPolicy.test.js@@ -17,6 +17,7 @@ vi.mock('../lib/fileUtils.js', async () => ({}));vi.mock('./cosState.js', () => ({ readAgentsStateForSafetyCheck: async () => ({ trusted: runtime.trusted, agents: runtime.agents }) }));vi.mock('./cosAgentLifecycle.js', () => ({+ getAgents: async () => [],getAgentRecord: async id => runtime.agents[id],updateAgent: async (id, patch) => { runtime.agents[id].metadata = { ...runtime.agents[id].metadata, ...patch.metadata }; },}));@@ -34,7 +35,8 @@ vi.mock('./github.js', () => ({},getIssueDispatchHint: async () => ({ status: 'unavailable' }),}));-vi.mock('./cos.js', () => ({ addTask: async task => ({ ...parseTasksMarkdown(generateTasksMarkdown([task]))[0], taskType: 'internal' }), forceSpawnTask: vi.fn(), getAgents: async () => [], updateTask: vi.fn() }));+vi.mock('./cosTaskStore.js', () => ({ addTask: async task => ({ ...parseTasksMarkdown(generateTasksMarkdown([task]))[0], taskType: 'internal' }), updateTask: vi.fn() }));+vi.mock('./cos.js', () => ({ forceSpawnTask: vi.fn() }));vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));vi.mock('./cosAgentIndex.js', () => ({ removeDanglingAgentIndexEntries: vi.fn(async ids => ids.length) }));vi.mock('./git.js', () => ({ parsePullRequestUrl, getBranches: async () => [{ name: 'feature/handoff', tracking: 'origin/feature/handoff' }], getDefaultBranch: async () => 'main', hasBranchMergeEvidence: async () => runtime.merged }));diff --git a/server/services/capabilitiesSnapshot.js b/server/services/capabilitiesSnapshot.jsindex c7c0b8499e..7273a993f9 100644--- a/server/services/capabilitiesSnapshot.js+++ b/server/services/capabilitiesSnapshot.js@@ -10,7 +10,7 @@ import { getAllProviderStatuses } from './providerStatus.js';import { listAccounts as listCalendarAccounts } from './calendarAccounts.js';import { listAccounts as listMessageAccounts } from './messageAccounts.js';import { countMemories } from './memoryBackend.js';-import { getConfig as getCosConfig } from './cos.js';+import { getConfig as getCosConfig } from './cosState.js';import { getVoiceConfig } from './voice/config.js';import { getNetworkExposureSetupStatus } from '../lib/networkExposure.js';import { getGenomeSummary } from './genome.js';diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 9ea0494fe1..4b397115e2 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -42,22 +42,26 @@ vi.mock('../lib/uuid.js', () => ({v4: vi.fn(() => 'mock-uuid')}));-vi.mock('./cos.js', () => ({- cosEvents: { on: vi.fn(), emit: vi.fn() },+vi.mock('./cosAgentLifecycle.js', () => ({registerAgent: vi.fn().mockResolvedValue(undefined),updateAgent: vi.fn().mockResolvedValue(undefined),completeAgent: vi.fn().mockResolvedValue(undefined),appendAgentOutput: vi.fn().mockResolvedValue(undefined),- getConfig: vi.fn().mockResolvedValue({}),- updateTask: vi.fn().mockResolvedValue(undefined),- addTask: vi.fn().mockResolvedValue(undefined),- emitLog: vi.fn(),- getTaskById: vi.fn().mockResolvedValue(null),- forceSpawnTask: vi.fn().mockResolvedValue({ success: true }),getAgent: vi.fn().mockResolvedValue(null),getAgentRecord: vi.fn().mockResolvedValue(null),getAgents: vi.fn().mockResolvedValue([])}));+vi.mock('./cosState.js', () => ({+ getConfig: vi.fn().mockResolvedValue({})+}));+vi.mock('./cosTaskStore.js', () => ({+ updateTask: vi.fn().mockResolvedValue(undefined),+ addTask: vi.fn().mockResolvedValue(undefined),+ getTaskById: vi.fn().mockResolvedValue(null)+}));+vi.mock('./cos.js', () => ({+ forceSpawnTask: vi.fn().mockResolvedValue({ success: true })+}));vi.mock('./appActivity.js', () => ({startAppCooldown: vi.fn(),@@ -248,7 +252,9 @@ import { existsSync as existsSyncMock } from 'fs';// They used to be pulled through the `subAgentSpawner.js` barrel, which was// retired in #3450.import { cleanupAgentWorktree, resolveWorktreeDisposition, spawnMergeRecoveryTask, spawnReviewLoopFollowUp, resolveResumePointer, resolveTaskResumePatch, recordTaskResumePointer, releaseRetryHold, resumePointerMetadata } from './agentWorktreeCleanup.js';-import { getAgent, getAgentRecord, getAgents, getTaskById, addTask, forceSpawnTask, updateTask, updateAgent } from './cos.js';+import { getAgent, getAgentRecord, getAgents, updateAgent } from './cosAgentLifecycle.js';+import { getTaskById, addTask, updateTask } from './cosTaskStore.js';+import { forceSpawnTask } from './cos.js';import { listWorktrees, removeWorktree } from './worktreeManager.js';import { PATHS } from '../lib/fileUtils.js';import * as git from './git.js';diff --git a/server/services/cos.js b/server/services/cos.jsindex efd811385d..814009057a 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -1,5 +1,4 @@import { maintenance } from '../lib/maintenanceAdmission.js';-import { getPendingTaskIds as readPendingTaskIds } from './cosTaskStore.js';import { mergePersistentMindMaintainer } from '../lib/persistentMindMaintainer.js';/*** Chief of Staff (CoS) Service@@ -53,49 +52,16 @@ import { useRunner, spawningTasks } from './agentState.js';// Shared state management (extracted to avoid circular deps)import { loadState, saveState, withStateLock, loadConfig, saveConfig, withConfigLock, ensureDirectories, isImprovementEnabled, canQueueImprovementTasks, SCRIPTS_DIR, isDaemonRunning, setDaemonRunning } from './cosState.js';-// Events and logging (canonical source: cosEvents.js)+// Events and loggingimport { cosEvents, emitLog } from './cosEvents.js';-export { cosEvents, emitLog };-// Agent lifecycle (re-export for backward compat with `import * as cos`).-//-// Sourced from the four modules that DECLARE these, not from a barrel: the-// `cosAgents.js` barrel these used to come through is retired (#3450), so this-// block is the last remaining second address for an agent function and the next-// one to collapse.-//-// `pauseAgent` / `killAgent` / `getAgentProcessStats` are deliberately NOT here:-// they are process-layer transitions, and re-exporting them from the task store-// is what forced the `await import()` forwarders in `cosAgentLifecycle.js`.-// Callers ask `agentOrchestrator.js` for those (#3450).-export { registerAgent, updateAgent, completeAgent, appendAgentOutput, getAgents, getAgent, getAgentRecord, getAgentPrompt, terminateAgent, sendBtwToAgent, cleanupZombieAgents, deleteAgent } from './cosAgentLifecycle.js';-export { getAgentDates, getAgentsByDate, getCompletedAgentPage, pruneOldAgentArchives } from './cosAgentIndex.js';-export {- submitAgentFeedback,- getFeedbackStats,- getPendingAgentFeedback,- getPendingAgentFeedbackCount,- getPendingAgentFeedbackPage,- initializeAgentFeedback,-} from './cosAgentFeedback.js';-export { archiveStaleAgents, clearCompletedAgents } from './cosAgentArchive.js';--// Reports and activity (re-export for backward compat with `import * as cos`)-export { generateReport, getReport, getTodayReport, listReports, listBriefings, getBriefing, getLatestBriefing, getTodayActivity, getWhileAwayActivity, getRecentTasks, formatRelativeTime } from './cosReports.js';--// Health monitoring (imported for internal use by start()/init() and re-exported-// for backward compat with `import * as cos` and the cos route handlers)-import { runHealthCheck, getHealthStatus } from './cosHealthMonitor.js';-export { runHealthCheck, getHealthStatus };--// Task store: CRUD + queue persistence (the `cos_tasks` queues). Imported for-// internal use by evaluateTasks/dequeueNextTask/generators and re-exported for-// backward compat with `import * as cos` and the cos route handlers. The store+import { runHealthCheck } from './cosHealthMonitor.js';++// Task store: CRUD + queue persistence (the `cos_tasks` queues). Callers import+// these from the declaring modules, not from here. The store// emits `tasks:changed`; init() below turns that into tryImmediateSpawn /// dequeueNextTask so the spawn-side logic stays here, not in the store.-import { firstLine, getUserTasks, getCosTasks, getAllTasks, getTaskView, getTasks, getTaskById, findTaskWithSource, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks } from './cosTaskStore.js';-export { getPendingTaskIds } from './cosTaskStore.js';-export { firstLine, getUserTasks, getCosTasks, getAllTasks, getTaskView, getTasks, getTaskById, findTaskWithSource, addTask, updateTask, reviveBlockedTask, deleteTask, reorderTasks, approveTask, challengeTask, resolveTaskChallenge, resolveTaskChallengeWithRecheck, sweepResolvedFailureTasks };+import { getPendingTaskIds as readPendingTaskIds, getUserTasks, getCosTasks, getAllTasks, getTaskById, addTask, updateTask, sweepResolvedFailureTasks } from './cosTaskStore.js';import { ensureInstanceId } from './instanceIdentity.js';import { isHeldByOther, buildRenewal, buildClaim, getClaimOwner } from './cosTaskClaim.js';import { retryTasksResolvedByInvestigation } from './investigationRetry.js';@@ -129,9 +95,7 @@ import { resolveAgentProviderAndModel } from './agentProviderResolution.js';// Task generation + evaluation engine (extracted to cosTaskGenerator.js).// `evaluateTasks` and the generators emit `task:ready`; the spawn-side// scheduler (dequeueNextTask / tryImmediateSpawn) below reacts to that. Most of-// these are imported for internal use by the scheduler; checkStagePrecondition-// is re-exported for agentCompletionCleanup.js, applyAppWorktreeDefault for the-// suite, and evaluateTasks for the cos route + `import * as cos`.+// these are imported for internal use by the scheduler.import {evaluateTasks,queueEligibleImprovementTasks,@@ -140,11 +104,8 @@ import {resolveAutonomyBudget,countRunningAgentsByProject,isWithinProjectLimit,- checkStagePrecondition,- applyAppWorktreeDefault,unblockExpiredCooldowns} from './cosTaskGenerator.js';-export { evaluateTasks, checkStagePrecondition, applyAppWorktreeDefault };// Autonomous-job + improvement-check timer machinery (extracted to// cosJobScheduler.js). Imported for internal use by start()/stop()/init() and@@ -180,19 +141,6 @@ import {// executes once it is actually running, but that a static edge instantiated in// every suite importing cos.js for an unrelated helper.-export {- getPersistentMindState,- setPersistentMindEnabled,- startPersistentMind,- pausePersistentMind,- resumePersistentMind,- stopPersistentMind,- enqueuePersistentMindMessage,- requestPersistentMindWake,- registerPersistentMindTurnAdapter,- unregisterPersistentMindTurnAdapter,-} from './persistentMindSupervisor.js';-/*** Get current CoS status*/@@ -225,10 +173,6 @@ export async function getStatus() {};}-// Get current configuration (moved to cosState.js to break an import cycle;-// re-exported here for backward compat with `import * as cos`).-export { getConfig } from './cosState.js';-/*** Update configuration*/@@ -1008,9 +952,6 @@ export async function getScript(name) {return { name, content, metadata };}-// Agent and report functions are now in the cosAgent* modules and cosReports.js-// Re-exported above for backward compat with `import * as cos from './cos.js'`-/*** Check if daemon is running*/diff --git a/server/services/cosMergeAdmission.cleanupRecovery.test.js b/server/services/cosMergeAdmission.cleanupRecovery.test.jsindex 1507b67b60..ac530658ec 100644--- a/server/services/cosMergeAdmission.cleanupRecovery.test.js+++ b/server/services/cosMergeAdmission.cleanupRecovery.test.js@@ -9,6 +9,7 @@ import { generateTasksMarkdown, parseTasksMarkdown } from '../lib/taskParser.js'// create another cognitive task for an absent, unverified original checkout.vi.mock('../lib/backupSnapshotBoundary.js', () => ({ withBackupAssetPublication: work => work() }));const f = vi.hoisted(() => ({ state: null, disk: null, tasks: {}, archive: {} }));+vi.mock('./cos.js', () => ({}));vi.mock('./cosState.js', () => ({AGENTS_DIR: '/synthetic/agents',withStateLock: createFileWriteQueue(),@@ -27,10 +28,10 @@ vi.mock('./cosAgentIndex.js', async () => ({}));vi.mock('./cosClaimOwnership.js', () => ({ readClaimOwnershipAgents: async () => Object.values(f.state.agents) }));vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() }, emitLog: vi.fn() }));-vi.mock('./cosTaskStore.js', () => ({ getTaskById: async id => f.tasks[id] ?? null }));-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({addTask: vi.fn(async () => ({ id: 'task-recovery-1' })),getAllTasks: vi.fn(async () => ({ user: { tasks: [] }, cos: { tasks: [] } })),+ getTaskById: async id => f.tasks[id] ?? null,}));vi.mock('./prWatcher.js', () => ({ readPendingMergePrs: () => [] }));vi.mock('./worktreeManager.js', () => ({ listWorktrees: async () => [] }));@@ -55,7 +56,7 @@ const BRANCH = vi.hoisted(() => 'cos/task-parent/parent-1');const PR_URL = 'https://github.com/example/repo/pull/7';const REPOSITORY = 'github.com/example/repo';-import { addTask } from './cos.js';+import { addTask } from './cosTaskStore.js';import { findPullRequestForBranch } from './github.js';import { buildTaskMetadata } from './cosTaskIntake.js';import { buildAgentRegistration } from '../lib/agentRegistrationRecord.js';diff --git a/server/services/cosMergeAdmission.reviewCoordinator.test.js b/server/services/cosMergeAdmission.reviewCoordinator.test.jsindex 9791dd2636..c44e80ae44 100644--- a/server/services/cosMergeAdmission.reviewCoordinator.test.js+++ b/server/services/cosMergeAdmission.reviewCoordinator.test.js@@ -14,11 +14,14 @@ vi.mock('./cosState.js', () => ({readMergeAdmissionStateForSafetyCheck: async () => ({ trusted: true, ...structuredClone(f.disk) }),}));vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() }, emitLog: vi.fn() }));+vi.mock('./cosTaskStore.js', () => ({+ addTask: async task => { f.tasks[task.id] = { ...parseTasksMarkdown(generateTasksMarkdown([task]))[0], taskType: 'internal' }; return task; }, updateTask: vi.fn(),+ getTaskById: async id => f.tasks[id],+}));vi.mock('./cos.js', () => ({- addTask: async task => { f.tasks[task.id] = { ...parseTasksMarkdown(generateTasksMarkdown([task]))[0], taskType: 'internal' }; return task; },- forceSpawnTask: vi.fn(), getAgents: async () => [], updateTask: vi.fn(),+ forceSpawnTask: vi.fn(),}));-vi.mock('./cosTaskStore.js', () => ({ getTaskById: async id => f.tasks[id] }));+vi.mock('./cosAgentLifecycle.js', async importOriginal => ({ ...(await importOriginal()), getAgents: async () => [] }));vi.mock('../lib/gitRemote.js', async importOriginal => ({ ...(await importOriginal()),getOriginInfo: async path => ({ host: f.originHost, fullName: path === '/repos/worktree' ? f.workspaceRepo : 'example/repo' }) }));vi.mock('./github.js', () => ({ execGh: vi.fn(async () => JSON.stringify(f.row)) }));diff --git a/server/services/cosMergeHandoff.test.js b/server/services/cosMergeHandoff.test.jsindex 6d9286e53c..227bb0c62d 100644--- a/server/services/cosMergeHandoff.test.js+++ b/server/services/cosMergeHandoff.test.js@@ -17,8 +17,10 @@ vi.mock('./cosState.js', async () => {readMergeAdmissionStateForSafetyCheck: async () => ({ trusted: true, ...structuredClone(f.state) }),};});-vi.mock('./cos.js', () => ({ addTask: vi.fn(async () => ({ id: 'cleanup-recovery' })) }));-vi.mock('./cosTaskStore.js', () => ({ getTaskById: async (id) => f.tasks[id] ?? null }));+vi.mock('./cosTaskStore.js', () => ({+ addTask: vi.fn(async () => ({ id: 'cleanup-recovery' })),+ getTaskById: async (id) => f.tasks[id] ?? null,+}));vi.mock('../lib/gitRemote.js', () => ({getOriginInfo: async (path) => ({ host: 'github.com', fullName: f.foreign.has(path) ? 'example/other' : 'example/repo' }),}));@@ -63,7 +65,7 @@ vi.mock('./heldCheckoutRecovery.js', () => ({ retirePendingMergeCheckout: (...arimport { handoffPendingMerge, hasQueuedMergeHandoff } from './cosMergeHandoff.js';import { processPendingMergePrs, readPendingMergePrs, nudgeLocalPendingMergePrs } from './prWatcher.js';import { claimMergeAdmission } from './cosMergeAdmission.js';-import { addTask } from './cos.js';+import { addTask } from './cosTaskStore.js';const HEAD = 'a'.repeat(40);const PR_URL = 'https://github.com/example/repo/pull/7';diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 356295c344..808ba91255 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -64,9 +64,9 @@ vi.mock('./cosState.js', async () => ({vi.mock('./cos.js', () => ({isRunning: vi.fn(() => false),+}));+vi.mock('./cosAgentLifecycle.js', () => ({getAgentRecord: vi.fn(),- getTaskById: (...args) => getTaskById(...args),- updateTask: (...args) => updateTask(...args),}));vi.mock('./cosEvents.js', () => ({diff --git a/server/services/creativeDirector/agentBridge.js b/server/services/creativeDirector/agentBridge.jsindex baca31bde4..43db78c57d 100644--- a/server/services/creativeDirector/agentBridge.js+++ b/server/services/creativeDirector/agentBridge.js@@ -16,7 +16,8 @@import { randomUUID } from 'crypto';import { fileURLToPath } from 'node:url';-import { addTask, reviveBlockedTask, cosEvents } from '../cos.js';+import { addTask, reviveBlockedTask } from '../cosTaskStore.js';+import { cosEvents } from '../cosEvents.js';import { buildTreatmentPrompt, buildEvaluatePrompt, buildPlanPrompt } from '../creativeDirectorPrompts.js';import { getToolSpecs } from '../creative/toolRegistry.js';import { getSettings } from '../settings.js';diff --git a/server/services/creativeDirector/agentBridge.test.js b/server/services/creativeDirector/agentBridge.test.jsindex ccc3b0e6a0..7c17fdc713 100644--- a/server/services/creativeDirector/agentBridge.test.js+++ b/server/services/creativeDirector/agentBridge.test.js@@ -15,9 +15,11 @@ const mocks = vi.hoisted(() => ({}));vi.mock('./videoExecution.js', () => ({ effectiveVideoProject: project => project, reserveVideoAttempt: vi.fn(async () => ({ id: 'example-attempt' })), assertVideoAttemptDispatch: vi.fn(async () => ({})), settleVideoAttempt: vi.fn(async () => {}), pauseVideoExecution: vi.fn(async () => {}) }));-vi.mock('../cos.js', () => ({+vi.mock('../cosTaskStore.js', () => ({addTask: mocks.addTask,reviveBlockedTask: mocks.reviveBlockedTask,+}));+vi.mock('../cosEvents.js', () => ({cosEvents: { emit: mocks.emit },}));vi.mock('../creativeDirectorPrompts.js', () => ({diff --git a/server/services/creativeDirector/recovery.test.js b/server/services/creativeDirector/recovery.test.jsindex 60ceaee562..c81f69a2a0 100644--- a/server/services/creativeDirector/recovery.test.js+++ b/server/services/creativeDirector/recovery.test.js@@ -37,7 +37,7 @@ vi.mock('../mediaJobQueue/index.js', () => ({cancelJob: (...args) => mockCancelJob(...args),}));-vi.mock('../cos.js', () => ({+vi.mock('../cosTaskStore.js', () => ({updateTask: (...args) => mockUpdateTask(...args),}));diff --git a/server/services/creativeDirector/renderFailureTask.js b/server/services/creativeDirector/renderFailureTask.jsindex 62b041d8e3..8ca696a45e 100644--- a/server/services/creativeDirector/renderFailureTask.js+++ b/server/services/creativeDirector/renderFailureTask.js@@ -33,7 +33,7 @@ export function buildCreativeDirectorRenderFailureTask({ projectId, sceneId = nuexport async function queueCreativeDirectorRenderFailureTask({ projectId, sceneId = null, jobId, error }) {const task = buildCreativeDirectorRenderFailureTask({ projectId, sceneId, jobId, error });- const { addTask } = await import('../cos.js');+ const { addTask } = await import('../cosTaskStore.js');const queued = await addTask(task, 'internal');if (queued?.duplicate) {console.log(`⚠️ CD render repair already queued for ${projectId}/${sceneId || 'project'} as ${queued.id}`);diff --git a/server/services/creativeDirector/stopProject.js b/server/services/creativeDirector/stopProject.jsindex ee17206392..84ab1fe086 100644--- a/server/services/creativeDirector/stopProject.js+++ b/server/services/creativeDirector/stopProject.js@@ -138,7 +138,7 @@ export async function retireRuns(projectId, { runs = [], reason = 'Stopped', tas// taskType MUST be 'internal' and status MUST be a value generateTasksMarkdown// supports — see the long-form rationale in recovery.js#recoverInFlightProjects,// which retires the same task rows.- const { updateTask } = await loadOrEmpty(() => import('../cos.js'), 'cos', projectId);+ const { updateTask } = await loadOrEmpty(() => import('../cosTaskStore.js'), 'cos', projectId);if (updateTask) {for (const taskId of taskIds) {tasks += await tally(updateTask(taskId, {diff --git a/server/services/creativeDirector/stopProject.test.js b/server/services/creativeDirector/stopProject.test.jsindex bcd0e5ad28..21bcc2da1c 100644--- a/server/services/creativeDirector/stopProject.test.js+++ b/server/services/creativeDirector/stopProject.test.js@@ -24,7 +24,7 @@ vi.mock('../agentManagement.js', () => ({}));const updateTaskMock = vi.fn(async () => ({}));-vi.mock('../cos.js', () => ({ updateTask: (...a) => updateTaskMock(...a) }));+vi.mock('../cosTaskStore.js', () => ({ updateTask: (...a) => updateTaskMock(...a) }));const listJobsMock = vi.fn(() => []);const cancelJobMock = vi.fn(async () => ({}));diff --git a/server/services/creativeDirector/videoExecution.js b/server/services/creativeDirector/videoExecution.jsindex 293c5fb88d..655e3b4f10 100644--- a/server/services/creativeDirector/videoExecution.js+++ b/server/services/creativeDirector/videoExecution.js@@ -171,7 +171,7 @@ export async function reconcileVideoExecution(projectId, { restarting = false, rif (!restarting) {const liveAgents = (snapshot?.videoExecution?.attempts || []).filter(attempt => !isMediaAttempt(attempt) && LIVE_ATTEMPTS.has(attempt.status) && attempt.taskId);if (liveAgents.length) {- const { getTaskById } = await import('../cos.js');+ const { getTaskById } = await import('../cosTaskStore.js');for (const attempt of liveAgents) tasks.set(attempt.taskId, await getTaskById(attempt.taskId));}}diff --git a/server/services/eidoverseWorldSources.js b/server/services/eidoverseWorldSources.jsindex 6b24f6bc5e..a98dbb4abc 100644--- a/server/services/eidoverseWorldSources.js+++ b/server/services/eidoverseWorldSources.js@@ -11,7 +11,10 @@ import { statfs } from 'node:fs/promises';import { parseFilesystemStats } from '../lib/fileCore.js';import { getAllApps } from './apps.js';import { getAppStatuses } from './appProcessStatus.js';-import { getStatus as getCosStatus, getAgents, getCosTasks, getTodayActivity } from './cos.js';+import { getStatus as getCosStatus } from './cos.js';+import { getAgents } from './cosAgentLifecycle.js';+import { getCosTasks } from './cosTaskStore.js';+import { getTodayActivity } from './cosReports.js';import { getPendingCounts } from './review.js';import { getPeers } from './instances.js';import { getInstanceFeatures } from './instanceFeatures.js';diff --git a/server/services/eidoverseWorldSources.test.js b/server/services/eidoverseWorldSources.test.jsindex 629d83ae0c..3fa63f1def 100644--- a/server/services/eidoverseWorldSources.test.js+++ b/server/services/eidoverseWorldSources.test.js@@ -33,10 +33,16 @@ vi.mock('./apps.js', () => ({vi.mock('./appProcessStatus.js', () => ({getAppStatuses: vi.fn(async () => sources.apps),}));-vi.mock('./cos.js', () => ({+vi.mock('./cosAgentLifecycle.js', () => ({getAgents: vi.fn(async () => sources.agents),+}));+vi.mock('./cosTaskStore.js', () => ({getCosTasks: vi.fn(async () => sources.taskState),+}));+vi.mock('./cos.js', () => ({getStatus: vi.fn(async () => sources.cosStatus),+}));+vi.mock('./cosReports.js', () => ({getTodayActivity: vi.fn(async () => sources.todayActivity),}));vi.mock('./review.js', () => ({ getPendingCounts: vi.fn(async () => sources.review) }));diff --git a/server/services/featureAgents.js b/server/services/featureAgents.jsindex f52264757c..fe6baa6c9c 100644--- a/server/services/featureAgents.js+++ b/server/services/featureAgents.js@@ -308,7 +308,8 @@ export async function triggerFeatureAgent(id) {}const task = generateTaskFromFeatureAgent(agent);- const { addTask, forceSpawnTask } = await import('./cos.js');+ const { addTask } = await import('./cosTaskStore.js');+ const { forceSpawnTask } = await import('./cos.js');const persisted = await addTask(task, 'internal', { raw: true, suppressDequeue: true });if (!persisted?.id) {return { triggered: false, reason: 'Feature agent run was not queued', agent };diff --git a/server/services/featureAgents.trigger.test.js b/server/services/featureAgents.trigger.test.jsindex 5224e252b5..d8633f37a4 100644--- a/server/services/featureAgents.trigger.test.js+++ b/server/services/featureAgents.trigger.test.js@@ -11,8 +11,10 @@ vi.mock('../lib/fileUtils.js', async () => {return makePathsProxy(actual, { dataRoot: tempRoot });});+vi.mock('./cosTaskStore.js', () => ({+ addTask: vi.fn()+}));vi.mock('./cos.js', () => ({- addTask: vi.fn(),forceSpawnTask: vi.fn()}));@@ -20,7 +22,8 @@ vi.mock('./apps.js', () => ({getAppById: vi.fn()}));-import { addTask, forceSpawnTask } from './cos.js';+import { addTask } from './cosTaskStore.js';+import { forceSpawnTask } from './cos.js';import { getAppById } from './apps.js';const { generateTaskFromFeatureAgent, triggerFeatureAgent, stopFeatureAgent, updateFeatureAgent } = await import('./featureAgents.js');import { cosEvents } from './cosEvents.js';diff --git a/server/services/githubNotifications.db.test.js b/server/services/githubNotifications.db.test.jsindex c5b095e9ee..abb2908e0d 100644--- a/server/services/githubNotifications.db.test.js+++ b/server/services/githubNotifications.db.test.js@@ -28,7 +28,7 @@ vi.mock('../lib/gitRemote.js', async (importOriginal) => ({readOriginRemoteUrl: vi.fn(async (repoPath) => (repoPath === '/example/acme-app' ? 'https://github.com/acme/app.git' : null)),}));vi.mock('./prReviewerSecurity.js', () => ({ listExternalOpenPullRequests: vi.fn() }));-vi.mock('./cos.js', () => ({ getAllTasks: vi.fn(async () => ({ user: { tasks: [] }, cos: { tasks: [] } })) }));+vi.mock('./cosTaskStore.js', () => ({ getAllTasks: vi.fn(async () => ({ user: { tasks: [] }, cos: { tasks: [] } })) }));vi.mock('./taskSchedule.js', () => ({ triggerOnDemandTask: vi.fn(), getOnDemandRequests: vi.fn(async () => []) }));vi.mock('./notifications.js', () => ({addNotification: vi.fn(async () => ({})),diff --git a/server/services/goalFidelityCalibration.js b/server/services/goalFidelityCalibration.jsindex b84ea4d3e7..82fdf9158a 100644--- a/server/services/goalFidelityCalibration.js+++ b/server/services/goalFidelityCalibration.js@@ -36,7 +36,7 @@**/-import { updateTask } from './cos.js';+import { updateTask } from './cosTaskStore.js';import { getAgents, updateAgent } from './cosAgentLifecycle.js';import { getSettings } from './settings.js';import { fileInvestigationTask } from './investigationTaskProducer.js';diff --git a/server/services/goalFidelityCalibration.test.js b/server/services/goalFidelityCalibration.test.jsindex f16fef9ca4..ed7464d9de 100644--- a/server/services/goalFidelityCalibration.test.js+++ b/server/services/goalFidelityCalibration.test.js@@ -25,7 +25,7 @@ const updateTask = vi.fn();const getAgents = vi.fn();const updateAgent = vi.fn();-vi.mock('./cos.js', () => ({ updateTask }));+vi.mock('./cosTaskStore.js', () => ({ updateTask }));vi.mock('./cosAgentLifecycle.js', () => ({ getAgents, updateAgent }));vi.mock('./settings.js', () => ({ getSettings }));vi.mock('./investigationTaskProducer.js', () => ({ fileInvestigationTask }));diff --git a/server/services/investigationTaskProducer.js b/server/services/investigationTaskProducer.jsindex 3a8e5927d9..cea168ec9c 100644--- a/server/services/investigationTaskProducer.js+++ b/server/services/investigationTaskProducer.js@@ -25,7 +25,7 @@* subscribes to it, so the facade would close a load-time cycle there.)*/-import { addTask, getAllTasks } from './cos.js';+import { addTask, getAllTasks } from './cosTaskStore.js';import {INVESTIGATION_CIRCUIT_MAX_CREATIONS,INVESTIGATION_CIRCUIT_WINDOW_MS,diff --git a/server/services/investigationTaskProducer.test.js b/server/services/investigationTaskProducer.test.jsindex 5a8f810133..dc9c7cda5e 100644--- a/server/services/investigationTaskProducer.test.js+++ b/server/services/investigationTaskProducer.test.js@@ -1,11 +1,11 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({addTask: vi.fn().mockResolvedValue({ id: 'sys-1' }),getAllTasks: vi.fn().mockResolvedValue({ user: { tasks: [] }, cos: { tasks: [] } }),}));-const { addTask, getAllTasks } = await import('./cos.js');+const { addTask, getAllTasks } = await import('./cosTaskStore.js');const {fileInvestigationTask,investigationCircuitOpen,diff --git a/server/services/localPersistentMindSetup.js b/server/services/localPersistentMindSetup.jsindex 81d808300b..59ed705efe 100644--- a/server/services/localPersistentMindSetup.js+++ b/server/services/localPersistentMindSetup.js@@ -22,7 +22,8 @@ import { getNavPageForPath } from '../lib/navManifest.js';import { getProviderById, updateProvider } from './providers.js';import { listModels } from './localLlm.js';import * as ollamaManager from './ollamaManager.js';-import { getConfig, updateConfig } from './cos.js';+import { getConfig } from './cosState.js';+import { updateConfig } from './cos.js';const STEP_IDS = Object.freeze(['recommendation',diff --git a/server/services/localPersistentMindSetup.test.js b/server/services/localPersistentMindSetup.test.jsindex 70cab1666f..ce0912397e 100644--- a/server/services/localPersistentMindSetup.test.js+++ b/server/services/localPersistentMindSetup.test.js@@ -16,8 +16,10 @@ vi.mock('./localLlm.js', () => ({vi.mock('./ollamaManager.js', () => ({getStatus: vi.fn(),}));-vi.mock('./cos.js', () => ({+vi.mock('./cosState.js', () => ({getConfig: vi.fn(),+}));+vi.mock('./cos.js', () => ({updateConfig: vi.fn(),}));@@ -26,7 +28,8 @@ const { findCommandOnPath } = await import('../lib/processEnv.js');const { getProviderById, updateProvider } = await import('./providers.js');const { listModels } = await import('./localLlm.js');const ollamaManager = await import('./ollamaManager.js');-const { getConfig, updateConfig } = await import('./cos.js');+const { getConfig } = await import('./cosState.js');+const { updateConfig } = await import('./cos.js');const {applyLocalPersistentMindSetup,describeLocalPersistentMindSetup,diff --git a/server/services/orphanedPrNotifier.js b/server/services/orphanedPrNotifier.jsindex 9d9a61cd70..148285fb8c 100644--- a/server/services/orphanedPrNotifier.js+++ b/server/services/orphanedPrNotifier.js@@ -34,7 +34,7 @@ async function handBackBlockedRemediation(task) {if (task.metadata.blockedCategory === 'pr-head-moved') return false;return queueHandback(task.id, async () => {const [{ getTaskById, updateTask }, { getAppById }, { handBackPrRemediation }] = await Promise.all([- import('./cos.js'), import('./apps.js'), import('./prRemediationFollowUp.js'),+ import('./cosTaskStore.js'), import('./apps.js'), import('./prRemediationFollowUp.js'),]);// Re-read inside the queue: overlapping block events may hold older snapshots.const current = await getTaskById(task.id);diff --git a/server/services/orphanedPrNotifier.test.js b/server/services/orphanedPrNotifier.test.jsindex b8e7246cf6..2da44a7e58 100644--- a/server/services/orphanedPrNotifier.test.js+++ b/server/services/orphanedPrNotifier.test.js@@ -16,13 +16,13 @@ vi.mock('./notifications.js', () => ({}));vi.mock('./brainTaskThreads.js', () => ({ ensureTaskThread: vi.fn().mockResolvedValue({}) }));-vi.mock('./cos.js', () => ({ addTask: vi.fn(), getTaskById: vi.fn(), updateTask: vi.fn() }));+vi.mock('./cosTaskStore.js', () => ({ addTask: vi.fn(), getTaskById: vi.fn(), updateTask: vi.fn() }));vi.mock('./github.js', () => ({ execGh: vi.fn().mockImplementation(async (args) => args[0] === 'api' ? 'maintainer' : 'false') }));vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));vi.mock('./forgeAuth.js', () => ({ resolveForgeForRepo: vi.fn().mockResolvedValue({ cli: 'gh', env: {} }) }));vi.mock('./apps.js', () => ({ getAppById: vi.fn().mockResolvedValue({ repoPath: '/repos/example' }) }));-import { getTaskById, updateTask } from './cos.js';+import { getTaskById, updateTask } from './cosTaskStore.js';import { execGh } from './github.js';import { notifyIfPrLeftOrphaned } from './orphanedPrNotifier.js';import { addNotification, exists } from './notifications.js';diff --git a/server/services/prDoReviewTask.js b/server/services/prDoReviewTask.jsindex 4b8ace4f1f..5abc702dd3 100644--- a/server/services/prDoReviewTask.js+++ b/server/services/prDoReviewTask.js@@ -116,7 +116,8 @@ export async function spawnPrDoReviewTask({app, pullRequest, repoFullName = '', provider, model, effort,selfReview = false, reviewerConfig = null,} = {}) {- const { addTask, forceSpawnTask } = await import('./cos.js');+ const { addTask } = await import('./cosTaskStore.js');+ const { forceSpawnTask } = await import('./cos.js');const { number, url } = pullRequest;const appLabel = String(app.name || app.id).replace(/\s+/g, ' ').trim();const repoLabel = repoFullName || appLabel;diff --git a/server/services/prDoReviewTask.test.js b/server/services/prDoReviewTask.test.jsindex c9b63686a4..c436da32be 100644--- a/server/services/prDoReviewTask.test.js+++ b/server/services/prDoReviewTask.test.js@@ -1,11 +1,14 @@import { describe, it, expect, vi, beforeEach } from 'vitest';-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({addTask: vi.fn(),+}));+vi.mock('./cos.js', () => ({forceSpawnTask: vi.fn(),}));-import { addTask, forceSpawnTask } from './cos.js';+import { addTask } from './cosTaskStore.js';+import { forceSpawnTask } from './cos.js';import { isDoReviewTask, spawnPrDoReviewTask } from './prDoReviewTask.js';const APP = { id: 'app-001', name: 'Widget' };diff --git a/server/services/prRemediationFollowUp.js b/server/services/prRemediationFollowUp.jsindex 5a6f382de7..66a3000e46 100644--- a/server/services/prRemediationFollowUp.js+++ b/server/services/prRemediationFollowUp.js@@ -49,7 +49,7 @@*/import { emitLog } from './cosEvents.js';-import { addTask } from './cos.js';+import { addTask } from './cosTaskStore.js';import { buildCiMergeGateSteps, buildForkBranchInstructions } from './promptSections/reviewLifecycle.js';import { normalizeForkHead, forkLocalBranch } from '../lib/forkHead.js';import { UNTRUSTED_PULL_REQUEST_NOTICE } from '../lib/promptFencing.js';diff --git a/server/services/prRemediationFollowUp.test.js b/server/services/prRemediationFollowUp.test.jsindex 5f0ab5435f..19d93bc93e 100644--- a/server/services/prRemediationFollowUp.test.js+++ b/server/services/prRemediationFollowUp.test.js@@ -1,7 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest';const addTaskMock = vi.fn();-vi.mock('./cos.js', () => ({ addTask: (...args) => addTaskMock(...args) }));+vi.mock('./cosTaskStore.js', () => ({ addTask: (...args) => addTaskMock(...args) }));vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));const execGhMock = vi.fn();vi.mock('./github.js', () => ({ execGh: (...args) => execGhMock(...args) }));diff --git a/server/services/prReviewerTargetedRun.js b/server/services/prReviewerTargetedRun.jsindex 8682c1abfe..db02025698 100644--- a/server/services/prReviewerTargetedRun.js+++ b/server/services/prReviewerTargetedRun.js@@ -6,7 +6,7 @@* an agent from the request's content directly.*/import { ServerError } from '../lib/errorHandler.js';-import { getAllTasks } from './cos.js';+import { getAllTasks } from './cosTaskStore.js';import { listExternalOpenPullRequests } from './prReviewerSecurity.js';import { getOnDemandRequests, triggerOnDemandTask } from './taskSchedule.js';diff --git a/server/services/prWatcher.js b/server/services/prWatcher.jsindex fe4a789965..7f1dd2d7fb 100644--- a/server/services/prWatcher.js+++ b/server/services/prWatcher.js@@ -439,7 +439,7 @@ async function recoverHeldCleanup(app, entry, binding) {? { ...entry, cleanup: { ...entry.cleanup, status: 'pending', retryAt: 0, recoveryCompleted: true } } : entry;}if (await currentHandoffOwnerPolicy(binding, { recovery: true })) return entry;- const { addTask } = await import('./cos.js');+ const { addTask } = await import('./cosTaskStore.js');const task = await addTask({description: `[Recovery] Prepare retained checkout for coordinator retirement: ${entry.prBranch} in ${app.name || app.id}`,app: app.id, priority: 'HIGH', isRecovery: true, useWorktree: false,diff --git a/server/services/referenceRepos.js b/server/services/referenceRepos.jsindex 71f5ddc072..5f5e18511c 100644--- a/server/services/referenceRepos.js+++ b/server/services/referenceRepos.js@@ -699,7 +699,7 @@ export async function triggerReferenceAnalysis(app, ref, snapshot) {}if (!app) return { queued: false, reason: 'app-not-found' };- const { addTask } = await import('./cos.js');+ const { addTask } = await import('./cosTaskStore.js');const { getTaskPrompt } = await import('./taskPromptService.js');const referenceDataBlock = formatReferenceForPrompt(ref, snapshot);diff --git a/server/services/referenceRepos.test.js b/server/services/referenceRepos.test.jsindex 8e2604ff23..636f012d38 100644--- a/server/services/referenceRepos.test.js+++ b/server/services/referenceRepos.test.js@@ -43,7 +43,7 @@ vi.mock('../lib/execGit.js', () => ({// Stubs for CoS task queuing — used by triggerReferenceAnalysis.const addTaskMock = vi.fn(async (task) => task);-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({addTask: (...args) => addTaskMock(...args),}));const getTaskPromptMock = vi.fn(async () => 'Analyze {appName} at {repoPath} for {appId} reviewer={reviewers}\n{referenceData}\n{planConstraint}\nTRACKER: {trackerInstructions}');diff --git a/server/services/repoIntake.js b/server/services/repoIntake.jsindex 46a1167c48..4021bda8f8 100644--- a/server/services/repoIntake.js+++ b/server/services/repoIntake.js@@ -23,7 +23,7 @@import { randomUUID } from 'crypto';import { existsSync } from 'fs';import { posix } from 'path';-import * as cos from './cos.js';+import { addTask } from './cosTaskStore.js';import { getAppById, PORTOS_APP_ID } from './apps.js';import { prepareScanReportDirectory, reportPathForId } from './malwareScanReports.js';import { resolveTrackerFilingBlock } from '../lib/workTracker.js';@@ -70,7 +70,7 @@ export async function queueMalwareScan(link) {Use that path as SCAN_DIR. Adhere to every Operational Invariant in the workflow body — this is a hostile-until-proven-safe audit. End the report with exactly one verdict heading: \`## Verdict: CLEAN\`, \`## Verdict: CAUTION\`, or \`## Verdict: DANGEROUS\`. When complete, summarize the verdict and top findings in your final response.`;- const result = await cos.addTask(+ const result = await addTask({description: `Malware scan: ${repoLabel(link)}`,// Multi-line ⇒ the agent PROMPT: `cosTaskStore.addTask` routes it to@@ -198,7 +198,7 @@ export async function queueRepoStudy(link, { targetAppId, studyContext, provider? {}: { issueLabelContract: GENERIC_REPO_STUDY_LABEL_CONTRACT });- const result = await cos.addTask(+ const result = await addTask({description: `Repo study: ${repoLabel(link)} — what can ${app.name} learn from it?`,// Workspace routing must follow the same managed app whose tracker anddiff --git a/server/services/repoIntake.test.js b/server/services/repoIntake.test.jsindex 2a8ef2de43..b36c74d508 100644--- a/server/services/repoIntake.test.js+++ b/server/services/repoIntake.test.js@@ -8,7 +8,7 @@ const readOriginRemoteUrl = vi.fn();const existsSync = vi.fn();const pullRepo = vi.fn();-vi.mock('./cos.js', () => ({ addTask: (...args) => addTask(...args) }));+vi.mock('./cosTaskStore.js', () => ({ addTask: (...args) => addTask(...args) }));vi.mock('./apps.js', () => ({PORTOS_APP_ID: 'portos-default',getAppById: (...args) => getAppById(...args),diff --git a/server/services/subAgentSpawner.test.js b/server/services/subAgentSpawner.test.jsindex 2a46281598..2c8d959407 100644--- a/server/services/subAgentSpawner.test.js+++ b/server/services/subAgentSpawner.test.js@@ -62,7 +62,7 @@ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'viteimport { isTruthyMeta, isFalsyMeta } from './agentState.js';import { cosEvents } from './cosEvents.js';import { initSpawner } from './subAgentSpawner.js';-import { applyAppWorktreeDefault } from './cos.js';+import { applyAppWorktreeDefault } from './cosTaskGenerator.js';/*** Pure decision helpers from the sub-agent spawn path.diff --git a/server/services/systemHealthSnapshot.js b/server/services/systemHealthSnapshot.jsindex 283be28748..cd6b8da648 100644--- a/server/services/systemHealthSnapshot.js+++ b/server/services/systemHealthSnapshot.js@@ -2,7 +2,9 @@ import os from 'os';import { stat, statfs } from 'fs/promises';import { listProcessesStrict } from './pm2.js';import { getAppStatusSummary, annotateExpectedExit } from './appProcessStatus.js';-import * as cos from './cos.js';+import { getAgents } from './cosAgentLifecycle.js';+import { getPendingTaskIds } from './cosTaskStore.js';+import { getStatus } from './cos.js';import { getSelf } from './instanceIdentity.js';import { checkHealth } from '../lib/db.js';import { getCurrentVersion } from './updateChecker.js';@@ -103,13 +105,13 @@ function probeHealthInputs() {console.error(`❌ App health probe failed (operation=getAppStatusSummary, code=${probeErrorCode(error)})`);return FAILED_PROBE;}),- cosProbe('cos-status', () => cos.getStatus()),+ cosProbe('cos-status', () => getStatus()),// Queue depth is read here rather than taken off `getStatus()`, which has no// such field — `cosStatus.queueLength` never existed, so the widget's// "N queued" was dead and always rendered 0. Both reads ride the same// `loadState()`/parse caches `getStatus()` above already warmed.- cosProbe('cos-queue', () => cos.getPendingTaskIds()),- cosProbe('cos-agents', () => cos.getAgents()),+ cosProbe('cos-queue', () => getPendingTaskIds()),+ cosProbe('cos-agents', () => getAgents()),getSelf().catch(() => null),checkHealth().catch(() => ({ connected: false, hasSchema: false, error: 'Health check failed' })),getCurrentVersion().catch(() => null),diff --git a/server/services/systemHealthSnapshot.test.js b/server/services/systemHealthSnapshot.test.jsindex 46042d74a1..bfb35a3a2c 100644--- a/server/services/systemHealthSnapshot.test.js+++ b/server/services/systemHealthSnapshot.test.js@@ -5,6 +5,8 @@ import { describe, it, expect, vi } from 'vitest';vi.mock('./pm2.js', () => ({ listProcessesStrict: vi.fn() }));vi.mock('./appProcessStatus.js', () => ({ getAppStatusSummary: vi.fn(), annotateExpectedExit: vi.fn() }));vi.mock('./cos.js', () => ({}));+vi.mock('./cosAgentLifecycle.js', () => ({}));+vi.mock('./cosTaskStore.js', () => ({}));vi.mock('./instanceIdentity.js', () => ({ getSelf: vi.fn() }));vi.mock('../lib/db.js', () => ({ checkHealth: vi.fn() }));vi.mock('./updateChecker.js', () => ({ getCurrentVersion: vi.fn() }));diff --git a/server/services/systemResources.js b/server/services/systemResources.jsindex 71ea2809b9..6690c7156d 100644--- a/server/services/systemResources.js+++ b/server/services/systemResources.js@@ -24,7 +24,9 @@ import { listModelStore } from './modelStoreStorage.js';import * as ollamaManager from './ollamaManager.js';import * as lmStudioManager from './lmStudioManager.js';import { getQueueCapacity } from './mediaJobQueue/index.js';-import * as cos from './cos.js';+import { getAgents } from './cosAgentLifecycle.js';+import { getAllTasks } from './cosTaskStore.js';+import { getStatus } from './cos.js';import { runningAgentsByTaskId, countSpawningTasks } from '../lib/cosSpawnWindow.js';import { getSettings } from './settings.js';import {@@ -343,7 +345,7 @@ function loadedModelInventory({ ollamaLoaded, lmStudioLoaded }) {let agentCensusUnavailable = false;function readAgentCensus() {- return cos.getAgents().then((agents) => {+ return getAgents().then((agents) => {if (agentCensusUnavailable) console.log('✅ Resource probe recovered (source=agent-census)');agentCensusUnavailable = false;return agents;@@ -448,8 +450,8 @@ export async function buildSystemResourceReport() {dirSize(npmCachePath, { strict: true }).catch(() => null),Promise.all(dependencyPaths.map((path) => dirSize(path, { strict: true }).catch(() => null))),dirSize(PATHS.browserDownloads, { strict: true }).catch(() => null),- cos.getAllTasks().catch(() => null),- cos.getStatus().catch(() => null),+ getAllTasks().catch(() => null),+ getStatus().catch(() => null),readAgentCensus(),scanModelDuplicates().catch(() => ({ pinokioDetected: null, items: [], totalReclaimableBytes: 0, error: 'Duplicate model scan unavailable' })),]);diff --git a/server/services/systemResources.test.js b/server/services/systemResources.test.jsindex 39d9fab08a..1de86a1993 100644--- a/server/services/systemResources.test.js+++ b/server/services/systemResources.test.js@@ -89,7 +89,7 @@ vi.mock('./mediaJobQueue/index.js', () => ({},})),}));-vi.mock('./cos.js', () => ({+vi.mock('./cosTaskStore.js', () => ({getAllTasks: vi.fn(async () => ({user: { grouped: { pending: [{ id: 'task-1' }], in_progress: [] } },cos: {@@ -97,7 +97,11 @@ vi.mock('./cos.js', () => ({awaitingApproval: [{ id: 'approval-1', approvalRequired: true }],},})),+}));+vi.mock('./cos.js', () => ({getStatus: vi.fn(async () => ({ running: true, paused: false, activeAgents: 0, pausedAgents: 0 })),+}));+vi.mock('./cosAgentLifecycle.js', () => ({getAgents: vi.fn(async () => []),}));vi.mock('./settings.js', () => ({@@ -120,7 +124,9 @@ const mediaModelStorage = await import('./mediaModelStorage.js');const modelStoreStorage = await import('./modelStoreStorage.js');const ollamaManager = await import('./ollamaManager.js');const lmStudioManager = await import('./lmStudioManager.js');-const cos = await import('./cos.js');+const { getAgents } = await import('./cosAgentLifecycle.js');+const { getAllTasks } = await import('./cosTaskStore.js');+const { getStatus } = await import('./cos.js');const settings = await import('./settings.js');const modelManifest = await import('./modelManifest.js');const {@@ -303,11 +309,11 @@ describe('system resource reporting', () => {// (lib/cosSpawnWindow.js), so counting the two lists independently reported// the same task as queued AND running — "Agent pending 1 / Agent running 1"// for a queue of one. It must move sides, not appear on both and not vanish.- cos.getAllTasks.mockResolvedValueOnce({+ getAllTasks.mockResolvedValueOnce({user: { grouped: { pending: [{ id: 'user/42', status: 'pending' }], in_progress: [] } },cos: { grouped: { pending: [], in_progress: [] }, awaitingApproval: [] },});- cos.getAgents.mockResolvedValueOnce([{ id: 'agent-1', taskId: 'user/42', status: 'running', startedAt: new Date().toISOString() }]);+ getAgents.mockResolvedValueOnce([{ id: 'agent-1', taskId: 'user/42', status: 'running', startedAt: new Date().toISOString() }]);const report = await buildSystemResourceReport();@@ -324,10 +330,10 @@ describe('system resource reporting', () => {user: { grouped: { pending: [{ id: 'user/42', status: 'pending' }], in_progress: [] } },cos: { grouped: { pending: [{ id: 'approval-1', approvalRequired: true }], in_progress: [] }, awaitingApproval: [{ id: 'approval-1' }] },};- cos.getAllTasks.mockResolvedValueOnce(tasks).mockResolvedValueOnce(tasks).mockResolvedValueOnce(tasks);- cos.getStatus.mockResolvedValueOnce({ running: true, paused: false, activeAgents: 1, pausedAgents: 2 });+ getAllTasks.mockResolvedValueOnce(tasks).mockResolvedValueOnce(tasks).mockResolvedValueOnce(tasks);+ getStatus.mockResolvedValueOnce({ running: true, paused: false, activeAgents: 1, pausedAgents: 2 });const failure = Object.assign(new Error('private census path'), { code: 'EIO' });- cos.getAgents.mockRejectedValueOnce(failure).mockRejectedValueOnce(failure)+ getAgents.mockRejectedValueOnce(failure).mockRejectedValueOnce(failure).mockResolvedValueOnce([{ id: 'agent-1', taskId: 'user/42', status: 'running', startedAt: new Date().toISOString() }]);const failed = await buildSystemResourceReport();@@ -356,11 +362,11 @@ describe('system resource reporting', () => {});it('treats a successful empty census as measured persisted-task counts', async () => {- cos.getAllTasks.mockResolvedValueOnce({+ getAllTasks.mockResolvedValueOnce({user: { grouped: { pending: [], in_progress: [{ id: 'user/42' }] } },cos: { grouped: { pending: [], in_progress: [] }, awaitingApproval: [] },});- cos.getAgents.mockResolvedValueOnce([]);+ getAgents.mockResolvedValueOnce([]);const report = await buildSystemResourceReport();expect(report.sourceErrors).not.toContain('agent-census');expect(report.queues.agents).toMatchObject({ pendingUser: 0, pendingSystem: 0, inProgress: 1 });@@ -368,8 +374,8 @@ describe('system resource reporting', () => {});it('preserves failed agent queue and status probes as unknown', async () => {- cos.getAllTasks.mockRejectedValueOnce(new Error('task store unavailable'));- cos.getStatus.mockRejectedValueOnce(new Error('daemon status unavailable'));+ getAllTasks.mockRejectedValueOnce(new Error('task store unavailable'));+ getStatus.mockRejectedValueOnce(new Error('daemon status unavailable'));const report = await buildSystemResourceReport();@@ -405,7 +411,7 @@ describe('system resource reporting', () => {});it('keeps daemon status unknown when only the COS status probe fails', async () => {- cos.getStatus.mockRejectedValueOnce(new Error('daemon status unavailable'));+ getStatus.mockRejectedValueOnce(new Error('daemon status unavailable'));const report = await buildSystemResourceReport();diff --git a/server/services/taskLearning.test.js b/server/services/taskLearning.test.jsindex 08d989e418..9d04da783e 100644--- a/server/services/taskLearning.test.js+++ b/server/services/taskLearning.test.js@@ -11,7 +11,8 @@ vi.mock('fs', () => ({}));// Mock cos.js to avoid circular dependency-vi.mock('./cos.js', () => ({+vi.mock('./cos.js', () => ({}));+vi.mock('./cosEvents.js', () => ({cosEvents: { on: vi.fn(), emit: vi.fn() },emitLog: vi.fn()}));diff --git a/server/services/taskLearning/lifecycle.js b/server/services/taskLearning/lifecycle.jsindex ca76a9375b..0c353df212 100644--- a/server/services/taskLearning/lifecycle.js+++ b/server/services/taskLearning/lifecycle.js@@ -88,7 +88,7 @@ export function initTaskLearning() {* Call this once to populate historical data*/export async function backfillFromHistory() {- const { getAgents } = await import('../cos.js');+ const { getAgents } = await import('../cosAgentLifecycle.js');const agents = await getAgents();let backfilled = 0;diff --git a/server/services/taskLearning/lifecycle.test.js b/server/services/taskLearning/lifecycle.test.jsindex 81519d47fd..ab7b7fa44d 100644--- a/server/services/taskLearning/lifecycle.test.js+++ b/server/services/taskLearning/lifecycle.test.js@@ -16,7 +16,8 @@ vi.mock('./store.js', () => ({cosEvents: { on: vi.fn() },emitLog: vi.fn(),}));-vi.mock('../cos.js', () => ({ getAgents: vi.fn(async () => agentsStore.list) }));+vi.mock('../cos.js', () => ({}));+vi.mock('../cosAgentLifecycle.js', () => ({ getAgents: vi.fn(async () => agentsStore.list) }));vi.mock('../agentChurn.js', () => ({observeAgentChurn: vi.fn(async () => ({ flagged: false })),}));diff --git a/server/services/toolStateMachine.test.js b/server/services/toolStateMachine.test.jsindex 673a617e4f..13cc5e5af7 100644--- a/server/services/toolStateMachine.test.js+++ b/server/services/toolStateMachine.test.js@@ -18,7 +18,7 @@ import {} from './toolStateMachine.js';// Mock the cosEvents to prevent actual event emission-vi.mock('./cos.js', () => ({+vi.mock('./cosEvents.js', () => ({cosEvents: {emit: vi.fn()}diff --git a/server/services/voice/tools.test.js b/server/services/voice/tools.test.jsindex a522142635..5cb75df520 100644--- a/server/services/voice/tools.test.js+++ b/server/services/voice/tools.test.js@@ -159,12 +159,14 @@ vi.mock('../cosState.js', () => ({vi.mock('../agentState.js', () => ({isTruthyMeta: (v) => v === true || v === 'true',}));-vi.mock('../cos.js', () => ({+vi.mock('../cosTaskStore.js', () => ({addTask: vi.fn(async (data) => ({ id: 'task-test', ...data })),reviveBlockedTask: vi.fn(async () => ({})),- isRunning: vi.fn(() => true),getAllTasks: vi.fn(async () => ({ user: { tasks: tasksRef.value }, cos: { tasks: [] } })),}));+vi.mock('../cos.js', () => ({+ isRunning: vi.fn(() => true),+}));// dispatch_code_agent fuzzy-resolves the optional `app` parameter against the// user's configured managed apps; default to two apps so the resolve / not-// found branches can be exercised.@@ -203,7 +205,8 @@ vi.mock('../providers.js', () => ({const { dispatchTool, getToolSpecs, getToolSpecsForIntent, classifyIntent } = await import('./tools.js');const { getVoiceConfig: mockedGetVoiceConfig } = await import('./config.js');-const { addTask: mockedAddTask, isRunning: mockedIsRunning } = await import('../cos.js');+const { addTask: mockedAddTask } = await import('../cosTaskStore.js');+const { isRunning: mockedIsRunning } = await import('../cos.js');const { getActiveProvider: mockedGetActiveProvider, getAllProviders: mockedGetAllProviders, getProviderById: mockedGetProviderById } = await import('../providers.js');describe('getToolSpecs', () => {diff --git a/server/services/voice/tools/code.js b/server/services/voice/tools/code.jsindex ac79b57240..b965041e6d 100644--- a/server/services/voice/tools/code.js+++ b/server/services/voice/tools/code.js@@ -77,7 +77,8 @@ export const CODE_TOOLS = [// Dynamic import: cos.js is a large module with its own import graph;// importing it lazily keeps tools.js load-time light and dodges any// cos → voice cycle.- const { addTask, reviveBlockedTask, isRunning } = await import('../../cos.js');+ const { addTask, reviveBlockedTask } = await import('../../cosTaskStore.js');+ const { isRunning } = await import('../../cos.js');const provider = typeof codeAgent.provider === 'string' ? codeAgent.provider.trim() : '';const model = typeof codeAgent.model === 'string' ? codeAgent.model.trim() : '';@@ -190,7 +191,7 @@ export const CODE_TOOLS = [},execute: async () => {const { loadState } = await import('../../cosState.js');- const { getAllTasks } = await import('../../cos.js');+ const { getAllTasks } = await import('../../cosTaskStore.js');const { isTruthyMeta } = await import('../../agentState.js');const state = await loadState();