Skip to content

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

refactor(cos): flush CoS / Agent lifecycle backlog (6 items) (#270)

[._.]/ Adam Eivy9493d9e0a6be
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index de5adc3c6c..1feb695aa3 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,9 @@
## Changed
+- **CoS agent completion paths now share `finalizeAgent` + `releaseAgentLane` helpers.** The TUI shell-session path, the direct-CLI path, and the runner-mode completion handler used to each carry their own copy of the lane release / completeAgent / completeAgentRun / updateTask / provider-marker / processAgentCompletion sequence. Drift between them silently broke one path at a time. Lane release + tool-execution tracking now run early (before output I/O) via `releaseAgentLane()`, and the centralized state writes (completeAgent → completeAgentRun → updateTask → provider markers → processAgentCompletion) go through `finalizeAgent()` — a future change in either contract is a one-place fix.
+- **CoS runner-agent map no longer leaks on hook crashes.** A throw from any post-completion step (memory extraction, JIRA push, provider marker, etc.) used to skip the final `runnerAgents.delete(agentId)` and strand the entry forever. The completion sequence is now wrapped in try/finally; the error still surfaces but the in-memory state stays coherent.
+- **TUI providers are now usable from the manual `/api/runs` runner panel.** The "Run Prompt" button on `/settings/ai-providers` was disabled for TUI providers with a hint that they had to go through CoS tasks. The server-side `executeTuiRun` branch already handled them — the client-side disable was stale.
- **Importer — auto-detect content type, in-place prose edit, and a "Replace all" toggle for re-imports.** The intake form has a new **Auto-detect** button that runs a light-tier LLM pass on the source head and pre-selects the content-type radio (still user-editable, with a confidence + reasoning hint). The review panel now has a collapsible **Prose excerpt** textarea per issue card so you can trim or correct boundaries without re-running Analyze (which burns three heavy-tier calls). Re-importing an existing series surfaces a destructive **Replace all** toggle that wipes existing issues and overwrites arc + seasons — off by default; canon is still merged additively in either mode.
- **Importer — review form no longer drifts from server-known arc roles + shapes.** The client-side hardcoded `IMPORTER_ARC_ROLES_FALLBACK` is gone — `/importer/config` (and the analyze response) now expose `arcShapeIds` alongside `arcRoles`, and the shape dropdown filters to only what the server will accept on commit. Long review sessions (~50 issues with 500K-char prose previews) also feel snappier — issue and season cards are memoized, so unedited cards skip render on every keystroke. The Season fallback label now names the actual lowest-numbered season instead of the misleading "(first season)" — accurate when seasons are sparsely numbered like [S2, S5, S99].
- **Importer — partial-commit retries no longer overwrite parallel-tab arc edits.** When the issue-loop rolls back mid-commit (`IMPORTER_PARTIAL_COMMIT_ISSUES`), the response now carries `context: { universeId, seriesId, arcAlreadyPersisted, skipArcOnRetry }`. The Importer page reads it and drops `arc` + `seasons` + `canonSelections` from the retry payload, so re-clicking Commit only re-creates the failed issues against the freshest server-side state. The screenplay split-logic prompt also no longer conflates the per-type default with a user-requested count — the act-break branch now gates on `isUserRequestedCount`.
diff --git a/DONE.md b/DONE.md
index 76c1c4e83e..050434adbd 100644
--- a/DONE.md
+++ b/DONE.md
@@ -8,6 +8,7 @@ For active roadmap see [PLAN.md](./PLAN.md). For project goals see [GOALS.md](./
## 2026-05
+- **CoS / Agent lifecycle hardening.** Six backlog items flushed in one pass. (1) TUI providers now usable from the manual `/api/runs` runner panel — the client-side disable was stale once the server-side `executeTuiRun` branch landed in `routes/runs.js`. (2) Extracted two complementary helpers in `agentLifecycle.js` so the central completion sequence is shared between runner-mode `handleAgentCompletion`, the TUI `finish` path, and the direct-CLI `close` handler: `releaseAgentLane({ agentId, success, duration, exitCode, executionId, laneName, errorExecutionMessage })` fires lane release + tool-execution tracking EARLY (before output I/O / error analysis / state writes) so other lane tasks aren't blocked, and `finalizeAgent({ agentId, task, runId, providerId, success, exitCode, duration, outputBuffer, errorAnalysis, terminatedByUser, isTruthyMetaFn, error, completionReason })` runs the centralized state writes sequentially (persistSimplifySummaries → completeAgent → completeAgentRun → updateTask → provider markers → processAgentCompletion). A future divergence in any leg is now a one-place fix. (3) Wrapped `handleAgentCompletion` in try/finally so a throw from any inner step still drops the `runnerAgents` Map entry (previously leaked forever on memory-extraction crashes, JIRA push failures, etc.). (4) Added `isTuiProvider` next to `isClaudeCliProvider` and lifted `providerTypeClass` from `AIProviders.jsx` into `client/src/utils/providers.js`. (5) Converted `spawnTuiAgent` + `spawnDirectly` from 11-positional-arg signatures to options objects. (6) Wrapped `shellService.createShellSession` for agent TUIs in a thin `createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onData, onExit })` helper. Regression-pin tests in `agentLifecycle.test.js` flipped from "documents the gap" to "asserts the guard fires."
- **Importer — section follow-ups landed.** Auto-detect content type stage (`importer-classify`, light-tier head pass that pre-selects the radio); in-place `proseExcerpt` edit affordance per issue card so users can trim/correct boundaries without re-running Analyze (3 heavy-tier calls); `replaceMode` flag wipes existing issues + overwrites arc/seasons on re-import (destructive opt-in for existing series); partial-commit retry now drops arc/seasons/canon from the retry payload via `arcAlreadyPersisted` context so a parallel-tab edit isn't overwritten; React.memo on per-issue and per-season cards (with stable patcher + memoized seasonOptions) so unedited cards skip render on keystroke; `ARC_SHAPE_IDS` exposed via `/importer/config` and `IMPORTER_ARC_ROLES_FALLBACK` retired from the client (server is now the sole source of arc roles + shape ids); screenplay-prompt split logic gates on `isUserRequestedCount` rather than conflating it with the per-type default; "(first season)" UI label replaced with the actual lowest-numbered season + title.
- **Sharing — auto-unsubscribe on local record delete.** `recordEvents.js` now hooks `deleteSeries` / `deleteUniverse` so orphaned `data/sharing/subscriptions.json` entries clean up automatically instead of logging errors on the next re-export attempt.
- **Pipeline — `spawningTasks` lifecycle.** Widened try/finally around `spawnAgentForTask` (`server/services/agentLifecycle.js`) so a throw in any async setup step releases the per-task spawn lock instead of stranding it forever.
diff --git a/PLAN.md b/PLAN.md
index 39290c8fe9..89ec8c9c9e 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -57,15 +57,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- [ ] **Native FFLF deeper test on real keyframe pairs.** Validate with last frame of clip A + first frame of clip B from the same scene; expose more pipeline knobs (cfg-scale, stg-scale, stage1-steps) if interpolation looks weak.
-### CoS / Agent lifecycle
-
-- [ ] **TUI providers in manual `/api/runs`.** Add a TUI-specific runner branch in `server/lib/aiToolkit/routes/runs.js` so devtools manual runs also open attachable shell sessions.
-- [ ] **Extract `finalizeAgent` helper shared across spawn paths.** Completion sequence is duplicated in `agentTuiSpawning.js`, `agentCliSpawning.js`, and `agentLifecycle.js#handleAgentCompletion`. A divergence in any leg silently breaks one path.
-- [ ] **Wrap `runnerAgents.delete` in `handleAgentCompletion` body with try/finally.** A throw from `completeAgent` / `completeAgentRun` / `updateTask` / `processAgentCompletion` leaks the runner-agents Map entry forever. Regression-pin tests in `agentLifecycle.test.js` document the gap.
-- [ ] **Shared `isTuiProvider` helper + client palette helper.** Mirror `isClaudeCliProvider`. Add `isTuiProvider` + lift `providerTypeClass` from `AIProviders.jsx` into `client/src/utils/providers.js`.
-- [ ] **`spawnTuiAgent` / `spawnDirectly` options-object refactor.** Convert 11 positional args + deps to a single options object before the surface area grows.
-- [ ] **Wrap `createShellSession` for agent TUIs.** Move callback/initial-command wiring into a thin `createAgentTuiSession()` in `agentTuiSpawning.js` that registers its own `pty.onData`.
-
### Voice agent
- [ ] **Voice CoS tool expansion** — `calendar_today` / `calendar_next` (existing Google Calendar MCP), `meatspace_log_workout` (wraps `meatspaceHealth.js`), `weather_now` (pick API: OpenWeather / WeatherKit / NWS), `timer_set` (reuses `agentActionExecutor.js`).
@@ -97,6 +88,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]
- [ ] **Client tests for deep routing + drag.** Smoke tests for `goToWorld(id)` URL transitions and chip-reorder ordering (mock `useSortable`).
- [ ] **Shallow-equal guard in `useMediaAnnotations` socket handler.** Speculative micro-opt; theoretical until observed.
- [ ] **Extract a `tryReadFile(path, encoding='utf8')` helper into `server/lib/fileUtils.js`.** The `readFile(path).catch(() => null)` pattern is inlined 15+ times across the codebase (`server/routes/apps.js:38` `safeReadJson`, `server/lib/fileUtils.js:505`, `server/lib/hfToken.js:16`, `server/services/agentDrafts.js:22`, `server/services/messageAccounts.js:10`, `server/services/missions.js:35`, `server/lib/tuiPromptRunner.js` new at line ~202, etc.). One helper + migrate; small win, prevents future drift. Defer until next infra pass.
+- [ ] **Sweep `provider.type === 'tui'` inline checks in client.** New `isTuiProvider` helper in `client/src/utils/providers.js` not yet adopted in `client/src/pages/AIProviders.jsx` (3 remaining inline checks at lines 262, 396, 421 of CONFIG-style chips) and `client/src/components/cos/TaskAddForm.jsx`. Low priority — these are visual chip predicates, not behavioral.
- [ ] **Skip the `text` accumulator in `promptRunner.runPromptThroughProvider` for TUI providers.** `APPEND_CHUNK(acc, chunk)` runs per stream chunk regardless of provider type, but the TUI branch (post `fix-prose-stage-override`) discards the accumulated `text` and uses `result.text` from `executeTuiRun` instead. Streams can hit hundreds of KB of screen redraws per run — gate the accumulator on `effectiveProvider.type !== 'tui'` in `onData` to skip the per-chunk string concat. Pre-existing buffer cap on `outputBuffer` inside `executeTuiRun` already bounds memory; this is a CPU/alloc micro-opt, not a correctness fix.
### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index b0cdd494a4..b40fbae57d 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -2,13 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
import socket from '../services/socket';
-import { filterSelectableModels } from '../utils/providers';
-
-const providerTypeClass = (type) => {
- if (type === 'cli') return 'bg-blue-500/20 text-blue-400';
- if (type === 'tui') return 'bg-emerald-500/20 text-emerald-400';
- return 'bg-purple-500/20 text-purple-400';
-};
+import { filterSelectableModels, providerTypeClass, isTuiProvider } from '../utils/providers';
export default function AIProviders() {
const [providers, setProviders] = useState([]);
@@ -97,7 +91,7 @@ export default function AIProviders() {
};
const supportsModelRefresh = (provider) => {
- if (provider.type === 'tui') {
+ if (isTuiProvider(provider)) {
return false;
}
// Gemini CLI doesn't require model specification
@@ -180,7 +174,7 @@ export default function AIProviders() {
};
const selectedRunProvider = providers.find(p => p.id === activeProviderId);
- const runProviderIsTui = selectedRunProvider?.type === 'tui';
+ const runProviderIsTui = isTuiProvider(selectedRunProvider);
if (loading) {
return (
@@ -340,7 +334,7 @@ export default function AIProviders() {
<div className="flex justify-between items-center">
<button
onClick={handleExecuteRun}
- disabled={!runPrompt.trim() || !activeProviderId || activeRun || runProviderIsTui}
+ disabled={!runPrompt.trim() || !activeProviderId || activeRun}
className="px-6 py-2 bg-port-success hover:bg-port-success/80 text-white rounded-lg transition-colors disabled:opacity-50"
>
{activeRun ? 'Running...' : 'Execute'}
@@ -358,7 +352,7 @@ export default function AIProviders() {
{runProviderIsTui && (
<div className="text-xs text-emerald-400 bg-emerald-500/10 border border-emerald-500/20 rounded-lg px-3 py-2">
- TUI providers run through CoS agent tasks so their terminal session can be tracked and completed.
+ TUI providers spawn a PTY-backed run that streams output here and is stoppable from the run list.
</div>
)}
@@ -424,7 +418,7 @@ export default function AIProviders() {
Headless: <code className="text-gray-300 break-all">{provider.headlessArgs.join(' ')}</code>
</p>
)}
- {provider.type === 'tui' && (
+ {isTuiProvider(provider) && (
<p className="text-xs break-words">
TUI: paste delay <span className="text-gray-300">{provider.tuiPromptDelayMs || 2500}ms</span>, idle complete <span className="text-gray-300">{provider.tuiIdleTimeoutMs || 180000}ms</span>
</p>
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index 56a8581277..5f7ce91421 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -13,3 +13,20 @@ export const CODEX_CONFIGURED_DEFAULT = 'codex-configured-default';
*/
export const filterSelectableModels = (models) =>
(models || []).filter(m => m !== CODEX_CONFIGURED_DEFAULT);
+
+/**
+ * Check if a provider is a TUI-backed agent provider. Mirror of
+ * `isTuiProvider` in server/services/agentCliSpawning.js.
+ */
+export const isTuiProvider = (provider) => provider?.type === 'tui';
+
+/**
+ * Tailwind chip classes for the provider type badge ('cli' / 'tui' / 'api').
+ * Lifted out of AIProviders.jsx so other components can render the same
+ * color treatment without redefining it.
+ */
+export const providerTypeClass = (type) => {
+ if (type === 'cli') return 'bg-blue-500/20 text-blue-400';
+ if (type === 'tui') return 'bg-emerald-500/20 text-emerald-400';
+ return 'bg-purple-500/20 text-purple-400';
+};
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 5c6243e67f..e090d5f961 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -13,14 +13,11 @@ import { homedir } from 'os';
import { cosEvents, emitLog } from './cosEvents.js';
import { updateAgent, completeAgent, appendAgentOutput } from './cosAgents.js';
import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';
-import { markProviderUsageLimit, markProviderRateLimited } from './providerStatus.js';
-import { updateTask } from './cos.js';
import { release } from './executionLanes.js';
import { completeExecution, errorExecution } from './toolStateMachine.js';
-import { analyzeAgentFailure, resolveFailedTaskUpdate } from './agentErrorAnalysis.js';
+import { analyzeAgentFailure } from './agentErrorAnalysis.js';
import { completeAgentRun } from './agentRunTracking.js';
-import { processAgentCompletion } from './agentCompletion.js';
-import { persistSimplifySummaries } from './agentLifecycle.js';
+import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';
import { activeAgents, userTerminatedAgents } from './agentState.js';
import { safeJSONParse, PATHS } from '../lib/fileUtils.js';
import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
@@ -287,6 +284,13 @@ export function buildCliSpawnConfig(provider, model) {
export const isClaudeCliProvider = (provider) =>
provider?.type === 'cli' && (provider.id === 'claude-code' || provider.id === 'claude-code-bedrock');
+/**
+ * Check if a provider is a TUI-backed agent provider (Claude Code, Codex,
+ * Gemini, etc. that run in a PTY). Used by callers that need to branch
+ * between headless CLI/API runs and TUI shell sessions.
+ */
+export const isTuiProvider = (provider) => provider?.type === 'tui';
+
/**
* Read env vars from ~/.claude/settings.json to inject into Claude CLI spawns.
* Ensures user's Bedrock/provider config (CLAUDE_CODE_USE_BEDROCK, AWS_PROFILE, etc.)
@@ -317,10 +321,31 @@ export async function getClaudeSettingsEnv() {
/**
* Spawn agent directly (fallback when runner not available).
- * `cleanupWorktreeFn` is passed in to avoid circular imports with agentLifecycle.js.
- * `isTruthyMetaFn` is passed in to avoid circular imports with subAgentSpawner.js.
+ * `cleanupWorktreeFn` and `isTruthyMetaFn` are passed in rather than
+ * imported directly. The agentLifecycle.js ↔ agentCliSpawning.js import
+ * graph is bidirectional (agentLifecycle calls `spawnDirectly`, this file
+ * calls `finalizeAgent`) and ES module hoisting handles it for top-level
+ * function references — but importing `cleanupAgentWorktree` /
+ * `isTruthyMeta` at module top level would force their `agentLifecycle`
+ * and `subAgentSpawner` modules to initialize before this one, racing
+ * the cycle in ways that surfaced as `undefined` reads on cold start.
+ * Passing them via the options object defers the lookup to call time.
*/
-export async function spawnDirectly(agentId, task, prompt, workspacePath, model, provider, runId, cliConfig, agentDir, executionId, laneName, { cleanupWorktreeFn, isTruthyMetaFn }) {
+export async function spawnDirectly({
+ agentId,
+ task,
+ prompt,
+ workspacePath,
+ model,
+ provider,
+ runId,
+ cliConfig,
+ agentDir,
+ executionId,
+ laneName,
+ cleanupWorktreeFn,
+ isTruthyMetaFn,
+}) {
const fullCommand = `${cliConfig.command} ${cliConfig.args.join(' ')} <<< "${(task.description || '').substring(0, 100)}..."`;
const ROOT_DIR = PATHS.root;
@@ -470,6 +495,30 @@ export async function spawnDirectly(agentId, task, prompt, workspacePath, model,
agentData.killTimer = null;
}
+ const terminatedByUser = userTerminatedAgents.has(agentId);
+ if (terminatedByUser) userTerminatedAgents.delete(agentId);
+
+ // If the user terminated the agent, force success=false even if the
+ // process happened to exit 0 in the race window — otherwise the run is
+ // recorded as successful while the task remains blocked. Mirrors the TUI
+ // `finish` path's `finalSuccess = terminatedByUser ? false : success`.
+ const finalSuccess = terminatedByUser ? false : success;
+ const finalError = terminatedByUser ? 'Agent terminated by user' : null;
+
+ // Release lane + complete execution tracking BEFORE the writeFile +
+ // error-analysis + state-write chain — neither call blocks on I/O, but
+ // lanes serialize related work. Fall back to outer scope when
+ // activeAgents was cleared by killAgent before close fired.
+ releaseAgentLane({
+ agentId,
+ success: finalSuccess,
+ duration,
+ exitCode: code,
+ executionId: agentData?.executionId || executionId,
+ laneName: agentData?.laneName || laneName,
+ errorExecutionMessage: finalError || undefined,
+ });
+
// Flush remaining stream parser data
if (streamParser) {
const remaining = streamParser.flush();
@@ -490,102 +539,51 @@ export async function spawnDirectly(agentId, task, prompt, workspacePath, model,
}
}
- // Release execution lane
- if (agentData?.laneName) {
- release(agentId);
- }
-
- // Complete tool execution tracking
- if (agentData?.executionId) {
- if (success) {
- completeExecution(agentData.executionId, { success: true, duration });
- } else {
- errorExecution(agentData.executionId, { message: `Agent exited with code ${code}`, code });
- completeExecution(agentData.executionId, { success: false });
- }
- }
-
await writeFile(outputFile, outputBuffer).catch(() => {});
// Use raw stream buffer for error analysis (contains full JSON with error details)
const analysisBuffer = rawStreamBuffer || outputBuffer;
- const errorAnalysis = success ? null : analyzeAgentFailure(analysisBuffer, task, model);
-
- if (success) {
- await persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMetaFn);
- }
-
- await completeAgent(agentId, {
- success,
- exitCode: code,
- duration,
- outputLength: outputBuffer.length,
- errorAnalysis
- });
-
- await completeAgentRun(agentData?.runId || runId, outputBuffer, code, duration, errorAnalysis);
-
- // Update task status with retry tracking
- // Skip if user-terminated — task already blocked by terminateAgent/killAgent
- if (userTerminatedAgents.has(agentId)) {
- userTerminatedAgents.delete(agentId);
- await updateTask(task.id, {
- status: 'blocked',
- metadata: {
- ...task.metadata,
- blockedReason: 'Terminated by user',
- blockedCategory: 'user-terminated',
- blockedAt: new Date().toISOString()
- }
- }, task.taskType || 'user');
- } else if (success) {
- await updateTask(task.id, { status: 'completed' }, task.taskType || 'user');
- } else {
- const failedUpdate = await resolveFailedTaskUpdate(task, errorAnalysis, agentId);
- await updateTask(task.id, failedUpdate, task.taskType || 'user');
-
- // Handle provider status updates on failure
- if (errorAnalysis) {
- if (errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {
- const providerId = agentData?.providerId || provider.id;
- if (providerId) {
- await markProviderUsageLimit(providerId, errorAnalysis).catch(err => {
- emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId });
- });
- }
- }
- if (errorAnalysis.category === 'rate-limit') {
- const providerId = agentData?.providerId || provider.id;
- if (providerId) {
- await markProviderRateLimited(providerId).catch(err => {
- emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId });
- });
- }
- }
- }
+ const errorAnalysis = finalSuccess ? null : analyzeAgentFailure(analysisBuffer, task, model);
+
+ // try/finally so a throw from finalizeAgent still runs the local
+ // cleanup (worktree, pid unregister, activeAgents delete). Mirrors the
+ // TUI path's pattern.
+ try {
+ await finalizeAgent({
+ agentId,
+ task,
+ runId: agentData?.runId || runId,
+ providerId: agentData?.providerId || provider.id,
+ success: finalSuccess,
+ exitCode: code,
+ duration,
+ outputBuffer,
+ errorAnalysis,
+ terminatedByUser,
+ isTruthyMetaFn,
+ error: finalError || undefined,
+ completionReason: terminatedByUser ? 'user-terminated' : undefined,
+ });
+ } finally {
+ // Clean up worktree if agent was using one. Claude Code CLI agents run
+ // `/simplify` + `/do:pr` themselves (see buildCliCompletionSection in
+ // agentPromptBuilder.js) — mirror the TUI cleanup contract so PortOS
+ // doesn't double-fire push+PR creation.
+ const directOpenPR = isTruthyMetaFn(task.metadata?.openPR);
+ const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
+ const directAgentOwnsPR = directOpenPR && (provider?.id === 'claude-code' || provider?.id === 'claude-code-bedrock');
+ await cleanupWorktreeFn(agentId, finalSuccess, {
+ openPR: directAgentOwnsPR ? false : directOpenPR,
+ requestCopilotReview: !directAgentOwnsPR && directOpenPR && isTruthyMetaFn(task.metadata?.reviewLoop),
+ skipMerge: directReviewLoopFollowUp || directAgentOwnsPR,
+ description: task.description,
+ agentOutput: outputBuffer,
+ originalTask: task
+ }).catch(err => console.error(`❌ CLI worktree cleanup failed for ${agentId}: ${err.message}`));
+
+ unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);
+ activeAgents.delete(agentId);
}
-
- // Process memory extraction and app cooldown
- await processAgentCompletion(agentId, task, success, outputBuffer);
-
- // Clean up worktree if agent was using one. Claude Code CLI agents run
- // `/simplify` + `/do:pr` themselves (see buildCliCompletionSection in
- // agentPromptBuilder.js) — mirror the TUI cleanup contract so PortOS
- // doesn't double-fire push+PR creation.
- const directOpenPR = isTruthyMetaFn(task.metadata?.openPR);
- const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
- const directAgentOwnsPR = directOpenPR && (provider?.id === 'claude-code' || provider?.id === 'claude-code-bedrock');
- await cleanupWorktreeFn(agentId, success, {
- openPR: directAgentOwnsPR ? false : directOpenPR,
- requestCopilotReview: !directAgentOwnsPR && directOpenPR && isTruthyMetaFn(task.metadata?.reviewLoop),
- skipMerge: directReviewLoopFollowUp || directAgentOwnsPR,
- description: task.description,
- agentOutput: outputBuffer,
- originalTask: task
- });
-
- unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);
- activeAgents.delete(agentId);
});
return agentId;
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index b877abf890..98c3aec544 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -29,7 +29,7 @@ import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';
import { analyzeAgentFailure, resolveFailedTaskUpdate } from './agentErrorAnalysis.js';
import { createAgentRun, completeAgentRun, checkForTaskCommit } from './agentRunTracking.js';
import { buildAgentPrompt, getAppWorkspace, getAppDataForTask, createJiraTicketForTask } from './agentPromptBuilder.js';
-import { buildCliSpawnConfig, isClaudeCliProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';
+import { buildCliSpawnConfig, isClaudeCliProvider, isTuiProvider, getClaudeSettingsEnv, spawnDirectly } from './agentCliSpawning.js';
import { extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';
import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';
import { selectModelForTask } from './agentModelSelection.js';
@@ -431,7 +431,7 @@ export async function spawnAgentForTask(task) {
}
} // end !isReadOnly
- const isTui = provider.type === 'tui';
+ const isTui = isTuiProvider(provider);
// Build the agent prompt. `provider.type` drives the light-vs-full split
// inside buildAgentPrompt — see its doc comment.
@@ -543,18 +543,40 @@ export async function spawnAgentForTask(task) {
// lane is released by the agent-completion handler when the work finishes.
try {
if (isTui) {
- return await spawnTuiAgent(agentId, task, prompt, workspacePath, selectedModel, provider, runId, cliConfig, agentDir, toolExecution.id, laneName, {
+ return await spawnTuiAgent({
+ agentId,
+ task,
+ prompt,
+ workspacePath,
+ model: selectedModel,
+ provider,
+ runId,
+ tuiConfig: cliConfig,
+ agentDir,
+ executionId: toolExecution.id,
+ laneName,
cleanupWorktreeFn: cleanupAgentWorktree,
- isTruthyMetaFn: isTruthyMeta
+ isTruthyMetaFn: isTruthyMeta,
});
}
if (useRunner) {
return await spawnViaRunner(agentId, task, { prompt, workspacePath, model: selectedModel, provider, runId, cliConfig, executionId: toolExecution.id, laneName });
}
// Direct spawn mode (fallback)
- return await spawnDirectly(agentId, task, prompt, workspacePath, selectedModel, provider, runId, cliConfig, agentDir, toolExecution.id, laneName, {
+ return await spawnDirectly({
+ agentId,
+ task,
+ prompt,
+ workspacePath,
+ model: selectedModel,
+ provider,
+ runId,
+ cliConfig,
+ agentDir,
+ executionId: toolExecution.id,
+ laneName,
cleanupWorktreeFn: cleanupAgentWorktree,
- isTruthyMetaFn: isTruthyMeta
+ isTruthyMetaFn: isTruthyMeta,
});
} finally {
spawningTasks.delete(task.id);
@@ -705,6 +727,117 @@ export function extractSimplifySummaries(outputBuffer) {
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 });
+ }
+}
+
+/**
+ * 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,
+}) {
+ 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);
+
+ // 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,
+ exitCode,
+ duration,
+ outputLength: outputBuffer?.length ?? 0,
+ errorAnalysis,
+ ...(error !== undefined ? { error } : {}),
+ ...(completionReason !== undefined ? { completionReason } : {}),
+ });
+
+ if (runId) {
+ await completeAgentRun(runId, outputBuffer, exitCode, duration, 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 });
+ });
+ }
+ }
+
+ await processAgentCompletion(agentId, task, success, outputBuffer);
+}
+
/**
* Persist task/simplify summaries for agents that ran with /simplify.
* Shared by handleAgentCompletion (runner mode) and spawnDirectly (direct mode).
@@ -900,280 +1033,274 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
const { task, runId, model, executionId, laneName } = agent;
- // Ensure taskType is set — recovered agents may lack it
- if (task && !task.taskType) {
- const id = task.id || '';
- task.taskType = isInternalTaskId(id) ? 'internal' : 'user';
- }
-
- // Release execution lane
- if (laneName) {
- release(agentId);
- }
-
- // Complete tool execution tracking
- if (executionId) {
- if (success) {
- completeExecution(executionId, { success: true, duration });
- } else {
- errorExecution(executionId, { message: `Agent exited with code ${exitCode}`, code: exitCode });
- completeExecution(executionId, { success: false });
- }
- }
-
- // Read output from agent directory
- const agentDir = join(AGENTS_DIR, agentId);
- const outputFile = join(agentDir, 'output.txt');
- let outputBuffer = '';
- if (existsSync(outputFile)) {
- outputBuffer = await readFile(outputFile, 'utf-8').catch(() => '');
- }
-
- // Post-execution validation: check for task commit even if exit code is non-zero
- let effectiveSuccess = success;
- if (!effectiveSuccess && task?.id) {
- const workspacePath = agent.workspacePath || ROOT_DIR;
- const commitFound = checkForTaskCommit(task.id, workspacePath);
- if (commitFound) {
- emitLog('warn', `Agent ${agentId} reported failure (exit ${exitCode}) but work completed - commit found for task ${task.id}`, { agentId, taskId: task.id, exitCode });
- effectiveSuccess = true;
+ // try/finally so a throw from any inner step still drops the runnerAgents
+ // entry — otherwise a memory-extraction crash etc. would strand it forever
+ // and no future spawn could reclaim the slot.
+ try {
+ // Normalize the agent's task shape — recovered agents (post-restart,
+ // via syncRunnerAgents) may lack taskType AND metadata, both of which
+ // downstream paths spread / read without a guard.
+ if (task) {
+ if (!task.taskType) {
+ const id = task.id || '';
+ task.taskType = isInternalTaskId(id) ? 'internal' : 'user';
+ }
+ if (!task.metadata) task.metadata = {};
}
- }
- // Analyze failure if applicable
- const errorAnalysis = effectiveSuccess ? null : analyzeAgentFailure(outputBuffer, task, model);
-
- // Extract pipeline output summary before completion writes metadata to disk
- if (task?.metadata?.pipeline && effectiveSuccess) {
- const workspacePath = agent.workspacePath || ROOT_DIR;
- const summary = await extractPipelineOutputSummary(task, workspacePath, outputBuffer).catch(err => {
- console.log(`⚠️ Failed to extract pipeline summary for ${agentId}: ${err.message}`);
- return null;
- });
- if (summary) {
- await updateAgent(agentId, { metadata: { outputSummary: summary } });
+ // Release the execution lane immediately — `release` is a sync Map
+ // mutation, so this just frees the slot for other tasks in the same
+ // lane. Tool-execution tracking is deferred until effectiveSuccess is
+ // known (the post-exit commit check can flip it false→true).
+ if (laneName) release(agentId);
+
+ // Read output from agent directory
+ const agentDir = join(AGENTS_DIR, agentId);
+ const outputFile = join(agentDir, 'output.txt');
+ let outputBuffer = '';
+ if (existsSync(outputFile)) {
+ outputBuffer = await readFile(outputFile, 'utf-8').catch(() => '');
}
- }
-
- if (effectiveSuccess) {
- await persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMeta);
- }
- await completeAgent(agentId, {
- success: effectiveSuccess,
- exitCode,
- duration,
- outputLength: outputBuffer.length,
- errorAnalysis
- });
-
- // Complete run tracking (skip if no runId - agent was recovered after restart)
- if (runId) {
- await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis);
- }
-
- // Update task status with retry tracking
- if (effectiveSuccess) {
- const result = await updateTask(task.id, { status: 'completed' }, task.taskType || 'user');
- if (result?.error) {
- emitLog('warn', `⚠️ Failed to mark task ${task.id} completed: ${result.error} (taskType=${task.taskType})`, { taskId: task.id, agentId, error: result.error });
- }
- } else {
- const failedUpdate = await resolveFailedTaskUpdate(task, errorAnalysis, agentId);
- const result = await updateTask(task.id, failedUpdate, task.taskType || 'user');
- if (result?.error) {
- emitLog('warn', `⚠️ Failed to update failed task ${task.id}: ${result.error} (taskType=${task.taskType})`, { taskId: task.id, agentId, error: result.error });
+ // Post-execution validation: check for task commit even if exit code is non-zero
+ let effectiveSuccess = success;
+ if (!effectiveSuccess && task?.id) {
+ const workspacePath = agent.workspacePath || ROOT_DIR;
+ const commitFound = checkForTaskCommit(task.id, workspacePath);
+ if (commitFound) {
+ emitLog('warn', `Agent ${agentId} reported failure (exit ${exitCode}) but work completed - commit found for task ${task.id}`, { agentId, taskId: task.id, exitCode });
+ effectiveSuccess = true;
+ }
}
- // Handle provider status updates on failure
- if (errorAnalysis) {
- if (errorAnalysis.category === 'usage-limit' && errorAnalysis.requiresFallback) {
- const providerId = agent.providerId || (await getActiveProvider())?.id;
- if (providerId) {
- await markProviderUsageLimit(providerId, errorAnalysis).catch(err => {
- emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId });
- });
- }
- }
- if (errorAnalysis.category === 'rate-limit') {
- const providerId = agent.providerId || (await getActiveProvider())?.id;
- if (providerId) {
- await markProviderRateLimited(providerId).catch(err => {
- emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId });
- });
- }
+ // Complete tool-execution tracking with effectiveSuccess so a
+ // commit-found promotion records consistently with completeAgent +
+ // updateTask below.
+ if (executionId) {
+ if (effectiveSuccess) {
+ completeExecution(executionId, { success: true, duration });
+ } else {
+ errorExecution(executionId, { message: `Agent exited with code ${exitCode}`, code: exitCode });
+ completeExecution(executionId, { success: false });
}
}
- }
-
- // Process memory extraction and app cooldown
- await processAgentCompletion(agentId, task, effectiveSuccess, outputBuffer);
- // Fetch agent state once for JIRA and plan-question blocks
- const { getAgent: getAgentState } = await import('./cos.js');
- const agentState = await getAgentState(agentId).catch(() => null);
+ // Analyze failure if applicable
+ const errorAnalysis = effectiveSuccess ? null : analyzeAgentFailure(outputBuffer, task, model);
- // JIRA integration: push branch, create PR, comment on ticket
- const jiraTicketId = agent.task?.metadata?.jiraTicketId;
- const jiraBranch = agent.task?.metadata?.jiraBranch;
- const jiraInstanceId = agent.task?.metadata?.jiraInstanceId;
- const jiraCreatePR = agent.task?.metadata?.jiraCreatePR;
-
- if (jiraTicketId && jiraBranch && success) {
- const workspace = agentState?.metadata?.workspacePath || ROOT_DIR;
+ // Extract pipeline output summary before completion writes metadata to disk
+ if (task?.metadata?.pipeline && effectiveSuccess) {
+ const workspacePath = agent.workspacePath || ROOT_DIR;
+ const summary = await extractPipelineOutputSummary(task, workspacePath, outputBuffer).catch(err => {
+ console.log(`⚠️ Failed to extract pipeline summary for ${agentId}: ${err.message}`);
+ return null;
+ });
+ if (summary) {
+ // .catch so a metadata-write failure doesn't skip finalizeAgent —
+ // pipeline summary is best-effort; lane release + completeAgent +
+ // updateTask + processAgentCompletion must still run.
+ await updateAgent(agentId, { metadata: { outputSummary: summary } }).catch(err => {
+ emitLog('warn', `Failed to save pipeline summary for ${agentId}: ${err.message}`, { agentId });
+ });
+ }
+ }
- let jiraTicketUrl = agent.task?.metadata?.jiraTicketUrl || null;
- if (!jiraTicketUrl && jiraInstanceId) {
- const jiraConfig = await jiraService.getInstances().catch(() => null);
- const baseUrl = jiraConfig?.instances?.[jiraInstanceId]?.baseUrl;
- if (baseUrl) jiraTicketUrl = `${baseUrl}/browse/${jiraTicketId}`;
+ // Catch + log instead of letting finalizeAgent's throw skip the rest of
+ // the cleanup (JIRA push, plan-question notification, pipeline
+ // progression, worktree cleanup). The error is still visible via
+ // emitLog + the agent's persisted state (completeAgent runs first
+ // inside finalizeAgent and is the most likely throw point — the
+ // partial-state cases are best-effort by design).
+ let finalizeError = null;
+ try {
+ await finalizeAgent({
+ agentId,
+ task,
+ runId,
+ providerId: agent.providerId,
+ success: effectiveSuccess,
+ exitCode,
+ duration,
+ outputBuffer,
+ errorAnalysis,
+ isTruthyMetaFn: isTruthyMeta,
+ });
+ } catch (err) {
+ finalizeError = err;
+ emitLog('error', `finalizeAgent threw for ${agentId} (continuing cleanup): ${err.message}`, { agentId, error: err.message });
}
- const jiraTicketRef = jiraTicketUrl ? `[${jiraTicketId}](${jiraTicketUrl})` : jiraTicketId;
- await git.push(workspace, jiraBranch).catch(err => {
- emitLog('warn', `Failed to push JIRA branch ${jiraBranch}: ${err.message}`, { agentId, ticketId: jiraTicketId });
- });
+ // Fetch agent state once for JIRA and plan-question blocks
+ const { getAgent: getAgentState } = await import('./cos.js');
+ const agentState = await getAgentState(agentId).catch(() => null);
+
+ // JIRA integration: push branch, create PR, comment on ticket
+ const jiraTicketId = agent.task?.metadata?.jiraTicketId;
+ const jiraBranch = agent.task?.metadata?.jiraBranch;
+ const jiraInstanceId = agent.task?.metadata?.jiraInstanceId;
+ const jiraCreatePR = agent.task?.metadata?.jiraCreatePR;
+
+ if (jiraTicketId && jiraBranch && effectiveSuccess) {
+ const workspace = agentState?.metadata?.workspacePath || ROOT_DIR;
+
+ let jiraTicketUrl = agent.task?.metadata?.jiraTicketUrl || null;
+ if (!jiraTicketUrl && jiraInstanceId) {
+ const jiraConfig = await jiraService.getInstances().catch(() => null);
+ const baseUrl = jiraConfig?.instances?.[jiraInstanceId]?.baseUrl;
+ if (baseUrl) jiraTicketUrl = `${baseUrl}/browse/${jiraTicketId}`;
+ }
+ const jiraTicketRef = jiraTicketUrl ? `[${jiraTicketId}](${jiraTicketUrl})` : jiraTicketId;
- let prUrl = null;
- if (jiraCreatePR !== false) {
- const { baseBranch, devBranch } = await git.getRepoBranches(workspace).catch(() => ({ baseBranch: null, devBranch: null }));
- const targetBranch = devBranch || baseBranch || 'main';
+ await git.push(workspace, jiraBranch).catch(err => {
+ emitLog('warn', `Failed to push JIRA branch ${jiraBranch}: ${err.message}`, { agentId, ticketId: jiraTicketId });
+ });
- const jiraPrBody = await git.generatePRDescription(workspace, targetBranch, jiraBranch, outputBuffer);
- const jiraPrBodyWithRef = `Resolves ${jiraTicketRef}\n\n${jiraPrBody}`;
+ let prUrl = null;
+ if (jiraCreatePR !== false) {
+ const { baseBranch, devBranch } = await git.getRepoBranches(workspace).catch(() => ({ baseBranch: null, devBranch: null }));
+ const targetBranch = devBranch || baseBranch || 'main';
- const baseTitle = await git.suggestPRTitle(workspace, targetBranch, jiraBranch, task.description);
- const jiraPrTitle = `${jiraTicketId}: ${baseTitle}`.substring(0, 100);
+ const jiraPrBody = await git.generatePRDescription(workspace, targetBranch, jiraBranch, outputBuffer);
+ const jiraPrBodyWithRef = `Resolves ${jiraTicketRef}\n\n${jiraPrBody}`;
- const prResult = await git.createPR(workspace, {
- title: jiraPrTitle,
- body: jiraPrBodyWithRef,
- base: targetBranch,
- head: jiraBranch
- }).catch(err => {
- emitLog('warn', `Failed to create PR for ${jiraTicketId}: ${err.message}`, { agentId });
- return null;
- });
+ const baseTitle = await git.suggestPRTitle(workspace, targetBranch, jiraBranch, task.description);
+ const jiraPrTitle = `${jiraTicketId}: ${baseTitle}`.substring(0, 100);
- if (prResult?.success) {
- prUrl = prResult.url;
- emitLog('success', `Created PR: ${prUrl}`, { agentId, ticketId: jiraTicketId });
+ const prResult = await git.createPR(workspace, {
+ title: jiraPrTitle,
+ body: jiraPrBodyWithRef,
+ base: targetBranch,
+ head: jiraBranch
+ }).catch(err => {
+ emitLog('warn', `Failed to create PR for ${jiraTicketId}: ${err.message}`, { agentId });
+ return null;
+ });
+
+ if (prResult?.success) {
+ prUrl = prResult.url;
+ emitLog('success', `Created PR: ${prUrl}`, { agentId, ticketId: jiraTicketId });
+ }
}
- }
- if (jiraInstanceId) {
- const commentLines = [`Agent completed task successfully.`];
- if (prUrl) {
- commentLines.push(`\n*Pull Request:* ${prUrl}`);
- } else if (jiraBranch) {
- commentLines.push(`\n*Branch:* \`${jiraBranch}\``);
+ if (jiraInstanceId) {
+ const commentLines = [`Agent completed task successfully.`];
+ if (prUrl) {
+ commentLines.push(`\n*Pull Request:* ${prUrl}`);
+ } else if (jiraBranch) {
+ commentLines.push(`\n*Branch:* \`${jiraBranch}\``);
+ }
+ await jiraService.addComment(jiraInstanceId, jiraTicketId, commentLines.join('\n')).catch(err => {
+ emitLog('warn', `Failed to comment on JIRA ticket ${jiraTicketId}: ${err.message}`, { agentId });
+ });
}
- await jiraService.addComment(jiraInstanceId, jiraTicketId, commentLines.join('\n')).catch(err => {
- emitLog('warn', `Failed to comment on JIRA ticket ${jiraTicketId}: ${err.message}`, { agentId });
+
+ const { devBranch: dev, baseBranch: base } = await git.getRepoBranches(workspace).catch(() => ({ devBranch: null, baseBranch: null }));
+ const returnBranch = dev || base || 'main';
+ await git.checkout(workspace, returnBranch).catch(err => {
+ emitLog('warn', `Failed to checkout back to ${returnBranch}: ${err.message}`, { agentId });
});
}
- const { devBranch: dev, baseBranch: base } = await git.getRepoBranches(workspace).catch(() => ({ devBranch: null, baseBranch: null }));
- const returnBranch = dev || base || 'main';
- await git.checkout(workspace, returnBranch).catch(err => {
- emitLog('warn', `Failed to checkout back to ${returnBranch}: ${err.message}`, { agentId });
- });
- }
-
- // Check for plan questions marker file (feature-ideas / plan-task needing user input)
- const planAnalysisType = task?.metadata?.analysisType;
- if (planAnalysisType === 'feature-ideas' || planAnalysisType === 'plan-task') {
- const planWorkspace = agentState?.metadata?.workspacePath || task?.metadata?.repoPath || ROOT_DIR;
- const markerPath = join(planWorkspace, '.plan-questions.md');
-
- const markerContent = await readFile(markerPath, 'utf8').catch(() => null);
- if (markerContent) {
- const titleMatch = markerContent.match(/^#\s+Plan Question:\s*(.+)/m);
- const title = titleMatch?.[1]?.trim() || 'PLAN.md item needs your input';
- const appId = task.metadata?.app;
-
- const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');
- await addNotification({
- type: NOTIFICATION_TYPES.PLAN_QUESTION,
- title,
- message: markerContent,
- priority: PRIORITY_LEVELS.MEDIUM,
- link: appId ? `/apps/${appId}/documents` : undefined,
- metadata: { appId, agentId, taskType: planAnalysisType }
- }).catch(err => {
- emitLog('warn', `Failed to create plan_question notification: ${err.message}`, { agentId });
- });
+ // Check for plan questions marker file (feature-ideas / plan-task needing user input)
+ const planAnalysisType = task?.metadata?.analysisType;
+ if (planAnalysisType === 'feature-ideas' || planAnalysisType === 'plan-task') {
+ const planWorkspace = agentState?.metadata?.workspacePath || task?.metadata?.repoPath || ROOT_DIR;
+ const markerPath = join(planWorkspace, '.plan-questions.md');
+
+ const markerContent = await readFile(markerPath, 'utf8').catch(() => null);
+ if (markerContent) {
+ const titleMatch = markerContent.match(/^#\s+Plan Question:\s*(.+)/m);
+ const title = titleMatch?.[1]?.trim() || 'PLAN.md item needs your input';
+ const appId = task.metadata?.app;
+
+ const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');
+ await addNotification({
+ type: NOTIFICATION_TYPES.PLAN_QUESTION,
+ title,
+ message: markerContent,
+ priority: PRIORITY_LEVELS.MEDIUM,
+ link: appId ? `/apps/${appId}/documents` : undefined,
+ metadata: { appId, agentId, taskType: planAnalysisType }
+ }).catch(err => {
+ emitLog('warn', `Failed to create plan_question notification: ${err.message}`, { agentId });
+ });
- await rm(markerPath).catch(() => {});
- emitLog('info', `📋 Plan question notification created: ${title}`, { agentId, appId });
+ await rm(markerPath).catch(() => {});
+ emitLog('info', `📋 Plan question notification created: ${title}`, { agentId, appId });
+ }
}
- }
- // Advance pipeline to next stage if applicable
- if (task?.metadata?.pipeline) {
- await handlePipelineProgression(task, agentId, effectiveSuccess);
- }
-
- // Advance Creative Director task chain if applicable. After a Creative
- // Director agent task (treatment or evaluate) finishes, the orchestrator
- // decides what comes next and enqueues it. Scene rendering and final
- // stitching run server-side rather than as separate CoS tasks, so they
- // never reach this hook directly. Failure marks the project failed; the
- // user can resume from the UI.
- if (task?.metadata?.creativeDirector) {
- const { handleCreativeDirectorCompletion } = await import('./creativeDirector/completionHook.js');
- handleCreativeDirectorCompletion(task, agentId, effectiveSuccess)
- .catch((err) => console.log(`⚠️ creativeDirector completion hook failed: ${err.message}`));
- }
+ // Advance pipeline to next stage if applicable
+ if (task?.metadata?.pipeline) {
+ await handlePipelineProgression(task, agentId, effectiveSuccess);
+ }
- // Clean up worktree if agent was using one (skip merge when JIRA branch — PR handles merge)
- if (!jiraBranch) {
- const taskOpenPR = isTruthyMeta(agent.task?.metadata?.openPR);
- const taskReviewLoop = isTruthyMeta(agent.task?.metadata?.reviewLoop);
- // Review-loop follow-up agents already merged via `gh pr merge` in the agent
- // body — re-merging the worktree branch into the source workspace would
- // duplicate the squashed commits, so suppress the auto-merge fallback.
- const taskReviewLoopFollowUp = isTruthyMeta(agent.task?.metadata?.reviewLoopFollowUp);
- // Claude Code CLI agents run `/simplify` + `/do:pr` themselves (see
- // buildCliCompletionSection in agentPromptBuilder.js) — they push the
- // branch and open the PR on their own. Mirror the TUI cleanup contract
- // so PortOS doesn't double-fire `gh pr create` ("a pull request already
- // exists" would preserve the worktree as a false-positive failure).
- const agentOwnsPR = taskOpenPR && (agent.providerId === 'claude-code' || agent.providerId === 'claude-code-bedrock');
- const cleanupWarnings = await cleanupAgentWorktree(agentId, success, {
- openPR: agentOwnsPR ? false : taskOpenPR,
- requestCopilotReview: !agentOwnsPR && taskOpenPR && taskReviewLoop,
- skipMerge: taskReviewLoopFollowUp || agentOwnsPR,
- description: task?.description,
- agentOutput: outputBuffer,
- originalTask: task
- });
+ // Advance Creative Director task chain if applicable. After a Creative
+ // Director agent task (treatment or evaluate) finishes, the orchestrator
+ // decides what comes next and enqueues it. Scene rendering and final
+ // stitching run server-side rather than as separate CoS tasks, so they
+ // never reach this hook directly. Failure marks the project failed; the
+ // user can resume from the UI.
+ if (task?.metadata?.creativeDirector) {
+ const { handleCreativeDirectorCompletion } = await import('./creativeDirector/completionHook.js');
+ handleCreativeDirectorCompletion(task, agentId, effectiveSuccess)
+ .catch((err) => console.log(`⚠️ creativeDirector completion hook failed: ${err.message}`));
+ }
- if (cleanupWarnings?.length > 0) {
- const { getAgent: getAgentForResult } = await import('./cos.js');
- const currentAgent = await getAgentForResult(agentId).catch(() => null);
- await updateAgent(agentId, { result: { ...currentAgent?.result, warnings: cleanupWarnings } });
-
- const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');
- const appName = task?.metadata?.appName || task?.metadata?.app || 'PortOS';
- await addNotification({
- type: NOTIFICATION_TYPES.AGENT_WARNING,
- title: `Agent cleanup issue: ${appName}`,
- description: cleanupWarnings.join('\n'),
- priority: PRIORITY_LEVELS.HIGH,
- link: '/cos/agents',
- metadata: { agentId, taskId: task?.id, warnings: cleanupWarnings }
- }).catch(err => {
- emitLog('warn', `Failed to create cleanup warning notification: ${err.message}`, { agentId });
+ // Clean up worktree if agent was using one (skip merge when JIRA branch — PR handles merge)
+ if (!jiraBranch) {
+ const taskOpenPR = isTruthyMeta(agent.task?.metadata?.openPR);
+ const taskReviewLoop = isTruthyMeta(agent.task?.metadata?.reviewLoop);
+ // Review-loop follow-up agents already merged via `gh pr merge` in the agent
+ // body — re-merging the worktree branch into the source workspace would
+ // duplicate the squashed commits, so suppress the auto-merge fallback.
+ const taskReviewLoopFollowUp = isTruthyMeta(agent.task?.metadata?.reviewLoopFollowUp);
+ // Claude Code CLI agents run `/simplify` + `/do:pr` themselves (see
+ // buildCliCompletionSection in agentPromptBuilder.js) — they push the
+ // branch and open the PR on their own. Mirror the TUI cleanup contract
+ // so PortOS doesn't double-fire `gh pr create` ("a pull request already
+ // exists" would preserve the worktree as a false-positive failure).
+ const agentOwnsPR = taskOpenPR && (agent.providerId === 'claude-code' || agent.providerId === 'claude-code-bedrock');
+ const cleanupWarnings = await cleanupAgentWorktree(agentId, effectiveSuccess, {
+ openPR: agentOwnsPR ? false : taskOpenPR,
+ requestCopilotReview: !agentOwnsPR && taskOpenPR && taskReviewLoop,
+ skipMerge: taskReviewLoopFollowUp || agentOwnsPR,
+ description: task?.description,
+ agentOutput: outputBuffer,
+ originalTask: task
});
- void spawnMergeRecoveryTask(cleanupWarnings, agentId, task, appName, currentAgent?.metadata?.sourceWorkspace).catch(err => {
- emitLog('warn', `Failed to spawn merge recovery task: ${err.message}`, { agentId, taskId: task?.id });
- });
+ if (cleanupWarnings?.length > 0) {
+ const { getAgent: getAgentForResult } = await import('./cos.js');
+ const currentAgent = await getAgentForResult(agentId).catch(() => null);
+ await updateAgent(agentId, { result: { ...currentAgent?.result, warnings: cleanupWarnings } });
+
+ const { addNotification, NOTIFICATION_TYPES, PRIORITY_LEVELS } = await import('./notifications.js');
+ const appName = task?.metadata?.appName || task?.metadata?.app || 'PortOS';
+ await addNotification({
+ type: NOTIFICATION_TYPES.AGENT_WARNING,
+ title: `Agent cleanup issue: ${appName}`,
+ description: cleanupWarnings.join('\n'),
+ priority: PRIORITY_LEVELS.HIGH,
+ link: '/cos/agents',
+ metadata: { agentId, taskId: task?.id, warnings: cleanupWarnings }
+ }).catch(err => {
+ emitLog('warn', `Failed to create cleanup warning notification: ${err.message}`, { agentId });
+ });
+
+ void spawnMergeRecoveryTask(cleanupWarnings, agentId, task, appName, currentAgent?.metadata?.sourceWorkspace).catch(err => {
+ emitLog('warn', `Failed to spawn merge recovery task: ${err.message}`, { agentId, taskId: task?.id });
+ });
+ }
}
- }
- runnerAgents.delete(agentId);
+ // Surface a finalizeAgent throw to the caller after best-effort
+ // cleanup completed — without this the runner harness would never see
+ // the failure and couldn't requeue or alert.
+ if (finalizeError) throw finalizeError;
+ } finally {
+ runnerAgents.delete(agentId);
+ }
}
/**
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index a64a0bf75e..420fa0b68a 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -541,21 +541,26 @@ function makeCompletionHarness({ taskId, agentId, throws = {}, taskType = 'user'
/**
* Inline replica of the completion flow up to and including the cleanup
- * delete. Mirrors agentLifecycle.js lines 935–987 + 1146, with branching
- * on `effectiveSuccess` as in production.
+ * delete. Mirrors agentLifecycle.js handleAgentCompletion with the
+ * try/finally added so `deleteRunner()` ALWAYS runs even when an inner
+ * step throws. This is the behavioral contract enforced by the
+ * regression tests below.
*/
async function runCompletion(harness, effectiveSuccess) {
- await harness.completeAgent(harness.agentId, { success: effectiveSuccess });
- if (harness.runId) {
- await harness.completeAgentRun(harness.runId);
- }
- if (effectiveSuccess) {
- await harness.updateTask(harness.taskId, { status: 'completed' }, harness.taskType);
- } else {
- await harness.updateTask(harness.taskId, { status: 'pending' }, harness.taskType);
+ try {
+ await harness.completeAgent(harness.agentId, { success: effectiveSuccess });
+ if (harness.runId) {
+ await harness.completeAgentRun(harness.runId);
+ }
+ if (effectiveSuccess) {
+ await harness.updateTask(harness.taskId, { status: 'completed' }, harness.taskType);
+ } else {
+ await harness.updateTask(harness.taskId, { status: 'pending' }, harness.taskType);
+ }
+ await harness.processAgentCompletion(harness.agentId, { id: harness.taskId }, effectiveSuccess, '');
+ } finally {
+ harness.deleteRunner();
}
- await harness.processAgentCompletion(harness.agentId, { id: harness.taskId }, effectiveSuccess, '');
- harness.deleteRunner();
}
describe('handleAgentCompletion — happy path', () => {
@@ -590,16 +595,16 @@ describe('handleAgentCompletion — happy path', () => {
});
});
-describe('handleAgentCompletion — error recovery (uncovered today)', () => {
+describe('handleAgentCompletion — error recovery (try/finally guard)', () => {
beforeEach(() => {
runnerAgents.clear();
});
- it('regression-pin: a throw from completeAgent (state save) prevents runner cleanup', async () => {
- // Production reference: agentLifecycle.js:939 — `await completeAgent(...)`
- // is NOT wrapped in try/catch. A throw bubbles to the caller, but more
- // importantly skips lines 940–1146, including the final
- // `runnerAgents.delete(agentId)`. The runner record is leaked.
+ it('a throw from completeAgent still removes the runner record (finally guard)', async () => {
+ // handleAgentCompletion wraps the entire completion sequence in
+ // try/finally so a throw from any inner step cannot leak the
+ // runnerAgents Map entry. The error still propagates to the caller —
+ // the finally only guards in-memory state.
runnerAgents.set('agent-C', { taskId: 'task-C' });
const h = makeCompletionHarness({
taskId: 'task-C',
@@ -609,22 +614,12 @@ describe('handleAgentCompletion — error recovery (uncovered today)', () => {
await expect(runCompletion(h, true)).rejects.toThrow('completeAgent failed');
- // BUG (documented): the runner-agents Map still has agent-C. A
- // follow-up completion event for the same agentId would re-enter
- // handleAgentCompletion and re-trigger the failing step. PLAN.md
- // backlog should track wrapping these steps in try/catch with a final
- // `runnerAgents.delete` in a finally block.
- expect(runnerAgents.has('agent-C')).toBe(true);
-
- // Downstream steps (updateTask, processAgentCompletion) never ran.
- expect(h.calls.map(c => c.step)).toEqual(['completeAgent']);
+ expect(runnerAgents.has('agent-C')).toBe(false);
+ // Downstream steps did not run, but the finally fired deleteRunner.
+ expect(h.calls.map(c => c.step)).toEqual(['completeAgent', 'deleteRunner']);
});
- it('regression-pin: a throw from updateTask leaves runner record + skips post-completion hooks', async () => {
- // Production reference: agentLifecycle.js:954 (success branch) / 960
- // (failure branch). The function only inspects `result?.error` for
- // soft-fail values — an actual thrown error bubbles up and skips
- // processAgentCompletion + the final cleanup.
+ it('a throw from updateTask still removes the runner record', async () => {
runnerAgents.set('agent-D', { taskId: 'task-D' });
const h = makeCompletionHarness({
taskId: 'task-D',
@@ -634,16 +629,11 @@ describe('handleAgentCompletion — error recovery (uncovered today)', () => {
await expect(runCompletion(h, true)).rejects.toThrow('updateTask failed');
- expect(runnerAgents.has('agent-D')).toBe(true);
- // processAgentCompletion never invoked — memory extraction skipped.
- expect(h.calls.map(c => c.step)).toEqual(['completeAgent', 'updateTask']);
+ expect(runnerAgents.has('agent-D')).toBe(false);
+ expect(h.calls.map(c => c.step)).toEqual(['completeAgent', 'updateTask', 'deleteRunner']);
});
- it('regression-pin: a throw from processAgentCompletion (hook dispatch) leaks the runner record', async () => {
- // Production reference: agentLifecycle.js:987 — the memory-extraction /
- // app-cooldown hook is called as `await processAgentCompletion(...)`
- // with no try/catch. A crash inside the hook (memory store down,
- // extraction throw) abandons the rest of the cleanup.
+ it('a throw from processAgentCompletion (hook dispatch) still removes the runner record', async () => {
runnerAgents.set('agent-E', { taskId: 'task-E' });
const h = makeCompletionHarness({
taskId: 'task-E',
@@ -653,21 +643,13 @@ describe('handleAgentCompletion — error recovery (uncovered today)', () => {
await expect(runCompletion(h, true)).rejects.toThrow('processAgentCompletion failed');
- expect(runnerAgents.has('agent-E')).toBe(true);
- // completeAgent + updateTask DID run — the task is marked completed in
- // state, but the runner record is still cached in memory. A subsequent
- // event for the same agentId hits the `if (!agent)` branch incorrectly
- // because the agent IS still cached, leading to re-attempted hook
- // dispatch that throws again.
+ expect(runnerAgents.has('agent-E')).toBe(false);
expect(h.calls.find(c => c.step === 'completeAgent')).toBeDefined();
expect(h.calls.find(c => c.step === 'updateTask')).toBeDefined();
- expect(h.calls.find(c => c.step === 'deleteRunner')).toBeUndefined();
+ expect(h.calls.find(c => c.step === 'deleteRunner')).toBeDefined();
});
- it('regression-pin: a throw from completeAgentRun (run-tracking) leaves the runner record', async () => {
- // Production reference: agentLifecycle.js:949 — only invoked when
- // runId exists. completeAgentRun writes usage stats; a write failure
- // shouldn't strand the runner-agent map.
+ it('a throw from completeAgentRun still removes the runner record', async () => {
runnerAgents.set('agent-F', { taskId: 'task-F' });
const h = makeCompletionHarness({
taskId: 'task-F',
@@ -678,7 +660,19 @@ describe('handleAgentCompletion — error recovery (uncovered today)', () => {
await expect(runCompletion(h, true)).rejects.toThrow('completeAgentRun failed');
- expect(runnerAgents.has('agent-F')).toBe(true);
+ expect(runnerAgents.has('agent-F')).toBe(false);
+ });
+});
+
+// Source-level regression: the runner-cleanup `runnerAgents.delete(agentId)`
+// MUST live inside a `finally` clause so it survives a throw from any step
+// of the completion sequence.
+describe('agentLifecycle source — try/finally guard', () => {
+ it('handleAgentCompletion wraps the body in try/finally with runnerAgents.delete inside finally', () => {
+ const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function handleAgentCompletion');
+ expect(fnStart, 'handleAgentCompletion must exist').toBeGreaterThan(-1);
+ const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
+ expect(fnBody).toMatch(/finally\s*\{[\s\S]{0,200}?runnerAgents\.delete\(agentId\)/);
});
});
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index fe3d989b70..5d59007c0c 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -11,16 +11,10 @@ import { existsSync } from 'fs';
import { appendFile, readFile, rm } from 'fs/promises';
import * as shellService from './shell.js';
import { emitLog } from './cosEvents.js';
-import { appendAgentOutputLines, updateAgent, completeAgent } from './cosAgents.js';
+import { appendAgentOutputLines, updateAgent } from './cosAgents.js';
import { registerSpawnedAgent, unregisterSpawnedAgent } from './agents.js';
-import { markProviderUsageLimit, markProviderRateLimited } from './providerStatus.js';
-import { updateTask } from './cos.js';
-import { release } from './executionLanes.js';
-import { completeExecution, errorExecution } from './toolStateMachine.js';
-import { analyzeAgentFailure, resolveFailedTaskUpdate } from './agentErrorAnalysis.js';
-import { completeAgentRun } from './agentRunTracking.js';
-import { processAgentCompletion } from './agentCompletion.js';
-import { persistSimplifySummaries } from './agentLifecycle.js';
+import { analyzeAgentFailure } from './agentErrorAnalysis.js';
+import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';
import { activeAgents, userTerminatedAgents } from './agentState.js';
import { PATHS } from '../lib/fileUtils.js';
import { resolveCliModel } from '../lib/providerModels.js';
@@ -65,6 +59,37 @@ function shellQuote(value) {
return `'${text.replace(/'/g, `'\\''`)}'`;
}
+/**
+ * Thin wrapper around `shellService.createShellSession` for the agent TUI
+ * path. Centralizes the agent-side defaults (kind, label, initialCommand)
+ * and pairs the returned session id with its underlying pty process so
+ * callers don't have to make a second `getSessionProcess` call inline.
+ *
+ * Returns `{ sessionId, ptyProcess, pid }`. When the shell service fails
+ * to create the session, `sessionId` is null and the caller is expected
+ * to bail out via its `finish` path.
+ */
+export function createAgentTuiSession({ agentId, provider, tuiConfig, cwd, onData, onExit }) {
+ const sessionId = shellService.createShellSession(null, {
+ cwd,
+ kind: 'agent-tui',
+ agentId,
+ label: `${provider.name} ${agentId}`,
+ command: tuiConfig.commandLine,
+ initialCommand: tuiConfig.commandLine,
+ env: provider.envVars || {},
+ onData,
+ onExit,
+ });
+
+ if (!sessionId) {
+ return { sessionId: null, ptyProcess: null, pid: null };
+ }
+
+ const ptyProcess = shellService.getSessionProcess(sessionId);
+ return { sessionId, ptyProcess, pid: ptyProcess?.pid || null };
+}
+
function appendModelArgs(args, model) {
const effectiveModel = resolveCliModel(model);
return effectiveModel ? [...args, '--model', effectiveModel] : args;
@@ -84,7 +109,21 @@ export function buildTuiSpawnConfig(provider, model) {
};
}
-export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model, provider, runId, tuiConfig, agentDir, executionId, laneName, { cleanupWorktreeFn, isTruthyMetaFn }) {
+export async function spawnTuiAgent({
+ agentId,
+ task,
+ prompt,
+ workspacePath,
+ model,
+ provider,
+ runId,
+ tuiConfig,
+ agentDir,
+ executionId,
+ laneName,
+ cleanupWorktreeFn,
+ isTruthyMetaFn,
+}) {
const outputFile = join(agentDir, 'output.txt');
const cwd = workspacePath && typeof workspacePath === 'string' ? workspacePath : PATHS.root;
const promptPreview = prompt.replace(/\s+/g, ' ').slice(0, 100);
@@ -164,90 +203,69 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
const finalSuccess = terminatedByUser ? false : success;
const finalError = terminatedByUser ? 'Agent terminated by user' : error;
- if (agentData?.laneName || laneName) release(agentId);
-
- const effectiveExecutionId = agentData?.executionId || executionId;
- if (effectiveExecutionId) {
- if (finalSuccess) {
- completeExecution(effectiveExecutionId, { success: true, duration });
- } else {
- errorExecution(effectiveExecutionId, { message: finalError || `TUI agent ended: ${reason}`, code: exitCode });
- completeExecution(effectiveExecutionId, { success: false });
- }
- }
+ // Release the lane + complete execution tracking BEFORE the
+ // potentially-slow error-analysis / completeAgent / processAgentCompletion
+ // chain — neither call blocks on I/O, but lanes serialize related work
+ // and we don't want them held longer than necessary.
+ releaseAgentLane({
+ agentId,
+ success: finalSuccess,
+ duration,
+ exitCode,
+ executionId: agentData?.executionId || executionId,
+ laneName: agentData?.laneName || laneName,
+ errorExecutionMessage: finalError || `TUI agent ended: ${reason}`,
+ });
// output.txt has already been incrementally appended via flushPendingLines;
// do NOT writeFile() it from outputBuffer at finalize — outputBuffer is
// capped at OUTPUT_BUFFER_CAP and would silently truncate the on-disk
// record for long runs. The append-only stream is the authoritative copy.
-
const analysisBuffer = rawBuffer || outputBuffer;
const errorAnalysis = finalSuccess ? null : analyzeAgentFailure(analysisBuffer, task, model);
- if (finalSuccess) {
- await persistSimplifySummaries(agentId, task, outputBuffer, isTruthyMetaFn);
- }
-
- await completeAgent(agentId, {
- success: finalSuccess,
- exitCode,
- duration,
- outputLength: outputBuffer.length,
- error: finalError || undefined,
- errorAnalysis,
- completionReason: reason
- });
-
- await completeAgentRun(runId, outputBuffer, exitCode, duration, errorAnalysis);
-
- if (terminatedByUser) {
- await updateTask(task.id, {
- status: 'blocked',
- metadata: {
- ...task.metadata,
- blockedReason: 'Terminated by user',
- blockedCategory: 'user-terminated',
- blockedAt: new Date().toISOString()
- }
- }, task.taskType || 'user');
- } else if (finalSuccess) {
- await updateTask(task.id, { status: 'completed' }, task.taskType || 'user');
- } else {
- const failedUpdate = await resolveFailedTaskUpdate(task, errorAnalysis, agentId);
- await updateTask(task.id, failedUpdate, task.taskType || 'user');
-
- if (errorAnalysis?.category === 'usage-limit' && errorAnalysis.requiresFallback) {
- await markProviderUsageLimit(provider.id, errorAnalysis).catch(err => {
- emitLog('warn', `Failed to mark provider unavailable: ${err.message}`, { providerId: provider.id });
- });
- }
- if (errorAnalysis?.category === 'rate-limit') {
- await markProviderRateLimited(provider.id).catch(err => {
- emitLog('warn', `Failed to mark provider rate limited: ${err.message}`, { providerId: provider.id });
- });
- }
+ // try/finally so a throw from finalizeAgent (e.g. processAgentCompletion
+ // hook crash) still runs the local cleanup — sentinel removal, worktree
+ // cleanup, pid unregister, activeAgents delete, session kill. Without
+ // this, a memory-extraction crash would strand the worktree and the
+ // shell session on disk.
+ try {
+ await finalizeAgent({
+ agentId,
+ task,
+ runId,
+ providerId: provider?.id,
+ success: finalSuccess,
+ exitCode,
+ duration,
+ outputBuffer,
+ errorAnalysis,
+ terminatedByUser,
+ isTruthyMetaFn,
+ error: finalError || undefined,
+ completionReason: reason,
+ });
+ } finally {
+ if (workspacePath) await rm(join(workspacePath, DONE_SENTINEL_NAME)).catch(() => {});
+
+ // TUI agents run /do:pr (or /do:push) themselves before signaling via
+ // .agent-done, so the system-side cleanup must NOT also push or open a
+ // PR — that would double-fire. `skipMerge` is forced on so the
+ // post-exit auto-merge doesn't trip over a branch the agent already
+ // pushed. The worktree directory itself is still cleaned up.
+ await cleanupWorktreeFn(agentId, finalSuccess, {
+ openPR: false,
+ requestCopilotReview: false,
+ skipMerge: true,
+ description: task.description,
+ agentOutput: outputBuffer,
+ originalTask: task
+ }).catch(err => emitLog('warn', `TUI worktree cleanup failed for ${agentId}: ${err.message}`, { agentId }));
+
+ if (agentData?.pid) unregisterSpawnedAgent(agentData.pid);
+ activeAgents.delete(agentId);
+ if (sessionId && shellService.getSession(sessionId)) shellService.killSession(sessionId);
}
-
- await processAgentCompletion(agentId, task, finalSuccess, outputBuffer);
- if (workspacePath) await rm(join(workspacePath, DONE_SENTINEL_NAME)).catch(() => {});
-
- // TUI agents run /do:pr (or /do:push) themselves before signaling via
- // .agent-done, so the system-side cleanup must NOT also push or open a
- // PR — that would double-fire. `skipMerge` is forced on so the
- // post-exit auto-merge doesn't trip over a branch the agent already
- // pushed. The worktree directory itself is still cleaned up.
- await cleanupWorktreeFn(agentId, finalSuccess, {
- openPR: false,
- requestCopilotReview: false,
- skipMerge: true,
- description: task.description,
- agentOutput: outputBuffer,
- originalTask: task
- });
-
- if (agentData?.pid) unregisterSpawnedAgent(agentData.pid);
- activeAgents.delete(agentId);
- if (sessionId && shellService.getSession(sessionId)) shellService.killSession(sessionId);
};
const handleData = async (data) => {
@@ -294,25 +312,22 @@ export async function spawnTuiAgent(agentId, task, prompt, workspacePath, model,
});
};
- sessionId = shellService.createShellSession(null, {
- cwd,
- kind: 'agent-tui',
+ const session = createAgentTuiSession({
agentId,
- label: `${provider.name} ${agentId}`,
- command: tuiConfig.commandLine,
- initialCommand: tuiConfig.commandLine,
- env: provider.envVars || {},
+ provider,
+ tuiConfig,
+ cwd,
onData: handleData,
- onExit: handleExit
+ onExit: handleExit,
});
+ sessionId = session.sessionId;
if (!sessionId) {
await finish({ success: false, exitCode: 1, error: 'Failed to create TUI shell session', reason: 'spawn-error' });
return null;
}
- const ptyProcess = shellService.getSessionProcess(sessionId);
- const pid = ptyProcess?.pid || null;
+ const { ptyProcess, pid } = session;
if (pid) {
registerSpawnedAgent(pid, {
fullCommand: tuiConfig.commandLine,
diff --git a/server/services/agentTuiSpawning.test.js b/server/services/agentTuiSpawning.test.js
index 928d82ee09..e19c098ba8 100644
--- a/server/services/agentTuiSpawning.test.js
+++ b/server/services/agentTuiSpawning.test.js
@@ -58,7 +58,9 @@ vi.mock('./agentCompletion.js', () => ({
}));
vi.mock('./agentLifecycle.js', () => ({
- persistSimplifySummaries: vi.fn().mockResolvedValue(undefined)
+ persistSimplifySummaries: vi.fn().mockResolvedValue(undefined),
+ finalizeAgent: vi.fn().mockResolvedValue(undefined),
+ releaseAgentLane: vi.fn()
}));
vi.mock('./agentState.js', () => ({
@@ -84,8 +86,7 @@ vi.mock('../lib/providerModels.js', () => ({
import { buildTuiSpawnConfig, spawnTuiAgent } from './agentTuiSpawning.js';
import * as shellService from './shell.js';
-import * as cosAgents from './cosAgents.js';
-import * as cos from './cos.js';
+import * as agentLifecycle from './agentLifecycle.js';
import * as agentErrorAnalysis from './agentErrorAnalysis.js';
import { activeAgents, userTerminatedAgents } from './agentState.js';
@@ -216,7 +217,20 @@ describe('spawnTuiAgent runtime', () => {
cleanupWorktreeFn: vi.fn().mockResolvedValue(undefined),
isTruthyMetaFn: (v) => !!v
};
- return spawnTuiAgent(agentId, task, prompt, workspacePath, model, provider, runId, tuiConfig, agentDir, executionId, laneName, helpers);
+ return spawnTuiAgent({
+ agentId,
+ task,
+ prompt,
+ workspacePath,
+ model,
+ provider,
+ runId,
+ tuiConfig,
+ agentDir,
+ executionId,
+ laneName,
+ ...helpers,
+ });
}
beforeEach(() => {
@@ -245,13 +259,20 @@ describe('spawnTuiAgent runtime', () => {
vi.useRealTimers();
});
+ // The TUI spawn path delegates the central completion sequence
+ // (completeAgent + completeAgentRun + updateTask + processAgentCompletion +
+ // provider markers) to `finalizeAgent` so those concerns stay shared with
+ // the runner-mode and direct-CLI paths. The tests below assert the
+ // arguments handed to `finalizeAgent`, not the downstream individual
+ // calls — those are covered by agentLifecycle.test.js.
+
// ── 1. Successful idle-complete path ────────────────────────────────────────
- it('idle-complete: calls completeAgent(success:true) and updateTask(completed) when idle fires after enough output and runtime', async () => {
- // Wire completeAgent to resolve a promise we can await, so we can detect
+ it('idle-complete: calls finalizeAgent(success:true) with completionReason=idle-complete when idle fires after enough output and runtime', async () => {
+ // Wire finalizeAgent to resolve a promise we can await, so we can detect
// when the async finish() chain completes without polling.
let resolveComplete;
const completeDone = new Promise((r) => { resolveComplete = r; });
- vi.mocked(cosAgents.completeAgent).mockImplementation(async () => { resolveComplete(); });
+ vi.mocked(agentLifecycle.finalizeAgent).mockImplementation(async () => { resolveComplete(); });
runSpawn();
@@ -283,23 +304,21 @@ describe('spawnTuiAgent runtime', () => {
// finish() is called as fire-and-forget inside the interval callback;
// switch to real timers and await our sentinel promise so the full async
- // chain (completeAgent → updateTask → ...) drains completely.
+ // chain (finalizeAgent → ...) drains completely.
vi.useRealTimers();
await completeDone;
- expect(cosAgents.completeAgent).toHaveBeenCalledWith(
- 'agent-1',
- expect.objectContaining({ success: true, completionReason: 'idle-complete' })
- );
- expect(cos.updateTask).toHaveBeenCalledWith(
- 'task-1',
- expect.objectContaining({ status: 'completed' }),
- expect.any(String)
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ success: true,
+ completionReason: 'idle-complete',
+ })
);
});
// ── 2. Command-not-found path ────────────────────────────────────────────────
- it('command-not-found: completeAgent called with exitCode 127 and task updated to failed', async () => {
+ it('command-not-found: finalizeAgent called with success:false, exitCode 127, completionReason=command-not-found', async () => {
const spawnPromise = runSpawn();
await flushMicrotasks();
@@ -310,24 +329,18 @@ describe('spawnTuiAgent runtime', () => {
await spawnPromise;
- expect(cosAgents.completeAgent).toHaveBeenCalledWith(
- 'agent-1',
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
expect.objectContaining({
+ agentId: 'agent-1',
success: false,
exitCode: 127,
- completionReason: 'command-not-found'
+ completionReason: 'command-not-found',
})
);
- // resolveFailedTaskUpdate mock returns { status: 'failed' }
- expect(cos.updateTask).toHaveBeenCalledWith(
- 'task-1',
- expect.objectContaining({ status: 'failed' }),
- expect.any(String)
- );
});
// ── 3. Shell-exit path with non-zero exit code ───────────────────────────────
- it('shell-exit: completeAgent called with success:false and exitCode 1 when shell exits non-zero', async () => {
+ it('shell-exit: finalizeAgent called with success:false and exitCode 1 when shell exits non-zero', async () => {
const spawnPromise = runSpawn();
await flushMicrotasks();
@@ -336,18 +349,18 @@ describe('spawnTuiAgent runtime', () => {
await spawnPromise;
- expect(cosAgents.completeAgent).toHaveBeenCalledWith(
- 'agent-1',
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
expect.objectContaining({
+ agentId: 'agent-1',
success: false,
exitCode: 1,
- completionReason: 'shell-exit'
+ completionReason: 'shell-exit',
})
);
});
// ── 4. Killed / user-terminated path ────────────────────────────────────────
- it('user-terminated: completeAgent receives terminated-by-user error and updateTask called with blocked+user-terminated', async () => {
+ it('user-terminated: finalizeAgent receives terminatedByUser:true + error=Agent terminated by user', async () => {
// Mark agent as user-terminated before the exit fires
userTerminatedAgents.add('agent-1');
@@ -359,36 +372,29 @@ describe('spawnTuiAgent runtime', () => {
await spawnPromise;
- expect(cosAgents.completeAgent).toHaveBeenCalledWith(
- 'agent-1',
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
expect.objectContaining({
+ agentId: 'agent-1',
success: false,
- error: 'Agent terminated by user'
+ terminatedByUser: true,
+ error: 'Agent terminated by user',
})
);
- expect(cos.updateTask).toHaveBeenCalledWith(
- 'task-1',
- expect.objectContaining({
- status: 'blocked',
- metadata: expect.objectContaining({ blockedCategory: 'user-terminated' })
- }),
- expect.any(String)
- );
});
// ── 5. Spawn-error path (createShellSession returns null) ────────────────────
- it('spawn-error: function returns null and completeAgent reports spawn-error when session creation fails', async () => {
+ it('spawn-error: function returns null and finalizeAgent reports spawn-error when session creation fails', async () => {
vi.mocked(shellService.createShellSession).mockReturnValue(null);
const result = await runSpawn();
expect(result).toBeNull();
- expect(cosAgents.completeAgent).toHaveBeenCalledWith(
- 'agent-1',
+ expect(agentLifecycle.finalizeAgent).toHaveBeenCalledWith(
expect.objectContaining({
+ agentId: 'agent-1',
success: false,
error: 'Failed to create TUI shell session',
- completionReason: 'spawn-error'
+ completionReason: 'spawn-error',
})
);
});
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index a94a6c44b3..baed6229eb 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -24,7 +24,7 @@ export { selectModelForTask } from './agentModelSelection.js';
export { createAgentRun, completeAgentRun, checkForTaskCommit, extractErrorFromOutput } from './agentRunTracking.js';
export { 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, getClaudeSettingsEnv } from './agentCliSpawning.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 { terminateAgent, getActiveAgents, killAgent, getAgentProcessStats, killAllAgents, isPidAlive, cleanupOrphanedAgents, handleOrphanedTask } from './agentManagement.js';
export { processAgentCompletion } from './agentCompletion.js';