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: point the four in-closure completeAgent callers at the module that declares it, not the cosAgents barrel (#3450)
[._.]/ Adam Eivy821a7c2460e7
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 8c9a414efb..56ca893fb5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -69,3 +69,5 @@- **The 1-second async-assertion timeout that flaked the QuotaBurn retry-budget test is now raised suite-wide, not per call site.** `QuotaBurn.test.jsx`'s "stops claiming it is saving once the retry budget is spent" failed roughly 1 run in 3 in isolation: it waits on a 500ms debounced save *plus* its retry — two sequential windows — against testing-library's uncustomized 1000ms `waitFor` default, which parallel-worker CPU contention pushes past. The same diagnosis had already been made once and fixed in one place (`settledInput.js`'s local `{ timeout: 3000 }`), leaving every other debounce-sensitive test exposed and the diagnosis waiting to be rediscovered. `client/src/test/setup.js` now calls `configure({ asyncUtilTimeout: 3000 })` once, carrying the rationale, and the five now-redundant local overrides in `settledInput.js`, `MediaCollections.test.jsx` and `ReferenceAnalysis.test.jsx` are gone. The cost is that a genuinely hung assertion takes 3s instead of 1s to fail; the full client suite still runs in ~26s.- **The CoS prompt-builder suite let the contributor's own global `CLAUDE.md` decide its results, so its suppression checks had never actually run on CI.** `buildAgentPrompt` reads `~/.claude/CLAUDE.md` off the real filesystem and splices it verbatim into the prompt, and `agentPromptBuilder.test.js` then asserts the prompt does *not* contain things like `gh pr merge`. That made every negative assertion in the file unsound in both directions: it false-failed on a machine whose personal global instructions happened to mention the string, and — worse — false-passed on a machine with no such file at all, which is exactly what CI is, so the suppression those assertions exist to prove was never exercised there. `homedir()` is now stubbed to a path that cannot exist, making the global section deterministically empty, and a new fixture-backed test closes the gap from the other side: it points the stub at a throwaway home whose global `CLAUDE.md` deliberately *does* contain the suppressed strings, asserts the fixture really is spliced in verbatim, and then asserts every section the builder itself authored still omits them on the reasoning-only path. Verified by breaking the suppression and watching the new test fail (#3475).++- **`completeAgent` had three addresses, and the four callers that most needed one address were using the wrong one.** Continuing #3450's sequencing: `agentManagement.js`, `agentLifecycle.js`, `agentFinalization.js` and `agentCliSpawning.js` all reached the completion transition through the `cosAgents.js` barrel. These four are the callers the "move the caller above the facade" recipe cannot reach — the first two DEFINE transitions `agentOrchestrator.js` re-exports, so importing the facade from either is the cycle itself, and the other two are leaves those two must call to spawn and to finalize. So the rule they follow is the other half of the same property: above the facade's closure a transition comes from the facade, inside it from the module that DECLARES it (`cosAgentLifecycle.js`), and never from a barrel. `cleanupOrphanedAgents`'s `await import('./cos.js')` went with it — it was pulling `completeAgent` and `getAgents` through the `cos.js` re-export block while the module was already a static import three lines up, so the deferral bought no cycle protection at all. The new guard in `agentImportCycles.test.js` derives the transition names from the facade's export blocks and walks re-export edges to work out which modules forward them, so a barrel added later is covered without being named; it catches a named import, a renamed one, a namespace property read and a destructure off a namespace handle, each bypass-probed.diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 738af197a0..f016bf9173 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -11,7 +11,10 @@ import { existsSync } from 'fs';import { spawn } from 'child_process';import { homedir } from 'os';import { cosEvents, emitLog } from './cosEvents.js';-import { updateAgent, completeAgent, createAgentOutputBatcher } from './cosAgents.js';+// The DEFINING module, not the `cosAgents.js` barrel (#3450) — see the note in+// `agentManagement.js`. This module is a LEAF that `agentLifecycle.js` imports,+// which puts it inside the facade's closure, so the facade is out of reach here.+import { updateAgent, completeAgent, createAgentOutputBatcher } from './cosAgentLifecycle.js';import { release } from './executionLanes.js';import { completeExecution, errorExecution } from './toolStateMachine.js';import { analyzeAgentFailure } from './agentErrorAnalysis.js';diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 6fc70c0c1d..cbda12e97d 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -3,13 +3,13 @@ import { EventEmitter } from 'events';// Heavy modules needed only by spawnDirectly — mock them all before importing.vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() }, emitLog: vi.fn() }));-vi.mock('./cosAgents.js', () => {+vi.mock('./cosAgentLifecycle.js', () => {const appendAgentOutput = vi.fn().mockResolvedValue(undefined);const appendAgentOutputLines = vi.fn().mockResolvedValue(undefined);// Faithful stand-in for the real debounced batcher: accumulates pushed lines// and, on flush(), routes them through the mocked appendAgentOutputLines while// swallowing+logging failures (mirrors the real createAgentOutputBatcher in- // cosAgents.js — whose error handling is unit-tested in cosAgents.test.js).+ // cosAgentLifecycle.js — whose error handling is unit-tested in cosAgents.test.js).const createAgentOutputBatcher = vi.fn((agentId) => {let pending = [];return {@@ -474,17 +474,17 @@ describe('stream error containment', () => {isTruthyMetaFn: vi.fn().mockReturnValue(false),};- // Re-import the mocked cosAgents module reference once — mocking is module-scoped.- let cosAgentsMocks;+ // Re-import the mocked cosAgentLifecycle module reference once — mocking is module-scoped.+ let agentStateMocks;beforeEach(async () => {fakeProcess = makeFakeProcess();// Fresh mocked module reference for each test so mockRejectedValueOnce is clean.- cosAgentsMocks = await import('./cosAgents.js');+ agentStateMocks = await import('./cosAgentLifecycle.js');// Reset all implementations to their default "resolve" state before each test.- cosAgentsMocks.updateAgent.mockResolvedValue(undefined);- cosAgentsMocks.completeAgent.mockResolvedValue(undefined);- cosAgentsMocks.appendAgentOutput.mockResolvedValue(undefined);- cosAgentsMocks.appendAgentOutputLines.mockResolvedValue(undefined);+ agentStateMocks.updateAgent.mockResolvedValue(undefined);+ agentStateMocks.completeAgent.mockResolvedValue(undefined);+ agentStateMocks.appendAgentOutput.mockResolvedValue(undefined);+ agentStateMocks.appendAgentOutputLines.mockResolvedValue(undefined);(await import('./agentRunTracking.js')).completeAgentRun.mockResolvedValue(undefined);(await import('./agentFinalization.js')).finalizeAgent.mockResolvedValue(undefined);minimalArgs.cleanupWorktreeFn.mockResolvedValue(undefined);@@ -503,7 +503,7 @@ describe('stream error containment', () => {// stdout output is now batched: the data handler pushes lines to the output// batcher and the close handler drains it. Make the drain's state write fail// and assert the batcher swallows+logs it with a ❌ prefix — no escape.- cosAgentsMocks.appendAgentOutputLines.mockRejectedValueOnce(new Error('db write failed'));+ agentStateMocks.appendAgentOutputLines.mockRejectedValueOnce(new Error('db write failed'));const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});const unhandledRejections = [];@@ -542,7 +542,7 @@ describe('stream error containment', () => {});it('drains stderr output on close and a failed batch flush is logged, not leaked as an unhandled rejection', async () => {- cosAgentsMocks.appendAgentOutputLines.mockRejectedValueOnce(new Error('stderr db write failed'));+ agentStateMocks.appendAgentOutputLines.mockRejectedValueOnce(new Error('stderr db write failed'));const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});const unhandledRejections = [];@@ -579,7 +579,7 @@ describe('stream error containment', () => {// metadata.phase, so it resolves normally and lets spawn finish).let releaseFirstWrite;const firstWriteGate = new Promise((r) => { releaseFirstWrite = r; });- cosAgentsMocks.updateAgent.mockImplementation((id, patch) => {+ agentStateMocks.updateAgent.mockImplementation((id, patch) => {if (patch?.metadata?.phase === 'working') return firstWriteGate;return Promise.resolve(undefined);});@@ -616,7 +616,7 @@ describe('stream error containment', () => {// Assert: the two chunks landed in emission order (serialized, not reordered// by the blocked first write racing the second).- const allLines = cosAgentsMocks.appendAgentOutputLines.mock.calls.flatMap((c) => c[1]);+ const allLines = agentStateMocks.appendAgentOutputLines.mock.calls.flatMap((c) => c[1]);const firstIdx = allLines.findIndex((l) => l.includes('first output line'));const usageIdx = allLines.findIndex((l) => l.includes('Now using extra usage'));expect(firstIdx).toBeGreaterThanOrEqual(0);@@ -716,7 +716,7 @@ describe('stream error containment', () => {it('calls updateAgent with working phase after 3s when agent has not started working', async () => {vi.useFakeTimers();const { activeAgents } = await import('./agentState.js');- const agents = cosAgentsMocks;+ const agents = agentStateMocks;const spawnPromise = spawnDirectly(minimalArgs);// Yield two microtask rounds so the getClaudeSettingsEnv await resolves and@@ -746,7 +746,7 @@ describe('stream error containment', () => {// before the 3-second setTimeout fires. Allow that first call to resolve// normally so spawnDirectly doesn't throw before the timeout test begins;// then reject the SECOND call (the phase-transition inside the timeout).- cosAgentsMocks.updateAgent+ agentStateMocks.updateAgent.mockResolvedValueOnce(undefined) // PID update — let it pass.mockRejectedValueOnce(new Error('db write failed')); // timeout update — reject@@ -859,7 +859,7 @@ describe('stream error containment', () => {beforeEach(async () => {const { finalizeAgent } = await import('./agentFinalization.js');finalizeAgent.mockClear();- cosAgentsMocks.updateAgent.mockClear();+ agentStateMocks.updateAgent.mockClear();});afterEach(() => resetHostShutdownFlagForTests());@@ -881,7 +881,7 @@ describe('stream error containment', () => {expect(finalizeAgent).not.toHaveBeenCalled();expect(cleanupWorktreeFn).not.toHaveBeenCalled();// The breadcrumb the orphan sweep falls back on when no marker names the agent.- expect(cosAgentsMocks.updateAgent).toHaveBeenCalledWith(+ expect(agentStateMocks.updateAgent).toHaveBeenCalledWith(minimalArgs.agentId,{ metadata: { phase: 'interrupted', interruptedBy: 'host-shutdown' } },);diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex b91cc4eb24..c9eb3bca7e 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -20,7 +20,11 @@import { join } from 'path';import { execGit } from '../lib/execGit.js';import { emitLog } from './cosEvents.js';-import { getAgent, updateAgent, completeAgent } from './cosAgents.js';+// The DEFINING module, not the `cosAgents.js` barrel (#3450) — see the note in+// `agentManagement.js`. This module is a LEAF that both transition modules+// import, which puts it inside the facade's closure, so the facade is out of+// reach here.+import { getAgent, updateAgent, completeAgent } from './cosAgentLifecycle.js';import { updateTask } from './cos.js';import { getActiveProvider } from './providers.js';import { markProviderUsageLimit, markProviderRateLimited } from './providerStatus.js';diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.jsindex d7b05438bb..33ab93568e 100644--- a/server/services/agentFinalization.outputHooks.test.js+++ b/server/services/agentFinalization.outputHooks.test.js@@ -3,7 +3,7 @@ import { readFileSync } from 'fs';import { dirname, join } from 'path';import { fileURLToPath } from 'url';-vi.mock('./cosAgents.js', () => ({+vi.mock('./cosAgentLifecycle.js', () => ({getAgent: vi.fn(),updateAgent: vi.fn(),completeAgent: vi.fn(),@@ -17,7 +17,7 @@ vi.mock('./taskTypeHooks.js', () => ({resolveTaskHookType: vi.fn(task => task?.metadata?.analysisType || null),}));-import { getAgent, updateAgent } from './cosAgents.js';+import { getAgent, updateAgent } from './cosAgentLifecycle.js';import { canRunTaskOutputHookWithoutPayload, getTaskOutputHook } from './taskTypeHooks.js';import {dispatchRecoveredTaskOutputHook,@@ -201,7 +201,7 @@ describe('recovery path wiring (#3182)', () => {const start = MANAGEMENT_SOURCE.indexOf('export async function cleanupOrphanedAgents');const body = MANAGEMENT_SOURCE.slice(start, start + 7_000);expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeGreaterThan(-1);- expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeLessThan(body.indexOf('await markComplete(agent.id'));+ expect(body.indexOf('dispatchRecoveredTaskOutputHook({')).toBeLessThan(body.indexOf('await completeAgent(agent.id'));});it('dispatches before post-restart recovery marks the agent complete', () => {diff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.jsindex c40bc19a0c..6e9f46367e 100644--- a/server/services/agentFinalization.prVerification.test.js+++ b/server/services/agentFinalization.prVerification.test.js@@ -35,7 +35,7 @@ vi.mock('./git.js', () => ({vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));const completeAgentMock = vi.fn();-vi.mock('./cosAgents.js', () => ({+vi.mock('./cosAgentLifecycle.js', () => ({getAgent: vi.fn(async () => null),updateAgent: vi.fn(async () => null),completeAgent: (...args) => completeAgentMock(...args),diff --git a/server/services/agentImportCycles.test.js b/server/services/agentImportCycles.test.jsindex 443bd486a4..36f9e08597 100644--- a/server/services/agentImportCycles.test.js+++ b/server/services/agentImportCycles.test.js@@ -105,6 +105,27 @@ function importsDynamically(file, mod) {return new RegExp(String.raw`\bimport\s*\(\s*[^)]*\b${mod.replace(/\./g, '\\.')}[^)]*\)`).test(src);}+// The names the facade re-exports out of `source`, in the facade's own spelling+// (the LEFT side of `x as y` — what the defining module calls it). Both quote+// styles throughout — `from "./x.js"` is valid ESM, and a matcher that only+// knows `'` reads as green over the exact statement it forbids.+//+// One parse shared by every guard that needs the facade's surface, for the same+// reason the static scan lives once in `server/lib/staticImportGraph.js`: two+// copies of a structural matcher is how a guard rots.+const FACADE = 'agentOrchestrator.js';+function reexportedFrom(source) {+ const facade = readFileSync(join(SERVICES_DIR, FACADE), 'utf-8');+ const block = facade.match(new RegExp(+ String.raw`export\s*\{([^}]*)\}\s*from\s*['"]\./${source.replace(/\./g, '\\.')}['"]`));+ expect(block, `facade no longer re-exports from ${source} — did the layering change?`).toBeTruthy();+ return block[1]+ .replace(/\/\/[^\n]*/g, '') // strip the per-export state-edge comments+ .split(',')+ .map(entry => entry.split(/\s+as\s+/)[0].trim())+ .filter(Boolean);+}+// Loaders for the modules whose REAL export surface the guards below assert on.// Spelled out one literal specifier each rather than `import(`./${name}`)` —// the bundler cannot analyze a fully-variable specifier and warns, and the point@@ -214,17 +235,6 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {// failing on a name `cos.js` is right to export.// Both quote styles throughout — `from "./x.js"` is valid ESM, and a matcher// that only knows `'` reads as green over the exact statement it forbids.- const facade = readFileSync(join(SERVICES_DIR, 'agentOrchestrator.js'), 'utf-8');- const reexportedFrom = (source) => {- const block = facade.match(new RegExp(- String.raw`export\s*\{([^}]*)\}\s*from\s*['"]\./${source.replace(/\./g, '\\.')}['"]`));- expect(block, `facade no longer re-exports from ${source} — did the layering change?`).toBeTruthy();- return block[1]- .replace(/\/\/[^\n]*/g, '') // strip the per-export state-edge comments- .split(',')- .map(entry => entry.split(/\s+as\s+/)[0].trim())- .filter(Boolean);- };const stateLayer = new Set(reexportedFrom('cosAgentLifecycle.js'));const forbidden = reexportedFrom('agentManagement.js').filter(name => !stateLayer.has(name));expect(forbidden.length, 'derived nothing to forbid — check the facade export blocks').toBeGreaterThan(0);@@ -278,6 +288,108 @@ describe('agent lifecycle cluster — no static import cycles (#2837)', () => {}});+ it('makes every transition caller name the facade or the defining module, never a barrel (#3450)', () => {+ // Step 3 of the #3450 sequencing, for the callers the "move the caller out"+ // recipe cannot reach. `agentManagement.js` and `agentLifecycle.js` DEFINE+ // transitions the facade re-exports, and `agentFinalization.js` /+ // `agentCliSpawning.js` are leaves those two must call — all four sit inside+ // the facade's closure permanently, so importing the facade is a cycle, not+ // an option. What is still achievable there is the property the facade was+ // built for: ONE address per transition. Above the closure that address is+ // the facade; inside it, the module that declares the function. A barrel is+ // never an answer — that is the third address this sequencing keeps deleting.+ //+ // Derived from the facade's own export blocks, so a transition added there+ // is guarded the moment it lands and `agentOrchestrator.js` stays the only+ // file anyone edits to change the rule.+ const declaringModules = ['agentManagement.js', 'cosAgentLifecycle.js', 'agentLifecycle.js'];+ const declaredBy = new Map(); // transition name → the modules allowed to serve it+ for (const source of declaringModules) {+ for (const name of reexportedFrom(source)) {+ if (!declaredBy.has(name)) declaredBy.set(name, new Set());+ declaredBy.get(name).add(source);+ }+ }+ // `terminateAgent` lands in two of them: the process-side one and the+ // state-side one the facade renames to `requestAgentTermination`. Both are+ // real definitions, so both stay allowed — the rule here is "not a barrel",+ // and that collision is a naming question the facade already answered.+ expect(declaredBy.size, 'derived no transitions — check the facade export blocks').toBeGreaterThan(3);++ // A FORWARDER is any module that re-exports its way to a declaring module, at+ // any depth: `cosAgents.js` is one hop (`export * from './cosAgentLifecycle.js'`),+ // `cos.js` is two (`export { … } from './cosAgents.js'`). Walking the+ // re-export edges instead of listing the barrels means a NEW barrel is+ // covered the day it is written, and the two this issue has yet to collapse+ // need no naming here. Asserted rather than merely computed, so collapsing+ // one has to come here and say so.+ const reexportEdges = (file) => [+ ...readFileSync(join(SERVICES_DIR, file), 'utf-8')+ .matchAll(/export\s*(?:\*|\{[^}]*\})\s*(?:as\s+\w+\s*)?from\s*['"]([^'"]+)['"]/g)+ ].map(m => relative(SERVICES_DIR, resolve(dirname(join(SERVICES_DIR, file)), m[1])));++ const forwarders = new Set();+ for (const file of graph.keys()) {+ if (file === FACADE || declaringModules.includes(file)) continue; // both are answers, not forwarders+ const seen = new Set([file]);+ const queue = [file];+ while (queue.length) {+ for (const target of reexportEdges(queue.pop())) {+ if (seen.has(target) || !graph.has(target)) continue;+ if (declaringModules.includes(target)) { forwarders.add(file); queue.length = 0; break; }+ seen.add(target);+ queue.push(target);+ }+ }+ }+ expect([...forwarders].sort(), 'the set of barrels still forwarding a transition changed — intended?')+ .toEqual(['cos.js', 'cosAgents.js']);++ // Production sources only. A test mirrors whatever its subject imports (a+ // mock pointed at a module the subject no longer imports silently stops+ // applying), so tests follow this rule rather than defining it.+ const allowed = new Set([FACADE, ...declaringModules]);+ const offenders = [];+ for (const file of graph.keys()) {+ if (file === FACADE) continue;+ const src = readFileSync(join(SERVICES_DIR, file), 'utf-8');+ const resolveSpec = (spec) => relative(SERVICES_DIR, resolve(dirname(join(SERVICES_DIR, file)), spec));++ // Named imports — `import { completeAgent as done } from './cos.js'`. The+ // binding's LEFT side is the transition name; renaming it on the way in+ // does not change where it came from.+ for (const [, names, spec] of src.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]([^'"]+)['"]/g)) {+ const target = resolveSpec(spec);+ if (allowed.has(target)) continue;+ for (const entry of names.split(',')) {+ const name = entry.split(/\s+as\s+/)[0].trim();+ if (!declaredBy.has(name) || declaredBy.get(name).has(target)) continue;+ offenders.push(`${file} imports ${name} from ${target}`);+ }+ }++ // `import * as cos from './cos.js'` names no bindings, so the loop above+ // cannot see it — yet it hands the caller every transition the barrel+ // forwards. Banning the namespace import outright is too blunt (that same+ // handle is how a dozen modules reach the task store, which is not this+ // issue's business), so check the two ways a transition comes back OFF the+ // handle: a property read and a destructure. Both, because either one+ // alone reads green over the other.+ for (const [, ns, spec] of src.matchAll(/import\s*\*\s*as\s+(\w+)\s*from\s*['"]([^'"]+)['"]/g)) {+ const target = resolveSpec(spec);+ if (!forwarders.has(target)) continue;+ for (const name of declaredBy.keys()) {+ const reached = new RegExp(String.raw`\b${ns}\s*\.\s*${name}\b`).test(src)+ || new RegExp(String.raw`\{[^}]*\b${name}\b[^}]*\}\s*=\s*(?:await\s+)?${ns}\b`).test(src);+ if (reached) offenders.push(`${file} reaches ${name} through the forwarder ${target}`);+ }+ }+ }+ expect(offenders.sort(),+ `a transition must come from the facade or the module that declares it:\n${offenders.join('\n')}`+ ).toEqual([]);+ });+it('keeps agentState.js an import-free leaf, so agents.js can use the facade (#3450)', () => {// `agentState.js` is what lets modules that cannot import each other share// state — the pid map moved here so `agentManagement.js` no longer had todiff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 424746040c..fbe6a664b9 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -29,7 +29,11 @@ import { join } from 'path';import { readFile, writeFile } from 'fs/promises';import { existsSync } from 'fs';import { cosEvents, emitLog } from './cosEvents.js';-import { registerAgent, updateAgent, completeAgent } from './cosAgents.js';+// The DEFINING module, not the `cosAgents.js` barrel (#3450) — see the note in+// `agentManagement.js`. This module owns the `spawnAgentForTask` transition the+// facade re-exports, so it is permanently inside the facade's closure and must+// name `completeAgent`'s home directly.+import { registerAgent, updateAgent, completeAgent } from './cosAgentLifecycle.js';// `getAgentRecord`, NOT `getAgent`: the record without its transcript. Both// consumers below want only `.status` / `.metadata`, and `getAgent` hydrates a// completed or paused record by reading the whole output.txt, line-splitting itdiff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex 5099efe207..9a8a468a04 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -8,8 +8,14 @@import { join } from 'path';import { ServerError } from '../lib/errorHandler.js';import { emitLog } from './cosEvents.js';-import { completeAgent, updateAgent } from './cosAgents.js';-import { updateTask, addTask, getTaskById } from './cos.js';+// The DEFINING module, not the `cosAgents.js` barrel (#3450). This module is one+// of the three `agentOrchestrator.js` imports, so it can never reach a transition+// through the facade — an import back from here closes the loop the facade exists+// to open. Inside the closure the single address for a transition is the module+// that declares it; a barrel would be a third answer to "where does completeAgent+// live", which is the thing this sequencing keeps removing.+import { completeAgent, updateAgent, getAgents } from './cosAgentLifecycle.js';+import { updateTask, addTask, getTaskById, evaluateTasks } from './cos.js';import { terminateAgentViaRunner, killAgentViaRunner, pauseAgentViaRunner, getAgentStatsFromRunner, getActiveAgentsFromRunner } from './cosRunnerClient.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';import { isInternalTaskId } from '../lib/taskParser.js';@@ -557,7 +563,12 @@ export async function settleOrphanedCreativeDirectorRun(task) {}export async function cleanupOrphanedAgents() {- const { getAgents, completeAgent: markComplete, evaluateTasks, getTaskById: getTask } = await import('./cos.js');+ // Was `await import('./cos.js')` destructuring all four of these (#3450). The+ // deferral bought nothing — this module already imports `./cos.js` statically+ // at the top, so the module was loaded either way — while routing two agent+ // functions through the `cos.js` re-export block, i.e. reaching a transition+ // through a barrel. `completeAgent`/`getAgents` now come from the module that+ // declares them and `evaluateTasks` joined the existing static `cos.js` import.const agents = await getAgents();let cleanedCount = 0;const orphanedTaskIds = [];@@ -617,7 +628,7 @@ export async function cleanupOrphanedAgents() {console.log(interrupted? `🛑 Recovering agent ${agent.id} interrupted by a PortOS restart (PID ${agent.pid || 'unknown'} not running)`: `🧹 Cleaning up orphaned agent ${agent.id} (PID ${agent.pid || 'unknown'} not running)`);- const task = agent.taskId ? await getTask(agent.taskId).catch(() => null) : null;+ const task = agent.taskId ? await getTaskById(agent.taskId).catch(() => null) : null;await dispatchRecoveredTaskOutputHook({agentId: agent.id,task,@@ -639,7 +650,7 @@ export async function cleanupOrphanedAgents() {category: interrupted ? 'interrupted' : 'orphaned',});}- await markComplete(agent.id, {+ await completeAgent(agent.id, {success: false,error: errorMessage,orphaned: true,@@ -676,7 +687,7 @@ export async function cleanupOrphanedAgents() {// Settle any Creative Director run tied to an orphaned agent (issue #2705)// BEFORE the retry below, so the project can advance without a server restart.for (const { taskId } of orphanedTaskIds) {- const task = await getTask(taskId).catch(() => null);+ const task = await getTaskById(taskId).catch(() => null);await settleOrphanedCreativeDirectorRun(task);}@@ -686,7 +697,7 @@ export async function cleanupOrphanedAgents() {// pointer reflects what actually survived — a dirty tree aborts removal, leaving// the whole worktree in place.for (const { taskId, agentId, agentMetadata } of orphanedTaskIds) {- await handleOrphanedTask(taskId, agentId, getTask, {+ await handleOrphanedTask(taskId, agentId, getTaskById, {agentMetadata,// `|| null`, not a bare boolean: a plain `false` would hard-override the// per-agent breadcrumb fallback, leaving this — the path that handlesdiff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex 0ec6351879..624c778799 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -46,9 +46,6 @@ vi.mock('./cos.js', () => ({addTask: vi.fn().mockResolvedValue({ id: 'sys-mocked' }),getTaskById: vi.fn(),getAllTasks: vi.fn(),- // cleanupOrphanedAgents pulls these in via a dynamic import.- getAgents: vi.fn().mockResolvedValue([]),- completeAgent: vi.fn().mockResolvedValue(undefined),evaluateTasks: vi.fn().mockResolvedValue(undefined)}));@@ -62,7 +59,14 @@ vi.mock('./agentRunTracking.js', () => ({}));// Stub other transitive imports we don't exercise in handleOrphanedTask.-vi.mock('./cosAgents.js', () => ({ completeAgent: vi.fn(), updateAgent: vi.fn().mockResolvedValue(undefined) }));+// The DEFINING module, not the `cosAgents.js` barrel — mirrors the production+// import (#3450). Mocking the barrel here would silently stop applying and let+// the real state layer load.+vi.mock('./cosAgentLifecycle.js', () => ({+ completeAgent: vi.fn().mockResolvedValue(undefined),+ updateAgent: vi.fn().mockResolvedValue(undefined),+ getAgents: vi.fn().mockResolvedValue([]),+}));vi.mock('./cosRunnerClient.js', () => ({terminateAgentViaRunner: vi.fn(),killAgentViaRunner: vi.fn(),@@ -97,16 +101,14 @@ vi.mock('./creativeDirector/completionHook.js', () => ({ advanceAfterSceneSettleimport { handleOrphanedTask, pauseAgent, settleOrphanedCreativeDirectorRun, cleanupOrphanedAgents } from './agentManagement.js';import { cleanupAgentWorktree, resolveTaskResumePatch } from './agentWorktreeCleanup.js';-import { getAgents } from './cos.js';+import { getAgents, updateAgent, completeAgent as markAgentComplete } from './cosAgentLifecycle.js';import { updateRun, getProject } from './creativeDirector/local.js';import { advanceAfterPlanStepSettled } from './creativeDirector/planAdvance.js';import { advanceAfterSceneSettled } from './creativeDirector/completionHook.js';import { updateTask, addTask, getTaskById } from './cos.js';-import { updateAgent } from './cosAgents.js';import { pauseAgentViaRunner } from './cosRunnerClient.js';import * as shellService from './shell.js';import { readHostShutdownMarker, clearHostShutdownMarker } from '../lib/hostShutdown.js';-import { completeAgent as markAgentComplete } from './cos.js';import { checkForTaskCommit, completeAgentRun } from './agentRunTracking.js';import { activeAgents, runnerAgents, pausedAgents } from './agentState.js';diff --git a/server/services/agentOrchestrator.js b/server/services/agentOrchestrator.jsindex 653d650b60..10ee609f50 100644--- a/server/services/agentOrchestrator.js+++ b/server/services/agentOrchestrator.js@@ -78,6 +78,24 @@* import: the guard rejects it, and it is how this cluster got here in the first* place. `agentState.js#spawnedAgentCommands` documents the worked example.*+ * ## When the caller CANNOT move out (the other half)+ *+ * Some callers are inside the closure permanently, and no edge-breaking changes+ * that. `agentManagement.js` and `agentLifecycle.js` DEFINE transitions this+ * module re-exports — importing the facade from either is the cycle, by+ * construction. `agentFinalization.js` and `agentCliSpawning.js` are leaves those+ * two must call to spawn and to finalize; inverting that would move the spawn+ * implementation and the completion flow, which buys nothing the facade wants.+ *+ * For those, the achievable property is not "use the facade" — it is the one the+ * facade exists to create: ONE address per transition. Above the closure that+ * address is this module; inside it, the module that DECLARES the function+ * (`cosAgentLifecycle.js` for `completeAgent`). A barrel is never an answer.+ * `agentImportCycles.test.js` derives the transition names from the export blocks+ * below, walks re-export edges to find which modules forward them, and fails any+ * production module that reaches a transition through one — by named import,+ * renamed import, namespace property read, or destructure off a namespace handle.+ ** ## What is still outstanding** `server/routes/cosAgentRoutes.js`, `agents.js` and `subAgentSpawner.js`'s event@@ -88,14 +106,16 @@* `grep -rn agentOrchestrator server/` is the live answer to what has moved —* do not keep a hand-written call-site inventory here; it only goes stale.*- * Remaining: the transitions below that still have callers INSIDE the closure- * (all four are `completeAgent`, reached through `cosAgents.js`), and the two- * barrels that still expose a partial view of the cluster — `cosAgents.js` and- * `cos.js`'s agent re-export block. Note that `agentFinalization.js` and- * `agentCliSpawning.js` are LEAVES that call a transition, so "move the caller- * out" does not apply to them as written: the closure edge to break is the one- * `agentLifecycle.js`/`agentManagement.js` hold INTO them, not an import of- * theirs.+ * Step 3 is done. The four in-closure `completeAgent` callers+ * (`agentManagement`, `agentLifecycle`, `agentFinalization`, `agentCliSpawning`)+ * name `cosAgentLifecycle.js` directly under the rule above, and the deferred+ * `import('./cos.js')` in `cleanupOrphanedAgents` — which reached `completeAgent`+ * and `getAgents` through the `cos.js` re-export block for no cycle-breaking+ * benefit, since that module is a static import here — is gone with it.+ *+ * Remaining: the two barrels that still expose a partial view of the cluster —+ * `cosAgents.js` and `cos.js`'s agent re-export block. Both are wide surfaces+ * (30+ importers, many `vi.mock`ed) and each wants its own PR.*/// Process/runner layer — owns the live agent maps and the OS-level signals.