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: break the agent-lifecycle import cycle by extracting shared leaf modules (#2837)
[._.]/ Adam Eivy72c2b2fee9bb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d94ccbeb0c..92512b37b2 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -55,3 +55,4 @@- **Commit the `server/` and `client/` lockfiles** — both were gitignored purely "to reduce merge noise" (`bbeab937d`), which left Dependabot able to see only the ~45 dependencies declared in their `package.json` files and blind to ~560 transitive packages; the repo's entire alert history is one alert against the root lockfile, whose tree has a single direct dep (pm2). CI's `npm install --prefix server|client` steps become `npm ci`, so the two trees holding all application code now resolve deterministically instead of re-resolving on every run and on every user's install. `setup-node`'s npm cache keys off all three lockfiles. `browser/package-lock.json` stays ignored (its `node_modules` is committed instead). Unrelated to the npm-workspaces revert in `b743222be`, which was about exFAT's lack of symlink support.- **Apply the mergeable Dependabot bumps in one commit** — server `vitest`/`@vitest/coverage-v8` 4.1.9→4.1.10 and `node-pty` 1.2.0-beta.10→beta.14; client `react`/`react-dom` 19.2.7→19.2.8, `vite` 8.0.16→8.1.5, and `@tailwindcss/postcss` 4.3.1→4.3.3. Applied together with regenerated lockfiles because the individual PRs predate lockfile tracking and each ERESOLVE'd in isolation: the two vitest packages must move in lockstep, `@tailwindcss/postcss` was stranded a patch behind the already-merged `tailwindcss` 4.3.3, and Dependabot's `react-dom` PR would have left `react` mismatched at 19.2.7. Holding back `undici` 8 (breaks the DNS-rebinding connect-time IP pinning in `safeUrlFetch.js`, #1859) and `eslint`/`@eslint/js` 10 (`[email protected]` peers at `^9.7`).- **[issue-2845] Standardize the `loraTraining` sample 404 error envelope** — new `sendErrorResponse`/`buildErrorEnvelope` helpers in `server/lib/errorHandler.js` build the shared `{ error, code, timestamp }` body in one place; `asyncHandler`, `errorMiddleware`, the `res.sendFile` 404 callback in `server/routes/loraTraining.js`, and the `authGate` 401/403 short-circuits now all route through it, so responses raised outside a handler's catch no longer omit `code`/`timestamp`. Mid-response failures (SSE/streaming routes) now delegate to Express's finalhandler so the socket is destroyed instead of the request hanging.+- **[issue-2837] Break the agent-lifecycle circular-dependency cluster** — `finalizeAgent`/`releaseAgentLane` (plus the success-criteria + output-hook helpers) move to `server/services/agentFinalization.js`, the summary extractors to `agentSummaryExtraction.js`, runner recovery to `agentRunnerSync.js`, and the runner output batchers to `agentRunnerOutputBatchers.js`. With those leaves in place the two static cycles (`agentLifecycle` ↔ `agentCliSpawning`, `agentLifecycle` ↔ `agentTuiSpawning`) are gone, and three `await import()` cycle-dodges — `handleOrphanedTask`, the spawner's init-time lifecycle/management lookups, and `flushRunnerOutputBatcher` — become plain static imports. `agentLifecycle.js` still re-exports every moved symbol, so no import path changes for callers. New `agentImportCycles.test.js` re-derives the static import graph and fails if a cycle is reintroduced.diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex f2b22ccd88..6955f522ee 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -17,7 +17,7 @@ import { release } from './executionLanes.js';import { completeExecution, errorExecution } from './toolStateMachine.js';import { analyzeAgentFailure } from './agentErrorAnalysis.js';import { completeAgentRun } from './agentRunTracking.js';-import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';+import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';import { activeAgents, userTerminatedAgents, pausedAgents } from './agentState.js';import { normalizeReviewers } from '../lib/validation.js';import { resolveReviewLoopOptions } from './codeReview.js';diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex f78f548683..83f85aeedb 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -49,7 +49,7 @@ vi.mock('./agentRunTracking.js', () => ({ completeAgentRun: vi.fn().mockResolved// pulling in the real worktreeManager → instances module graph. Default: no// owner-matched account → empty overlay (ambient gh auth untouched).vi.mock('./git.js', () => ({ resolveForgeTokenEnv: vi.fn().mockResolvedValue({}) }));-vi.mock('./agentLifecycle.js', () => ({+vi.mock('./agentFinalization.js', () => ({finalizeAgent: vi.fn().mockResolvedValue(undefined),releaseAgentLane: vi.fn(),}));@@ -456,7 +456,7 @@ describe('stream error containment', () => {cosAgentsMocks.appendAgentOutput.mockResolvedValue(undefined);cosAgentsMocks.appendAgentOutputLines.mockResolvedValue(undefined);(await import('./agentRunTracking.js')).completeAgentRun.mockResolvedValue(undefined);- (await import('./agentLifecycle.js')).finalizeAgent.mockResolvedValue(undefined);+ (await import('./agentFinalization.js')).finalizeAgent.mockResolvedValue(undefined);minimalArgs.cleanupWorktreeFn.mockResolvedValue(undefined);// Reset the resolve+wrap helper to its POSIX passthrough before each test// (afterEach's restoreAllMocks can clear the factory implementation).diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsnew file mode 100644index 0000000000..542a7babaa--- /dev/null+++ b/server/services/agentFinalization.js@@ -0,0 +1,495 @@+/**+ * Agent Finalization+ *+ * The shared end-of-run path for ALL three spawn modes (runner-mode+ * `handleAgentCompletion`, the TUI `finish()` handler, and the direct-CLI+ * `close` handler): lane release + execution tracking, success-criteria+ * evaluation, the programmatic-I/O output hook, and the centralized state+ * writes (`completeAgent` / `updateTask` / run tracking).+ *+ * Extracted from `agentLifecycle.js` (issue #2837) to break the static import+ * cycle it sat in the middle of: `agentCliSpawning.js` and+ * `agentTuiSpawning.js` both need `finalizeAgent` / `releaseAgentLane`, while+ * `agentLifecycle.js` imports BOTH spawners. This module is a leaf with+ * respect to that cluster — it must NOT import `agentLifecycle.js`,+ * `agentCliSpawning.js`, `agentTuiSpawning.js`, or `agentManagement.js`, or the+ * cycle comes straight back. `server/services/agentImportCycles.test.js`+ * enforces that.+ */++import { join } from 'path';+import { emitLog } from './cosEvents.js';+import { updateAgent, completeAgent } from './cosAgents.js';+import { updateTask } from './cos.js';+import { getActiveProvider } from './providers.js';+import { markProviderUsageLimit, markProviderRateLimited } from './providerStatus.js';+import { release } from './executionLanes.js';+import { completeExecution, errorExecution } from './toolStateMachine.js';+import { resolveFailedTaskUpdate, resolveTypeFailureSignal } from './agentErrorAnalysis.js';+import { completeAgentRun, checkForTaskCommit } from './agentRunTracking.js';+import { isProgrammaticIoTaskType, resolveTaskHookType, isNonCommittingCoordinatorTask } from './taskTypeHooks.js';+import { processAgentCompletion } from './agentCompletion.js';+import { extractSimplifySummaries } from './agentSummaryExtraction.js';++/**+ * Release the execution lane and complete tool-execution tracking for a+ * finishing agent. Pulled OUT of finalizeAgent so callers can fire it+ * EARLY (before reading output.txt, running error analysis, or writing+ * state) — neither call blocks on I/O, but lanes serialize related work+ * and we don't want them held longer than necessary.+ *+ * Idempotent enough to be a no-op when laneName / executionId are absent+ * (recovered agents post-restart, error paths that already released).+ */+export function releaseAgentLane({ agentId, success, duration, exitCode, executionId, laneName, errorExecutionMessage }) {+ if (laneName) release(agentId);+ if (!executionId) return;+ if (success) {+ completeExecution(executionId, { success: true, duration });+ } else {+ errorExecution(executionId, { message: errorExecutionMessage || `Agent exited with code ${exitCode}`, code: exitCode });+ completeExecution(executionId, { success: false });+ }+}++/**+ * Evaluate a completed autonomous run against its DECLARED success criteria+ * (issue #2344). Distinct from the runner's exit-code `success`: it answers+ * "did the run actually produce the work it was supposed to?" using the one+ * machine-checkable criterion the CoS already relies on — a `[task-<id>]` commit.+ *+ * Returns a null sentinel when NO criterion is declared (interactive/user tasks,+ * user-terminated runs, or a run with no task id / workspace to validate+ * against), so downstream telemetry never conflates "not declared" with+ * "declared and failed". For autonomous tasks it verifies the commit on BOTH+ * success and failure — a clean exit that committed nothing is an honest miss,+ * and that is exactly the signal task-learning wants. `checkForTaskCommit` is+ * git-repo-gated, off the event loop, and hard-timeout-bounded, so a non-repo+ * workspace or a hung git degrades to "no commit" rather than stalling finalize.+ *+ * `hookResult` is the programmatic-I/O output-hook result (from+ * `dispatchTaskOutputHook`), which finalizeAgent resolves BEFORE calling this so+ * those task types can be judged by their real deliverable; `success` is the+ * runner's exit-code verdict that hook result is weighed against. Both are+ * absent/null for every other task shape.+ */+export async function evaluateSuccessCriteria({ task, terminatedByUser, workspacePath, success = false, hookResult = null }) {+ if (terminatedByUser) return null;+ const taskType = task?.taskType || 'user';+ // The SCHEDULED type (`metadata.analysisType`) if any, else the queue category —+ // the same resolution the programmatic-I/O gate uses, reused for the coordinator+ // gate below so both key on the task's real type, not the CoS bucket ('internal').+ const scheduledType = resolveTaskHookType(task);+ // Programmatic-I/O tasks (taskTypeHooks.js) declare their OWN criterion — the+ // sentinel parsed and the hook accepted it — so this branch comes FIRST: it is+ // keyed on the hook result rather than on a workspace/commit, and must not be+ // pre-empted by the `!workspacePath` bail below (a hook that already ran and+ // threw is a real verdict even if the worktree is gone). Their prompts+ // explicitly FORBID committing or opening a PR (the worktree is discarded), so+ // the `[task-<id>]` commit check would mark every correct run a failure (#2700).+ // Judging them purely by exit code instead is also wrong: an exit-0 run whose+ // `.agent-done` sentinel was missing/malformed, or whose hook threw, produced+ // nothing usable and must be recorded as the failure it is (#2727).+ if (isProgrammaticIoTaskType(scheduledType)) {+ return resolveProgrammaticIoVerdict({ success, hookResult });+ }+ // Interactive/user tasks declare no machine-checkable criterion; neither does+ // a run missing the task id or workspace needed to validate.+ if (taskType === 'user' || !task?.id || !workspacePath) return null;+ // Pipeline/media tasks deliver artifacts, not a `[task-<id>]` commit — the+ // commit criterion doesn't apply, so don't mislabel a clean artifact run as a+ // validation miss (which would also pollute the correlation window). null =+ // no commit criterion declared for this task shape. Unlike programmatic-I/O+ // tasks they register no output hook, so there is no deliverable signal to+ // judge them by — they stay exit-code-judged (unchanged by #2727).+ if (task?.metadata?.pipeline || task?.metadata?.mediaJob) return null;+ // gh/git/external COORDINATOR task types (NON_COMMITTING_COORDINATOR_TASK_TYPES in+ // taskTypeHooks.js — branch-reconcile/issue-reconcile/branch-cleanup/jira-status-report)+ // deliver their work as a side effect — a merged PR, a resolved conflict, a deleted+ // branch, a posted report — and by design NEVER produce a `[task-<id>]` commit. Because+ // their workspacePath IS set (the app's live checkout), the commit check above would+ // return false on every SUCCESSFUL run and drive their learning bucket to ~0% (#2696) —+ // the same artifact #2700 fixed for the programmatic-I/O reasoning run. They register no+ // output hook, so like pipeline/media jobs there is no deliverable signal to judge them+ // by; fall back to the exit code (null = criterion undeclared). Uses the predicate (not a+ // bare `scheduledType` lookup) so the archived `taskAnalysisType` shape resolves the same+ // way the learning bucket does — see isNonCommittingCoordinatorTask.+ if (isNonCommittingCoordinatorTask(task)) return null;+ return await checkForTaskCommit(task.id, workspacePath);+}++/**+ * The programmatic-I/O success criterion (#2727): "the agent's structured output+ * parsed and the output hook accepted it". Pure.+ *+ * The question this answers is about the AGENT'S OUTPUT, not about whether the+ * hook's downstream side effect ultimately landed. So a hook that accepted the+ * payload and then couldn't reach the tracker (`file-failed`, `tracker-read-failed`)+ * is NOT a failure of the run: the reasoning was sound and delivered, and a forge+ * outage is environmental. Blaming the run would tank the type's measured success+ * rate — and, through the shared classification below, auto-park the whole task+ * type — every time `gh` has a bad afternoon. Deliberate, not inherited: raised in+ * review on #2727 and kept.+ *+ * Delegates the accept/reject classification to `resolveTypeFailureSignal`, the+ * same pure decision the #2616 type-level failure ledger uses — so the learning+ * verdict and the ledger can never drift apart on what counts as a bad run, and a+ * new benign reason only has to be taught to one function.+ *+ * Sentinel discipline throughout — three distinct answers, never collapsed:+ * - `false` — the hook ran and REJECTED the output (threw, or `unparseable-response`).+ * - `null` — NOTHING evaluated the output (no hook ran, it timed out, or it+ * returned no structured outcome), so no criterion was declared and+ * task-learning falls back to the exit code exactly as before. "Not evaluated"+ * must never become "accepted".+ * - `true` — the hook ran and accepted the output.+ *+ * @returns {boolean|null} true = accepted, false = rejected, null = undeclared+ */+export function resolveProgrammaticIoVerdict({ success, hookResult }) {+ if (!hookResult?.ran) return null;+ // A thrown hook rejected the output. Classified FIRST: it carries no outcome (so+ // it must precede the outcome-shape guard), and a rejection shouldn't hinge on+ // the exit-code guard below.+ if (hookResult.threw) return false;+ // An absent/non-boolean exit-code verdict can't be weighed against anything.+ if (typeof success !== 'boolean') return null;+ // Ran, but handed back no structured outcome to read: nothing evaluated the+ // output, so declare no verdict rather than defaulting to "accepted".+ if (!hookResult.outcome || typeof hookResult.outcome !== 'object') return null;+ // Ran, but bailed out BEFORE it ever looked at the output (its app was deleted+ // mid-run, or the task carries no app). Nothing evaluated the agent's work — and+ // these paths don't even record a run — so this is "undeclared", not a free+ // success for the type.+ if (HOOK_ABORTED_BEFORE_EVALUATION.has(hookResult.outcome.reason)) return null;+ return resolveTypeFailureSignal({ success, hookResult }).record === 'success';+}++// Output-hook outcomes that mean "the hook returned before validating the agent's+// output at all" — distinct from both a rejection and an acceptance.+const HOOK_ABORTED_BEFORE_EVALUATION = new Set(['no-app', 'app-not-found']);++/**+ * Hard bound on output-hook dispatch (#2727). The hook is only awaited BEFORE+ * `completeAgent` so its verdict can be recorded — but `status: 'running'` is what+ * the CoS concurrency gate counts (`cos.js`, default 3 slots), and that flips in+ * completeAgent. So an un-bounded hook (it shells out to `gh`/`glab` and can walk+ * up to 50 embeddings for semantic dedup) would hold a slot for its whole+ * duration, and a HUNG one would hold it until restart — with the task stuck+ * `in_progress` and the orphan reaper protecting the zombie rather than reaping+ * it, because it too filters on `status === 'running'`.+ *+ * A timeout resolves to the "no verdict" sentinel, NOT a rejection: a hook we+ * stopped waiting for told us nothing about the agent's output, so finalize+ * proceeds and task-learning falls back to the exit code (the pre-#2727+ * behavior). Generous by design — this is a hang backstop, not a latency budget;+ * a slow-but-honest hook should still get to return its real verdict.+ *+ * Timing out only stops us WAITING — it can't cancel the hook, which keeps running+ * and still lands its side effects (filing the issue, recording the run). That's+ * the desired trade: the work completes, it just no longer pins a concurrency slot+ * or gates the completion write. A late rejection is still handled (Promise.race+ * subscribes to both), so it can't surface as an unhandled rejection.+ */+const OUTPUT_HOOK_TIMEOUT_MS = 5 * 60_000;++export function withOutputHookTimeout(promise, { agentId, timeoutMs = OUTPUT_HOOK_TIMEOUT_MS }) {+ let timer;+ const timeout = new Promise(resolve => {+ timer = setTimeout(() => {+ // Resolve BEFORE logging, and never let the log throw out of the callback:+ // this runs outside the request lifecycle, so an uncaught throw here would+ // crash the process — and a throw before `resolve` would leave the race+ // permanently unsettled, wedging the exact finalize this timer exists to+ // rescue.+ resolve({ ran: false, timedOut: true });+ try {+ emitLog('error', `⏱️ processTaskOutput hook timed out after ${timeoutMs}ms for ${agentId} — finalizing with no verdict`, { agentId });+ } catch (err) {+ console.error(`❌ Failed to log output-hook timeout for ${agentId}: ${err.message}`);+ }+ }, timeoutMs);+ // Never let the backstop itself hold the event loop open.+ timer.unref?.();+ });+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));+}++/**+ * Stamp an LI hand-off's per-proposal execution verdict into a completion `taskUpdate`'s+ * federated metadata (#2779), mutating `taskUpdate.metadata` in place. Shared by every+ * agent-completion path that marks an LI hand-off task terminal — finalizeAgent (the main+ * path) AND the post-restart recovery path in handleAgentCompletion — so a hand-off that+ * completes through a bypass still federates its outcome to the originating peer (codex P2);+ * without this only finalizeAgent-completed hand-offs would ever reach peer A.+ *+ * `buildLiExecutionVerdict` reuses the exact validation-authoritative outcome + environmental+ * gate the LOCAL #2765 write uses, so both peers record the identical verdict; a non-hand-off+ * task (no `liProposal`) or an environmental completion yields null (no stamp). Best-effort+ * and defensive (runs outside the request lifecycle): a lazy-import/build failure logs and+ * leaves `taskUpdate` unstamped rather than throwing into the completion path. Lazy imports+ * keep the taskLearning/LI graphs off agentLifecycle's static chain.+ *+ * @param {object} taskUpdate the update object about to be passed to updateTask (mutated)+ * @param {object} task the persisted task (carries `metadata.liProposal` when a hand-off)+ * @param {{ success:boolean, validationPassed?:boolean|null, errorAnalysis?:object|null }} signals+ * @returns {Promise<object>} the same `taskUpdate` (stamped when applicable)+ */+export async function stampLiExecutionVerdict(taskUpdate, task, { success, validationPassed = null, errorAnalysis = null } = {}) {+ const liProposal = task?.metadata?.liProposal || null;+ if (!liProposal) return taskUpdate;+ try {+ const [{ buildLiExecutionVerdict }, { LI_EXECUTION_VERDICT_KEY }] = await Promise.all([+ import('./taskLearning/metrics.js'),+ import('./layeredIntelligenceOutcomes.js')+ ]);+ const verdict = buildLiExecutionVerdict({ liProposal, success, validationPassed, errorAnalysis, executedAt: new Date().toISOString() });+ if (verdict) {+ taskUpdate.metadata = { ...(taskUpdate.metadata || {}), [LI_EXECUTION_VERDICT_KEY]: verdict };+ }+ } catch (err) {+ emitLog('warn', `⚠️ Failed to stamp LI execution verdict for task ${task?.id}: ${err.message}`, { taskId: task?.id });+ }+ return taskUpdate;+}++/**+ * Shared end-of-run state writes for all three spawn paths+ * (`handleAgentCompletion` runner-mode, TUI `finish`, direct-CLI `close`).+ * Path-specific cleanup (worktree, sentinel removal, pty kill, in-memory+ * map deletes) stays at the calling site; lane release + execution+ * tracking should fire EARLIER via `releaseAgentLane()` — this helper+ * owns the centralized state writes only.+ */+export async function finalizeAgent({+ agentId,+ task,+ runId,+ providerId,+ success,+ exitCode,+ duration,+ outputBuffer,+ errorAnalysis,+ terminatedByUser = false,+ isTruthyMetaFn,+ error,+ completionReason,+ workspacePath = null,+}) {+ if (success && isTruthyMetaFn) {+ await persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMetaFn);+ }++ const taskType = task?.taskType || 'user';+ const taskUpdate = terminatedByUser+ ? {+ status: 'blocked',+ metadata: {+ ...task.metadata,+ blockedReason: 'Terminated by user',+ blockedCategory: 'user-terminated',+ blockedAt: new Date().toISOString(),+ },+ }+ : success+ ? { status: 'completed' }+ : await resolveFailedTaskUpdate(task, errorAnalysis, agentId);++ // Programmatic-I/O task types (e.g. layered-intelligence) run a deterministic+ // post-agent step on the agent's STRUCTURED output — the parsed `.agent-done`+ // payload — rather than only handling the completion sentinel. Read + dispatch+ // it mode-agnostically here (the single finalize chokepoint for TUI/CLI/runner+ // agents), gated on the task type actually registering an output hook so a+ // normal agent pays no extra I/O. Its side effects (filing an issue, etc.) are+ // isolated from the agent's discarded worktree — the payload is the only+ // durable channel out. Errors are caught: a hook failure must not strand the+ // rest of finalize. See taskTypeHooks.js + the design plan.+ //+ // Ordering (#2727): this runs BEFORE completeAgent because the hook result is+ // the only signal that can judge a programmatic-I/O run (see+ // evaluateSuccessCriteria), and completeAgent is what writes the learning+ // verdict — so the judgement has to exist first. Safe for every other task+ // shape: dispatchTaskOutputHook is a no-op unless the type registers a hook+ // (isProgrammaticIoTaskType), so nothing else is reordered. The lane is already+ // released by this point (releaseAgentLane fires earlier, in the spawn paths),+ // and `agent:completed` — which schedules the next dequeue — still fires from+ // completeAgent below, i.e. AFTER any handoff task the hook enqueues. The cost+ // of awaiting here is that the agent still counts against the CoS concurrency+ // gate for the hook's duration, so the dispatch is hard-bounded — see+ // withOutputHookTimeout.+ const hookResult = await withOutputHookTimeout(+ dispatchTaskOutputHook({ agentId, task, success, workspacePath }),+ { agentId }+ ).catch(err => {+ emitLog('error', `❌ processTaskOutput hook threw for ${agentId} (${task?.taskType}): ${err.message}`, { agentId, error: err.message });+ // A thrown hook is a non-success signal for the type ledger (#2616) and a+ // rejected success criterion for task-learning (#2727).+ return { ran: true, threw: true };+ });++ // Success-criteria validation (issue #2344): stamp an explicit pass/fail (or+ // null-when-undeclared) verdict onto the completion result, distinct from the+ // exit-code `success`, so task-learning telemetry can distinguish "ran clean+ // but produced nothing" from a genuine success. Best-effort — a validation+ // check failure must never block finalize (falls back to the null sentinel).+ const validationPassed = await evaluateSuccessCriteria({ task, terminatedByUser, workspacePath, success, hookResult })+ .catch(err => {+ emitLog('warn', `⚠️ Success-criteria validation failed for ${agentId}: ${err.message}`, { agentId });+ return null;+ });++ // Sequential by design: completeAgent + updateTask share the cosState+ // mutex (`withStateLock`) so parallelism gains nothing, AND ordering+ // matters — if completeAgent throws, we must not mark the task completed.+ // completeAgentRun writes its own runs/<id>/metadata.json (separate lock),+ // so its place in the chain is purely about progress reporting on partial+ // failure.+ await completeAgent(agentId, {+ success,+ validationPassed,+ exitCode,+ duration,+ outputLength: outputBuffer?.length ?? 0,+ errorAnalysis,+ ...(error !== undefined ? { error } : {}),+ ...(completionReason !== undefined ? { completionReason } : {}),+ });++ if (runId) {+ await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis);+ }++ // LI hand-off execution verdict (#2779): stamp the per-proposal execution outcome into+ // the task's FEDERATED metadata as part of this completion write, so the originating peer+ // (which filed the proposal and runs LI for that app) can derive `recordProposalExecution`+ // from the terminal synced task — cross-peer parity for the #2765 LOCAL write, which only+ // lands on the peer that ran the agent.+ await stampLiExecutionVerdict(taskUpdate, task, { success, validationPassed, errorAnalysis });++ const taskResult = await updateTask(task.id, taskUpdate, taskType);+ if (taskResult?.error) {+ const label = terminatedByUser ? 'blocked' : success ? 'completed' : 'failed';+ emitLog('warn', `⚠️ Failed to update ${label} task ${task.id}: ${taskResult.error} (taskType=${taskType})`, { taskId: task.id, agentId, error: taskResult.error });+ }++ if (!success && !terminatedByUser && errorAnalysis) {+ // Lazy provider lookup — only resolve the active provider when a marker+ // fires AND the caller didn't already know the id. This keeps the+ // successful-completion hot path free of a settings-file read.+ const markerProviderId = errorAnalysis.category === 'usage-limit' || errorAnalysis.category === 'rate-limit'+ ? providerId || (await getActiveProvider())?.id+ : null;+ if (markerProviderId && errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {+ await markProviderUsageLimit(markerProviderId, errorAnalysis).catch(err => {+ emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId: markerProviderId });+ });+ }+ if (markerProviderId && errorAnalysis.category === 'rate-limit') {+ await markProviderRateLimited(markerProviderId).catch(err => {+ emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId: markerProviderId });+ });+ }+ }++ // Type-level consecutive-failure ledger (#2616): feed the per-type+ // backoff/auto-park in taskSchedule. Only SCHEDULED task types carry+ // `metadata.analysisType`; user/ad-hoc tasks don't participate — so this gate+ // deliberately does NOT use resolveTaskHookType (#2727). That resolver falls back+ // to `task.taskType`, which for an ad-hoc task is the CoS queue category+ // ('internal', 'user'); ledgering those would invent a failure ledger for a+ // "task type" that no schedule owns. "Which tasks run a hook" and "which task+ // types back off" are genuinely different questions. The pure+ // resolveTypeFailureSignal decides success vs failure vs skip — including the+ // exit-0-but-unparseable-output case that must count as a failure.+ const scheduledType = task?.metadata?.analysisType || null;+ if (scheduledType) {+ const signal = resolveTypeFailureSignal({+ success,+ terminatedByUser,+ hookResult,+ errorCategory: errorAnalysis?.category+ });+ if (signal.record !== 'skip') {+ const ledgerAppId = task?.metadata?.app || null;+ const { recordTaskTypeFailure, recordTaskTypeSuccess } = await import('./taskSchedule.js');+ const ledgerUpdate = signal.record === 'failure'+ ? recordTaskTypeFailure(scheduledType, ledgerAppId, { errorCategory: signal.category })+ : recordTaskTypeSuccess(scheduledType, ledgerAppId);+ await ledgerUpdate.catch(err => {+ emitLog('warn', `⚠️ Task-type ledger update failed for ${scheduledType}: ${err.message}`, { taskType: scheduledType, agentId });+ });+ }+ }++ await processAgentCompletion(agentId, task, success, outputBuffer);+}++/**+ * Read the finished agent's `.agent-done` payload and run the task type's+ * `processTaskOutput` hook, if it registers one. No-op for the vast majority of+ * task types (no hook). The hook receives `{ appId, success, payload, ... }` and+ * loads its own app/config — finalizeAgent stays domain-agnostic.+ */+async function dispatchTaskOutputHook({ agentId, task, success, workspacePath }) {+ // Shared resolver with evaluateSuccessCriteria's gate — "runs a hook" and "gets+ // the programmatic-I/O criterion" must stay the same question (#2727).+ const taskType = resolveTaskHookType(task);+ if (!taskType) return { ran: false };+ const { getTaskOutputHook } = await import('./taskTypeHooks.js');+ const hook = await getTaskOutputHook(taskType);+ if (!hook) return { ran: false };++ const cwd = workspacePath || task?.metadata?.repoPath || null;+ let payload = null;+ if (cwd) {+ const { DONE_SENTINEL_NAME, parseSentinelPayload, salvageSentinelPayload } = await import('../lib/agentSentinel.js');+ const { tryReadFile } = await import('../lib/fileUtils.js');+ const contents = await tryReadFile(join(cwd, DONE_SENTINEL_NAME));+ payload = parseSentinelPayload(contents).payload;+ // A less-capable (often local) reasoner can emit an almost-valid+ // `{ summary, payload }` envelope — ```json-fenced, prose-trailed, or with+ // raw newlines in the markdown body — that strict parse rejects, dropping a+ // real proposal as "unparseable-response" and filing nothing. Before giving+ // up, run the robust LLM-JSON extractor over the raw sentinel.+ if (payload == null) {+ const salvaged = await salvageSentinelPayload(contents);+ if (salvaged.payload != null) {+ payload = salvaged.payload;+ emitLog('info', `Recovered structured .agent-done payload for ${agentId} (${taskType}) via lenient JSON extraction`, { agentId });+ }+ }+ }++ const outcome = await hook({+ appId: task?.metadata?.app || null,+ success,+ payload,+ workspacePath: cwd,+ agentId,+ task,+ });+ // The outcome's `reason` is what lets finalizeAgent count a "completed" run+ // that produced nothing usable (`unparseable-response`) as a type-level+ // failure (#2616) — an exit-0 run whose structured output couldn't be parsed.+ return { ran: true, outcome };+}++/**+ * Persist task/simplify summaries for agents that ran with /simplify.+ * Shared by handleAgentCompletion (runner mode) and spawnDirectly (direct mode).+ */+export async function persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMetaFn) {+ if (!isTruthyMetaFn(task.metadata?.simplify)) return;+ const summaries = extractSimplifySummaries(outputBuffer);+ if (!summaries) return;+ // Persist whenever *either* summary is present — e.g. if the /simplify+ // marker appears at the very top of the output, taskSummary will be null+ // but simplifySummary is still worth keeping.+ if (summaries.taskSummary || summaries.simplifySummary) {+ await updateAgent(agentId, { metadata: {+ taskSummary: summaries.taskSummary || null,+ simplifySummary: summaries.simplifySummary || null+ } });+ }+}diff --git a/server/services/agentLifecycle.successCriteria.test.js b/server/services/agentFinalization.successCriteria.test.jssimilarity index 99%rename from server/services/agentLifecycle.successCriteria.test.jsrename to server/services/agentFinalization.successCriteria.test.jsindex 36d9d5e4bb..1110cb5c65 100644--- a/server/services/agentLifecycle.successCriteria.test.js+++ b/server/services/agentFinalization.successCriteria.test.js@@ -15,7 +15,7 @@ vi.mock('./agentRunTracking.js', () => ({completeAgentRun: vi.fn(),}));-import { evaluateSuccessCriteria, resolveProgrammaticIoVerdict, withOutputHookTimeout } from './agentLifecycle.js';+import { evaluateSuccessCriteria, resolveProgrammaticIoVerdict, withOutputHookTimeout } from './agentFinalization.js';import { checkForTaskCommit } from './agentRunTracking.js';describe('evaluateSuccessCriteria (#2344)', () => {diff --git a/server/services/agentImportCycles.test.js b/server/services/agentImportCycles.test.jsnew file mode 100644index 0000000000..99c498544b--- /dev/null+++ b/server/services/agentImportCycles.test.js@@ -0,0 +1,116 @@+/**+ * Regression guard for the agent-lifecycle circular-dependency cluster (#2837).+ *+ * The cluster — agentLifecycle / agentCliSpawning / agentTuiSpawning /+ * agentManagement / subAgentSpawner / cosAgents — used to contain two real+ * STATIC cycles plus three `await import(...)` workarounds whose only job was to+ * dodge the load-time cycle. Both were fixed by extracting the shared pieces+ * (finalize, summary extraction, runner sync, runner output batchers) into leaf+ * modules that nothing in the cluster is imported BY.+ *+ * This test re-derives the static import graph of `server/services` from source+ * and asserts the cluster is acyclic. It scans STATIC imports/re-exports only —+ * `await import()` is deferred to call time and therefore harmless for module+ * initialization order; a static cycle is what produces TDZ/undefined-binding+ * failures at boot.+ */++import { describe, it, expect } from 'vitest';+import { readdirSync, readFileSync } from 'fs';+import { fileURLToPath } from 'url';+import { dirname, join } from 'path';++const SERVICES_DIR = dirname(fileURLToPath(import.meta.url));++// The modules the #2837 audit named, plus the leaf modules extracted to break+// the cycle. A cycle anywhere in `server/services` will be reported, but only a+// cycle TOUCHING one of these fails the assertion — unrelated pre-existing+// cycles elsewhere are out of scope for this guard.+const CLUSTER = [+ 'agentLifecycle.js',+ 'agentCliSpawning.js',+ 'agentTuiSpawning.js',+ 'agentManagement.js',+ 'subAgentSpawner.js',+ 'cosAgents.js',+ 'cosAgentLifecycle.js',+ 'agentFinalization.js',+ 'agentSummaryExtraction.js',+ 'agentRunnerSync.js',+ 'agentRunnerOutputBatchers.js',+];++// Matches `import … from './x.js'`, `export … from './x.js'`, and bare+// `import './x.js'` at the start of a line. Deliberately does NOT match+// `await import('./x.js')` (dynamic) or the same string inside a comment,+// because a comment never starts with `import`/`export`.+const STATIC_FROM = /^\s*(?:import|export)\b[^;]*?from\s*['"]\.\/([\w.\-/]+\.js)['"]/gm;+const STATIC_BARE = /^\s*import\s*['"]\.\/([\w.\-/]+\.js)['"]/gm;++function buildStaticGraph() {+ const files = readdirSync(SERVICES_DIR).filter(f => f.endsWith('.js') && !f.includes('.test.'));+ const known = new Set(files);+ const graph = new Map();+ for (const file of files) {+ const src = readFileSync(join(SERVICES_DIR, file), 'utf-8');+ const deps = new Set();+ for (const re of [STATIC_FROM, STATIC_BARE]) {+ re.lastIndex = 0;+ let match;+ while ((match = re.exec(src)) !== null) {+ if (known.has(match[1])) deps.add(match[1]);+ }+ }+ graph.set(file, [...deps]);+ }+ return graph;+}++function findCycles(graph) {+ const cycles = new Set();+ const stack = [];+ const state = new Map(); // 1 = on stack, 2 = done+ const visit = (node) => {+ state.set(node, 1);+ stack.push(node);+ for (const dep of graph.get(node) || []) {+ if (state.get(dep) === 1) {+ cycles.add(stack.slice(stack.indexOf(dep)).concat(dep).join(' -> '));+ } else if (!state.has(dep)) {+ visit(dep);+ }+ }+ stack.pop();+ state.set(node, 2);+ };+ for (const node of graph.keys()) if (!state.has(node)) visit(node);+ return [...cycles];+}++describe('agent lifecycle cluster — no static import cycles (#2837)', () => {+ const graph = buildStaticGraph();++ it('has no static import cycle touching the agent-lifecycle cluster', () => {+ const offending = findCycles(graph).filter(cycle => CLUSTER.some(m => cycle.includes(m)));+ expect(offending, `static import cycle(s) reintroduced:\n${offending.join('\n')}`).toEqual([]);+ });++ it('keeps the extracted leaves free of back-edges into the cluster orchestrators', () => {+ // These four exist ONLY to be depended on. If any of them grows an import of+ // an orchestrator, the cycle comes straight back — fail loudly and early+ // rather than waiting for the graph walk above to go red for a subtler reason.+ const orchestrators = ['agentLifecycle.js', 'agentCliSpawning.js', 'agentTuiSpawning.js', 'agentManagement.js', 'subAgentSpawner.js'];+ for (const leaf of ['agentFinalization.js', 'agentSummaryExtraction.js', 'agentRunnerSync.js', 'agentRunnerOutputBatchers.js']) {+ const back = (graph.get(leaf) || []).filter(dep => orchestrators.includes(dep));+ expect(back, `${leaf} must not import ${back.join(', ')}`).toEqual([]);+ }+ });++ it('no longer needs the dynamic-import workaround for handleOrphanedTask', () => {+ // The cycle-dodge this issue was filed for: agentLifecycle reached+ // agentManagement via `await import()` because agentManagement imported it back.+ const src = readFileSync(join(SERVICES_DIR, 'agentLifecycle.js'), 'utf-8');+ expect(src).not.toMatch(/await import\(\s*['"]\.\/agentManagement\.js['"]\s*\)/);+ expect(src).toMatch(/import \{ handleOrphanedTask \} from '\.\/agentManagement\.js';/);+ });+});diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 9c730d72ca..3a0e42ef11 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -1,8 +1,25 @@/*** Agent Lifecycle*- * Handles agent spawning, runner synchronization, pipeline progression,- * agent completion, and worktree cleanup.+ * The spawn/completion ORCHESTRATOR: it picks a provider, prepares the+ * workspace, dispatches to one of the three spawn modes, and drives pipeline+ * progression + worktree cleanup on the way out.+ *+ * Layering (issue #2837): this module sits ABOVE the spawners+ * (`agentCliSpawning.js`, `agentTuiSpawning.js`) and `agentManagement.js`, and+ * imports all three. The pieces THEY need are therefore not allowed to live+ * here — they were extracted into leaf modules that nothing in the cluster is+ * imported by:+ *+ * - `agentFinalization.js` — finalizeAgent / releaseAgentLane (both spawners)+ * - `agentSummaryExtraction.js` — extractFinalSummary / extractSimplifySummaries+ * - `agentRunnerSync.js` — syncRunnerAgents (agentManagement, subAgentSpawner)+ * - `agentState.js` — the shared in-memory agent maps+ *+ * All of them are re-exported below so existing `from './agentLifecycle.js'`+ * imports keep resolving. Do NOT move a function back in here if a spawner or+ * agentManagement calls it — that re-creates the cycle, and+ * `agentImportCycles.test.js` will fail.*/import { join } from 'path';@@ -11,23 +28,19 @@ import { existsSync } from 'fs';import { cosEvents, emitLog } from './cosEvents.js';import { registerAgent, updateAgent, completeAgent } from './cosAgents.js';import { getConfig, updateTask, getTaskById } from './cos.js';-import { spawnAgentViaRunner, getActiveAgentsFromRunner, getRunnerHealth } from './cosRunnerClient.js';-import { getActiveProvider } from './providers.js';-import { markProviderUsageLimit, markProviderRateLimited } from './providerStatus.js';+import { spawnAgentViaRunner, getRunnerHealth } from './cosRunnerClient.js';import { MAX_TOTAL_SPAWNS, normalizeReviewers } from '../lib/validation.js';import { isInternalTaskId } from '../lib/taskParser.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';-import { analyzeAgentFailure, resolveFailedTaskUpdate, resolveTypeFailureSignal } from './agentErrorAnalysis.js';-import { createAgentRun, completeAgentRun, checkForTaskCommit } from './agentRunTracking.js';-import { isProgrammaticIoTaskType, resolveTaskHookType, isNonCommittingCoordinatorTask } from './taskTypeHooks.js';+import { analyzeAgentFailure } from './agentErrorAnalysis.js';+import { createAgentRun, checkForTaskCommit } from './agentRunTracking.js';import { buildAgentPrompt, getAppWorkspace } from './agentPromptBuilder.js';import { isOllamaClaudeProvider, isClaudeCommand, providerSuppliesGithubToken } from '../lib/providerModels.js';import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';-import { extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';import { processAgentCompletion } from './agentCompletion.js';import { releaseAppReviewMarker } from './appActivity.js';@@ -47,6 +60,9 @@ import { resolveAgentProviderAndModel } from './agentProviderResolution.js';import { prepareAgentWorkspace } from './agentWorkspacePrep.js';import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';import { runAgentCompletionCleanup } from './agentCompletionCleanup.js';+import { finalizeAgent, stampLiExecutionVerdict } from './agentFinalization.js';+import { extractFinalSummary } from './agentSummaryExtraction.js';+import { handleOrphanedTask } from './agentManagement.js';// Re-export the moved functions so existing consumers (subAgentSpawner,// agentManagement) keep importing them from agentLifecycle.js. cleanupAgentWorktree@@ -55,66 +71,18 @@ import { runAgentCompletionCleanup } from './agentCompletionCleanup.js';export { cleanupAgentWorktree };export { spawnReviewLoopFollowUp, spawnMergeRecoveryTask } from './agentWorktreeCleanup.js';export { handlePipelineProgression } from './agentCompletionCleanup.js';+// The finalize/summary/runner-sync clusters moved OUT to their own modules to+// break the static import cycle with the two spawners (issue #2837). Re-exported+// here so long-standing consumers (subAgentSpawner's barrel, agentManagement,+// existing tests) keep resolving them from agentLifecycle.js.+export { finalizeAgent, releaseAgentLane, evaluateSuccessCriteria, resolveProgrammaticIoVerdict, withOutputHookTimeout, persistSimplifySummaries } from './agentFinalization.js';+export { extractFinalSummary, extractSimplifySummaries } from './agentSummaryExtraction.js';+export { syncRunnerAgents } from './agentRunnerSync.js';const ROOT_DIR = PATHS.root;const AGENTS_DIR = PATHS.cosAgents;-/**- * Sync running agents from the runner (recovery after server restart).- * This allows us to receive completion events for agents spawned before restart.- */-export async function syncRunnerAgents() {- const agents = await getActiveAgentsFromRunner().catch(err => {- console.error(`❌ Failed to get active agents from runner: ${err.message}`);- return [];- });- if (agents.length === 0) return 0;-- console.log(`🔄 Syncing ${agents.length} running agents from CoS Runner`);-- // Get all tasks to find task data for each agent- const { getAllTasks } = await import('./cos.js');- const allTasksData = await getAllTasks().catch(() => ({ user: {}, cos: {} }));-- // Build a task lookup map from all task sources, tagging each with its taskType- const taskMap = new Map();- const addTasks = (groupedTasks, taskType) => {- if (!groupedTasks) return;- for (const tasks of Object.values(groupedTasks)) {- if (Array.isArray(tasks)) {- for (const task of tasks) {- taskMap.set(task.id, { ...task, taskType });- }- }- }- };-- addTasks(allTasksData.user?.grouped, 'user');- addTasks(allTasksData.cos?.grouped, 'internal');-- let syncedCount = 0;- for (const agent of agents) {- // Only sync if not already tracked- if (!runnerAgents.has(agent.id)) {- const task = taskMap.get(agent.taskId);-- const inferredType = isInternalTaskId(agent.taskId) ? 'internal' : 'user';- runnerAgents.set(agent.id, {- taskId: agent.taskId,- task: task || { id: agent.taskId, taskType: inferredType, description: 'Recovered from runner' },- runId: null, // Run tracking may be lost on restart- model: null,- hasStartedWorking: true,- startedAt: agent.startedAt- });- console.log(`🔄 Recovered agent ${agent.id} (task: ${agent.taskId})`);- syncedCount++;- }- }-- return syncedCount;-}/*** Spawn an agent for a task.@@ -732,525 +700,6 @@ export async function spawnViaRunner(agentId, task, opts) {return agentId;}-/**- * Extract the final summary section from agent output.- * Walks backwards from the end to find the last block of non-tool-call content.- */-export function extractFinalSummary(outputBuffer) {- if (!outputBuffer) return null;-- const codexTail = extractCodexAssistantTail(outputBuffer);- if (codexTail) return codexTail;-- const lines = outputBuffer.split('\n');- const contentLines = [];- let foundContent = false;-- for (let i = lines.length - 1; i >= 0; i--) {- const line = lines[i];- const isTool = line.startsWith('🔧') || line.startsWith(' →') || line.startsWith(' ↳') || line.startsWith('[stderr]');-- if (!isTool && line.trim()) {- contentLines.unshift(line);- foundContent = true;- } else if (foundContent && isTool) {- break;- }- }-- const summary = contentLines.join('\n').trim();- return summary || null;-}--const RE_SIMPLIFY_MARKER = /\/simplify/;-const RE_SIMPLIFY_ACTION = /\b(run|running|launch|now)\b/i;--export function extractSimplifySummaries(outputBuffer) {- if (!outputBuffer) return null;-- // Codex CLI cannot execute slash commands like /simplify, so any match- // inside its output is from a diff/grep dump that quotes source code.- // Treat the assistant tail as the task summary and skip the simplify split.- const codexTail = extractCodexAssistantTail(outputBuffer);- if (codexTail) return { taskSummary: codexTail, simplifySummary: null };-- const lines = outputBuffer.split('\n');- let simplifyIdx = -1;- for (let i = 0; i < lines.length; i++) {- if (RE_SIMPLIFY_MARKER.test(lines[i]) && RE_SIMPLIFY_ACTION.test(lines[i])) {- simplifyIdx = i;- break;- }- }- if (simplifyIdx < 0) return null;-- const taskSummary = extractFinalSummary(lines.slice(0, simplifyIdx).join('\n'));- const simplifySummary = extractFinalSummary(lines.slice(simplifyIdx + 1).join('\n'));- return { taskSummary, simplifySummary };-}--/**- * Release the execution lane and complete tool-execution tracking for a- * finishing agent. Pulled OUT of finalizeAgent so callers can fire it- * EARLY (before reading output.txt, running error analysis, or writing- * state) — neither call blocks on I/O, but lanes serialize related work- * and we don't want them held longer than necessary.- *- * Idempotent enough to be a no-op when laneName / executionId are absent- * (recovered agents post-restart, error paths that already released).- */-export function releaseAgentLane({ agentId, success, duration, exitCode, executionId, laneName, errorExecutionMessage }) {- if (laneName) release(agentId);- if (!executionId) return;- if (success) {- completeExecution(executionId, { success: true, duration });- } else {- errorExecution(executionId, { message: errorExecutionMessage || `Agent exited with code ${exitCode}`, code: exitCode });- completeExecution(executionId, { success: false });- }-}--/**- * Evaluate a completed autonomous run against its DECLARED success criteria- * (issue #2344). Distinct from the runner's exit-code `success`: it answers- * "did the run actually produce the work it was supposed to?" using the one- * machine-checkable criterion the CoS already relies on — a `[task-<id>]` commit.- *- * Returns a null sentinel when NO criterion is declared (interactive/user tasks,- * user-terminated runs, or a run with no task id / workspace to validate- * against), so downstream telemetry never conflates "not declared" with- * "declared and failed". For autonomous tasks it verifies the commit on BOTH- * success and failure — a clean exit that committed nothing is an honest miss,- * and that is exactly the signal task-learning wants. `checkForTaskCommit` is- * git-repo-gated, off the event loop, and hard-timeout-bounded, so a non-repo- * workspace or a hung git degrades to "no commit" rather than stalling finalize.- *- * `hookResult` is the programmatic-I/O output-hook result (from- * `dispatchTaskOutputHook`), which finalizeAgent resolves BEFORE calling this so- * those task types can be judged by their real deliverable; `success` is the- * runner's exit-code verdict that hook result is weighed against. Both are- * absent/null for every other task shape.- */-export async function evaluateSuccessCriteria({ task, terminatedByUser, workspacePath, success = false, hookResult = null }) {- if (terminatedByUser) return null;- const taskType = task?.taskType || 'user';- // The SCHEDULED type (`metadata.analysisType`) if any, else the queue category —- // the same resolution the programmatic-I/O gate uses, reused for the coordinator- // gate below so both key on the task's real type, not the CoS bucket ('internal').- const scheduledType = resolveTaskHookType(task);- // Programmatic-I/O tasks (taskTypeHooks.js) declare their OWN criterion — the- // sentinel parsed and the hook accepted it — so this branch comes FIRST: it is- // keyed on the hook result rather than on a workspace/commit, and must not be- // pre-empted by the `!workspacePath` bail below (a hook that already ran and- // threw is a real verdict even if the worktree is gone). Their prompts- // explicitly FORBID committing or opening a PR (the worktree is discarded), so- // the `[task-<id>]` commit check would mark every correct run a failure (#2700).- // Judging them purely by exit code instead is also wrong: an exit-0 run whose- // `.agent-done` sentinel was missing/malformed, or whose hook threw, produced- // nothing usable and must be recorded as the failure it is (#2727).- if (isProgrammaticIoTaskType(scheduledType)) {- return resolveProgrammaticIoVerdict({ success, hookResult });- }- // Interactive/user tasks declare no machine-checkable criterion; neither does- // a run missing the task id or workspace needed to validate.- if (taskType === 'user' || !task?.id || !workspacePath) return null;- // Pipeline/media tasks deliver artifacts, not a `[task-<id>]` commit — the- // commit criterion doesn't apply, so don't mislabel a clean artifact run as a- // validation miss (which would also pollute the correlation window). null =- // no commit criterion declared for this task shape. Unlike programmatic-I/O- // tasks they register no output hook, so there is no deliverable signal to- // judge them by — they stay exit-code-judged (unchanged by #2727).- if (task?.metadata?.pipeline || task?.metadata?.mediaJob) return null;- // gh/git/external COORDINATOR task types (NON_COMMITTING_COORDINATOR_TASK_TYPES in- // taskTypeHooks.js — branch-reconcile/issue-reconcile/branch-cleanup/jira-status-report)- // deliver their work as a side effect — a merged PR, a resolved conflict, a deleted- // branch, a posted report — and by design NEVER produce a `[task-<id>]` commit. Because- // their workspacePath IS set (the app's live checkout), the commit check above would- // return false on every SUCCESSFUL run and drive their learning bucket to ~0% (#2696) —- // the same artifact #2700 fixed for the programmatic-I/O reasoning run. They register no- // output hook, so like pipeline/media jobs there is no deliverable signal to judge them- // by; fall back to the exit code (null = criterion undeclared). Uses the predicate (not a- // bare `scheduledType` lookup) so the archived `taskAnalysisType` shape resolves the same- // way the learning bucket does — see isNonCommittingCoordinatorTask.- if (isNonCommittingCoordinatorTask(task)) return null;- return await checkForTaskCommit(task.id, workspacePath);-}--/**- * The programmatic-I/O success criterion (#2727): "the agent's structured output- * parsed and the output hook accepted it". Pure.- *- * The question this answers is about the AGENT'S OUTPUT, not about whether the- * hook's downstream side effect ultimately landed. So a hook that accepted the- * payload and then couldn't reach the tracker (`file-failed`, `tracker-read-failed`)- * is NOT a failure of the run: the reasoning was sound and delivered, and a forge- * outage is environmental. Blaming the run would tank the type's measured success- * rate — and, through the shared classification below, auto-park the whole task- * type — every time `gh` has a bad afternoon. Deliberate, not inherited: raised in- * review on #2727 and kept.- *- * Delegates the accept/reject classification to `resolveTypeFailureSignal`, the- * same pure decision the #2616 type-level failure ledger uses — so the learning- * verdict and the ledger can never drift apart on what counts as a bad run, and a- * new benign reason only has to be taught to one function.- *- * Sentinel discipline throughout — three distinct answers, never collapsed:- * - `false` — the hook ran and REJECTED the output (threw, or `unparseable-response`).- * - `null` — NOTHING evaluated the output (no hook ran, it timed out, or it- * returned no structured outcome), so no criterion was declared and- * task-learning falls back to the exit code exactly as before. "Not evaluated"- * must never become "accepted".- * - `true` — the hook ran and accepted the output.- *- * @returns {boolean|null} true = accepted, false = rejected, null = undeclared- */-export function resolveProgrammaticIoVerdict({ success, hookResult }) {- if (!hookResult?.ran) return null;- // A thrown hook rejected the output. Classified FIRST: it carries no outcome (so- // it must precede the outcome-shape guard), and a rejection shouldn't hinge on- // the exit-code guard below.- if (hookResult.threw) return false;- // An absent/non-boolean exit-code verdict can't be weighed against anything.- if (typeof success !== 'boolean') return null;- // Ran, but handed back no structured outcome to read: nothing evaluated the- // output, so declare no verdict rather than defaulting to "accepted".- if (!hookResult.outcome || typeof hookResult.outcome !== 'object') return null;- // Ran, but bailed out BEFORE it ever looked at the output (its app was deleted- // mid-run, or the task carries no app). Nothing evaluated the agent's work — and- // these paths don't even record a run — so this is "undeclared", not a free- // success for the type.- if (HOOK_ABORTED_BEFORE_EVALUATION.has(hookResult.outcome.reason)) return null;- return resolveTypeFailureSignal({ success, hookResult }).record === 'success';-}--// Output-hook outcomes that mean "the hook returned before validating the agent's-// output at all" — distinct from both a rejection and an acceptance.-const HOOK_ABORTED_BEFORE_EVALUATION = new Set(['no-app', 'app-not-found']);--/**- * Hard bound on output-hook dispatch (#2727). The hook is only awaited BEFORE- * `completeAgent` so its verdict can be recorded — but `status: 'running'` is what- * the CoS concurrency gate counts (`cos.js`, default 3 slots), and that flips in- * completeAgent. So an un-bounded hook (it shells out to `gh`/`glab` and can walk- * up to 50 embeddings for semantic dedup) would hold a slot for its whole- * duration, and a HUNG one would hold it until restart — with the task stuck- * `in_progress` and the orphan reaper protecting the zombie rather than reaping- * it, because it too filters on `status === 'running'`.- *- * A timeout resolves to the "no verdict" sentinel, NOT a rejection: a hook we- * stopped waiting for told us nothing about the agent's output, so finalize- * proceeds and task-learning falls back to the exit code (the pre-#2727- * behavior). Generous by design — this is a hang backstop, not a latency budget;- * a slow-but-honest hook should still get to return its real verdict.- *- * Timing out only stops us WAITING — it can't cancel the hook, which keeps running- * and still lands its side effects (filing the issue, recording the run). That's- * the desired trade: the work completes, it just no longer pins a concurrency slot- * or gates the completion write. A late rejection is still handled (Promise.race- * subscribes to both), so it can't surface as an unhandled rejection.- */-const OUTPUT_HOOK_TIMEOUT_MS = 5 * 60_000;--export function withOutputHookTimeout(promise, { agentId, timeoutMs = OUTPUT_HOOK_TIMEOUT_MS }) {- let timer;- const timeout = new Promise(resolve => {- timer = setTimeout(() => {- // Resolve BEFORE logging, and never let the log throw out of the callback:- // this runs outside the request lifecycle, so an uncaught throw here would- // crash the process — and a throw before `resolve` would leave the race- // permanently unsettled, wedging the exact finalize this timer exists to- // rescue.- resolve({ ran: false, timedOut: true });- try {- emitLog('error', `⏱️ processTaskOutput hook timed out after ${timeoutMs}ms for ${agentId} — finalizing with no verdict`, { agentId });- } catch (err) {- console.error(`❌ Failed to log output-hook timeout for ${agentId}: ${err.message}`);- }- }, timeoutMs);- // Never let the backstop itself hold the event loop open.- timer.unref?.();- });- return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));-}--/**- * Stamp an LI hand-off's per-proposal execution verdict into a completion `taskUpdate`'s- * federated metadata (#2779), mutating `taskUpdate.metadata` in place. Shared by every- * agent-completion path that marks an LI hand-off task terminal — finalizeAgent (the main- * path) AND the post-restart recovery path in handleAgentCompletion — so a hand-off that- * completes through a bypass still federates its outcome to the originating peer (codex P2);- * without this only finalizeAgent-completed hand-offs would ever reach peer A.- *- * `buildLiExecutionVerdict` reuses the exact validation-authoritative outcome + environmental- * gate the LOCAL #2765 write uses, so both peers record the identical verdict; a non-hand-off- * task (no `liProposal`) or an environmental completion yields null (no stamp). Best-effort- * and defensive (runs outside the request lifecycle): a lazy-import/build failure logs and- * leaves `taskUpdate` unstamped rather than throwing into the completion path. Lazy imports- * keep the taskLearning/LI graphs off agentLifecycle's static chain.- *- * @param {object} taskUpdate the update object about to be passed to updateTask (mutated)- * @param {object} task the persisted task (carries `metadata.liProposal` when a hand-off)- * @param {{ success:boolean, validationPassed?:boolean|null, errorAnalysis?:object|null }} signals- * @returns {Promise<object>} the same `taskUpdate` (stamped when applicable)- */-async function stampLiExecutionVerdict(taskUpdate, task, { success, validationPassed = null, errorAnalysis = null } = {}) {- const liProposal = task?.metadata?.liProposal || null;- if (!liProposal) return taskUpdate;- try {- const [{ buildLiExecutionVerdict }, { LI_EXECUTION_VERDICT_KEY }] = await Promise.all([- import('./taskLearning/metrics.js'),- import('./layeredIntelligenceOutcomes.js')- ]);- const verdict = buildLiExecutionVerdict({ liProposal, success, validationPassed, errorAnalysis, executedAt: new Date().toISOString() });- if (verdict) {- taskUpdate.metadata = { ...(taskUpdate.metadata || {}), [LI_EXECUTION_VERDICT_KEY]: verdict };- }- } catch (err) {- emitLog('warn', `⚠️ Failed to stamp LI execution verdict for task ${task?.id}: ${err.message}`, { taskId: task?.id });- }- return taskUpdate;-}--/**- * Shared end-of-run state writes for all three spawn paths- * (`handleAgentCompletion` runner-mode, TUI `finish`, direct-CLI `close`).- * Path-specific cleanup (worktree, sentinel removal, pty kill, in-memory- * map deletes) stays at the calling site; lane release + execution- * tracking should fire EARLIER via `releaseAgentLane()` — this helper- * owns the centralized state writes only.- */-export async function finalizeAgent({- agentId,- task,- runId,- providerId,- success,- exitCode,- duration,- outputBuffer,- errorAnalysis,- terminatedByUser = false,- isTruthyMetaFn,- error,- completionReason,- workspacePath = null,-}) {- if (success && isTruthyMetaFn) {- await persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMetaFn);- }-- const taskType = task?.taskType || 'user';- const taskUpdate = terminatedByUser- ? {- status: 'blocked',- metadata: {- ...task.metadata,- blockedReason: 'Terminated by user',- blockedCategory: 'user-terminated',- blockedAt: new Date().toISOString(),- },- }- : success- ? { status: 'completed' }- : await resolveFailedTaskUpdate(task, errorAnalysis, agentId);-- // Programmatic-I/O task types (e.g. layered-intelligence) run a deterministic- // post-agent step on the agent's STRUCTURED output — the parsed `.agent-done`- // payload — rather than only handling the completion sentinel. Read + dispatch- // it mode-agnostically here (the single finalize chokepoint for TUI/CLI/runner- // agents), gated on the task type actually registering an output hook so a- // normal agent pays no extra I/O. Its side effects (filing an issue, etc.) are- // isolated from the agent's discarded worktree — the payload is the only- // durable channel out. Errors are caught: a hook failure must not strand the- // rest of finalize. See taskTypeHooks.js + the design plan.- //- // Ordering (#2727): this runs BEFORE completeAgent because the hook result is- // the only signal that can judge a programmatic-I/O run (see- // evaluateSuccessCriteria), and completeAgent is what writes the learning- // verdict — so the judgement has to exist first. Safe for every other task- // shape: dispatchTaskOutputHook is a no-op unless the type registers a hook- // (isProgrammaticIoTaskType), so nothing else is reordered. The lane is already- // released by this point (releaseAgentLane fires earlier, in the spawn paths),- // and `agent:completed` — which schedules the next dequeue — still fires from- // completeAgent below, i.e. AFTER any handoff task the hook enqueues. The cost- // of awaiting here is that the agent still counts against the CoS concurrency- // gate for the hook's duration, so the dispatch is hard-bounded — see- // withOutputHookTimeout.- const hookResult = await withOutputHookTimeout(- dispatchTaskOutputHook({ agentId, task, success, workspacePath }),- { agentId }- ).catch(err => {- emitLog('error', `❌ processTaskOutput hook threw for ${agentId} (${task?.taskType}): ${err.message}`, { agentId, error: err.message });- // A thrown hook is a non-success signal for the type ledger (#2616) and a- // rejected success criterion for task-learning (#2727).- return { ran: true, threw: true };- });-- // Success-criteria validation (issue #2344): stamp an explicit pass/fail (or- // null-when-undeclared) verdict onto the completion result, distinct from the- // exit-code `success`, so task-learning telemetry can distinguish "ran clean- // but produced nothing" from a genuine success. Best-effort — a validation- // check failure must never block finalize (falls back to the null sentinel).- const validationPassed = await evaluateSuccessCriteria({ task, terminatedByUser, workspacePath, success, hookResult })- .catch(err => {- emitLog('warn', `⚠️ Success-criteria validation failed for ${agentId}: ${err.message}`, { agentId });- return null;- });-- // Sequential by design: completeAgent + updateTask share the cosState- // mutex (`withStateLock`) so parallelism gains nothing, AND ordering- // matters — if completeAgent throws, we must not mark the task completed.- // completeAgentRun writes its own runs/<id>/metadata.json (separate lock),- // so its place in the chain is purely about progress reporting on partial- // failure.- await completeAgent(agentId, {- success,- validationPassed,- exitCode,- duration,- outputLength: outputBuffer?.length ?? 0,- errorAnalysis,- ...(error !== undefined ? { error } : {}),- ...(completionReason !== undefined ? { completionReason } : {}),- });-- if (runId) {- await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis);- }-- // LI hand-off execution verdict (#2779): stamp the per-proposal execution outcome into- // the task's FEDERATED metadata as part of this completion write, so the originating peer- // (which filed the proposal and runs LI for that app) can derive `recordProposalExecution`- // from the terminal synced task — cross-peer parity for the #2765 LOCAL write, which only- // lands on the peer that ran the agent.- await stampLiExecutionVerdict(taskUpdate, task, { success, validationPassed, errorAnalysis });-- const taskResult = await updateTask(task.id, taskUpdate, taskType);- if (taskResult?.error) {- const label = terminatedByUser ? 'blocked' : success ? 'completed' : 'failed';- emitLog('warn', `⚠️ Failed to update ${label} task ${task.id}: ${taskResult.error} (taskType=${taskType})`, { taskId: task.id, agentId, error: taskResult.error });- }-- if (!success && !terminatedByUser && errorAnalysis) {- // Lazy provider lookup — only resolve the active provider when a marker- // fires AND the caller didn't already know the id. This keeps the- // successful-completion hot path free of a settings-file read.- const markerProviderId = errorAnalysis.category === 'usage-limit' || errorAnalysis.category === 'rate-limit'- ? providerId || (await getActiveProvider())?.id- : null;- if (markerProviderId && errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {- await markProviderUsageLimit(markerProviderId, errorAnalysis).catch(err => {- emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId: markerProviderId });- });- }- if (markerProviderId && errorAnalysis.category === 'rate-limit') {- await markProviderRateLimited(markerProviderId).catch(err => {- emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId: markerProviderId });- });- }- }-- // Type-level consecutive-failure ledger (#2616): feed the per-type- // backoff/auto-park in taskSchedule. Only SCHEDULED task types carry- // `metadata.analysisType`; user/ad-hoc tasks don't participate — so this gate- // deliberately does NOT use resolveTaskHookType (#2727). That resolver falls back- // to `task.taskType`, which for an ad-hoc task is the CoS queue category- // ('internal', 'user'); ledgering those would invent a failure ledger for a- // "task type" that no schedule owns. "Which tasks run a hook" and "which task- // types back off" are genuinely different questions. The pure- // resolveTypeFailureSignal decides success vs failure vs skip — including the- // exit-0-but-unparseable-output case that must count as a failure.- const scheduledType = task?.metadata?.analysisType || null;- if (scheduledType) {- const signal = resolveTypeFailureSignal({- success,- terminatedByUser,- hookResult,- errorCategory: errorAnalysis?.category- });- if (signal.record !== 'skip') {- const ledgerAppId = task?.metadata?.app || null;- const { recordTaskTypeFailure, recordTaskTypeSuccess } = await import('./taskSchedule.js');- const ledgerUpdate = signal.record === 'failure'- ? recordTaskTypeFailure(scheduledType, ledgerAppId, { errorCategory: signal.category })- : recordTaskTypeSuccess(scheduledType, ledgerAppId);- await ledgerUpdate.catch(err => {- emitLog('warn', `⚠️ Task-type ledger update failed for ${scheduledType}: ${err.message}`, { taskType: scheduledType, agentId });- });- }- }-- await processAgentCompletion(agentId, task, success, outputBuffer);-}--/**- * Read the finished agent's `.agent-done` payload and run the task type's- * `processTaskOutput` hook, if it registers one. No-op for the vast majority of- * task types (no hook). The hook receives `{ appId, success, payload, ... }` and- * loads its own app/config — finalizeAgent stays domain-agnostic.- */-async function dispatchTaskOutputHook({ agentId, task, success, workspacePath }) {- // Shared resolver with evaluateSuccessCriteria's gate — "runs a hook" and "gets- // the programmatic-I/O criterion" must stay the same question (#2727).- const taskType = resolveTaskHookType(task);- if (!taskType) return { ran: false };- const { getTaskOutputHook } = await import('./taskTypeHooks.js');- const hook = await getTaskOutputHook(taskType);- if (!hook) return { ran: false };-- const cwd = workspacePath || task?.metadata?.repoPath || null;- let payload = null;- if (cwd) {- const { DONE_SENTINEL_NAME, parseSentinelPayload, salvageSentinelPayload } = await import('../lib/agentSentinel.js');- const { tryReadFile } = await import('../lib/fileUtils.js');- const contents = await tryReadFile(join(cwd, DONE_SENTINEL_NAME));- payload = parseSentinelPayload(contents).payload;- // A less-capable (often local) reasoner can emit an almost-valid- // `{ summary, payload }` envelope — ```json-fenced, prose-trailed, or with- // raw newlines in the markdown body — that strict parse rejects, dropping a- // real proposal as "unparseable-response" and filing nothing. Before giving- // up, run the robust LLM-JSON extractor over the raw sentinel.- if (payload == null) {- const salvaged = await salvageSentinelPayload(contents);- if (salvaged.payload != null) {- payload = salvaged.payload;- emitLog('info', `Recovered structured .agent-done payload for ${agentId} (${taskType}) via lenient JSON extraction`, { agentId });- }- }- }-- const outcome = await hook({- appId: task?.metadata?.app || null,- success,- payload,- workspacePath: cwd,- agentId,- task,- });- // The outcome's `reason` is what lets finalizeAgent count a "completed" run- // that produced nothing usable (`unparseable-response`) as a type-level- // failure (#2616) — an exit-0 run whose structured output couldn't be parsed.- return { ran: true, outcome };-}--/**- * Persist task/simplify summaries for agents that ran with /simplify.- * Shared by handleAgentCompletion (runner mode) and spawnDirectly (direct mode).- */-export async function persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMetaFn) {- if (!isTruthyMetaFn(task.metadata?.simplify)) return;- const summaries = extractSimplifySummaries(outputBuffer);- if (!summaries) return;- // Persist whenever *either* summary is present — e.g. if the /simplify- // marker appears at the very top of the output, taskSummary will be null- // but simplifySummary is still worth keeping.- if (summaries.taskSummary || summaries.simplifySummary) {- await updateAgent(agentId, { metadata: {- taskSummary: summaries.taskSummary || null,- simplifySummary: summaries.simplifySummary || null- } });- }-}/*** Extract a concise output summary for pipeline stage agents.@@ -1328,8 +777,6 @@ export async function handleAgentCompletion(agentId, exitCode, success, durationconst taskUpdate = await stampLiExecutionVerdict({ status: 'completed' }, task, { success });await updateTask(cosAgent.taskId, taskUpdate, task.taskType || 'user');} else {- // Import handleOrphanedTask dynamically to avoid circular dep with agentManagement- const { handleOrphanedTask } = await import('./agentManagement.js');await handleOrphanedTask(cosAgent.taskId, agentId, getTaskById);// If orphan recovery settled the task into a terminal `blocked` state (retry budget// exhausted), the local completion already recorded the proposal failure — so stampdiff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 7a0b4ea592..d8b34a6e32 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -35,6 +35,10 @@ import { isInternalTaskId } from '../lib/taskParser.js';const __dirname = dirname(fileURLToPath(import.meta.url));const AGENT_LIFECYCLE_SRC = readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf-8');+// finalizeAgent + stampLiExecutionVerdict moved to their own module (issue #2837)+// so both spawners can import them without cycling back through the lifecycle+// orchestrator. The source-level assertions below follow them there.+const AGENT_FINALIZATION_SRC = readFileSync(join(__dirname, 'agentFinalization.js'), 'utf-8');function deferred() {let resolve;@@ -244,20 +248,20 @@ describe('agentLifecycle — guard wiring', () => {});it('finalizeAgent stamps the LI execution verdict into the completion task write (#2779)', () => {- const idx = AGENT_LIFECYCLE_SRC.indexOf('export async function finalizeAgent');+ const idx = AGENT_FINALIZATION_SRC.indexOf('export async function finalizeAgent');expect(idx, 'finalizeAgent must exist').toBeGreaterThan(-1);- const updateIdx = AGENT_LIFECYCLE_SRC.indexOf('await updateTask(task.id, taskUpdate, taskType)', idx);+ const updateIdx = AGENT_FINALIZATION_SRC.indexOf('await updateTask(task.id, taskUpdate, taskType)', idx);expect(updateIdx, 'finalizeAgent must persist the task via updateTask').toBeGreaterThan(idx);- const body = AGENT_LIFECYCLE_SRC.slice(idx, updateIdx);+ const body = AGENT_FINALIZATION_SRC.slice(idx, updateIdx);// The verdict is stamped into taskUpdate via the shared helper BEFORE the updateTask// call, so it federates in the same write that marks the task terminal.expect(body).toMatch(/await stampLiExecutionVerdict\(taskUpdate, task, \{ success, validationPassed, errorAnalysis \}\)/);});it('stampLiExecutionVerdict builds the verdict from the task liProposal marker via the shared builder (#2779)', () => {- const idx = AGENT_LIFECYCLE_SRC.indexOf('async function stampLiExecutionVerdict');+ const idx = AGENT_FINALIZATION_SRC.indexOf('async function stampLiExecutionVerdict');expect(idx, 'stampLiExecutionVerdict must exist').toBeGreaterThan(-1);- const body = AGENT_LIFECYCLE_SRC.slice(idx, idx + 1500);+ const body = AGENT_FINALIZATION_SRC.slice(idx, idx + 1500);// Derived from the persisted task's liProposal marker via the shared builder (parity// with the local #2765 write) and merged into taskUpdate.metadata under the verdict key.expect(body).toMatch(/task\?\.metadata\?\.liProposal/);diff --git a/server/services/agentManagement.js b/server/services/agentManagement.jsindex b1ef7516f2..c0915cb7b3 100644--- a/server/services/agentManagement.js+++ b/server/services/agentManagement.js@@ -5,7 +5,6 @@* and orphaned task retry logic.*/-import { join } from 'path';import { ServerError } from '../lib/errorHandler.js';import { emitLog } from './cosEvents.js';import { completeAgent, updateAgent } from './cosAgents.js';@@ -15,7 +14,13 @@ import { unregisterSpawnedAgent } from './agents.js';import { MAX_TOTAL_SPAWNS } from '../lib/validation.js';import { isInternalTaskId } from '../lib/taskParser.js';import { activeAgents, runnerAgents, userTerminatedAgents, pausedAgents, useRunner } from './agentState.js';-import { cleanupAgentWorktree, syncRunnerAgents } from './agentLifecycle.js';+// Both were extracted out of agentLifecycle.js (issue #2837) so this module no+// longer depends on the lifecycle orchestrator — which depends on THIS module+// for handleOrphanedTask. Importing them from their own leaf modules is what+// lets that edge be a plain static import instead of a dynamic-import dodge.+import { cleanupAgentWorktree } from './agentWorktreeCleanup.js';+import { syncRunnerAgents } from './agentRunnerSync.js';+import { flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';import { checkForTaskCommit } from './agentRunTracking.js';import { PATHS } from '../lib/fileUtils.js';import { killProcessTree } from '../lib/bufferedSpawn.js';@@ -60,10 +65,8 @@ async function terminateRunnerAgent(agentId, runnerFn, errorMessage, blockedReasif (result.success) {// Drain + drop this agent's runner output batcher before the terminal// record so pending ~250ms-batched output lands first, and the Map entry- // doesn't leak if the runner never emits a later completion event. Dynamic- // import avoids a static cycle (subAgentSpawner statically re-exports this- // module). flushRunnerOutputBatcher is a no-op if no batcher exists.- const { flushRunnerOutputBatcher } = await import('./subAgentSpawner.js');+ // doesn't leak if the runner never emits a later completion event.+ // flushRunnerOutputBatcher is a no-op if no batcher exists.await flushRunnerOutputBatcher(agentId);await completeAgent(agentId, { success: false, error: errorMessage });const task = agentInfo?.task;diff --git a/server/services/agentManagement.test.js b/server/services/agentManagement.test.jsindex c7c2a2f5fd..0fe7475745 100644--- a/server/services/agentManagement.test.js+++ b/server/services/agentManagement.test.js@@ -69,10 +69,9 @@ vi.mock('./agents.js', () => ({ unregisterSpawnedAgent: vi.fn() }));vi.mock('./executionLanes.js', () => ({ release: vi.fn() }));vi.mock('./toolStateMachine.js', () => ({ completeExecution: vi.fn(), errorExecution: vi.fn() }));vi.mock('./shell.js', () => ({ writeToSession: vi.fn(), killSession: vi.fn() }));-vi.mock('./agentLifecycle.js', () => ({- cleanupAgentWorktree: vi.fn(),- syncRunnerAgents: vi.fn().mockResolvedValue(0)-}));+vi.mock('./agentWorktreeCleanup.js', () => ({ cleanupAgentWorktree: vi.fn() }));+vi.mock('./agentRunnerSync.js', () => ({ syncRunnerAgents: vi.fn().mockResolvedValue(0) }));+vi.mock('./agentRunnerOutputBatchers.js', () => ({ flushRunnerOutputBatcher: vi.fn().mockResolvedValue(undefined) }));vi.mock('./worktreeManager.js', () => ({ cleanupOrphanedWorktrees: vi.fn() }));vi.mock('./creativeDirector/local.js', () => ({updateRun: vi.fn().mockResolvedValue(undefined),diff --git a/server/services/agentRunnerOutputBatchers.js b/server/services/agentRunnerOutputBatchers.jsnew file mode 100644index 0000000000..6f5dbe7da5--- /dev/null+++ b/server/services/agentRunnerOutputBatchers.js@@ -0,0 +1,39 @@+/**+ * Per-agent debounced output batchers for the CoS Runner stream path.+ *+ * The runner emits `agent:output` per parsed line (see cos-runner/index.js), so+ * a chatty agent would otherwise trigger a full state load+save per line. Each+ * batcher coalesces a ~250ms window; we drain + drop it when the agent+ * completes/errors so the final lines persist before the completion event.+ *+ * Extracted from `subAgentSpawner.js` (issue #2837) so `agentManagement.js` can+ * import `flushRunnerOutputBatcher` statically. It previously reached for it via+ * `await import('./subAgentSpawner.js')` purely to dodge a cycle — the spawner+ * barrel re-exports agentManagement. Leaf module: only depends on the state+ * layer (`cosAgents.js`).+ */++import { createAgentOutputBatcher } from './cosAgents.js';++const runnerOutputBatchers = new Map();++export function getRunnerOutputBatcher(agentId) {+ let batcher = runnerOutputBatchers.get(agentId);+ if (!batcher) {+ batcher = createAgentOutputBatcher(agentId);+ runnerOutputBatchers.set(agentId, batcher);+ }+ return batcher;+}++export async function flushRunnerOutputBatcher(agentId) {+ const batcher = runnerOutputBatchers.get(agentId);+ if (!batcher) return;+ // Flush BEFORE deleting: the agent is still in `runnerAgents` at this point+ // (handleAgentCompletion removes it afterwards), so a line racing in during+ // the awaited flush lands in this same batcher instead of orphaning a new+ // one. The `agent:output` guard in the spawner drops any truly+ // post-completion stray.+ await batcher.flush();+ runnerOutputBatchers.delete(agentId);+}diff --git a/server/services/agentRunnerSync.js b/server/services/agentRunnerSync.jsnew file mode 100644index 0000000000..e6eb7cc5f7--- /dev/null+++ b/server/services/agentRunnerSync.js@@ -0,0 +1,72 @@+/**+ * Runner agent recovery.+ *+ * Rehydrates the in-memory `runnerAgents` map from the CoS Runner after a+ * server restart, so completion events for agents spawned before the restart+ * still land. Extracted from `agentLifecycle.js` (issue #2837): both+ * `agentManagement.js` and `subAgentSpawner.js` need it, and importing it from+ * the lifecycle orchestrator dragged that whole module graph into a cycle.+ *+ * Leaf with respect to the agent cluster — must not import `agentLifecycle.js`+ * or `agentManagement.js` (enforced by `agentImportCycles.test.js`).+ */++import { getActiveAgentsFromRunner } from './cosRunnerClient.js';+import { isInternalTaskId } from '../lib/taskParser.js';+import { runnerAgents } from './agentState.js';++/**+ * Sync running agents from the runner (recovery after server restart).+ * This allows us to receive completion events for agents spawned before restart.+ */+export async function syncRunnerAgents() {+ const agents = await getActiveAgentsFromRunner().catch(err => {+ console.error(`❌ Failed to get active agents from runner: ${err.message}`);+ return [];+ });+ if (agents.length === 0) return 0;++ console.log(`🔄 Syncing ${agents.length} running agents from CoS Runner`);++ // Get all tasks to find task data for each agent+ const { getAllTasks } = await import('./cos.js');+ const allTasksData = await getAllTasks().catch(() => ({ user: {}, cos: {} }));++ // Build a task lookup map from all task sources, tagging each with its taskType+ const taskMap = new Map();+ const addTasks = (groupedTasks, taskType) => {+ if (!groupedTasks) return;+ for (const tasks of Object.values(groupedTasks)) {+ if (Array.isArray(tasks)) {+ for (const task of tasks) {+ taskMap.set(task.id, { ...task, taskType });+ }+ }+ }+ };++ addTasks(allTasksData.user?.grouped, 'user');+ addTasks(allTasksData.cos?.grouped, 'internal');++ let syncedCount = 0;+ for (const agent of agents) {+ // Only sync if not already tracked+ if (!runnerAgents.has(agent.id)) {+ const task = taskMap.get(agent.taskId);++ const inferredType = isInternalTaskId(agent.taskId) ? 'internal' : 'user';+ runnerAgents.set(agent.id, {+ taskId: agent.taskId,+ task: task || { id: agent.taskId, taskType: inferredType, description: 'Recovered from runner' },+ runId: null, // Run tracking may be lost on restart+ model: null,+ hasStartedWorking: true,+ startedAt: agent.startedAt+ });+ console.log(`🔄 Recovered agent ${agent.id} (task: ${agent.taskId})`);+ syncedCount++;+ }+ }++ return syncedCount;+}diff --git a/server/services/agentSummaryExtraction.js b/server/services/agentSummaryExtraction.jsnew file mode 100644index 0000000000..91472d6c68--- /dev/null+++ b/server/services/agentSummaryExtraction.js@@ -0,0 +1,67 @@+/**+ * Agent output summary extraction.+ *+ * Pure, dependency-light helpers that turn a raw agent output buffer into the+ * human-readable summary the UI shows. Extracted from `agentLifecycle.js` as a+ * leaf so BOTH the finalize path (`agentFinalization.js`) and the lifecycle+ * orchestrator can use them without either importing the other (issue #2837).+ */++import { extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';++/**+ * Extract the final summary section from agent output.+ * Walks backwards from the end to find the last block of non-tool-call content.+ */+export function extractFinalSummary(outputBuffer) {+ if (!outputBuffer) return null;++ const codexTail = extractCodexAssistantTail(outputBuffer);+ if (codexTail) return codexTail;++ const lines = outputBuffer.split('\n');+ const contentLines = [];+ let foundContent = false;++ for (let i = lines.length - 1; i >= 0; i--) {+ const line = lines[i];+ const isTool = line.startsWith('🔧') || line.startsWith(' →') || line.startsWith(' ↳') || line.startsWith('[stderr]');++ if (!isTool && line.trim()) {+ contentLines.unshift(line);+ foundContent = true;+ } else if (foundContent && isTool) {+ break;+ }+ }++ const summary = contentLines.join('\n').trim();+ return summary || null;+}++const RE_SIMPLIFY_MARKER = /\/simplify/;+const RE_SIMPLIFY_ACTION = /\b(run|running|launch|now)\b/i;++export function extractSimplifySummaries(outputBuffer) {+ if (!outputBuffer) return null;++ // Codex CLI cannot execute slash commands like /simplify, so any match+ // inside its output is from a diff/grep dump that quotes source code.+ // Treat the assistant tail as the task summary and skip the simplify split.+ const codexTail = extractCodexAssistantTail(outputBuffer);+ if (codexTail) return { taskSummary: codexTail, simplifySummary: null };++ const lines = outputBuffer.split('\n');+ let simplifyIdx = -1;+ for (let i = 0; i < lines.length; i++) {+ if (RE_SIMPLIFY_MARKER.test(lines[i]) && RE_SIMPLIFY_ACTION.test(lines[i])) {+ simplifyIdx = i;+ break;+ }+ }+ if (simplifyIdx < 0) return null;++ const taskSummary = extractFinalSummary(lines.slice(0, simplifyIdx).join('\n'));+ const simplifySummary = extractFinalSummary(lines.slice(simplifyIdx + 1).join('\n'));+ return { taskSummary, simplifySummary };+}diff --git a/server/services/agentSummaryExtraction.test.js b/server/services/agentSummaryExtraction.test.jsindex bb2f977798..6b7195e80e 100644--- a/server/services/agentSummaryExtraction.test.js+++ b/server/services/agentSummaryExtraction.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { extractFinalSummary, extractSimplifySummaries } from './agentLifecycle.js';+import { extractFinalSummary, extractSimplifySummaries } from './agentSummaryExtraction.js';describe('extractFinalSummary', () => {it('returns the last block of non-tool text', () => {diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.jsindex 9364726e93..916e313a17 100644--- a/server/services/agentTuiSpawning.js+++ b/server/services/agentTuiSpawning.js@@ -15,7 +15,7 @@ import { updateAgent } from './cosAgents.js';import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';import { createOutputSpooler } from './agentTuiSpawning/outputSpooler.js';import { captureWorktreeDiff, worktreeHasChanges, resolveErrorAnalysis } from './agentTuiSpawning/finalizeHelpers.js';-import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';+import { finalizeAgent, releaseAgentLane } from './agentFinalization.js';import { activeAgents, userTerminatedAgents, pausedAgents } from './agentState.js';import { PATHS } from '../lib/fileUtils.js';import { DONE_SENTINEL_NAME, parseSentinelPayload } from '../lib/agentSentinel.js';diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.jsindex c08b838cd5..9a539fb308 100644--- a/server/services/agentTuiSpawning.test.js+++ b/server/services/agentTuiSpawning.test.js@@ -58,7 +58,7 @@ vi.mock('./agentCompletion.js', () => ({processAgentCompletion: vi.fn().mockResolvedValue(undefined)}));-vi.mock('./agentLifecycle.js', () => ({+vi.mock('./agentFinalization.js', () => ({persistSimplifySummaries: vi.fn().mockResolvedValue(undefined),finalizeAgent: vi.fn().mockResolvedValue(undefined),releaseAgentLane: vi.fn()@@ -164,7 +164,7 @@ import { readFile } from 'fs/promises';import { execFile } from 'child_process';import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';import * as shellService from './shell.js';-import * as agentLifecycle from './agentLifecycle.js';+import * as agentLifecycle from './agentFinalization.js';import * as agentErrorAnalysis from './agentErrorAnalysis.js';import * as cosAgents from './cosAgents.js';import * as gitService from './git.js';diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.jsindex 4d5c8fc528..6292246fdb 100644--- a/server/services/cosAgentLifecycle.js+++ b/server/services/cosAgentLifecycle.js@@ -365,14 +365,21 @@ export async function terminateAgent(agentId) {}// Pause an agent without completing its task or cleaning up its worktree.+//+// The three delegations below stay DYNAMIC on purpose (#2837): this module is+// the agent STATE layer that `agentManagement.js` builds on (via the+// `cosAgents.js` barrel), so a static import here would invert the layering and+// reintroduce a cycle. They now target `agentManagement.js` directly rather than+// the `subAgentSpawner.js` barrel, so the deferred load pulls in one module+// instead of the entire spawner graph.export async function pauseAgent(agentId, reason = null) {- const { pauseAgent: pauseAgentFromSpawner } = await import('./subAgentSpawner.js');+ const { pauseAgent: pauseAgentFromSpawner } = await import('./agentManagement.js');return pauseAgentFromSpawner(agentId, reason);}// Force kill an agent with SIGKILL (immediate, no graceful shutdown)export async function killAgent(agentId) {- const { killAgent: killAgentFromSpawner } = await import('./subAgentSpawner.js');+ const { killAgent: killAgentFromSpawner } = await import('./agentManagement.js');return killAgentFromSpawner(agentId);}@@ -444,7 +451,7 @@ export async function sendBtwToAgent(agentId, message) {// Get process stats for an agent (CPU, memory)export async function getAgentProcessStats(agentId) {- const { getAgentProcessStats: getStatsFromSpawner } = await import('./subAgentSpawner.js');+ const { getAgentProcessStats: getStatsFromSpawner } = await import('./agentManagement.js');return getStatsFromSpawner(agentId);}diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex ddf0fc9a54..f020ff06f8 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -11,13 +11,18 @@*/import { join } from 'path';-import { readFile, readdir, rm, stat } from 'fs/promises';+import { readdir, rm, stat } from 'fs/promises';import { existsSync } from 'fs';import { emitLog, cosEvents } from './cosEvents.js';-import { createAgentOutputBatcher, updateAgent, completeAgent } from './cosAgents.js';+import { updateAgent, completeAgent } from './cosAgents.js';import { initProviderStatus } from './providerStatus.js';import { onCosRunnerEvent, initCosRunnerConnection, isRunnerAvailable } from './cosRunnerClient.js';-import { ensureDir, loadSlashdoFile, PATHS } from '../lib/fileUtils.js';+import { loadSlashdoFile, PATHS } from '../lib/fileUtils.js';+import { getRunnerOutputBatcher, flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';+import { syncRunnerAgents } from './agentRunnerSync.js';+import { handleAgentCompletion, spawnAgentForTask } from './agentLifecycle.js';+import { cleanupOrphanedAgents, terminateAgent } from './agentManagement.js';+import { completeAgentRun } from './agentRunTracking.js';// ─── Shared state (imported from agentState.js) ──────────────────────────────export { activeAgents, runnerAgents, userTerminatedAgents, spawningTasks, useRunner, isTruthyMeta, isFalsyMeta, getActiveAgentIds } from './agentState.js';@@ -29,39 +34,19 @@ export { createAgentRun, completeAgentRun, checkForTaskCommit, extractErrorFromOexport { ERROR_PATTERNS, analyzeAgentFailure, createInvestigationTask, API_ACCESS_ERROR_CATEGORIES, maybeCreateInvestigationTask, resolveFailedTaskUpdate, MAX_TASK_RETRIES } from './agentErrorAnalysis.js';export { buildAgentPrompt, getAppWorkspace, getAppDataForTask, generateJiraTitle, createJiraTicketForTask, getClaudeMdContext, buildCompactionSection, detectSkillTemplate, loadSkillTemplate } from './agentPromptBuilder.js';export { spawnDirectly, createStreamJsonParser, summarizeToolInput, safeParse, buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv } from './agentCliSpawning.js';-export { syncRunnerAgents, spawnAgentForTask, waitForRunnerStability, spawnViaRunner, extractFinalSummary, extractPipelineOutputSummary, handlePipelineProgression, handleAgentCompletion, cleanupAgentWorktree, spawnMergeRecoveryTask, spawnReviewLoopFollowUp } from './agentLifecycle.js';+export { spawnAgentForTask, waitForRunnerStability, spawnViaRunner, extractPipelineOutputSummary, handlePipelineProgression, handleAgentCompletion, cleanupAgentWorktree, spawnMergeRecoveryTask, spawnReviewLoopFollowUp } from './agentLifecycle.js';+export { syncRunnerAgents } from './agentRunnerSync.js';+export { extractFinalSummary } from './agentSummaryExtraction.js';export { terminateAgent, pauseAgent, getActiveAgents, killAgent, getAgentProcessStats, killAllAgents, isPidAlive, cleanupOrphanedAgents, handleOrphanedTask } from './agentManagement.js';export { processAgentCompletion } from './agentCompletion.js';-const ROOT_DIR = PATHS.root;const RUNS_DIR = PATHS.runs;-// Per-agent debounced output batchers for the CoS Runner stream path. The-// runner emits `agent:output` per parsed line (see cos-runner/index.js), so a-// chatty agent would otherwise trigger a full state load+save per line. Each-// batcher coalesces a ~250ms window; we drain + drop it when the agent-// completes/errors so the final lines persist before the completion event.-const runnerOutputBatchers = new Map();--function getRunnerOutputBatcher(agentId) {- let batcher = runnerOutputBatchers.get(agentId);- if (!batcher) {- batcher = createAgentOutputBatcher(agentId);- runnerOutputBatchers.set(agentId, batcher);- }- return batcher;-}--export async function flushRunnerOutputBatcher(agentId) {- const batcher = runnerOutputBatchers.get(agentId);- if (!batcher) return;- // Flush BEFORE deleting: the agent is still in `runnerAgents` at this point- // (handleAgentCompletion removes it afterwards), so a line racing in during- // the awaited flush lands in this same batcher instead of orphaning a new- // one. The `agent:output` guard below drops any truly post-completion stray.- await batcher.flush();- runnerOutputBatchers.delete(agentId);-}+// The runner output batchers moved to their own leaf module (issue #2837) so+// agentManagement.js can import `flushRunnerOutputBatcher` statically instead of+// dynamically reaching back through this barrel. Re-exported for consumers that+// still import it from here.+export { flushRunnerOutputBatcher } from './agentRunnerOutputBatchers.js';/**@@ -123,11 +108,6 @@ async function runInitSpawner() {const runnerAvailable = await isRunnerAvailable();setUseRunner(runnerAvailable);- // Lazy-import lifecycle functions (avoids circular dep at module init time)- const { syncRunnerAgents, handleAgentCompletion, spawnAgentForTask } = await import('./agentLifecycle.js');- const { cleanupOrphanedAgents, terminateAgent } = await import('./agentManagement.js');- const { completeAgentRun } = await import('./agentRunTracking.js');-if (runnerAvailable) {console.log('🤖 Sub-agent spawner initialized (using CoS Runner)');initCosRunnerConnection();