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(cos): split durable config out of data/cos/state.json (#6182)
Adam Eivyed19786aa003
diff --git a/client/src/components/cos/tabs/TaskItem.jsx b/client/src/components/cos/tabs/TaskItem.jsxindex 2c53ca88fc..15e5be8f6d 100644--- a/client/src/components/cos/tabs/TaskItem.jsx+++ b/client/src/components/cos/tabs/TaskItem.jsx@@ -679,22 +679,6 @@ export default function TaskItem({ task, agent = null, isSystem, spawning = fals{/* Clamped: server-side auto-blocks write `blockedReason` fromLLM error analysis / raw stderr, which can run very long. */}<div className="min-w-0 flex-1">- {/* A fail-closed orchestration lane (#5993) reads as a bare- "agent failed" without this: the reason sentence is long- and gets clamped, so the two facts that make the fix- obvious — WHICH role stopped and WHICH provider it wanted- — get a headline of their own above the clamp. */}- {task.metadata?.blockedCategory === 'orchestration-lane-unavailable' && task.metadata?.orchestrationLane?.role && (- <div className="font-medium text-port-error mb-0.5">- {`${task.metadata.orchestrationLane.role} lane unavailable`}- {task.metadata.orchestrationLane.requestedProvider- ? ` — ${task.metadata.orchestrationLane.requestedProvider}`- : ''}- {task.metadata.orchestrationLane.requestedModel- ? ` / ${task.metadata.orchestrationLane.requestedModel}`- : ''}- </div>- )}<CollapsibleTextid={`task-blocker-${idScope}-${task.id}`}text={task.metadata.blocker || task.metadata.blockedReason}diff --git a/client/src/components/cos/tabs/TaskItem.test.jsx b/client/src/components/cos/tabs/TaskItem.test.jsxindex 5edb8e88df..0d5db21c56 100644--- a/client/src/components/cos/tabs/TaskItem.test.jsx+++ b/client/src/components/cos/tabs/TaskItem.test.jsx@@ -828,34 +828,3 @@ describe('TaskItem editing a pin whose instance has left the registry (#4520)',expect(api.updateCosTask.mock.calls[0][1].targetInstanceId).toBe('peer-instance-id');});});--describe('TaskItem fail-closed orchestration lane (#5993)', () => {- const blockedOnLane = {- ...task,- id: 'orch-lane',- status: 'blocked',- metadata: {- blockedCategory: 'orchestration-lane-unavailable',- blockedReason: 'Orchestrated implementer lane stopped: provider "p-cheap" model "m-cheap" is unavailable — not authenticated (no implementer.fallbackProvider is configured).',- orchestrationLane: { role: 'implementer', requestedProvider: 'p-cheap', requestedModel: 'm-cheap' },- },- };-- it('headlines the role and provider so the fix is obvious', () => {- render(<TaskItem task={blockedOnLane} onRefresh={vi.fn()} providers={providers} />);-- expect(screen.getByText('implementer lane unavailable — p-cheap / m-cheap')).toBeInTheDocument();- });-- it('adds no headline to an ordinary block', () => {- const ordinary = {- ...blockedOnLane,- id: 'ordinary-block',- metadata: { blockedReason: 'Max spawn attempts reached', blockedCategory: 'max-spawns' },- };- render(<TaskItem task={ordinary} onRefresh={vi.fn()} providers={providers} />);-- expect(screen.queryByText(/lane unavailable/)).toBeNull();- expect(screen.getByText('Max spawn attempts reached')).toBeInTheDocument();- });-});diff --git a/client/src/hooks/usePortosRestartWatch.test.js b/client/src/hooks/usePortosRestartWatch.test.jsdeleted file mode 100644index 2763789231..0000000000--- a/client/src/hooks/usePortosRestartWatch.test.js+++ /dev/null@@ -1,390 +0,0 @@-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { act, renderHook } from '@testing-library/react';--// The socket is a module singleton; capture its handlers so a test can fire the-// events a dying server produces without standing up socket.io.-const socketHandlers = new Map();-vi.mock('../services/socket', () => ({- default: {- on: (event, fn) => { socketHandlers.set(event, fn); },- off: (event, fn) => { if (socketHandlers.get(event) === fn) socketHandlers.delete(event); },- emit: () => {},- },-}));-const mockToast = vi.hoisted(() => Object.assign(vi.fn(), {- success: vi.fn(), error: vi.fn(), loading: vi.fn(), dismiss: vi.fn(),-}));-vi.mock('../components/ui/Toast', () => ({ default: mockToast }));-const mockCheckHealth = vi.fn();-vi.mock('../services/api', () => ({ checkHealth: (...a) => mockCheckHealth(...a) }));--import { usePortosRestartWatch } from './usePortosRestartWatch';--// Mirrors of the hook's own constants. Duplicated deliberately: they are the-// contract this file pins, so importing them would let a change to the source-// silently move the assertions with it.-const POLL_MS = 2000;-const DISCONNECT_CONFIRM_MS = 1500;-const DOWN_WAIT_MS = 60 * 1000;-const RECOVERY_TIMEOUT_MS = 30 * 60 * 1000;-const TOAST_ID = 'portos-update-restart';--const UP = { version: '2.24.0', uptime: 120 };--let reload;--// The poll body awaits checkHealth, so every tick lands a microtask deep;-// advanceTimersByTimeAsync flushes those between timer firings.-const tick = async (ms = POLL_MS) => {- await act(async () => { await vi.advanceTimersByTimeAsync(ms); });-};--const setVisibility = (state) => {- Object.defineProperty(document, 'visibilityState', { value: state, configurable: true });-};--const mountWatch = () => renderHook(() => usePortosRestartWatch({}));--/**- * Drive the real pre-update sequence: sample the still-running server the way a- * surface does before dispatching, then arm and let the watch's first poll tick- * land. `before` is what health reports at baseline time, `after` what it- * reports once polling starts.- */-const armWith = async (result, { before = UP, after = before, armOpts } = {}) => {- mockCheckHealth.mockResolvedValue(before);- await act(async () => { await result.current.captureBaseline(); });- mockCheckHealth.mockResolvedValue(after);- await act(async () => { result.current.arm(armOpts); });- await act(async () => {});-};--describe('usePortosRestartWatch', () => {- beforeEach(() => {- socketHandlers.clear();- vi.clearAllMocks();- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));- setVisibility('visible');- reload = vi.fn();- vi.stubGlobal('location', { reload });- mockCheckHealth.mockResolvedValue(UP);- });-- afterEach(() => {- vi.useRealTimers();- vi.unstubAllGlobals();- setVisibility('visible');- });-- describe('restart detection', () => {- it('treats a changed version as the restart and reloads', async () => {- const { result } = mountWatch();- await armWith(result);- expect(result.current.polling).toBe(true);-- mockCheckHealth.mockResolvedValue({ version: '2.25.0', uptime: 4 });- await tick();-- expect(result.current.polling).toBe(false);- expect(mockToast.success).toHaveBeenCalledWith('Updated to v2.25.0', { id: TOAST_ID });- expect(reload).not.toHaveBeenCalled();- await tick(1000);- expect(reload).toHaveBeenCalledTimes(1);- });-- it('reconciles a same-version restart proven by a down→up dip', async () => {- const { result } = mountWatch();- await armWith(result);-- // Server goes away mid-restart. Uptime on the way back stays HIGH, so the- // dip is the only evidence — the uptime branch cannot cover for it.- mockCheckHealth.mockResolvedValue(null);- await tick();- expect(result.current.polling).toBe(true);-- mockCheckHealth.mockResolvedValue({ version: '2.24.0', uptime: 900 });- await tick();-- expect(result.current.polling).toBe(false);- expect(mockToast.success).toHaveBeenCalledWith('Install reconciled — reloading', { id: TOAST_ID });- await tick(1000);- expect(reload).toHaveBeenCalledTimes(1);- });-- it('reconciles a same-version restart proven by an uptime drop alone', async () => {- // The restart too fast for a 2s poll to ever sample the down window:- // health never fails, and the server is already back by the FIRST tick, so- // the peak captureBaseline seeded off the still-running server is the only- // thing the drop can be measured against.- const { result } = mountWatch();- await armWith(result, {- before: { version: '2.24.0', uptime: 3600 },- after: { version: '2.24.0', uptime: 3 },- });-- expect(result.current.polling).toBe(false);- expect(mockToast.success).toHaveBeenCalledWith('Install reconciled — reloading', { id: TOAST_ID });- });-- it('carries a confirmed-down observation into the poll as restart evidence', async () => {- // `arm({ healthDown: true })` exists so the hook does not depend on- // `useAutoRefetch`'s `immediate: true` default to re-observe the down- // window. Here health is UP and unchanged on every tick and there is no- // baseline, so the carried observation is the only proof a restart- // happened — the page adopted an update it did not start.- const { result } = mountWatch();- mockCheckHealth.mockResolvedValue({ version: '2.24.0', uptime: 900 });- await act(async () => { result.current.arm({ healthDown: true }); });- await act(async () => {});-- expect(result.current.polling).toBe(false);- expect(mockToast.success).toHaveBeenCalledWith('Install reconciled — reloading', { id: TOAST_ID });- });-- it('prefers the caller-supplied version over what health reports', async () => {- // `UpdateTab` passes the version it already rendered. Health answering- // with something else at baseline time must not overwrite it, or the- // version-change comparison is made against the wrong "before".- const { result } = mountWatch();- mockCheckHealth.mockResolvedValue({ version: '2.99.0', uptime: 120 });- await act(async () => { await result.current.captureBaseline('2.24.0'); });- await act(async () => { result.current.arm(); });- await act(async () => {});-- expect(result.current.polling).toBe(false);- expect(mockToast.success).toHaveBeenCalledWith('Updated to v2.99.0', { id: TOAST_ID });- });-- it('does not read a within-slack uptime wobble as a restart', async () => {- // 2s below the peak — inside UPTIME_DROP_SLACK_S, i.e. clock jitter.- const { result } = mountWatch();- await armWith(result, {- before: { version: '2.24.0', uptime: 3600 },- after: { version: '2.24.0', uptime: 3598 },- });-- expect(result.current.polling).toBe(true);- expect(mockToast.success).not.toHaveBeenCalled();- });- });-- describe('phase budgets', () => {- it('gives up at DOWN_WAIT_MS when the server never went down', async () => {- const { result } = mountWatch();- await armWith(result);-- await tick(DOWN_WAIT_MS - POLL_MS);- expect(result.current.polling).toBe(true);- expect(mockToast.error).not.toHaveBeenCalled();-- await tick(POLL_MS);-- expect(result.current.polling).toBe(false);- expect(mockToast.error).toHaveBeenCalledWith(- 'PortOS never went down — the update may not have started', { id: TOAST_ID },- );- });-- it('keeps polling far past DOWN_WAIT_MS once the server is confirmed down', async () => {- // The #6169 regression: a flat 60s ceiling measured phase 2 with phase- // 1's ruler, so every real update timed out mid-`npm install`.- const { result } = mountWatch();- await armWith(result, { after: null });-- await tick(DOWN_WAIT_MS * 5);- expect(result.current.polling).toBe(true);- expect(mockToast.error).not.toHaveBeenCalled();-- await tick(RECOVERY_TIMEOUT_MS - DOWN_WAIT_MS * 5);-- expect(result.current.polling).toBe(false);- expect(mockToast.error).toHaveBeenCalledWith(- 'Restart timed out — try reloading manually', { id: TOAST_ID },- );- });-- it('measures the budget from the FIRST arm, not the most recent one', async () => {- const { result } = mountWatch();- await armWith(result);-- await tick(DOWN_WAIT_MS / 2);- await act(async () => { result.current.arm(); });- await tick(DOWN_WAIT_MS / 2);-- // A clock restarted by the second arm would still be mid-budget here.- expect(result.current.polling).toBe(false);- expect(mockToast.error).toHaveBeenCalledWith(- 'PortOS never went down — the update may not have started', { id: TOAST_ID },- );- });-- it('lets a tick after a hidden-tab gap recognize the restart before the budget bites', async () => {- // `useAutoRefetch` skips its tick while the tab is hidden, so a wall-clock- // budget can lapse with zero observations. The success checks run BEFORE- // the budget check precisely so the first tick back still wins.- const { result } = mountWatch();- await armWith(result);-- setVisibility('hidden');- mockCheckHealth.mockClear();- await tick(DOWN_WAIT_MS * 2);- expect(mockCheckHealth).not.toHaveBeenCalled();- expect(result.current.polling).toBe(true);-- setVisibility('visible');- mockCheckHealth.mockResolvedValue({ version: '2.25.0', uptime: 4 });- await tick();-- expect(mockToast.success).toHaveBeenCalledWith('Updated to v2.25.0', { id: TOAST_ID });- expect(mockToast.error).not.toHaveBeenCalled();- });- });-- describe('arming from the update stream', () => {- // No production caller arms by hand: `UpdateTab` and `useAppOperation` both- // pass `active` and let these handlers decide.- const mountActive = async () => {- const view = renderHook(() => usePortosRestartWatch({ active: true }));- await act(async () => {});- return view;- };-- const fireDisconnect = async () => {- await act(async () => { socketHandlers.get('disconnect')(); });- await act(async () => { await vi.advanceTimersByTimeAsync(DISCONNECT_CONFIRM_MS); });- };-- it('arms once a disconnect is confirmed unreachable', async () => {- const { result } = await mountActive();- mockCheckHealth.mockResolvedValue(null);-- await fireDisconnect();-- expect(result.current.polling).toBe(true);- expect(mockToast.loading).toHaveBeenCalledWith(- 'PortOS is restarting...', expect.objectContaining({ id: TOAST_ID }),- );- });-- it('ignores a disconnect that leaves the server reachable', async () => {- // PortOS is commonly used remotely over Tailscale, where a blip during- // git-pull fires 'disconnect' on a very-much-alive server. Arming there- // would park a bogus "restarting" toast and then fail the update with- // "PortOS never went down" on every network hiccup.- const { result } = await mountActive();- mockCheckHealth.mockResolvedValue(UP);-- await fireDisconnect();-- expect(result.current.polling).toBe(false);- expect(mockToast.loading).not.toHaveBeenCalled();- });-- it('arms on the restarting step but not on a failed one', async () => {- const { result } = await mountActive();-- await act(async () => { socketHandlers.get('portos:update:step')({ step: 'restarting', status: 'error' }); });- expect(result.current.polling).toBe(false);-- await act(async () => { socketHandlers.get('portos:update:step')({ step: 'restarting' }); });- await act(async () => {});- expect(result.current.polling).toBe(true);- });-- it('arms on a successful completion that beat the restart', async () => {- const { result } = await mountActive();-- await act(async () => { socketHandlers.get('portos:update:complete')({ success: true }); });- await act(async () => {});-- expect(result.current.polling).toBe(true);- });-- it('does not touch state when the surface unmounts mid-confirmation', async () => {- // The confirmation is a 1.5s detached timer; a user navigating away- // inside that window would otherwise arm a watch on a dead component.- const { unmount } = await mountActive();- mockCheckHealth.mockResolvedValue(null);-- await act(async () => { socketHandlers.get('disconnect')(); });- unmount();- await act(async () => { await vi.advanceTimersByTimeAsync(DISCONNECT_CONFIRM_MS); });-- expect(mockToast.loading).not.toHaveBeenCalled();- });-- it('reports a completion that reports failure instead of arming', async () => {- const onFailure = vi.fn();- const { result } = renderHook(() => usePortosRestartWatch({ active: true, onFailure }));- await act(async () => {});-- await act(async () => { socketHandlers.get('portos:update:complete')({ success: false }); });-- expect(onFailure).toHaveBeenCalledWith({ message: null });- expect(result.current.polling).toBe(false);- });-- it('ignores update events for an update this surface did not launch', async () => {- // `active: false` — another tab's update, or one already reconciled here.- const { result } = renderHook(() => usePortosRestartWatch({ active: false }));- await act(async () => {});- mockCheckHealth.mockResolvedValue(null);-- await act(async () => { socketHandlers.get('portos:update:step')({ step: 'restarting' }); });- await act(async () => { socketHandlers.get('portos:update:complete')({ success: true }); });- await fireDisconnect();-- expect(result.current.polling).toBe(false);- expect(mockToast.loading).not.toHaveBeenCalled();- });- });-- describe('watch lifecycle', () => {- it('ignores a second arm while already polling', async () => {- const onRestart = vi.fn();- const { result } = renderHook(() => usePortosRestartWatch({ onRestart }));-- await act(async () => { result.current.arm(); });- await act(async () => { result.current.arm(); });- await act(async () => {});-- expect(onRestart).toHaveBeenCalledTimes(1);- expect(mockToast.loading).toHaveBeenCalledTimes(1);- });-- it('stops polling health once the restart is confirmed', async () => {- const { result } = mountWatch();- await armWith(result);-- mockCheckHealth.mockResolvedValue({ version: '2.25.0', uptime: 4 });- await tick();- expect(result.current.polling).toBe(false);-- mockCheckHealth.mockClear();- await tick(DOWN_WAIT_MS);-- expect(mockCheckHealth).not.toHaveBeenCalled();- expect(mockToast.error).not.toHaveBeenCalled();- });-- it('reports a failed update instead of watching for a restart', async () => {- const onFailure = vi.fn();- renderHook(() => usePortosRestartWatch({ active: true, onFailure }));- await act(async () => {});-- await act(async () => { socketHandlers.get('portos:update:error')({ message: 'build failed' }); });-- expect(onFailure).toHaveBeenCalledWith({ message: 'build failed' });- expect(mockToast.dismiss).toHaveBeenCalledWith(TOAST_ID);- expect(mockToast.loading).not.toHaveBeenCalled();- });-- it('subscribes to nothing when disabled', async () => {- renderHook(() => usePortosRestartWatch({ enabled: false, active: true }));- await act(async () => {});-- expect(socketHandlers.size).toBe(0);- });- });-});diff --git a/data.reference/cos/config.json b/data.reference/cos/config.jsonnew file mode 100644index 0000000000..8eebdbb4d6--- /dev/null+++ b/data.reference/cos/config.json@@ -0,0 +1,42 @@+{+ "userTasksFile": "data/TASKS.md",+ "cosTasksFile": "data/COS-TASKS.md",+ "healthCheckIntervalMs": 900000,+ "maxConcurrentAgents": 3,+ "maxConcurrentAgentsPerProject": 2,+ "maxProcessMemoryMb": 2048,+ "maxTotalProcesses": 50,+ "mcpServers": [+ {+ "name": "filesystem",+ "command": "npx",+ "args": [+ "-y",+ "@anthropic/mcp-server-filesystem"+ ]+ },+ {+ "name": "puppeteer",+ "command": "npx",+ "args": [+ "-y",+ "@anthropic/mcp-puppeteer",+ "--isolated"+ ]+ }+ ],+ "autoStart": false,+ "alwaysOn": false,+ "selfImprovementEnabled": true,+ "dynamicAvatar": true,+ "persistentMindCapabilities": {+ "schemaVersion": 5,+ "createTasks": false,+ "manageMind": false,+ "manageEidoverse": false,+ "callUser": false,+ "readPortos": false,+ "writePortos": false,+ "taskModelAllowlist": []+ }+}diff --git a/data.reference/cos/state.json b/data.reference/cos/state.jsonindex 59aaef9b23..03c3ca142c 100644--- a/data.reference/cos/state.json+++ b/data.reference/cos/state.json@@ -1,47 +1,5 @@{"running": false,- "config": {- "userTasksFile": "data/TASKS.md",- "cosTasksFile": "data/COS-TASKS.md",- "healthCheckIntervalMs": 900000,- "maxConcurrentAgents": 3,- "maxConcurrentAgentsPerProject": 2,- "maxProcessMemoryMb": 2048,- "maxTotalProcesses": 50,- "mcpServers": [- {- "name": "filesystem",- "command": "npx",- "args": [- "-y",- "@anthropic/mcp-server-filesystem"- ]- },- {- "name": "puppeteer",- "command": "npx",- "args": [- "-y",- "@anthropic/mcp-puppeteer",- "--isolated"- ]- }- ],- "autoStart": false,- "alwaysOn": false,- "selfImprovementEnabled": true,- "dynamicAvatar": true,- "persistentMindCapabilities": {- "schemaVersion": 5,- "createTasks": false,- "manageMind": false,- "manageEidoverse": false,- "callUser": false,- "readPortos": false,- "writePortos": false,- "taskModelAllowlist": []- }- },"stats": {"tasksCompleted": 0,"totalRuntime": 0,diff --git a/scripts/migrations/234-autopilot-gap-task-app-routing.js b/scripts/migrations/234-autopilot-gap-task-app-routing.jsindex 343e7bf8e0..16dc4c3ec0 100644--- a/scripts/migrations/234-autopilot-gap-task-app-routing.js+++ b/scripts/migrations/234-autopilot-gap-task-app-routing.js@@ -48,6 +48,7 @@import { readFile } from 'fs/promises';import { join } from 'path';import { atomicWrite } from '../../server/lib/fileUtils.js';+import { readCosConfig } from './_lib.js';// The task header line, per `server/lib/taskParser.js`. Both spellings — with// and without the AUTO/APPROVAL flag — since internal tasks carry it and the@@ -64,14 +65,13 @@ const STRANDED = [];/**- * Repo-relative path of a queue file, honouring an install that moved it in- * `data/cos/state.json` (`config.userTasksFile` / `config.cosTasksFile` — the- * same values `cosTaskStore` reads). Migrating only the defaults would record- * this migration as applied while the live queue stayed stranded.+ * Repo-relative path of a queue file, honouring an install that moved it in its+ * CoS config (`userTasksFile` / `cosTasksFile` — the same values `cosTaskStore`+ * reads). Migrating only the defaults would record this migration as applied+ * while the live queue stayed stranded.*/async function queuePaths(rootDir) {- const raw = await readFile(join(rootDir, 'data', 'cos', 'state.json'), 'utf-8').catch(() => null);- const config = raw ? JSON.parse(raw)?.config ?? {} : {};+ const config = await readCosConfig({ rootDir, label: 'migration 234' });return STRANDED.map((producer) => ({...producer,file: typeof config[producer.configKey] === 'string' && config[producer.configKey]diff --git a/scripts/migrations/262-revive-null-app-blocked-merge-followups.js b/scripts/migrations/262-revive-null-app-blocked-merge-followups.jsindex 821461e605..08d53ffd71 100644--- a/scripts/migrations/262-revive-null-app-blocked-merge-followups.js+++ b/scripts/migrations/262-revive-null-app-blocked-merge-followups.js@@ -57,6 +57,7 @@import { readFile } from 'fs/promises';import { join } from 'path';import { atomicWrite } from '../../server/lib/fileUtils.js';+import { readCosConfig } from './_lib.js';// The task header line, per `server/lib/taskParser.js`. Both spellings — with// and without the AUTO/APPROVAL flag — since internal tasks carry it and the@@ -76,17 +77,12 @@ const QUEUE_FILES = [/*** Repo-relative paths of the queue files, honouring an install that moved them- * in `data/cos/state.json` (`config.cosTasksFile` / `config.userTasksFile` — the- * same values `cosTaskStore` reads). Migrating only the defaults would record- * this migration as applied while the live queue stayed stranded.+ * in its CoS config (`cosTasksFile` / `userTasksFile` — the same values+ * `cosTaskStore` reads). Migrating only the defaults would record this+ * migration as applied while the live queue stayed stranded.*/async function queuePaths(rootDir) {- const raw = await readFile(join(rootDir, 'data', 'cos', 'state.json'), 'utf-8').catch(() => null);- // A truncated/corrupted state.json (left behind by a prior crash) must not- // abort this migration and every one after it — fall back to the defaults- // exactly as a missing file already does.- const parsed = raw ? (() => { try { return JSON.parse(raw); } catch { return null; } })() : null;- const config = parsed?.config ?? {};+ const config = await readCosConfig({ rootDir, label: 'migration 262' });return QUEUE_FILES.map(({ configKey, file }) => (typeof config[configKey] === 'string' && config[configKey] ? config[configKey] : file));diff --git a/scripts/migrations/270-cos-task-prompt-split.js b/scripts/migrations/270-cos-task-prompt-split.jsindex 55b86a86d6..6909691b4c 100644--- a/scripts/migrations/270-cos-task-prompt-split.js+++ b/scripts/migrations/270-cos-task-prompt-split.js@@ -47,6 +47,7 @@import { readFile } from 'fs/promises';import { join } from 'path';import { atomicWrite } from '../../server/lib/fileUtils.js';+import { readCosConfig } from './_lib.js';import { isPromptPayload, TASK_PROMPT_KEY, TASK_CONTEXT_KEY } from '../../server/lib/cosTaskPrompt.js';// The task header line, per `server/lib/taskParser.js`. Both spellings — with@@ -171,24 +172,13 @@ export function splitPromptMetadata(markdown, { stamp }) {}/**- * Repo-relative path of a queue file, honouring an install that moved it in- * `data/cos/state.json` (`config.userTasksFile` / `config.cosTasksFile` — the- * same values `cosTaskStore` reads). Migrating only the defaults would record- * this migration as applied while the live queue stayed unsplit.+ * Repo-relative path of a queue file, honouring an install that moved it in its+ * CoS config (`userTasksFile` / `cosTasksFile` — the same values `cosTaskStore`+ * reads). Migrating only the defaults would record this migration as applied+ * while the live queue stayed unsplit.*/async function queuePaths(rootDir) {- const raw = await readFile(join(rootDir, 'data', 'cos', 'state.json'), 'utf-8').catch(() => null);- let config = {};- if (raw) {- try {- config = JSON.parse(raw)?.config ?? {};- } catch {- // State recovery is intentionally tolerant elsewhere. A malformed- // optional config file must not prevent this migration from splitting- // the default queues and letting the normal state loader repair it.- console.warn('⚠️ migration 270: invalid CoS state; using default task queue paths');- }- }+ const config = await readCosConfig({ rootDir, label: 'migration 270' });return QUEUE_FILES.map(({ configKey, file }) => (typeof config[configKey] === 'string' && config[configKey] ? config[configKey] : file));diff --git a/scripts/migrations/270-cos-task-prompt-split.test.js b/scripts/migrations/270-cos-task-prompt-split.test.jsindex 85708ad7d5..da7ddd370b 100644--- a/scripts/migrations/270-cos-task-prompt-split.test.js+++ b/scripts/migrations/270-cos-task-prompt-split.test.js@@ -225,6 +225,20 @@ describe('migration 270 up()', () => {await expect(migration.up({ rootDir, now: STAMP })).resolves.toMatchObject({ ok: true, split: 1 });expect(parseTasksMarkdown(await readFile(cosTasks(), 'utf-8'))[0].metadata.prompt).toBe(AGENT_BODY);- expect(warn).toHaveBeenCalledWith(expect.stringContaining('invalid CoS state'));+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('invalid JSON in data/cos/state.json'));+ });++ // Config moved to its own file in migration 339. A fresh install runs 270+ // against that shape, so the relocated queue must still resolve from there.+ it('honours a relocated queue file recorded in data/cos/config.json', async () => {+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ await writeFile(+ join(rootDir, 'data', 'cos', 'config.json'),+ JSON.stringify({ cosTasksFile: 'data/cos/MY-TASKS.md' })+ );+ const moved = join(rootDir, 'data', 'cos', 'MY-TASKS.md');+ await writeFile(moved, queue(task('sys-1', { context: AGENT_BODY })));+ await expect(migration.up({ rootDir, now: STAMP })).resolves.toMatchObject({ ok: true, split: 1 });+ expect(parseTasksMarkdown(await readFile(moved, 'utf-8'))[0].metadata.prompt).toBe(AGENT_BODY);});});diff --git a/scripts/migrations/339-cos-config-split.js b/scripts/migrations/339-cos-config-split.jsnew file mode 100644index 0000000000..afdd48f13b--- /dev/null+++ b/scripts/migrations/339-cos-config-split.js@@ -0,0 +1,87 @@+/**+ * Split the durable CoS user configuration out of `data/cos/state.json` into+ * its own `data/cos/config.json` (#6182).+ *+ * `state.json` is rewritten on every agent status change and every batched+ * output flush; `config` (concurrency caps, domain autonomy/budgets, the+ * Persistent Mind grants/profile/prompt) is written only when the user changes+ * a setting. Coupling them re-serialized ~180 KB of settings on every hot-path+ * write and put near-impossible-to-reconstruct settings at risk from any damage+ * to the runtime file.+ *+ * Idempotent: the lift is a no-op once `config.json` exists. `loadConfig()`+ * keeps a back-compat read of a legacy `config` slice, so an install that has+ * not run this migration (an un-upgraded peer, a restored pre-split backup)+ * still boots on its own settings rather than defaults.+ *+ * Also removes the `config.last-known-good.json` sidecar. That file mirrored the+ * config slice out of state.json precisely because the two shared a file;+ * config.json IS the low-frequency copy now, nothing reads the sidecar any more,+ * and leaving a stale "last known good config" on disk only invites someone to+ * restore settings from it that the live file has since moved past.+ */++import { readFile, rm } from 'fs/promises';+import { join } from 'path';+import { atomicWrite } from '../../server/lib/fileUtils.js';++const STATE_PATH = join('data', 'cos', 'state.json');+const CONFIG_PATH = join('data', 'cos', 'config.json');+const RETIRED_BACKUP_PATH = join('data', 'cos', 'config.last-known-good.json');++async function readJson(path) {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ try {+ return JSON.parse(raw);+ } catch {+ return null;+ }+}++/** Best-effort removal of the retired sidecar; its absence is the normal case. */+async function removeRetiredBackup(rootDir) {+ const removed = await rm(join(rootDir, RETIRED_BACKUP_PATH)).then(() => true).catch(() => false);+ if (removed) console.log(`🧹 Removed retired ${RETIRED_BACKUP_PATH} — config.json owns the settings now`);+ return removed;+}++export default {+ async up({ rootDir }) {+ // Runs on every path below, including the already-split no-op: an install+ // that got config.json some other way still has the sidecar to clean up.+ const removedBackup = await removeRetiredBackup(rootDir);+ const configPath = join(rootDir, CONFIG_PATH);+ // Presence, not parseability, is the guard: a config.json that exists but+ // is unreadable belongs to the state loader's quarantine path, not to a+ // migration that would overwrite it with a stale copy from state.json.+ const alreadySplit = await readFile(configPath, 'utf-8').then(() => true).catch(() => false);+ if (alreadySplit) return { split: false, removedBackup, reason: 'config.json already exists' };++ const statePath = join(rootDir, STATE_PATH);+ const state = await readJson(statePath);+ // A missing/corrupt state.json is not this migration's problem — the state+ // loader quarantines and re-defaults it. Nothing to lift out, so record the+ // migration as applied and let the config file be created on first write.+ if (!state || typeof state !== 'object' || Array.isArray(state)) {+ return { split: false, removedBackup, reason: 'no readable state.json' };+ }++ const config = state.config;+ if (!config || typeof config !== 'object' || Array.isArray(config)) {+ return { split: false, removedBackup, reason: 'state.json carries no config slice' };+ }++ // Write the config file FIRST. If the process dies between the two writes,+ // the settings exist in both places (config.json wins on read) rather than+ // in neither.+ await atomicWrite(configPath, `${JSON.stringify(config, null, 2)}\n`);+ delete state.config;+ await atomicWrite(statePath, `${JSON.stringify(state, null, 2)}\n`);+ console.log(`📦 ${CONFIG_PATH}: lifted ${Object.keys(config).length} config keys out of ${STATE_PATH}`);+ return { split: true, removedBackup, keys: Object.keys(config).length };+ },+};diff --git a/scripts/migrations/339-cos-config-split.test.js b/scripts/migrations/339-cos-config-split.test.jsnew file mode 100644index 0000000000..7bdb54e25d--- /dev/null+++ b/scripts/migrations/339-cos-config-split.test.js@@ -0,0 +1,118 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './339-cos-config-split.js';++const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`);+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));++describe('migration 339 — split CoS config out of state.json', () => {+ let rootDir;+ let statePath;+ let configPath;++ beforeEach(() => {+ rootDir = mkdtempSync(join(tmpdir(), 'migration-339-'));+ mkdirSync(join(rootDir, 'data', 'cos'), { recursive: true });+ statePath = join(rootDir, 'data', 'cos', 'state.json');+ configPath = join(rootDir, 'data', 'cos', 'config.json');+ });++ afterEach(() => {+ rmSync(rootDir, { recursive: true, force: true });+ });++ it('lifts config into its own file and rewrites state.json without it', async () => {+ writeJson(statePath, {+ running: false,+ paused: false,+ config: { maxConcurrentAgents: 7, persistentMindPrompt: { body: 'keep me' } },+ stats: { tasksCompleted: 4 },+ agents: { 'agent-1': { status: 'running' } },+ });++ const result = await migration.up({ rootDir });++ expect(result.split).toBe(true);+ expect(readJson(configPath)).toEqual({+ maxConcurrentAgents: 7,+ persistentMindPrompt: { body: 'keep me' },+ });+ const state = readJson(statePath);+ expect(state.config).toBeUndefined();+ // Everything that is NOT config stays exactly where it was.+ expect(state).toEqual({+ running: false,+ paused: false,+ stats: { tasksCompleted: 4 },+ agents: { 'agent-1': { status: 'running' } },+ });+ });++ it('is idempotent — a second run leaves the split files untouched', async () => {+ writeJson(statePath, { running: true, config: { maxConcurrentAgents: 7 }, agents: {} });+ await migration.up({ rootDir });+ const configAfterFirst = readFileSync(configPath, 'utf-8');+ const stateAfterFirst = readFileSync(statePath, 'utf-8');++ const result = await migration.up({ rootDir });++ expect(result.split).toBe(false);+ expect(readFileSync(configPath, 'utf-8')).toBe(configAfterFirst);+ expect(readFileSync(statePath, 'utf-8')).toBe(stateAfterFirst);+ });++ // A pre-existing config.json is the newer, authoritative copy. Overwriting it+ // from a stale `config` slice still sitting in state.json would silently roll+ // the user's settings back.+ it('never overwrites an existing config.json from a stale state.json slice', async () => {+ writeJson(configPath, { maxConcurrentAgents: 9 });+ writeJson(statePath, { running: false, config: { maxConcurrentAgents: 2 }, agents: {} });++ const result = await migration.up({ rootDir });++ expect(result.split).toBe(false);+ expect(readJson(configPath)).toEqual({ maxConcurrentAgents: 9 });+ });++ // The sidecar mirrored config out of state.json because the two shared a+ // file. Nothing reads it after the split, and a stale "last known good+ // config" left on disk only invites a restore that undoes newer settings.+ it('removes the retired config.last-known-good.json sidecar', async () => {+ const sidecar = join(rootDir, 'data', 'cos', 'config.last-known-good.json');+ writeJson(sidecar, { maxConcurrentAgents: 2 });+ writeJson(statePath, { running: false, config: { maxConcurrentAgents: 7 }, agents: {} });++ expect((await migration.up({ rootDir })).removedBackup).toBe(true);+ expect(existsSync(sidecar)).toBe(false);+ expect(readJson(configPath)).toEqual({ maxConcurrentAgents: 7 });+ });++ // An install that reached the split shape some other way still has one.+ it('removes the sidecar even when the lift itself is a no-op', async () => {+ const sidecar = join(rootDir, 'data', 'cos', 'config.last-known-good.json');+ writeJson(sidecar, { maxConcurrentAgents: 2 });+ writeJson(configPath, { maxConcurrentAgents: 9 });++ const result = await migration.up({ rootDir });++ expect(result).toMatchObject({ split: false, removedBackup: true });+ expect(existsSync(sidecar)).toBe(false);+ expect(readJson(configPath)).toEqual({ maxConcurrentAgents: 9 });+ });++ it('is a no-op when state.json is missing, unreadable, or carries no config', async () => {+ expect((await migration.up({ rootDir })).split).toBe(false);+ expect(existsSync(configPath)).toBe(false);++ writeFileSync(statePath, '{"running": tru');+ expect((await migration.up({ rootDir })).split).toBe(false);+ expect(existsSync(configPath)).toBe(false);++ writeJson(statePath, { running: false, agents: {} });+ expect((await migration.up({ rootDir })).split).toBe(false);+ expect(existsSync(configPath)).toBe(false);+ });+});diff --git a/scripts/migrations/_lib.js b/scripts/migrations/_lib.jsindex a0df499dbf..2b0dcd6695 100644--- a/scripts/migrations/_lib.js+++ b/scripts/migrations/_lib.js@@ -36,6 +36,10 @@* when retiring an id from the shipped seed; reach for 7b when a later* tier needs to be OFFERED without disturbing whatever the user already* has listed.+ * 8. CoS config reads — `readCosConfig` resolves the durable CoS settings a+ * migration needs to honour an install-specific path, across both the+ * pre- and post-339 layouts (`data/cos/state.json`'s `config` slice and+ * `data/cos/config.json`).** Families 5, 7, and 7b all target `data/providers.json` and share its* read → parse → shape-guard preamble via `readProvidersDoc`; each still owns@@ -679,6 +683,43 @@ export async function writeMediaRegistry(path, config) {await atomicWrite(path, `${JSON.stringify(config, null, 2)}\n`);}+// ---- CoS config readers ----++/**+ * Read the durable CoS user configuration a migration needs to resolve an+ * install-specific path (`userTasksFile` / `cosTasksFile` are the ones that+ * matter today). Returns `{}` when there is nothing usable — every caller+ * already falls back to the shipped defaults.+ *+ * Config moved out of `data/cos/state.json` into `data/cos/config.json` in+ * migration 339. Both are consulted, config file first, so this resolves+ * correctly whether the reading migration runs before or after that split (and+ * on an install restored from a pre-split backup).+ *+ * Deliberately tolerant: a truncated/corrupt file left by a prior crash must+ * not abort the reading migration and every one after it — the state loader+ * owns quarantining and repairing those files.+ */+export async function readCosConfig({ rootDir, label = 'migration' }) {+ for (const relPath of ['data/cos/config.json', 'data/cos/state.json']) {+ const raw = await readFile(join(rootDir, relPath), 'utf-8').catch(() => null);+ if (raw === null) continue;+ let parsed;+ try {+ parsed = JSON.parse(raw);+ } catch {+ // Not necessarily the final answer — the next source in the list may+ // still carry a usable config, so this says only what was skipped.+ console.warn(`⚠️ ${label}: invalid JSON in ${relPath}; ignoring it`);+ continue;+ }+ // config.json IS the config; state.json nests it under `config`.+ const config = relPath.endsWith('config.json') ? parsed : parsed?.config;+ if (config && typeof config === 'object' && !Array.isArray(config)) return config;+ }+ return {};+}+// ---- brain seed-record migration family ----//// `scripts/setup-data.js` copies `data.reference/` wholesale, so a FRESH installdiff --git a/scripts/seed-readme-demo-data.mjs b/scripts/seed-readme-demo-data.mjsindex f54bab2aca..3ae532c102 100644--- a/scripts/seed-readme-demo-data.mjs+++ b/scripts/seed-readme-demo-data.mjs@@ -168,23 +168,26 @@ writeJson('providers.json', {},});+// Durable user config lives in its own file (#6182); state.json holds only the+// runtime records.+writeJson('cos/config.json', {+ userTasksFile,+ cosTasksFile,+ healthCheckIntervalMs: 900000,+ maxConcurrentAgents: 3,+ maxConcurrentAgentsPerProject: 2,+ maxProcessMemoryMb: 2048,+ maxTotalProcesses: 50,+ autoStart: false,+ alwaysOn: false,+ selfImprovementEnabled: true,+ dynamicAvatar: true,+ avatarStyle: 'svg',+});+writeJson('cos/state.json', {running: false,paused: false,- config: {- userTasksFile,- cosTasksFile,- healthCheckIntervalMs: 900000,- maxConcurrentAgents: 3,- maxConcurrentAgentsPerProject: 2,- maxProcessMemoryMb: 2048,- maxTotalProcesses: 50,- autoStart: false,- alwaysOn: false,- selfImprovementEnabled: true,- dynamicAvatar: true,- avatarStyle: 'svg',- },stats: {tasksCompleted: 18,totalRuntime: 8940000,diff --git a/server/lib/agentRunEvents.js b/server/lib/agentRunEvents.jsindex 748c8084b0..eeab5a6887 100644--- a/server/lib/agentRunEvents.js+++ b/server/lib/agentRunEvents.js@@ -99,14 +99,7 @@ export const AGENT_RUN_EVENT_KINDS = Object.freeze([// `endTime` that no exit ever produced, and nothing would say where it came// from. Adding this kind is not an envelope shape change — older builds fold// unknown kinds as no-ops — so AGENT_RUN_EVENT_SCHEMA_VERSION stays at 1.- 'run.reconciled',- // A configured orchestration lane refused to substitute providers and stopped- // the run before it spawned (#5993). Its own kind because the durable record- // this ledger annotates does NOT exist for it — no run directory is created —- // so without this line the only trace of a fail-closed lane is a blocked task,- // and "the cheap tier was down" is indistinguishable from every other block.- // Carries no runId (there is no run); keyed by agentId via `runEventKey`.- 'run.lane-refused'+ 'run.reconciled']);/** All writeable kinds in the shared machine-local ledger. */@@ -515,9 +508,8 @@ export function projectRunStates(events) {* Every non-terminal arm below is guarded by this: the ledger is read in append* order, but a late-arriving annotation (a stop request that raced the exit, a* reconnect logged after the process was already reaped) must not resurrect a- * finished run as `running`. Only `run.finalized` and `run.lane-refused` may set- * a terminal status — the second because a refused lane never spawned a process,- * so no finalize will ever arrive for it (#5993) — and once set it stays.+ * finished run as `running`. `run.finalized` is the only arm that may set a+ * terminal status, so once set it stays.*/const isTerminal = (state) => state.status === 'completed' || state.status === 'failed';@@ -542,24 +534,6 @@ const canObserveRunning = (state) => !isTerminal(state) && !state.paused;function applyKind(state, event) {const data = event.data ?? {};switch (event.kind) {- case 'run.lane-refused':- // Terminal, and the ONLY arm besides `run.finalized` allowed to say so:- // a refused lane never spawned a process, so no exit will ever arrive to- // finalize it, and leaving the projection `unknown` would read as "still- // being figured out" for a run that is definitively over. Guarded like- // every other arm so it can never overwrite a real verdict.- if (!isTerminal(state)) {- state.status = 'failed';- state.success = false;- }- state.endedAt = state.endedAt ?? event.at;- state.laneRefused = {- role: typeof data.role === 'string' ? data.role : null,- requestedProvider: typeof data.requestedProvider === 'string' ? data.requestedProvider : null,- requestedModel: typeof data.requestedModel === 'string' ? data.requestedModel : null,- reason: typeof data.reason === 'string' ? data.reason : null,- };- break;case 'run.spawned':// Guarded like every other non-terminal arm. A spawn should never follow a// finalize for the same run, but the ledger is a stream several@@ -570,10 +544,6 @@ function applyKind(state, event) {state.startedAt = state.startedAt ?? event.at;if (typeof data.providerId === 'string') state.providerId = data.providerId;if (typeof data.model === 'string') state.model = data.model;- // The tier this run actually ran as, plus the same-role alternate it fell- // to, if any — so a diagnostic can show the split the user configured.- if (typeof data.orchestrationRole === 'string') state.orchestrationRole = data.orchestrationRole;- if (typeof data.laneSubstitutedFrom === 'string') state.laneSubstitutedFrom = data.laneSubstitutedFrom;break;case 'run.runner-recovered':// A survivor is still running — recovery is an annotation on a live run,diff --git a/server/lib/agentRunEvents.test.js b/server/lib/agentRunEvents.test.jsindex 1e159d7cb5..bc9c834dae 100644--- a/server/lib/agentRunEvents.test.js+++ b/server/lib/agentRunEvents.test.js@@ -560,62 +560,3 @@ describe('projectRunStates — run.reconciled (#4540)', () => {expect(state).toMatchObject({ reconciled: false, reconciledCount: 0 });});});--describe('run.lane-refused — fail-closed orchestration lanes (#5993)', () => {- it('is terminal even though no run ever spawned', () => {- const event = buildRunEvent({- kind: 'run.lane-refused',- agentId: 'agent-1',- taskId: 'task-1',- at: AT,- data: { role: 'implementer', requestedProvider: 'p-cheap', requestedModel: 'm-cheap', reason: 'not authenticated' },- });- const [state] = projectRunStates([event]);- // Keyed by the agent: the refusal happens before a run id exists.- expect(state.id).toBe('agent:agent-1');- expect(state.status).toBe('failed');- expect(state.success).toBe(false);- expect(state.endedAt).toBe(AT);- expect(state.laneRefused).toEqual({- role: 'implementer',- requestedProvider: 'p-cheap',- requestedModel: 'm-cheap',- reason: 'not authenticated',- });- });-- it('never talks a run that already reached a verdict back to failed', () => {- const finalized = buildRunEvent({- kind: 'run.finalized',- runId: 'run-1',- agentId: 'agent-2',- at: AT,- data: { exitCode: 0, success: true },- });- const refused = buildRunEvent({- kind: 'run.lane-refused',- runId: 'run-1',- agentId: 'agent-2',- at: '2026-08-18T12:05:00.000Z',- data: { role: 'reviewer', reason: 'down' },- });- const [state] = projectRunStates([finalized, refused]);- expect(state.status).toBe('completed');- expect(state.success).toBe(true);- expect(state.laneRefused.role).toBe('reviewer');- });-- it('records the tier a spawned run actually ran as', () => {- const spawned = buildRunEvent({- kind: 'run.spawned',- runId: 'run-2',- agentId: 'agent-3',- at: AT,- data: { providerId: 'p-cheap-2', model: 'alt-m', orchestrationRole: 'architect', laneSubstitutedFrom: 'p-cheap' },- });- const [state] = projectRunStates([spawned]);- expect(state.orchestrationRole).toBe('architect');- expect(state.laneSubstitutedFrom).toBe('p-cheap');- expect(state.providerId).toBe('p-cheap-2');- });-});diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.jsindex 52e20c9aa5..57bfb49354 100644--- a/server/lib/cosValidation.js+++ b/server/lib/cosValidation.js@@ -136,26 +136,7 @@ const orchestrationRoleSchema = z.object({// Per-role reasoning effort. The architect's own rung for its planning pass;// for the implementer it is the DEFAULT a spec's `REASONING:` line overrides.effort: z.enum(EFFORT_LEVELS).optional(),- // The role's SAME-ROLE alternate (#5993) — the only provider swap a configured- // lane accepts. Without one, an unavailable lane stops the run rather than- // walking the run-level fallback chain back onto the architect's provider.- fallbackProvider: z.string().trim().min(1).max(120).optional(),- fallbackModel: z.string().trim().min(1).max(300).optional(),-}).strict().superRefine((role, ctx) => {- // Reject here what `normalizeRoleAssignment` would silently drop, and what the- // resolver would refuse at spawn time. Accepting them returns 200 for a profile- // that is permanently inert (or that stops every run the first time its provider- // blinks), and the user finds out only when a task blocks days later.- if (role.fallbackProvider && !role.provider && !role.model) {- ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['fallbackProvider'], message: 'fallbackProvider needs a provider or model pin on the same role to be an alternate to' });- }- if (role.fallbackModel && !role.fallbackProvider) {- ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['fallbackModel'], message: 'fallbackModel needs a fallbackProvider on the same role' });- }- if (role.model && role.fallbackProvider && !role.fallbackModel) {- ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['fallbackModel'], message: 'a role pinning a model must name the fallbackModel its fallbackProvider runs it as' });- }-});+}).strict();export const orchestrationProfileSchema = z.object(Object.fromEntries(ORCHESTRATION_ROLES.map(role => [role, orchestrationRoleSchema.optional()]))diff --git a/server/lib/cosValidation.test.js b/server/lib/cosValidation.test.jsindex 87d7fff6df..abb9f5d904 100644--- a/server/lib/cosValidation.test.js+++ b/server/lib/cosValidation.test.js@@ -280,39 +280,3 @@ describe('createCosTaskSchema isInvestigation (#6043)', () => {expect(parsed).not.toHaveProperty('investigationFingerprint');});});--/**- * Same-role alternates (#5993). The schema rejects exactly what the normalizer- * would drop and what the resolver would refuse — a 200 on a permanently-inert- * profile is a configuration the user only discovers when a task blocks later.- */-describe('cosValidation orchestration role alternates', () => {- const parseRole = (architect) => createCosTaskSchema.safeParse({- description: 'x',- orchestrationProfile: { architect },- });-- it('accepts an alternate beside a provider pin', () => {- expect(parseRole({ provider: 'p-cheap', fallbackProvider: 'p-cheap-2' }).success).toBe(true);- });-- it('accepts a model-pinned role whose alternate names its own model', () => {- expect(parseRole({- provider: 'p-cheap', model: 'm-cheap', fallbackProvider: 'p-cheap-2', fallbackModel: 'm-cheap-2',- }).success).toBe(true);- });-- it('rejects an alternate with no pin to be an alternate to', () => {- expect(parseRole({ effort: 'high', fallbackProvider: 'p-cheap-2' }).success).toBe(false);- });-- it('rejects a fallbackModel with no fallbackProvider', () => {- expect(parseRole({ provider: 'p-cheap', fallbackModel: 'm-cheap-2' }).success).toBe(false);- });-- it('rejects a model-pinned role whose alternate has no model to run it as', () => {- // Accepting this would let the run silently land on the alternate's own- // default — the substitution the fail-closed lane exists to prevent.- expect(parseRole({ provider: 'p-cheap', model: 'm-cheap', fallbackProvider: 'p-cheap-2' }).success).toBe(false);- });-});diff --git a/server/lib/orchestrationProfile.js b/server/lib/orchestrationProfile.jsindex 9daa75082c..ea43b8dec3 100644--- a/server/lib/orchestrationProfile.js+++ b/server/lib/orchestrationProfile.js@@ -72,34 +72,17 @@ const trimmedString = (value, maxLength) => {* only a model inherits the run's provider, and a role that pins nothing at all* normalizes away entirely (null) rather than persisting an empty object that* would read as a configured-but-blank override.- *- * `fallbackProvider` / `fallbackModel` are the role's SAME-ROLE alternate- * (#5993): the only substitution a configured lane accepts when its provider is- * unavailable. It is deliberately per-role rather than the run-level- * `metadata.fallbackProvider`, because the run-level chain is what silently- * collapses a cheap cross-vendor lane back onto the architect's provider.- *- * It rides on a `provider` OR a `model` pin — the same pair the resolver treats- * as fail-closed. A MODEL-only role is fail-closed too (its model is what the- * generic chain would drop), so it needs the alternate just as much; dropping- * one there would leave the refusal telling the user to configure a field this- * normalizer discards. A fallback pinned beside neither is dropped: there is- * nothing for it to be an alternate TO, and keeping it would read as a lane.*/function normalizeRoleAssignment(raw) {if (!isPlainObject(raw)) return null;const provider = trimmedString(raw.provider, MAX_PROVIDER_ID_LENGTH);const model = trimmedString(raw.model, MAX_MODEL_ID_LENGTH);const effort = EFFORT_LEVELS.includes(raw.effort) ? raw.effort : null;- const fallbackProvider = provider || model ? trimmedString(raw.fallbackProvider, MAX_PROVIDER_ID_LENGTH) : null;- const fallbackModel = fallbackProvider ? trimmedString(raw.fallbackModel, MAX_MODEL_ID_LENGTH) : null;if (!provider && !model && !effort) return null;return Object.freeze({...(provider ? { provider } : {}),...(model ? { model } : {}),...(effort ? { effort } : {}),- ...(fallbackProvider ? { fallbackProvider } : {}),- ...(fallbackModel ? { fallbackModel } : {}),});}diff --git a/server/lib/orchestrationProfile.test.js b/server/lib/orchestrationProfile.test.jsindex 7474c88f7c..feb610a8e5 100644--- a/server/lib/orchestrationProfile.test.js+++ b/server/lib/orchestrationProfile.test.js@@ -83,53 +83,3 @@ describe('role vocabulary', () => {expect([...ORCHESTRATION_ROLES]).toEqual(['architect', 'implementer', 'reviewer']);});});--/**- * Same-role alternates (#5993). The alternate rides on the pin it substitutes- * for, so what the normalizer keeps has to match what the resolver treats as a- * fail-closed lane — otherwise a refusal names a field that was silently dropped.- */-describe('same-role alternates', () => {- it('keeps a fallbackProvider + fallbackModel beside a provider pin', () => {- const profile = normalizeOrchestrationProfile({- implementer: { provider: 'p-cheap', model: 'm-cheap', fallbackProvider: 'p-cheap-2', fallbackModel: 'm-cheap-2' },- });- expect(profile.implementer).toEqual({- provider: 'p-cheap',- model: 'm-cheap',- fallbackProvider: 'p-cheap-2',- fallbackModel: 'm-cheap-2',- });- });-- // A model-only role is fail-closed too — the generic chain would drop its model- // pin — so it must be able to carry the alternate the refusal points the user at.- it('keeps the alternate on a model-only role', () => {- const profile = normalizeOrchestrationProfile({- implementer: { model: 'm-cheap', fallbackProvider: 'p-cheap-2', fallbackModel: 'm-cheap-2' },- });- expect(profile.implementer).toEqual({- model: 'm-cheap',- fallbackProvider: 'p-cheap-2',- fallbackModel: 'm-cheap-2',- });- });-- it('drops an alternate on a role that pins neither a provider nor a model', () => {- const profile = normalizeOrchestrationProfile({- implementer: { effort: 'high', fallbackProvider: 'p-cheap-2', fallbackModel: 'm-cheap-2' },- });- expect(profile.implementer).toEqual({ effort: 'high' });- });-- it('drops a fallbackModel with no fallbackProvider to attach to', () => {- const profile = normalizeOrchestrationProfile({- implementer: { provider: 'p-cheap', fallbackModel: 'm-cheap-2' },- });- expect(profile.implementer).toEqual({ provider: 'p-cheap' });- });-- it('does not make an alternate alone enough to persist a role', () => {- expect(normalizeOrchestrationProfile({ implementer: { fallbackProvider: 'p-cheap-2' } })).toBeNull();- });-});diff --git a/server/lib/taskBlockCategories.js b/server/lib/taskBlockCategories.jsindex 4f21ab158b..64c90e8b5d 100644--- a/server/lib/taskBlockCategories.js+++ b/server/lib/taskBlockCategories.js@@ -17,14 +17,6 @@import { AGENT_PAUSED_CATEGORY } from './taskPauseHold.js';-/**- * A fail-closed orchestration lane refused to substitute providers (#5993). Its- * own exported name because three places key on it — `agentLifecycle.js` stamps- * it, and BOTH sets below list it — which is exactly the literal drift this- * module exists to prevent.- */-export const ORCHESTRATION_LANE_BLOCKED_CATEGORY = 'orchestration-lane-unavailable';-/*** Pauses a TIMER clears, not a person: the task carries a `cooldownUntil` and the* cooldown sweeper (`unblockExpiredCooldowns`, cosTaskGenerator.js) flips it back@@ -54,16 +46,7 @@ export const TIMED_COOLDOWN_BLOCKED_CATEGORIES = new Set([export const PAUSED_BLOCKED_CATEGORIES = new Set([...TIMED_COOLDOWN_BLOCKED_CATEGORIES,'app-unresolved', // the task's app has no usable Repository Path- 'workspace-invalid', // the resolved workspace isn't a usable directory- // A fail-closed lane is a CONFIG pause of the same shape: the user authenticates- // the provider (or gives the role a fallbackProvider) and revives the task. It- // is not TIMED, so no cooldown sweeper picks it up. Listing it here is what- // keeps the resume pointer — without it a lane that blocked on a merely- // rate-limited provider would strip `existingBranch` / `resumeWorktreePath`,- // and the revived task would restart clean and orphan its predecessor's- // worktree. Before fail-closed that case stayed `pending` with its pointer- // intact, so omitting it here would be a NEW way to abandon work.- ORCHESTRATION_LANE_BLOCKED_CATEGORY+ 'workspace-invalid' // the resolved workspace isn't a usable directory]);/**@@ -82,13 +65,7 @@ export const USER_DECISION_BLOCKED_CATEGORIES = new Set([AGENT_PAUSED_CATEGORY, // user paused; resumable on demand'challenge-escalation', // parked awaiting the user's arbitration'app-unresolved',- 'workspace-invalid',- // Waiting on the same kind of fix as the workspace blocks above: authenticate- // the lane's provider, pick another model for the role, or give it a- // fallbackProvider. Without the exemption the failure sweep retires it to- // `completed` with an `auto-expired` marker after 14 days — turning the loud,- // deliberate stop into exactly the silent success the lane exists to prevent.- ORCHESTRATION_LANE_BLOCKED_CATEGORY+ 'workspace-invalid']);/**diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex d7c47507f5..0abdd60282 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -45,7 +45,6 @@ import { spawnAgentViaRunner, getRunnerHealth, classifyRunnerSpawnFailure, RUNNEimport { MAX_TOTAL_SPAWNS, normalizeReviewers } from '../lib/validation.js';import { isInternalTaskId } from '../lib/taskParser.js';import { isRetryHeld } from '../lib/taskRetryHold.js';-import { ORCHESTRATION_LANE_BLOCKED_CATEGORY } from '../lib/taskBlockCategories.js';import { ensureDir, PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';import { createToolExecution, startExecution, completeExecution, errorExecution } from './toolStateMachine.js';import { determineLane, acquire, release } from './executionLanes.js';@@ -412,50 +411,23 @@ async function runAgentSpawn(task) {// `in_progress` record clobbered to `blocked` — which outranks `in_progress`// in the claim-aware merge. Transient failures fall through, skip the block,// and stay pending to retry.- // A configured orchestration lane that refused to substitute providers- // (#5993) is its OWN terminal outcome, not a generic provider failure: the- // fix is specific to the role ("authenticate that CLI", "pick another model- // for the implementer", "give it a fallbackProvider"), and a run that- // stopped for it must never be reported as anything else. The structured- // detail rides along on the task metadata, the `agent:error` event, and the- // ledger below so each surface names the role and provider itself.- const lane = resolution.orchestrationLane || null;if (resolution.permanent) {await updateTask(task.id, {status: 'blocked',metadata: {...task.metadata,blockedReason: resolution.error,- blockedCategory: lane ? ORCHESTRATION_LANE_BLOCKED_CATEGORY : 'provider-config',- ...(lane ? { orchestrationLane: lane } : {}),+ blockedCategory: 'provider-config',blockedAt: new Date().toISOString()}}, task.taskType || 'user').catch(() => {});}- // Recorded BEFORE cleanup so the ledger holds the reason even if cleanup- // throws. No runId exists — the run never spawned — so this is keyed by the- // agent id, which is exactly the `agent:<id>` fallback `runEventKey` has.- if (lane) {- await appendRunEvent({- kind: 'run.lane-refused',- agentId,- taskId: task.id,- eventId: `lane-refused:${agentId}:${lane.role}`,- data: {- role: lane.role,- requestedProvider: lane.requestedProvider,- requestedModel: lane.requestedModel,- reason: lane.reason,- },- });- }await cleanupOnError(resolution.error);cosEvents.emit('agent:error', {taskId: task.id,error: resolution.error,...(resolution.providerId && { providerId: resolution.providerId }),...(resolution.providerStatus && { providerStatus: resolution.providerStatus }),- ...(lane && { orchestrationLane: lane }),});return null;}@@ -748,8 +720,7 @@ async function runAgentSpawn(task) {model: selectedModel,provider,workspacePath,- appName: resolvedAppName,- orchestrationLane: resolution.orchestrationLane ?? null+ appName: resolvedAppName});const executionMode = !spawnHeadless ? (dispatchUseRunner ? 'runner-tui' : 'tui') : dispatchUseRunner ? 'runner' : 'direct';diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex d691196c36..d6c3b4f77e 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -612,50 +612,19 @@ describe('runAgentSpawn source — app-review marker release (issue #989)', () =// re-dispatch. Without a block, the task stays pending and silently re-fails// forever. Pin that the permanent branch flips the task to blocked BEFORE the// lease is released, so a federated peer can't be clobbered.-// Wide enough to cover the whole `if (!resolution.ok)` arm — its comments carry-// the reasoning for the ordering these tests pin, so the window has to include-// them rather than being trimmed to the statements.-const RESOLUTION_FAILURE_WINDOW = 4000;-describe('runAgentSpawn source — permanent provider-config failure blocks the task', () => {it('the resolution-failure path blocks a permanent failure with a provider-config reason', () => {const idx = AGENT_LIFECYCLE_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');expect(idx, 'resolution call must exist').toBeGreaterThan(-1);- const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + RESOLUTION_FAILURE_WINDOW);+ const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 2000);expect(body, 'gates the block on resolution.permanent').toMatch(/if\s*\(resolution\.permanent\)/);expect(body, 'flips the task to blocked').toMatch(/status:\s*'blocked'/);- expect(body, 'tags the block category').toMatch(/blockedCategory:[^\n]*'provider-config'/);- });-- // A configured orchestration lane that refuses to substitute providers (#5993)- // is a DISTINCT terminal outcome: same block, its own category and structured- // detail, so the client can name the role and provider instead of showing a- // generic provider-config failure.- it('tags a refused orchestration lane with its own category and detail', () => {- const idx = AGENT_LIFECYCLE_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');- const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + RESOLUTION_FAILURE_WINDOW);- expect(body, 'reads the structured lane detail').toMatch(/const lane = resolution\.orchestrationLane/);- // The category is referenced through the shared constant, not re-typed: the- // failure sweep exempts the same value, and two literals would drift.- expect(body, 'has its own block category').toMatch(/ORCHESTRATION_LANE_BLOCKED_CATEGORY/);- expect(AGENT_LIFECYCLE_SRC, 'takes the category from the shared module')- .toMatch(/import \{ ORCHESTRATION_LANE_BLOCKED_CATEGORY \} from '\.\.\/lib\/taskBlockCategories\.js';/);- expect(body, 'carries the detail onto the task').toMatch(/orchestrationLane: lane/);- expect(body, 'records the refusal in the ledger').toMatch(/kind: 'run\.lane-refused'/);- });-- it('records the lane refusal BEFORE cleanup, so the reason survives a failing cleanup', () => {- const idx = AGENT_LIFECYCLE_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');- const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + RESOLUTION_FAILURE_WINDOW);- const ledgerIdx = body.indexOf("kind: 'run.lane-refused'");- const cleanupIdx = body.indexOf('await cleanupOnError(resolution.error)');- expect(ledgerIdx, 'ledger append must exist').toBeGreaterThan(-1);- expect(ledgerIdx, 'ledger append must precede cleanup').toBeLessThan(cleanupIdx);+ expect(body, 'tags the block category').toMatch(/blockedCategory:\s*'provider-config'/);});it('blocks BEFORE releasing the lease so a federated peer cannot be clobbered', () => {const idx = AGENT_LIFECYCLE_SRC.indexOf('const resolution = await resolveAgentProviderAndModel(task)');- const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + RESOLUTION_FAILURE_WINDOW);+ const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 2000);const permanentIdx = body.indexOf('if (resolution.permanent)');const cleanupIdx = body.indexOf('await cleanupOnError(resolution.error)');expect(permanentIdx, 'permanent block must exist').toBeGreaterThan(-1);diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 280e1bc082..0cc731c20f 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -623,7 +623,7 @@ async function requeuePausedTask({ task, taskType, overrides }) {// state owned by the spent task/run so the replacement gets a new retry budget,// lease, workspace pointer, and output-hook dispatch.const REPLACEMENT_RUNTIME_METADATA_KEYS = new Set([- 'blockedReason', 'blockedCategory', 'blockedAt', 'blocker', 'orchestrationLane', 'failureCount',+ 'blockedReason', 'blockedCategory', 'blockedAt', 'blocker', 'failureCount','lastErrorCategory', 'lastFailureAt', 'cooldownUntil', 'totalSpawnCount','orphanRetryCount', 'lastOrphanedAt', 'lastOrphanedAgentId', 'worktreeBusyAttempts',LAST_SPAWNED_AT_KEY, 'interruptedByRestart', 'lastInterruptedAt', 'lastInterruptedAgentId',diff --git a/server/services/agentProviderResolution.js b/server/services/agentProviderResolution.jsindex 483d8a04e2..61f86d46cd 100644--- a/server/services/agentProviderResolution.js+++ b/server/services/agentProviderResolution.js@@ -18,7 +18,7 @@ import { getActiveProvider, getAllProviders, getProviderById } from './providersimport { isProviderAvailable, getFallbackProvider, getProviderStatus } from './providerStatus.js';import { selectModelForRole, selectModelForTask } from './agentModelSelection.js';import { modelPinIsOffered } from '../lib/localProviderRuntime.js';-import { PRIMARY_ORCHESTRATION_ROLE, isOrchestratedTask, roleAssignment } from '../lib/orchestrationProfile.js';+import { PRIMARY_ORCHESTRATION_ROLE, roleAssignment } from '../lib/orchestrationProfile.js';import { publicReviewPostureForTask, resolvePublicReviewProvider } from './publicReviewProviderSelection.js';/**@@ -112,36 +112,6 @@ async function resolvePublicReviewAgentProvider(task, posture) {return { ok: true, provider, selectedModel, modelSelection };}-/**- * A configured orchestration lane refused to substitute providers (#5993).- *- * Shaped so every consumer reads one structure: the caller blocks the task with- * `error` as its reason, the `agent:error` event and the run ledger carry- * `orchestrationLane` verbatim, and the client names the role and provider from- * the same fields rather than re-parsing the sentence.- *- * Always PERMANENT. That is the point of a fail-closed lane: a rate-limited- * cheap provider that would recover in an hour is still a lane the user has to- * decide about, and quietly re-dispatching until it comes back is the silent- * behavior this replaces. Unblocking is one click once the CLI is authenticated- * or a `fallbackProvider` is configured; a lane that retried itself would spend- * the architect's budget with nobody watching.- */-function laneUnavailable({ role, requestedProvider, requestedModel, reason }) {- const requested = requestedProvider- ? `its provider "${requestedProvider}"${requestedModel ? ` (model "${requestedModel}")` : ''} is unavailable`- : `its pinned model "${requestedModel}" has nothing to run on`;- return {- ok: false,- permanent: true,- error: `Orchestrated ${role} lane stopped — ${requested}: ${reason}. `- + `PortOS will not substitute another provider for a configured lane; authenticate or repair that provider, `- + `pick another model for the ${role} role, or configure ${role}.fallbackProvider.`,- providerId: requestedProvider || undefined,- orchestrationLane: { role, requestedProvider: requestedProvider || null, requestedModel: requestedModel || null, reason },- };-}-async function resolveOrdinaryProviderAndModel(task) {// A task can pin a specific provider via metadata.provider (e.g. a CoS job's// per-job AI override). Resolve it BEFORE the active-provider availability@@ -156,68 +126,19 @@ async function resolveOrdinaryProviderAndModel(task) {// (availability, fallback swap, the model-pin invalidation a swap triggers)// rather than growing a second, subtly-different resolution path. Null on a// `direct` task, so the metadata pin stays authoritative as before.- //- // …with ONE exception, and it is the whole of #5993. An orchestrated run's- // roles exist BECAUSE they are different providers: the implementer lane is- // cheap and cross-vendor on purpose. Swapping a configured lane onto whatever- // is healthy spends the architect's premium tokens on mechanical editing —- // the exact cost orchestration was turned on to avoid — and collapses the- // vendor split with nobody told. So when the role carries an assignment at- // all, this lane is FAIL-CLOSED: the only substitution it accepts is the- // role's own `fallbackProvider`, and anything else stops the run loudly.- // `direct`-mode runs keep the pin → active → fallback chain untouched- // (`roleAssignment` returns null for every role on one).- const laneRole = PRIMARY_ORCHESTRATION_ROLE;- const roleAssign = roleAssignment(task, laneRole);- // Fail-closed applies only to a role that pinned WHERE it runs. A role- // carrying nothing but an `effort` rung has expressed no vendor or model- // preference to protect, so refusing to substitute for it would strand a run- // over a choice the user never made — it keeps the ordinary chain.- const lane = roleAssign?.provider || roleAssign?.model ? roleAssign : null;- const userProviderId = lane?.provider || task.metadata?.provider;+ const userProviderId = roleAssignment(task, PRIMARY_ORCHESTRATION_ROLE)?.provider || task.metadata?.provider;let userProviderMissing = false;if (userProviderId) {const userProvider = await getProviderById(userProviderId);if (userProvider) {emitLog('info', `Using user-specified provider: ${userProviderId}`, { taskId: task.id });provider = userProvider;- } else if (lane?.provider) {- // A configured lane whose provider record does not exist is a config error- // that re-fails identically forever — never "use the active provider".- return laneUnavailable({- role: laneRole,- requestedProvider: userProviderId,- requestedModel: lane.model || null,- reason: 'no provider with that id is configured on this install',- });} else {userProviderMissing = true;emitLog('warn', `User-specified provider "${userProviderId}" not found, using active provider`, { taskId: task.id });}}if (!provider) provider = await getActiveProvider();- // A lane that pins only a MODEL inherits whatever provider the task resolves- // to — so both ways that inheritance can fail are the LANE failing, and both- // say so in the lane's own shape rather than falling through.- //- // `userProviderMissing` is the one that bites: the `else` above continues on- // the active provider, which makes `providerSwapped` true below, which drops- // the lane's pinned model to that provider's default. That is the silent- // model-axis substitution the `no-model` refusal and the alternate's- // pass-through exemption exist to close, arriving on a path with no block, no- // `orchestrationLane`, and nothing naming the role. The other is simpler: no- // active provider at all, where the generic "No active AI provider configured"- // below would lose the role and leave the client nothing to name.- if (lane && (!provider || userProviderMissing)) {- return laneUnavailable({- role: laneRole,- requestedProvider: userProviderMissing ? userProviderId : null,- requestedModel: lane.model || null,- reason: userProviderMissing- ? 'the provider pinned for this task is not configured on this install'- : 'no active AI provider is configured for it to inherit',- });- }if (!provider) {return { ok: false, error: 'No active AI provider configured' };@@ -242,9 +163,6 @@ async function resolveOrdinaryProviderAndModel(task) {// Model" pin — it overrides the usual per-task model selection so the// user's chosen fallback provider+model pair is honored on agent runs.let fallbackModelPin = null;- // The one substitution a configured lane DID accept, recorded so the run- // ledger can show the tier really ran where the user said it could (#5993).- let laneSubstitution = null;const providerAvailable = isProviderAvailable(provider.id);if (!providerAvailable) {const status = getProviderStatus(provider.id);@@ -254,88 +172,36 @@ async function resolveOrdinaryProviderAndModel(task) {reason: status.reason});- // A configured lane never walks the GENERIC chain (#5993). Its only accepted- // substitution is the same-role alternate the user named on the role itself,- // and that alternate must be a real, currently-available provider — an- // alternate that is itself down is not a lane, it is the same silent- // collapse one hop later.- if (lane) {- const alternateId = lane.fallbackProvider;- const alternate = alternateId ? await getProviderById(alternateId) : null;- // An `api`-type alternate is rejected HERE rather than left to the harness- // guard below. That guard computes its `permanent` flag from the lane's own- // (CLI) primary, so an api alternate reaching it returns a TRANSIENT failure- // with no lane detail — the task never blocks, never records the refusal,- // and re-dispatches into the same dead end forever. Silent re-failure is the- // behavior this whole path exists to end, so it cannot be the way it ends.- //- // A lane that pinned a MODEL also needs the alternate to name one. Without- // `fallbackModel` the pin belongs to the primary, the swap invalidates it,- // and the run silently lands on the alternate's own default — the same- // substitution this closes, moved from the provider axis to the model axis.- const alternateUnusable = !alternate ? 'missing'- : alternate.type === 'api' ? 'no-harness'- : !isProviderAvailable(alternate.id) ? 'unavailable'- : lane.model && !lane.fallbackModel ? 'no-model'- : null;- if (alternateUnusable) {- const why = !alternateId- ? `${status.message} (no ${laneRole}.fallbackProvider is configured)`- : alternateUnusable === 'missing'- ? `${status.message}, and its ${laneRole}.fallbackProvider "${alternateId}" is not a configured provider`- : alternateUnusable === 'no-harness'- ? `${status.message}, and its ${laneRole}.fallbackProvider "${alternateId}" is an HTTP API provider with no file-writing harness`- : alternateUnusable === 'no-model'- ? `${status.message}, and its ${laneRole}.fallbackProvider "${alternateId}" was given no ${laneRole}.fallbackModel to run the pinned model "${lane.model}" on`- : `${status.message}, and its ${laneRole}.fallbackProvider "${alternateId}" is also unavailable (${getProviderStatus(alternate.id).message})`;- return laneUnavailable({- role: laneRole,- requestedProvider: provider.id,- requestedModel: lane.model || null,- reason: why,- });- }- emitLog('info', `Orchestrated ${laneRole} lane using its same-role alternate ${alternate.id}`, {+ // Try to get a fallback provider (check task-level, then provider-level, then system default).+ // getFallbackProvider indexes its providers arg by id, so pass a map — NOT the+ // { activeProvider, providers: [...] } shape getAllProviders() returns (mirrors promptRunner.js).+ const { providers: providerList = [] } = await getAllProviders();+ const providersMap = Object.fromEntries(providerList.map((p) => [p.id, p]));+ const taskFallbackId = task.metadata?.fallbackProvider;+ const taskFallbackModel = task.metadata?.fallbackModel;+ const fallbackResult = await getFallbackProvider(provider.id, providersMap, taskFallbackId, taskFallbackModel);++ if (fallbackResult) {+ emitLog('info', `Using fallback provider: ${fallbackResult.provider.id} (source: ${fallbackResult.source})`, {taskId: task.id,primaryProvider: provider.id,- fallbackProvider: alternate.id,- fallbackSource: `orchestration-${laneRole}`,+ fallbackProvider: fallbackResult.provider.id,+ fallbackSource: fallbackResult.source});- laneSubstitution = { role: laneRole, from: provider.id, to: alternate.id, reason: status.message };- provider = alternate;- fallbackModelPin = lane.fallbackModel || null;+ provider = fallbackResult.provider;+ fallbackModelPin = fallbackResult.model || null;} else {- // Try to get a fallback provider (check task-level, then provider-level, then system default).- // getFallbackProvider indexes its providers arg by id, so pass a map — NOT the- // { activeProvider, providers: [...] } shape getAllProviders() returns (mirrors promptRunner.js).- const { providers: providerList = [] } = await getAllProviders();- const providersMap = Object.fromEntries(providerList.map((p) => [p.id, p]));- const taskFallbackId = task.metadata?.fallbackProvider;- const taskFallbackModel = task.metadata?.fallbackModel;- const fallbackResult = await getFallbackProvider(provider.id, providersMap, taskFallbackId, taskFallbackModel);-- if (fallbackResult) {- emitLog('info', `Using fallback provider: ${fallbackResult.provider.id} (source: ${fallbackResult.source})`, {- taskId: task.id,- primaryProvider: provider.id,- fallbackProvider: fallbackResult.provider.id,- fallbackSource: fallbackResult.source- });- provider = fallbackResult.provider;- fallbackModelPin = fallbackResult.model || null;- } else {- const errorMsg = `Provider ${provider.id} unavailable (${status.message}) and no fallback available`;- // TRANSIENT, never permanent: a null fallback here can mean a configured- // CLI/TUI fallback is merely momentarily down (getFallbackProvider skips- // unavailable candidates), so blocking would strand a task that recovers- // when that fallback returns. Permanence is decided by PROVIDER TYPE where we- // can actually inspect it — the harness check below, reached once the- // provider is available again — not inferred from a transient unavailable +- // null-fallback combination. A down api provider with no viable path retries- // cheaply (it fails fast here, spawning no agent) and self-heals to a- // permanent block the moment it becomes reachable.- return { ok: false, error: errorMsg, providerId: provider.id, providerStatus: status };- }+ const errorMsg = `Provider ${provider.id} unavailable (${status.message}) and no fallback available`;+ // TRANSIENT, never permanent: a null fallback here can mean a configured+ // CLI/TUI fallback is merely momentarily down (getFallbackProvider skips+ // unavailable candidates), so blocking would strand a task that recovers+ // when that fallback returns. Permanence is decided by PROVIDER TYPE where we+ // can actually inspect it — the harness check below, reached once the+ // provider is available again — not inferred from a transient unavailable ++ // null-fallback combination. A down api provider with no viable path retries+ // cheaply (it fails fast here, spawning no agent) and self-heals to a+ // permanent block the moment it becomes reachable.+ return { ok: false, error: errorMsg, providerId: provider.id, providerStatus: status };}}@@ -406,16 +272,7 @@ async function resolveOrdinaryProviderAndModel(task) {const providerSwapped = userProviderMissing || provider.id !== directProviderId;const pinnedProviderId = userProviderId || directProviderId;const isUserPin = modelSelection.tier === 'user-specified' && !fallbackModelPin;- // A lane's own `fallbackModel` is as explicit as `metadata.model` — the user- // named THIS model FOR THIS alternate (#5993). The `models` list is a- // convenience enumeration the pass-through CLIs don't enforce, and whose alias- // forms already disagree across records (see the note below), so downgrading- // the pin to the alternate's default here would silently run the lane on a- // model nobody chose — the model-axis substitution the `no-model` refusal- // above exists to close, arriving one branch later.- const isLaneAlternateModel = Boolean(laneSubstitution)- && fallbackModelPin != null && fallbackModelPin === lane?.fallbackModel;- const isUserPinnedModel = (isUserPin && !providerSwapped) || isLaneAlternateModel;+ const isUserPinnedModel = isUserPin && !providerSwapped;if (isUserPin && providerSwapped && !(provider.models || []).includes(selectedModel)) {// Handled here rather than left to the list check below, which can't fire at// all for a fallback provider that enumerates no `models`.@@ -460,26 +317,5 @@ async function resolveOrdinaryProviderAndModel(task) {...(modelSelection.learningReason && { learningReason: modelSelection.learningReason })});- return {- ok: true,- provider,- selectedModel,- modelSelection,- // What the run ledger records so `/cos/runs` can show the tier split really- // happened (#5993): the role this run was dispatched as, the provider it- // ACTUALLY ran on, and the one substitution — if any — the lane accepted.- // Gated on the RUN being orchestrated, not on this role being pinned: a- // profile that pins only the cheap implementer/reviewer lanes and leaves the- // architect on the run default is a normal config, and it is exactly the run- // whose tier split is worth showing. Absent on a `direct`-mode run.- ...(isOrchestratedTask(task) ? {- orchestrationLane: {- role: laneRole,- requestedProvider: roleAssign?.provider || directProviderId,- providerId: provider.id,- model: selectedModel,- ...(laneSubstitution ? { substitution: laneSubstitution } : {}),- },- } : {}),- };+ return { ok: true, provider, selectedModel, modelSelection };}diff --git a/server/services/agentProviderResolution.test.js b/server/services/agentProviderResolution.test.jsindex 4846b6d656..a2f35fff61 100644--- a/server/services/agentProviderResolution.test.js+++ b/server/services/agentProviderResolution.test.js@@ -513,353 +513,3 @@ describe('orchestration profiles (#5992)', () => {expect(result.provider.id).toBe('p-pinned');});});--/**- * Fail-closed orchestration lanes (#5993).- *- * The regression these exist for: a cheap cross-vendor implementer/architect- * lane silently becoming the expensive same-vendor lane. Every case below is a- * point where the generic pin → active → fallback chain WOULD have substituted- * a provider, and asserts it refuses instead.- */-describe('resolveAgentProviderAndModel — fail-closed orchestration lanes', () => {- const orchestrated = (architect, extraMetadata = {}) => ({- id: 'task-orch',- metadata: {- orchestrationMode: 'orchestrated',- orchestrationProfile: { architect },- ...extraMetadata,- },- });-- it('refuses to fall back to the active provider when the lane provider is not configured', async () => {- getProviderById.mockResolvedValue(null);- getActiveProvider.mockResolvedValue({ id: 'p-active', type: 'cli', defaultModel: 'm-active' });-- const r = await resolveAgentProviderAndModel(orchestrated({ provider: 'p-cheap', model: 'm-cheap' }));-- expect(r.ok).toBe(false);- expect(r.permanent).toBe(true);- expect(r.orchestrationLane).toEqual({- role: 'architect',- requestedProvider: 'p-cheap',- requestedModel: 'm-cheap',- reason: 'no provider with that id is configured on this install',- });- expect(r.error).toContain('architect');- expect(r.error).toContain('p-cheap');- expect(getActiveProvider).not.toHaveBeenCalled();- });-- it('refuses the generic fallback chain when a lane provider is unavailable', async () => {- getProviderById.mockResolvedValue({ id: 'p-cheap', type: 'cli', defaultModel: 'm-cheap' });- isProviderAvailable.mockReturnValue(false);- getProviderStatus.mockReturnValue({ message: 'not authenticated', reason: 'auth' });-- const r = await resolveAgentProviderAndModel(- // A run-level fallback is configured and must still be ignored: it is the- // exact silent collapse onto the architect's provider this closes.- orchestrated({ provider: 'p-cheap' }, { fallbackProvider: 'p-premium' }),- );-- expect(r.ok).toBe(false);- expect(r.permanent).toBe(true);- expect(r.orchestrationLane.reason).toContain('not authenticated');- expect(r.orchestrationLane.reason).toContain('no architect.fallbackProvider is configured');- expect(getFallbackProvider).not.toHaveBeenCalled();- });-- it('honors the same-role alternate and records the substitution', async () => {- const cheap = { id: 'p-cheap', type: 'cli', defaultModel: 'm-cheap' };- const alternate = { id: 'p-cheap-2', type: 'cli', models: ['alt-m'], defaultModel: 'alt-default' };- getProviderById.mockImplementation(async (id) => (id === 'p-cheap' ? cheap : alternate));- isProviderAvailable.mockImplementation((id) => id === 'p-cheap-2');- getProviderStatus.mockReturnValue({ message: 'rate limited', reason: 'limit' });-- const r = await resolveAgentProviderAndModel(orchestrated({- provider: 'p-cheap',- fallbackProvider: 'p-cheap-2',- fallbackModel: 'alt-m',- }));-- expect(r.ok).toBe(true);- expect(r.provider).toBe(alternate);- expect(r.selectedModel).toBe('alt-m');- expect(r.orchestrationLane).toEqual({- role: 'architect',- requestedProvider: 'p-cheap',- providerId: 'p-cheap-2',- model: 'alt-m',- substitution: { role: 'architect', from: 'p-cheap', to: 'p-cheap-2', reason: 'rate limited' },- });- expect(getFallbackProvider).not.toHaveBeenCalled();- });-- it('refuses when the same-role alternate is itself unavailable', async () => {- getProviderById.mockImplementation(async (id) => ({ id, type: 'cli', defaultModel: `m-${id}` }));- isProviderAvailable.mockReturnValue(false);- getProviderStatus.mockImplementation((id) => ({ message: `${id} down`, reason: 'down' }));-- const r = await resolveAgentProviderAndModel(orchestrated({- provider: 'p-cheap',- fallbackProvider: 'p-cheap-2',- }));-- expect(r.ok).toBe(false);- expect(r.orchestrationLane.reason).toContain('p-cheap-2');- expect(r.orchestrationLane.reason).toContain('also unavailable');- });-- it('refuses a model-only lane rather than inheriting a swapped provider', async () => {- getActiveProvider.mockResolvedValue(null);-- const r = await resolveAgentProviderAndModel(orchestrated({ model: 'm-cheap' }));-- expect(r.ok).toBe(false);- expect(r.permanent).toBe(true);- expect(r.orchestrationLane).toEqual({- role: 'architect',- requestedProvider: null,- requestedModel: 'm-cheap',- reason: 'no active AI provider is configured for it to inherit',- });- });-- it('reports the lane a healthy orchestrated run actually ran on', async () => {- const cheap = { id: 'p-cheap', type: 'cli', models: ['m-default'] };- getProviderById.mockResolvedValue(cheap);-- const r = await resolveAgentProviderAndModel(orchestrated({ provider: 'p-cheap' }));-- expect(r.ok).toBe(true);- expect(r.orchestrationLane).toEqual({- role: 'architect',- requestedProvider: 'p-cheap',- providerId: 'p-cheap',- model: 'm-default',- });- });-- it('leaves a direct-mode run on the generic fallback chain', async () => {- const primary = { id: 'p1', type: 'cli' };- const fallback = { id: 'p2', type: 'cli', models: ['m-fb'] };- getActiveProvider.mockResolvedValue(primary);- isProviderAvailable.mockReturnValue(false);- getProviderStatus.mockReturnValue({ message: 'usage-limit', reason: 'limit' });- getAllProviders.mockResolvedValue({ providers: [primary, fallback] });- getFallbackProvider.mockResolvedValue({ provider: fallback, source: 'system', model: 'm-fb' });-- const r = await resolveAgentProviderAndModel({ id: 'task-direct-2', metadata: {} });-- expect(r.ok).toBe(true);- expect(r.provider).toBe(fallback);- expect(r.orchestrationLane).toBeUndefined();- expect(getFallbackProvider).toHaveBeenCalled();- });-});--/**- * An `effort`-only role assignment pins a reasoning rung, not a vendor — there- * is no cross-vendor split for the fail-closed rule to protect, so it must not- * strand the run over a choice the user never made.- */-describe('resolveAgentProviderAndModel — effort-only orchestration roles', () => {- const effortOnly = {- id: 'task-effort',- metadata: {- orchestrationMode: 'orchestrated',- orchestrationProfile: { architect: { effort: 'high' } },- },- };-- it('keeps the generic fallback chain for a role that pins no provider or model', async () => {- const primary = { id: 'p1', type: 'cli' };- const fallback = { id: 'p2', type: 'cli', models: ['m-fb'] };- getActiveProvider.mockResolvedValue(primary);- isProviderAvailable.mockReturnValue(false);- getProviderStatus.mockReturnValue({ message: 'usage-limit', reason: 'limit' });- getAllProviders.mockResolvedValue({ providers: [primary, fallback] });- getFallbackProvider.mockResolvedValue({ provider: fallback, source: 'system', model: 'm-fb' });-- const r = await resolveAgentProviderAndModel(effortOnly);-- expect(r.ok).toBe(true);- expect(r.provider).toBe(fallback);- expect(getFallbackProvider).toHaveBeenCalled();- // Still accounted for — the run WAS dispatched as the architect role.- expect(r.orchestrationLane).toEqual({- role: 'architect',- requestedProvider: 'p1',- providerId: 'p2',- model: 'm-fb',- });- });-});--/**- * The same-role alternate is the ONE substitution a fail-closed lane accepts, so- * it has to clear every bar the primary would have: a real provider, currently- * available, with a file-writing harness, and — when the lane pinned a model — a- * model of its own to run. An alternate that fails any of these is not a lane,- * it is the same silent collapse one hop later.- */-describe('resolveAgentProviderAndModel — what a same-role alternate must satisfy', () => {- const orchestrated = (architect) => ({- id: 'task-alt',- metadata: { orchestrationMode: 'orchestrated', orchestrationProfile: { architect } },- });-- beforeEach(() => {- getProviderStatus.mockImplementation((id) => ({ message: `${id} down`, reason: 'down' }));- });-- it('refuses an api-type alternate instead of leaking into the transient harness guard', async () => {- // The harness guard below computes `permanent` from the lane's CLI primary,- // so an api alternate reaching it returns a retryable failure with no lane- // detail — the task would never block and would re-fail forever.- getProviderById.mockImplementation(async (id) => (- id === 'p-cheap'- ? { id, type: 'cli', defaultModel: 'm-cheap' }- : { id, type: 'api', defaultModel: 'm-api' }- ));- isProviderAvailable.mockImplementation((id) => id !== 'p-cheap');-- const r = await resolveAgentProviderAndModel(orchestrated({ provider: 'p-cheap', fallbackProvider: 'p-api' }));-- expect(r.ok).toBe(false);- expect(r.permanent).toBe(true);- expect(r.orchestrationLane.role).toBe('architect');- expect(r.orchestrationLane.reason).toContain('no file-writing harness');- });-- it('refuses when a model-pinned lane names an alternate with no fallbackModel', async () => {- getProviderById.mockImplementation(async (id) => ({ id, type: 'cli', defaultModel: `m-${id}` }));- isProviderAvailable.mockImplementation((id) => id !== 'p-cheap');-- const r = await resolveAgentProviderAndModel(orchestrated({- provider: 'p-cheap',- model: 'm-cheap',- fallbackProvider: 'p-cheap-2',- }));-- expect(r.ok).toBe(false);- expect(r.orchestrationLane.reason).toContain('no architect.fallbackModel');- expect(r.orchestrationLane.requestedModel).toBe('m-cheap');- });-- it('lets a provider-only lane take an alternate that supplies its own default', async () => {- const alternate = { id: 'p-cheap-2', type: 'cli', models: ['alt-default'], defaultModel: 'alt-default' };- getProviderById.mockImplementation(async (id) => (- id === 'p-cheap' ? { id, type: 'cli', defaultModel: 'm-cheap' } : alternate- ));- isProviderAvailable.mockImplementation((id) => id === 'p-cheap-2');- selectModelForTask.mockResolvedValue({ model: 'alt-default', tier: 'medium', reason: 'default' });-- const r = await resolveAgentProviderAndModel(orchestrated({ provider: 'p-cheap', fallbackProvider: 'p-cheap-2' }));-- expect(r.ok).toBe(true);- expect(r.provider).toBe(alternate);- expect(r.orchestrationLane.substitution.to).toBe('p-cheap-2');- });-- // The alternate enumerates a DIFFERENT model on purpose: a provider's `models`- // list is a convenience enumeration the pass-through CLIs never enforce, so- // letting it downgrade the user's configured fallbackModel to the alternate's- // own default would re-open the model-axis substitution on the one path that- // is allowed to swap providers at all.- it('carries a model-pinned lane onto its alternate using the configured fallbackModel', async () => {- const alternate = { id: 'p-cheap-2', type: 'cli', models: ['something-else'], defaultModel: 'alt-default' };- getProviderById.mockImplementation(async (id) => (- id === 'p-cheap' ? { id, type: 'cli', defaultModel: 'm-cheap' } : alternate- ));- isProviderAvailable.mockImplementation((id) => id === 'p-cheap-2');-- const r = await resolveAgentProviderAndModel(orchestrated({- provider: 'p-cheap',- model: 'm-cheap',- fallbackProvider: 'p-cheap-2',- fallbackModel: 'alt-m',- }));-- expect(r.ok).toBe(true);- // Never the alternate's own default — that is the substitution this closes.- expect(r.selectedModel).toBe('alt-m');- });-});--/**- * The run ledger's tier accounting keys off the RUN being orchestrated, not off- * the architect happening to be pinned — a profile that pins only the cheap- * implementer/reviewer lanes is a normal config, and its split is the one most- * worth showing.- */-describe('resolveAgentProviderAndModel — orchestration accounting coverage', () => {- it('accounts for an orchestrated run whose profile pins no architect', async () => {- const provider = { id: 'p-active', type: 'cli', models: ['m-default'] };- getActiveProvider.mockResolvedValue(provider);-- const r = await resolveAgentProviderAndModel({- id: 'task-no-architect',- metadata: {- orchestrationMode: 'orchestrated',- orchestrationProfile: { implementer: { provider: 'p-cheap' }, reviewer: { provider: 'p-cheap' } },- },- });-- expect(r.ok).toBe(true);- expect(r.orchestrationLane).toEqual({- role: 'architect',- requestedProvider: 'p-active',- providerId: 'p-active',- model: 'm-default',- });- });-});--/**- * Both ways a model-only lane's provider inheritance can fail. The- * missing-task-pin case is the sharp one: it used to continue on the active- * provider, which counts as a provider swap and drops the lane's model to that- * provider's default — a silent substitution with no block and nothing naming- * the role.- */-describe('resolveAgentProviderAndModel — a model-only lane with nothing to inherit', () => {- const modelOnly = {- id: 'task-model-only',- metadata: {- provider: 'p-gone',- orchestrationMode: 'orchestrated',- orchestrationProfile: { architect: { model: 'm-cheap' } },- },- };-- it('refuses when the task-level provider pin names a missing record', async () => {- getProviderById.mockResolvedValue(null);- getActiveProvider.mockResolvedValue({ id: 'p-active', type: 'cli', models: ['m-active'], defaultModel: 'm-active' });- selectModelForTask.mockResolvedValue({ model: 'm-cheap', tier: 'user-specified', reason: 'orchestration-role-architect' });-- const r = await resolveAgentProviderAndModel(modelOnly);-- expect(r.ok).toBe(false);- expect(r.permanent).toBe(true);- expect(r.orchestrationLane).toEqual({- role: 'architect',- requestedProvider: 'p-gone',- requestedModel: 'm-cheap',- reason: 'the provider pinned for this task is not configured on this install',- });- });-- it('still refuses when there is no active provider to inherit at all', async () => {- getActiveProvider.mockResolvedValue(null);-- const r = await resolveAgentProviderAndModel({- ...modelOnly,- metadata: { ...modelOnly.metadata, provider: undefined },- });-- expect(r.ok).toBe(false);- expect(r.orchestrationLane.requestedProvider).toBeNull();- expect(r.orchestrationLane.reason).toContain('no active AI provider');- });-});diff --git a/server/services/agentRunTracking.js b/server/services/agentRunTracking.jsindex 88a02325e6..e40e0143f3 100644--- a/server/services/agentRunTracking.js+++ b/server/services/agentRunTracking.js@@ -25,12 +25,8 @@ const RUNS_DIR = PATHS.runs;* @param {{ id: string, name: string, defaultModel?: string }} options.provider* @param {string} options.workspacePath* @param {string} [options.appName] - Defaults to 'portos'.- * @param {{ role: string, requestedProvider?: string, providerId: string, model?: string,- * substitution?: { role: string, from: string, to: string, reason?: string } }}- * [options.orchestrationLane] - The tier this run was dispatched as, when the- * task runs under an orchestration profile (#5993). Absent for `direct` runs.*/-export async function createAgentRun({ agentId, task, model, provider, workspacePath, appName, orchestrationLane = null }) {+export async function createAgentRun({ agentId, task, model, provider, workspacePath, appName }) {const runId = uuidv4();const runDir = join(RUNS_DIR, runId);@@ -53,7 +49,6 @@ export async function createAgentRun({ agentId, task, model, provider, workspace// Full prompt size (chars) for input-token estimation on completion —// `prompt` above is truncated for display.promptLength: (task.description || '').length,- ...(orchestrationLane ? { orchestrationLane } : {}),startTime: new Date().toISOString(),endTime: null,duration: null,@@ -88,12 +83,7 @@ export async function createAgentRun({ agentId, task, model, provider, workspacemodel: metadata.model,workspacePath,workspaceName: metadata.workspaceName,- promptChars: metadata.promptLength,- // Orchestration accounting (#5993): the role, and — when the lane took its- // configured same-role alternate — the provider it was configured for. Both- // omitted on a `direct` run so the event shape is unchanged there.- ...(orchestrationLane?.role ? { orchestrationRole: orchestrationLane.role } : {}),- ...(orchestrationLane?.substitution?.from ? { laneSubstitutedFrom: orchestrationLane.substitution.from } : {}),+ promptChars: metadata.promptLength}});diff --git a/server/services/brain.test.js b/server/services/brain.test.jsindex f3b550333e..d88aaeae81 100644--- a/server/services/brain.test.js+++ b/server/services/brain.test.js@@ -107,7 +107,10 @@ tryReadFile: vi.fn().mockResolvedValue(null),}),PATHS: { data: '/tmp/portos-test', cos: '/tmp/portos-test/cos', reports: '/tmp/portos-test/reports', scripts: '/tmp/portos-test/scripts', root: '/tmp/portos-test' },atomicWrite: vi.fn().mockResolvedValue(undefined),- ensureDirs: vi.fn().mockResolvedValue(undefined)+ ensureDirs: vi.fn().mockResolvedValue(undefined),+ // cosState's config reader; `ok: true, value: null` is "no config file yet",+ // which resolves to DEFAULT_CONFIG — what this suite's autonomy gate expects.+ readJSONFileStrict: vi.fn().mockResolvedValue({ ok: true, value: null }),}));// recoverStuckClassifications() resolves this instance's id to skip peer-origindiff --git a/server/services/cos.js b/server/services/cos.jsindex 77a94c8a55..59028bf592 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -46,7 +46,7 @@ import { pendingCosActionReservations } from './cosAdmissionReservations.js';import { useRunner } from './agentState.js';// Shared state management (extracted to avoid circular deps)-import { loadState, saveState, withStateLock, ensureDirectories, isImprovementEnabled, canQueueImprovementTasks, SCRIPTS_DIR, isDaemonRunning, setDaemonRunning } from './cosState.js';+import { loadState, saveState, withStateLock, loadConfig, saveConfig, withConfigLock, ensureDirectories, isImprovementEnabled, canQueueImprovementTasks, SCRIPTS_DIR, isDaemonRunning, setDaemonRunning } from './cosState.js';// Events and logging (canonical source: cosEvents.js)import { cosEvents, emitLog } from './cosEvents.js';@@ -231,22 +231,24 @@ export { getConfig } from './cosState.js';*/export async function updateConfig(updates) {let persistentMindWakeCadenceChanged = false;- const config = await withStateLock(async () => {- const state = await loadState();+ // Config has its own file and its own tail (#6182) — a settings write no+ // longer serializes behind the runtime-record writes in state.json.+ const config = await withConfigLock(async () => {+ const current = await loadConfig();// domainAutonomy is a partial-friendly map: a PATCH that names only one// domain must merge over the others rather than replace the whole object.// Capture the prior map BEFORE the spread clobbers it, then normalize the// merge so an unknown/invalid stored value resolves to the `execute` default.- const priorDomainAutonomy = state.config.domainAutonomy;+ const priorDomainAutonomy = current.domainAutonomy;// Same for domainBudgets — a PATCH naming one domain (or one cap on one// domain) must merge field-by-field over the rest, not replace the map.- const priorDomainBudgets = state.config.domainBudgets;- const priorPersistentMindCapabilities = state.config.persistentMindCapabilities;- const priorPersistentMindProfile = state.config.persistentMindProfile;- const priorPersistentMindPrompt = state.config.persistentMindPrompt;- state.config = { ...state.config, ...updates };+ const priorDomainBudgets = current.domainBudgets;+ const priorPersistentMindCapabilities = current.persistentMindCapabilities;+ const priorPersistentMindProfile = current.persistentMindProfile;+ const priorPersistentMindPrompt = current.persistentMindPrompt;+ const next = { ...current, ...updates };if (updates.domainAutonomy !== undefined) {- state.config.domainAutonomy = normalizeDomainAutonomy({+ next.domainAutonomy = normalizeDomainAutonomy({...priorDomainAutonomy,...updates.domainAutonomy});@@ -256,7 +258,7 @@ export async function updateConfig(updates) {for (const [id, caps] of Object.entries(updates.domainBudgets)) {mergedBudgets[id] = { ...(priorDomainBudgets?.[id] || {}), ...caps };}- state.config.domainBudgets = normalizeDomainBudgets(mergedBudgets);+ next.domainBudgets = normalizeDomainBudgets(mergedBudgets);}if (updates.persistentMindProfile !== undefined) {const nextPersistentMindProfile = mergePersistentMindProfile(@@ -265,22 +267,21 @@ export async function updateConfig(updates) {);persistentMindWakeCadenceChanged = nextPersistentMindProfile.wakeIntervalMinutes!== normalizePersistentMindProfile(priorPersistentMindProfile).wakeIntervalMinutes;- state.config.persistentMindProfile = nextPersistentMindProfile;+ next.persistentMindProfile = nextPersistentMindProfile;}if (updates.persistentMindCapabilities !== undefined) {- state.config.persistentMindCapabilities = mergePersistentMindCapabilities(+ next.persistentMindCapabilities = mergePersistentMindCapabilities(priorPersistentMindCapabilities,updates.persistentMindCapabilities,);}if (updates.persistentMindPrompt !== undefined) {- state.config.persistentMindPrompt = mergePersistentMindPrompt(+ next.persistentMindPrompt = mergePersistentMindPrompt(priorPersistentMindPrompt,updates.persistentMindPrompt,);}- await saveState(state);- return state.config;+ return saveConfig(next);});const improveKeys = ['improvementEnabled', 'selfImprovementEnabled', 'appImprovementEnabled'];const improvePatch = Object.fromEntries(diff --git a/server/services/cosState.js b/server/services/cosState.jsindex 009c12d3c9..deeb7c706a 100644--- a/server/services/cosState.js+++ b/server/services/cosState.js@@ -4,11 +4,11 @@* Shared state management for Chief of Staff services.*/-import { readFile, writeFile, readdir, rm } from 'fs/promises';+import { readFile, writeFile, readdir, rm, rename } from 'fs/promises';import { existsSync } from 'fs';-import { join, dirname } from 'path';+import { join, dirname, basename } from 'path';import { createFileWriteQueue } from '../lib/fileWriteQueue.js';-import { ensureDirs, safeJSONParse, readJSONFile, PATHS, atomicWrite } from '../lib/fileUtils.js';+import { ensureDirs, safeJSONParse, readJSONFileStrict, PATHS, atomicWrite } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';import { normalizeDomainAutonomy, getDomainMode } from '../lib/domainAutonomy.js';import { normalizeDomainBudgets } from '../lib/domainBudgets.js';@@ -19,6 +19,16 @@ import { createDefaultPersistentMindPrompt, normalizePersistentMindPrompt } fromimport { DEFAULT_ALWAYS_APPROVE_KINDS } from './taskLearning/safetyKind.js';export const STATE_FILE = join(PATHS.cos, 'state.json');+// Durable user configuration lives in its own file (#6182). state.json is+// rewritten on every agent status change and every batched output flush; config+// is written only when the user changes a setting. Splitting them keeps the hot+// path from re-serializing ~180 KB of settings it never touched, and keeps+// damage to the runtime file away from settings that are near-impossible to+// reconstruct. This retires the `config.last-known-good.json` sidecar, which+// mirrored the config slice out of state.json precisely because the two shared+// a file — config.json IS the low-frequency copy now, so a second one would+// only add a way for the two to disagree. Migration 339 removes the sidecar.+export const CONFIG_FILE = join(PATHS.cos, 'config.json');export const AGENTS_DIR = join(PATHS.cos, 'agents');export const REPORTS_DIR = PATHS.reports;export const SCRIPTS_DIR = PATHS.scripts;@@ -35,6 +45,11 @@ export const ROOT_DIR = PATHS.root;// poison subsequent waiters (a strict improvement over the prior mutex).export const withStateLock = createFileWriteQueue();+// Config gets its OWN tail, so a settings read or write never queues behind the+// runtime-record writes that dominate state.json (#6182). Same+// `(fn) => Promise` contract as `withStateLock`.+export const withConfigLock = createFileWriteQueue();+export const DEFAULT_CONFIG = {userTasksFile: 'data/TASKS.md',cosTasksFile: 'data/COS-TASKS.md',@@ -113,7 +128,6 @@ export const DEFAULT_STATE = {paused: false,pausedAt: null,pauseReason: null,- config: DEFAULT_CONFIG,stats: {tasksCompleted: 0,totalRuntime: 0,@@ -142,8 +156,8 @@ export async function ensureDirectories() {* silently reset the user's config to DEFAULT_CONFIG. `JSON.parse` rejects a* genuine `{…}{…}` concatenation on its own, so the guess protected nothing.*/-function parseStateFile(content) {- const parsed = safeJSONParse(content, null, { allowArray: false, logError: true, context: 'CoS state' });+function parseStateFile(content, context = 'CoS state') {+ const parsed = safeJSONParse(content, null, { allowArray: false, logError: true, context });return isPlainObject(parsed) ? parsed : null;}@@ -190,71 +204,114 @@ function mergeStoredConfig(storedConfig) {};}-// Mirror of the config slice as it was last persisted. state.json bundles the-// user's durable settings with the agent records and Mind runtime state, so it-// is rewritten constantly while the settings inside it are near-impossible to-// reconstruct. `atomicWrite` already rules out a torn write; what remains is-// disk-level damage or an out-of-tree editor — and when that lands, the-// recovery below merges this file back in rather than dropping the user to-// DEFAULT_CONFIG. Settings the user never touched are already the defaults, so-// a missing sidecar loses nothing that wasn't already lost.-export const CONFIG_BACKUP_FILE = join(PATHS.cos, 'config.last-known-good.json');--// Serialized copy of what the sidecar already holds, so the common saveState-// (an agent status tick, config untouched) stays a single file write.-let lastConfigBackupJson = null;--async function persistConfigBackup(config) {- if (!isPlainObject(config)) return;- // Serialize once and hand `atomicWrite` the string it would otherwise- // produce itself, so the changed-config save doesn't stringify twice.- const json = JSON.stringify(config, null, 2);- if (json === lastConfigBackupJson) return;- await atomicWrite(CONFIG_BACKUP_FILE, json)- .then(() => { lastConfigBackupJson = json; })- .catch((err) => console.error(`❌ Failed to back up CoS config: ${err.message}`));+/**+ * Quarantine an unreadable JSON file next to itself and prune all but the three+ * most recent quarantined copies, so the lost bytes stay inspectable.+ *+ * `remove` moves the file instead of copying it, so it leaves the active path.+ * config.json needs that: it is written only when the user changes a setting,+ * so a copy would leave the corrupt original to be re-read, re-warned about,+ * and re-quarantined on every boot. state.json deliberately keeps the copy —+ * the next runtime write overwrites it within seconds, and+ * `readStateForSafetyCheck()` reports an unreadable file as `trusted: false`+ * ("could not establish what is there"); removing it would turn that into+ * "known empty" and let the update gate restart out from under a live agent.+ */+async function quarantineCorruptFile(filePath, content, label, { remove = false } = {}) {+ const backupPath = `${filePath}.corrupted.${Date.now()}`;+ const moved = remove && await rename(filePath, backupPath).then(() => true).catch(() => false);+ if (!moved) await writeFile(backupPath, content).catch(() => {});+ console.log(`📝 Backed up corrupted ${label} to ${backupPath}`);+ const dir = dirname(filePath);+ const prefix = `${basename(filePath)}.corrupted.`;+ const files = await readdir(dir).catch(() => []);+ const corrupted = files.filter(f => f.startsWith(prefix)).sort().reverse();+ for (const old of corrupted.slice(3)) {+ await rm(join(dir, old)).catch(() => {});+ }+ if (corrupted.length > 3) {+ console.log(`🗑️ Cleaned up ${corrupted.length - 3} old corrupted ${label} backups`);+ }}-// `readJSONFile` rather than a hand-rolled read: it carries the Windows-// swap-window retry, so a read that lands between `atomicWrite`'s temp write-// and its rename doesn't report "no sidecar" and drop the recovery below to-// DEFAULT_CONFIG — the exact loss the sidecar exists to prevent.-const readConfigBackup = () =>- readJSONFile(CONFIG_BACKUP_FILE, null, { allowArray: false, logError: true });-/**- * Fall back to default state after an unreadable state.json, keeping the- * user's settings when the sidecar above can supply them. Backs the bad bytes- * up first (retaining the 3 most recent) so the loss is inspectable.+ * Fall back to default runtime state after an unreadable state.json, backing+ * the bad bytes up first. Config is unaffected — it lives in its own file, so+ * there is nothing to recover here that state.json could have taken with it.*/async function recoverFromUnreadableState(content) {console.log(`⚠️ Corrupted or empty state file at ${STATE_FILE}, returning default state`);- const backupPath = `${STATE_FILE}.corrupted.${Date.now()}`;- await writeFile(backupPath, content).catch(() => {});- console.log(`📝 Backed up corrupted state to ${backupPath}`);- // Cleanup old corrupted backups (keep only 3 most recent)- const cosDir = dirname(STATE_FILE);- const files = await readdir(cosDir).catch(() => []);- const corrupted = files- .filter(f => f.startsWith('state.json.corrupted.'))- .sort()- .reverse();- for (const old of corrupted.slice(3)) {- await rm(join(cosDir, old)).catch(() => {});- }- if (corrupted.length > 3) {- console.log(`🗑️ Cleaned up ${corrupted.length - 3} old corrupted state backups`);+ await quarantineCorruptFile(STATE_FILE, content, 'CoS state');+ return structuredClone(DEFAULT_STATE);+}++// In-memory config cache. Every mutation goes through `withConfigLock` ++// `saveConfig`, so the cache stays consistent.+let configCache = null;++/**+ * Read the raw persisted config object, and say where it came from.+ *+ * Prefers `data/cos/config.json`. `readJSONFileStrict` carries the Windows+ * swap-window retry, so a read landing between `atomicWrite`'s temp write and+ * its rename reports the real file rather than "absent" — reporting absent here+ * would fall through to the legacy path and, on an already-split install, hand+ * back DEFAULT_CONFIG. `ok: false` is present-but-unreadable, which is the only+ * case that quarantines.+ *+ * Falls back to the `config` slice a legacy `state.json` still carries (a peer+ * that has not upgraded, a restored pre-split backup) so an un-migrated install+ * never boots on bare defaults.+ */+async function readPersistedConfig() {+ const { ok, value } = await readJSONFileStrict(CONFIG_FILE, null, { allowArray: false, logError: true });+ if (ok && isPlainObject(value)) return { config: value, fromConfigFile: true };+ if (!ok) {+ console.log(`⚠️ Corrupted or empty config file at ${CONFIG_FILE}, falling back to legacy/default config`);+ const content = await readFile(CONFIG_FILE, 'utf-8').catch(() => '');+ await quarantineCorruptFile(CONFIG_FILE, content, 'CoS config', { remove: true });}+ // Back-compat read. Deliberately does NOT quarantine or rewrite state.json —+ // loadState() owns that file's recovery.+ if (!existsSync(STATE_FILE)) return { config: null, fromConfigFile: false };+ const stateContent = await readFile(STATE_FILE, 'utf-8');+ const state = parseStateFile(stateContent, 'CoS state (legacy config)');+ const legacy = state?.config;+ return { config: isPlainObject(legacy) ? legacy : null, fromConfigFile: false };+}- const recovered = structuredClone(DEFAULT_STATE);- const savedConfig = await readConfigBackup();- if (savedConfig) {- // Already normalized when it was mirrored; re-merging costs nothing and- // covers a sidecar that was hand-edited or written by an older version.- recovered.config = mergeStoredConfig(savedConfig);- console.log(`♻️ Restored CoS config from ${CONFIG_BACKUP_FILE}`);+/**+ * Load the durable user configuration.+ */+export async function loadConfig() {+ if (configCache) return configCache;+ await ensureDirectories();+ const { config, fromConfigFile } = await readPersistedConfig();+ configCache = mergeStoredConfig(config);+ // Recovering settings out of a legacy state.json is a READ; nothing has+ // written them to their own file yet. `saveState` strips `config` from+ // state.json on the very next runtime write, so leaving the recovery in+ // memory would destroy those settings on the next restart. Complete the split+ // here — migration 339's job, done lazily for the installs it cannot reach (a+ // restored pre-split backup on a machine that already recorded it as applied).+ if (config && !fromConfigFile) {+ console.log(`📦 Recovered CoS config from a legacy state.json — writing ${CONFIG_FILE}`);+ await atomicWrite(CONFIG_FILE, configCache);}- return recovered;+ return configCache;+}++/**+ * Persist the durable user configuration to its own file. Keeps any live+ * `loadState()` result pointing at the same object so a state reader taken+ * before the write does not go stale.+ */+export async function saveConfig(config) {+ await ensureDirectories();+ configCache = config;+ if (stateCache) stateCache.config = config;+ await atomicWrite(CONFIG_FILE, config);+ return config;}// In-memory state cache — avoids re-reading state.json from disk on every call.@@ -279,11 +336,11 @@ export function canQueueImprovementTasks(state) {}/**- * Get current configuration+ * Get current configuration. Reads the config file's own cache — it no longer+ * queues behind, or deserializes, the runtime records in state.json.*/export async function getConfig() {- const state = await loadState();- return state.config;+ return loadConfig();}export async function loadState() {@@ -291,8 +348,11 @@ export async function loadState() {await ensureDirectories();+ // Config is its own file now, so it survives every state.json failure path.+ const config = await loadConfig();+if (!existsSync(STATE_FILE)) {- stateCache = structuredClone(DEFAULT_STATE);+ stateCache = Object.assign(structuredClone(DEFAULT_STATE), { config });return stateCache;}@@ -300,14 +360,17 @@ export async function loadState() {const state = parseStateFile(content);if (!state) {- stateCache = await recoverFromUnreadableState(content);+ stateCache = Object.assign(await recoverFromUnreadableState(content), { config });return stateCache;}stateCache = {...DEFAULT_STATE,...state,- config: mergeStoredConfig(state.config),+ // Always the config file's copy — a legacy `config` slice still sitting in+ // state.json was already folded in by `readPersistedConfig()`, and must+ // never shadow the (newer) config file on an install carrying both.+ config,stats: { ...DEFAULT_STATE.stats, ...state.stats },persistentMind: normalizePersistentMindState(state.persistentMind),agents: state.agents ?? {}@@ -349,11 +412,25 @@ export async function readAgentsStateForSafetyCheck() {};}+/**+ * Persist the runtime records. `config` is NOT this function's to write — it is+ * owned by `saveConfig()` / `updateConfig()` and lives in its own file.+ *+ * The cached state is re-anchored on the authoritative config object first, so+ * a caller that passed a state carrying a stale config (a shallow copy taken+ * before a concurrent `updateConfig`) or no config at all (a hand-built object)+ * can neither publish that copy nor leave `stateCache.config` undefined for the+ * next `state.config.…` reader. A caller wanting to CHANGE a setting must call+ * `updateConfig()`; `state.config` is a read-only view.+ */export async function saveState(state) {await ensureDirectories();+ state.config = await loadConfig();stateCache = state;- await atomicWrite(STATE_FILE, state);- await persistConfigBackup(state.config);+ // Config lives in its own file; never re-serialize it onto the hot path.+ const persisted = { ...state };+ delete persisted.config;+ await atomicWrite(STATE_FILE, persisted);}// Resolve a single domain's autonomy mode (off | dry-run | execute) withoutdiff --git a/server/services/cosState.test.js b/server/services/cosState.test.jsindex 5fc8bc6998..b9599cb57f 100644--- a/server/services/cosState.test.js+++ b/server/services/cosState.test.js@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterAll, vi } from 'vitest';-import { mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs';+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'fs';import { join } from 'path';import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';@@ -9,17 +9,21 @@ vi.mock('../lib/fileUtils.js', async (importOriginal) => makeProxy(await importOconst COS_DIR = join(tempRoot, 'cos');const STATE_PATH = join(COS_DIR, 'state.json');+const CONFIG_PATH = join(COS_DIR, 'config.json');afterAll(cleanup);-// The module caches state in memory and remembers what it last mirrored to the-// config sidecar, so every case needs a fresh module instance.+// The module caches state and config in memory, so every case needs a fresh+// module instance reading whatever the case just wrote to disk.const freshModule = async () => {vi.resetModules();return import('./cosState.js');};const writeState = (state) => writeFileSync(STATE_PATH, JSON.stringify(state, null, 2));+const writeConfig = (config) => writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2));+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));+const quarantined = (prefix) => readdirSync(COS_DIR).filter(f => f.startsWith(`${prefix}.corrupted.`));beforeEach(() => {rmSync(COS_DIR, { recursive: true, force: true });@@ -32,12 +36,12 @@ describe('cosState persistence', () => {// `{value}{ — project|global}`, a diff carrying JSX), and the fallback reset// every user setting to DEFAULT_CONFIG.it('keeps user config when a stored string contains "}{"', async () => {+ writeConfig({+ maxConcurrentAgents: 20,+ maxConcurrentAgentsPerProject: 12,+ });writeState({running: false,- config: {- maxConcurrentAgents: 20,- maxConcurrentAgentsPerProject: 12,- },agents: {'agent-1': {id: 'agent-1',@@ -54,7 +58,21 @@ describe('cosState persistence', () => {expect(state.config.maxConcurrentAgentsPerProject).toBe(12);expect(state.agents['agent-1']).toBeDefined();// A valid file is never treated as corrupt, so nothing is quarantined.- expect(readdirSync(COS_DIR).filter(f => f.startsWith('state.json.corrupted.'))).toHaveLength(0);+ expect(quarantined('state.json')).toHaveLength(0);+ });++ it('keeps user config when config.json itself contains "}{"', async () => {+ writeConfig({+ maxConcurrentAgents: 20,+ persistentMindPrompt: { instructions: 'quote {value}{ — project|global} verbatim' },+ });++ const { getConfig } = await freshModule();+ const config = await getConfig();++ expect(config.maxConcurrentAgents).toBe(20);+ expect(config.persistentMindPrompt.instructions).toBe('quote {value}{ — project|global} verbatim');+ expect(quarantined('config.json')).toHaveLength(0);});it('reports a "}{"-carrying state file as trusted to the update safety gate', async () => {@@ -70,29 +88,151 @@ describe('cosState persistence', () => {});});- // Full round trip: save mirrors the config slice, and a state.json that is- // genuinely unreadable afterwards recovers those settings instead of- // dropping the user to DEFAULT_CONFIG.- it('recovers saved config when state.json becomes unreadable', async () => {+ // The split's version of what the sidecar used to buy: config lives in its+ // own file, so an unreadable state.json cannot take the settings with it.+ it('keeps config when state.json becomes unreadable', async () => {const saved = await freshModule();- const state = await saved.loadState();- state.config.maxConcurrentAgents = 20;- state.config.maxConcurrentAgentsPerProject = 12;- await saved.saveState(state);- expect(JSON.parse(readFileSync(saved.CONFIG_BACKUP_FILE, 'utf-8')).maxConcurrentAgents).toBe(20);+ await saved.saveConfig({+ ...(await saved.loadConfig()),+ maxConcurrentAgents: 20,+ maxConcurrentAgentsPerProject: 12,+ });// A double-append: two complete objects concatenated. JSON.parse rejects it.- writeFileSync(STATE_PATH, `${JSON.stringify({ config: {} })}${JSON.stringify({ config: {} })}`);+ writeFileSync(STATE_PATH, `${JSON.stringify({ running: true })}${JSON.stringify({ running: true })}`);const { loadState, DEFAULT_CONFIG } = await freshModule();const recovered = await loadState();expect(recovered.config.maxConcurrentAgents).toBe(20);expect(recovered.config.maxConcurrentAgentsPerProject).toBe(12);- // Settings the sidecar doesn't carry still fall back to the shipped default.+ // Settings the user never changed still come from the shipped defaults.expect(recovered.config.maxTotalProcesses).toBe(DEFAULT_CONFIG.maxTotalProcesses);// Agent records are genuinely lost — but the bad bytes stay inspectable.expect(recovered.agents).toEqual({});- expect(readdirSync(COS_DIR).filter(f => f.startsWith('state.json.corrupted.'))).toHaveLength(1);+ expect(quarantined('state.json')).toHaveLength(1);+ });+});++describe('CoS config lives in its own file', () => {+ it('never writes config back into state.json', async () => {+ writeConfig({ maxConcurrentAgents: 9 });+ writeState({ running: true, agents: { a1: { status: 'running' } } });+ const { loadState, saveState, getConfig } = await freshModule();++ const state = await loadState();+ expect(state.config.maxConcurrentAgents).toBe(9);+ // Absent keys still fall back to the shipped defaults.+ expect(state.config.maxConcurrentAgentsPerProject).toBe(2);+ await expect(getConfig()).resolves.toBe(state.config);++ state.agents.a2 = { status: 'running' };+ await saveState(state);++ const persisted = readJson(STATE_PATH);+ expect(persisted.config).toBeUndefined();+ expect(Object.keys(persisted.agents)).toEqual(['a1', 'a2']);+ // config.json is untouched by a runtime-record write.+ expect(readJson(CONFIG_PATH)).toEqual({ maxConcurrentAgents: 9 });+ });++ it('saveConfig writes only config.json and refreshes a live state read', async () => {+ writeState({ running: false, agents: {} });+ const { loadState, loadConfig, saveConfig } = await freshModule();++ const state = await loadState();+ await saveConfig({ ...(await loadConfig()), maxConcurrentAgents: 5 });++ expect(readJson(CONFIG_PATH).maxConcurrentAgents).toBe(5);+ // The already-loaded state object must not go stale behind the write.+ expect(state.config.maxConcurrentAgents).toBe(5);+ expect(readJson(STATE_PATH).config).toBeUndefined();+ });++ // Back-compat: an un-upgraded peer, or a restored pre-split backup, still+ // carries `config` inside state.json.+ it('falls back to a legacy config slice still sitting in state.json', async () => {+ writeState({ running: false, config: { maxConcurrentAgents: 11, alwaysOn: false }, agents: {} });+ const { getConfig } = await freshModule();++ const config = await getConfig();+ expect(config.maxConcurrentAgents).toBe(11);+ expect(config.alwaysOn).toBe(false);+ });++ it('prefers config.json over a stale legacy slice when both exist', async () => {+ writeConfig({ maxConcurrentAgents: 4 });+ writeState({ running: false, config: { maxConcurrentAgents: 99 }, agents: {} });+ const { loadState } = await freshModule();++ expect((await loadState()).config.maxConcurrentAgents).toBe(4);+ });++ // A recovered legacy slice exists only in memory; the very next saveState+ // strips `config` out of state.json, so failing to complete the split here+ // destroys the user's settings on the following restart.+ it('completes the split when it recovers config from a legacy state.json', async () => {+ writeState({ running: false, config: { maxConcurrentAgents: 11 }, agents: {} });+ const { loadState, saveState } = await freshModule();++ const state = await loadState();+ expect(readJson(CONFIG_PATH).maxConcurrentAgents).toBe(11);++ await saveState(state);+ expect(readJson(STATE_PATH).config).toBeUndefined();+ // Survives the restart that the strip above would otherwise have broken.+ const { getConfig } = await freshModule();+ expect((await getConfig()).maxConcurrentAgents).toBe(11);+ });++ // Config is owned by config.json. A state snapshot taken before a concurrent+ // updateConfig carries a stale copy; publishing it from saveState would+ // silently roll the user's settings back.+ it('never lets a stale state.config clobber config.json', async () => {+ writeConfig({ maxConcurrentAgents: 3 });+ writeState({ running: false, agents: {} });+ const { loadState, loadConfig, saveConfig, saveState } = await freshModule();++ const snapshot = { ...(await loadState()) };+ await saveConfig({ ...(await loadConfig()), maxConcurrentAgents: 8 });++ await saveState(snapshot);++ expect(readJson(CONFIG_PATH).maxConcurrentAgents).toBe(8);+ expect(readJson(STATE_PATH).config).toBeUndefined();+ // The re-anchored snapshot reports the live config, not its stale copy.+ expect(snapshot.config.maxConcurrentAgents).toBe(8);+ });++ // saveState() caches whatever it is handed; a state built without `config`+ // would otherwise leave every later `state.config.…` reader on undefined.+ it('re-anchors config when handed a state that carries none', async () => {+ writeConfig({ maxConcurrentAgents: 3 });+ const { saveState, loadState } = await freshModule();++ await saveState({ running: true, agents: {} });++ expect((await loadState()).config.maxConcurrentAgents).toBe(3);+ });+});++describe('config recovery', () => {+ it('quarantines a truncated config.json and moves it out of the active path', async () => {+ writeFileSync(CONFIG_PATH, '{"maxConcurrentAgents": 3');+ const { getConfig, DEFAULT_CONFIG } = await freshModule();++ expect((await getConfig()).maxConcurrentAgents).toBe(DEFAULT_CONFIG.maxConcurrentAgents);+ expect(quarantined('config.json')).toHaveLength(1);+ // Moved, not copied — config.json is written only when the user changes a+ // setting, so a copy left in place would be re-quarantined on every boot.+ expect(existsSync(CONFIG_PATH)).toBe(false);+ });++ it('quarantines a config.json that parses as a non-object', async () => {+ writeFileSync(CONFIG_PATH, '["not", "a", "config"]');+ const { getConfig, DEFAULT_CONFIG } = await freshModule();++ expect((await getConfig()).maxConcurrentAgents).toBe(DEFAULT_CONFIG.maxConcurrentAgents);+ expect(quarantined('config.json')).toHaveLength(1);});});diff --git a/server/services/cosTaskStore.js b/server/services/cosTaskStore.jsindex 6c9ee68a2a..666492d61b 100644--- a/server/services/cosTaskStore.js+++ b/server/services/cosTaskStore.js@@ -751,7 +751,7 @@ async function writeTaskUpdate(taskId, updates, taskType, { now, suppressDequeue// agent record then read its own pause as spent and spawned a SECOND agent on a// fresh task. The clear belongs at the transition, not at one caller.if (updates.status && updates.status !== 'blocked' && tasks[taskIndex].status === 'blocked') {- for (const key of ['blocker', 'blockedReason', 'blockedCategory', 'blockedAt', 'orchestrationLane', 'failureCount', 'lastErrorCategory', 'lastFailureAt', ...PAUSE_METADATA_KEYS]) {+ for (const key of ['blocker', 'blockedReason', 'blockedCategory', 'blockedAt', 'failureCount', 'lastErrorCategory', 'lastFailureAt', ...PAUSE_METADATA_KEYS]) {delete updatedMetadata[key];}}diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 0ee2166dda..10b7e9324a 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -118,7 +118,6 @@ import {} from './cosTaskStore.js';import { AGENT_PAUSED_CATEGORY, PAUSE_METADATA_KEYS, registerPauseReleaseAdapter, __resetPauseReleaseAdapter } from '../lib/taskPauseHold.js';import { MAX_TOTAL_SPAWNS } from '../lib/cosValidation.js';-import { ORCHESTRATION_LANE_BLOCKED_CATEGORY } from '../lib/taskBlockCategories.js';const USER_FILE = join('/root', 'TASKS.md');const COS_FILE = join('/root', 'COS-TASKS.md');@@ -988,23 +987,6 @@ describe('cosTaskStore.updateTask', () => {expect(reopened.metadata.blockedCategory).toBeUndefined();});- // The structured detail of a refused orchestration lane (#5993) goes with it.- // The task record federates, so a stale lane naming a provider the task is no- // longer blocked on would travel to every peer alongside a running task.- it('clears the orchestration lane detail when the block ends', async () => {- await addTask({ description: 'lane', id: 'task-lane' }, 'user');- await updateTask('task-lane', {- status: 'blocked',- metadata: {- blockedReason: 'Orchestrated architect lane stopped',- blockedCategory: 'orchestration-lane-unavailable',- orchestrationLane: { role: 'architect', requestedProvider: 'p-cheap', requestedModel: null, reason: 'not authenticated' },- },- }, 'user');- const reopened = await updateTask('task-lane', { status: 'pending' }, 'user');- expect(reopened.metadata.orchestrationLane).toBeUndefined();- });-// The pause hold goes with it, whatever un-blocked the task. `resumeAgent` is only// ONE of the paths back to pending — a dedupe revive, an autopilot re-dispatch, a// cooldown expiry and a human unblocking it all land here — and every one of them@@ -1195,25 +1177,6 @@ describe('cosTaskStore.updateTask', () => {expect(blocked.metadata.resumeWorktreePath).toBe('/w/agent-x');});- // Same CONFIG-pause shape (#5993): the user authenticates the lane's provider- // and revives the task. Stripping the pointer here would restart the revived- // task clean and orphan its predecessor's worktree — and before this block- // category existed, that same condition left the task pending with its pointer- // intact, so losing it would be a NEW way to abandon work.- it('keeps the resume pointer through a refused orchestration lane', async () => {- await addTask({ description: 'lane', id: 'task-lane-ptr' }, 'user');- await updateTask('task-lane-ptr', {- metadata: { existingBranch: 'cos/b', resumedFromAgentId: 'agent-x', resumeWorktreePath: '/w/agent-x' }- }, 'user');- const blocked = await updateTask('task-lane-ptr', {- status: 'blocked',- metadata: { blockedCategory: ORCHESTRATION_LANE_BLOCKED_CATEGORY }- }, 'user');- expect(blocked.metadata.existingBranch).toBe('cos/b');- expect(blocked.metadata.resumeWorktreePath).toBe('/w/agent-x');- expect(blocked.metadata.resumedFromAgentId).toBe('agent-x');- });-// An `existingBranch` with no `resumedFromAgentId` beside it was never written// by the resume mechanism — it is the task's OWN configuration. A merge// follow-up is the producer: it exists to land the PR on that branch. Stripping@@ -1750,24 +1713,6 @@ describe('cosTaskStore — stale failure-artifact reaper (#2619)', () => {expect(after.tasks.find(t => t.id === 'task-stop').status).toBe('blocked');});- // A fail-closed orchestration lane (#5993) stops the run ON PURPOSE and waits- // on a user config fix. Retiring it to `completed` after 14 days would convert- // that deliberate loud stop into the silent success the whole feature exists- // to prevent — so it is exempt like the other user-decision blocks.- it('leaves a refused orchestration lane for the user however long it sits', async () => {- await addTask({ description: 'lane blocked', id: 'task-lane-old', priority: 'LOW' }, 'user', { now: NOW });- await updateTask('task-lane-old', {- status: 'blocked',- metadata: { blockedCategory: ORCHESTRATION_LANE_BLOCKED_CATEGORY, blockedAt: daysAgo(90) },- }, 'user', { now: NOW });- const res = await sweepResolvedFailureTasks({ now: NOW });- expect(res.reaped).toBe(0);- const after = await getUserTasks();- const task = after.tasks.find(t => t.id === 'task-lane-old');- expect(task.status).toBe('blocked');- expect(task.metadata.resolution).toBeUndefined();- });-it('flips an investigation whose originating task has completed', async () => {await addTask({ description: 'origin work', id: 'task-origin', priority: 'HIGH' }, 'user', { now: NOW });await updateTask('task-origin', { status: 'completed' }, 'user', { now: NOW });diff --git a/server/services/promptSections/orchestrationDoctrine.js b/server/services/promptSections/orchestrationDoctrine.jsindex 1424832a85..ecb4b163ca 100644--- a/server/services/promptSections/orchestrationDoctrine.js+++ b/server/services/promptSections/orchestrationDoctrine.js@@ -31,18 +31,7 @@ function roleLine(task, role) {assignment?.effort ? `default reasoning \`${assignment.effort}\`` : null,].filter(Boolean);const target = pins.length ? pins.join(', ') : 'this run’s own provider and model';- // The lane's ONE permitted substitution (#5993). Named here because the- // architect otherwise has no way to know a lane is fail-closed, and would plan- // around a fallback that does not exist.- // Gated on a provider/model pin — the SAME condition the resolver uses. An- // effort-only role stays on the ordinary fallback chain, so telling the- // architect its run would stop would be false (and reads as nonsense besides:- // the "target" there is a reasoning rung, not a provider).- const failClosed = Boolean(assignment?.provider || assignment?.model);- const alternate = failClosed && assignment.fallbackProvider- ? ` If it is unavailable, the lane may use \`${assignment.fallbackProvider}\`${assignment.fallbackModel ? ` with model \`${assignment.fallbackModel}\`` : ''} — and nothing else.`- : (failClosed ? ' If it is unavailable, the run STOPS — no other provider is substituted for this lane.' : '');- return `- **${role}** — ${ROLE_DUTIES[role]}. Runs on ${target}.${alternate}`;+ return `- **${role}** — ${ROLE_DUTIES[role]}. Runs on ${target}.`;}/**diff --git a/server/services/promptSections/orchestrationDoctrine.test.js b/server/services/promptSections/orchestrationDoctrine.test.jsindex 9ece340682..5fdbab2462 100644--- a/server/services/promptSections/orchestrationDoctrine.test.js+++ b/server/services/promptSections/orchestrationDoctrine.test.js@@ -46,54 +46,3 @@ describe('buildOrchestrationDoctrineSection', () => {expect(section).toMatch(/never rounded/);});});--describe('fail-closed lane doctrine (#5993)', () => {- const orchestrated = (profile) => ({- metadata: { orchestrationMode: 'orchestrated', orchestrationProfile: profile },- });-- it('tells the architect a pinned lane has no substitute', () => {- const section = buildOrchestrationDoctrineSection(orchestrated({ implementer: { provider: 'p-cheap' } }));- expect(section).toContain('the run STOPS — no other provider is substituted for this lane');- });-- it('names the one alternate a lane may use', () => {- const section = buildOrchestrationDoctrineSection(orchestrated({- implementer: { provider: 'p-cheap', fallbackProvider: 'p-cheap-2', fallbackModel: 'm-cheap-2' },- }));- expect(section).toContain('the lane may use `p-cheap-2` with model `m-cheap-2` — and nothing else');- expect(section.split('\n').find(l => l.startsWith('- **implementer**'))).not.toContain('STOPS');- });-- it('says nothing about substitution for a role that pins nothing', () => {- const section = buildOrchestrationDoctrineSection(orchestrated({ architect: { provider: 'p1' } }));- expect(section).toContain('- **reviewer** —');- expect(section.split('\n').find(l => l.startsWith('- **reviewer**'))).not.toContain('STOPS');- });-});--describe('the doctrine states fail-closed only for the lanes that are', () => {- const orchestrated = (profile) => ({- metadata: { orchestrationMode: 'orchestrated', orchestrationProfile: profile },- });- const roleLineFor = (section, role) => section.split('\n').find(l => l.startsWith(`- **${role}**`));-- it('says nothing about substitution for an effort-only role', () => {- // That role stays on the ordinary fallback chain, so promising the architect- // the run would stop is false — and reads as nonsense, since its only "pin"- // is a reasoning rung rather than a provider.- const section = buildOrchestrationDoctrineSection(orchestrated({- implementer: { effort: 'high' },- architect: { provider: 'p1' },- }));- expect(roleLineFor(section, 'implementer')).not.toContain('STOPS');- expect(roleLineFor(section, 'architect')).toContain('STOPS');- });-- it('names the alternate a model-only lane may use', () => {- const section = buildOrchestrationDoctrineSection(orchestrated({- implementer: { model: 'm-cheap', fallbackProvider: 'p-cheap-2', fallbackModel: 'm-cheap-2' },- }));- expect(roleLineFor(section, 'implementer')).toContain('the lane may use `p-cheap-2` with model `m-cheap-2` — and nothing else');- });-});