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

fix([agent-spawn-widen-try-finally-guard]): widen spawn-guard try/catch to cover full setup path

[._.]/ Adam Eivy3d7b9f5464e8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 9692bad1ec..1151a46fde 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -22,5 +22,6 @@
- **[legacy-series-canon-orphan-universe-leak-on-throw] Retrying a failed peer-share import no longer leaves empty "(auto-migrated)" universes behind** — when a transient disk error interrupted importing a peer's series, each retry used to mint a fresh empty universe; the importer now reuses the same one across retries so the import either lands cleanly or is harmless to retry.
- **[ansistrip-osc-alternative-unreachable] TUI output no longer leaks window-title and hyperlink escape bodies** — terminal OSC sequences (the ones CLIs use to set window titles or emit clickable links) are now stripped in full instead of leaving fragments like `0;title␇` visible in agent/TUI transcripts, prompt-runner logs, and arc-planner output.
- **Migration 003 no longer crashes `update.sh` when a stage prompt was renamed upstream.** `pipeline-tv-script.md` was renamed to `pipeline-teleplay.md` in a later commit, leaving older installs unable to run migration 003 (ENOENT on the missing sample file). The migration now treats a sample-side rename/retirement as a soft delete: unmodified copies of the old file are removed cleanly, customized copies emit a warning so edits can be merged into the replacement manually.
+- **[agent-spawn-widen-try-finally-guard] A failed agent spawn no longer permanently blocks the task that triggered it.** Previously, when an agent failed to start due to a transient I/O or disk error mid-setup, the autonomous task scheduler could enter a state where that specific task was treated as "already spawning" forever and was silently skipped until the server restarted. Now any such failure releases the in-flight guard immediately so the next scheduler tick can retry the task.
## Removed
diff --git a/PLAN.md b/PLAN.md
index ecaac48253..2d7aee9b87 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -4,7 +4,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
## Next Up
-- [ ] [agent-spawn-widen-try-finally-guard] **Widen the `spawningTasks` guard in `agentLifecycle.js` to cover the whole spawn path.** `server/services/agentLifecycle.js:~165` adds `task.id` to `spawningTasks` but the `try/finally` only wraps a narrow window; an uncaught throw inside `buildAgentPrompt`, `writeFile('prompt.txt')`, `createAgentRun`, or `registerAgent` (lines ~165–525) leaks the guard forever, permanently blocking re-spawns of that task id until process restart. Four `it.skip('TODO(plan.md backlog): …')` tests at `agentLifecycle.test.js:440-490` already pin the regression and flip green on fix. Single-user system means a stuck guard is silently un-recoverable.
- [ ] [bump-stale-shipped-md5-on-settled-migrations] **Bump stale `NEW_SHIPPED_MD5` entries on settled migrations + add `runPromptMigrationTests` coverage.** Migrations 003 / 004 / 005 / 013 still record their original NEW hash, but downstream migrations have since evolved the same files (e.g. 003's `pipeline-idea-expansion.md` is at the post-025 hash today, 005's `pipeline-arc-overview.md` is at the post-019 hash, 013's `pipeline-comic-script.md` is past `133d200d069c2e8173b7c129eea58f53`). That's a latent bug: a fresh install with `data/migrations.applied.json` cleared misclassifies every shipped file as "customized" instead of "already current," and `runPromptMigrationTests`'s drift-catch can't be wired up. Per the 019 convention, bump each migration's `NEW_SHIPPED_MD5` entry to the current `data.sample` hash and append the intermediate hash(es) to `ACCEPTED_OLD_MD5`; then add a `<num>.test.js` that calls `runPromptMigrationTests`. Skipped from `[backport-pre-023-migrations-to-_lib]` because that PR was scoped to a pure refactor.
- [ ] [codex5-polling-consolidation] **[P2][PERF]** Migrate remaining `setInterval` callers to `useAutoRefetch`. The shared hook at `client/src/hooks/useAutoRefetch.js` exists; 20+ pages/components still spin local `setInterval`s — ChiefOfStaff, Brain, DigitalTwin, Loops, Browser, CyberCity, ImageGen, Ambient, AgentsPage, calendar, meatspace, city tabs. Migrate each to `useAutoRefetch` (which already provides the `document.visibilityState === 'hidden'` short-circuit); for domains with a Socket.IO event stream, switch to event-driven refetch instead of polling.
- [ ] [codex5-client-error-reporter] **[P2][OBSERVABILITY]** Funnel client errors into Review Hub. `client/src/main.jsx`'s `window.onerror` + `unhandledrejection` listeners only `console.log` today. Add `POST /api/client-errors` with redaction (drop tokens / long payloads) + rate-limit (~1/sec, drop duplicates by message+stack hash). Surface grouped client errors in the Review Hub feed; optionally raise a CoS task at a configurable threshold.
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index a49f4c07d7..2e5c1358bc 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -154,269 +154,246 @@ export async function spawnAgentForTask(task) {
completeExecution(toolExecution.id, { success: false });
};
- // Get configuration
- const config = await getConfig();
- let provider = await getActiveProvider();
-
- if (!provider) {
- cleanupOnError('No active AI provider configured');
- cosEvents.emit('agent:error', { taskId: task.id, error: 'No active AI provider configured' });
- return null;
- }
-
- // Check provider availability (usage limits, rate limits, etc.)
- const providerAvailable = isProviderAvailable(provider.id);
- if (!providerAvailable) {
- const status = getProviderStatus(provider.id);
- emitLog('warn', `Provider ${provider.id} unavailable: ${status.message}`, {
- taskId: task.id,
- providerId: provider.id,
- reason: status.reason
- });
+ // try/catch/finally wraps the whole spawn path so any uncaught throw
+ // from the async setup (buildAgentPrompt, writeFile, createAgentRun,
+ // registerAgent, etc.) still releases the dedup guard, the execution
+ // lane, and the tool-execution state. Without this, a throw mid-setup
+ // leaks `spawningTasks` and permanently blocks re-spawns of that task
+ // id until process restart.
+ try {
+ // Get configuration
+ const config = await getConfig();
+ let provider = await getActiveProvider();
- // Try to get a fallback provider (check task-level, then provider-level, then system default)
- const allProviders = await getAllProviders();
- const taskFallbackId = task.metadata?.fallbackProvider;
- const fallbackResult = await getFallbackProvider(provider.id, allProviders, taskFallbackId);
+ if (!provider) {
+ cleanupOnError('No active AI provider configured');
+ cosEvents.emit('agent:error', { taskId: task.id, error: 'No active AI provider configured' });
+ return null;
+ }
- if (fallbackResult) {
- emitLog('info', `Using fallback provider: ${fallbackResult.provider.id} (source: ${fallbackResult.source})`, {
- taskId: task.id,
- primaryProvider: provider.id,
- fallbackProvider: fallbackResult.provider.id,
- fallbackSource: fallbackResult.source
- });
- provider = fallbackResult.provider;
- } else {
- const errorMsg = `Provider ${provider.id} unavailable (${status.message}) and no fallback available`;
- cleanupOnError(errorMsg);
- cosEvents.emit('agent:error', {
+ // Check provider availability (usage limits, rate limits, etc.)
+ const providerAvailable = isProviderAvailable(provider.id);
+ if (!providerAvailable) {
+ const status = getProviderStatus(provider.id);
+ emitLog('warn', `Provider ${provider.id} unavailable: ${status.message}`, {
taskId: task.id,
- error: errorMsg,
providerId: provider.id,
- providerStatus: status
+ reason: status.reason
});
- return null;
+
+ // Try to get a fallback provider (check task-level, then provider-level, then system default)
+ const allProviders = await getAllProviders();
+ const taskFallbackId = task.metadata?.fallbackProvider;
+ const fallbackResult = await getFallbackProvider(provider.id, allProviders, taskFallbackId);
+
+ if (fallbackResult) {
+ emitLog('info', `Using fallback provider: ${fallbackResult.provider.id} (source: ${fallbackResult.source})`, {
+ taskId: task.id,
+ primaryProvider: provider.id,
+ fallbackProvider: fallbackResult.provider.id,
+ fallbackSource: fallbackResult.source
+ });
+ provider = fallbackResult.provider;
+ } else {
+ const errorMsg = `Provider ${provider.id} unavailable (${status.message}) and no fallback available`;
+ cleanupOnError(errorMsg);
+ cosEvents.emit('agent:error', {
+ taskId: task.id,
+ error: errorMsg,
+ providerId: provider.id,
+ providerStatus: status
+ });
+ return null;
+ }
}
- }
- // Check if user specified a different provider in task metadata
- const userProviderId = task.metadata?.provider;
- if (userProviderId && userProviderId !== provider.id) {
- const userProvider = await getProviderById(userProviderId);
- if (userProvider) {
- emitLog('info', `Using user-specified provider: ${userProviderId}`, { taskId: task.id });
- provider = userProvider;
- } else {
- emitLog('warn', `User-specified provider "${userProviderId}" not found, using active provider`, { taskId: task.id });
+ // Check if user specified a different provider in task metadata
+ const userProviderId = task.metadata?.provider;
+ if (userProviderId && userProviderId !== provider.id) {
+ const userProvider = await getProviderById(userProviderId);
+ if (userProvider) {
+ emitLog('info', `Using user-specified provider: ${userProviderId}`, { taskId: task.id });
+ provider = userProvider;
+ } else {
+ emitLog('warn', `User-specified provider "${userProviderId}" not found, using active provider`, { taskId: task.id });
+ }
}
- }
- // Select optimal model for this task (async to allow learning-based suggestions)
- const modelSelection = await selectModelForTask(task, provider);
- let selectedModel = modelSelection.model;
+ // Select optimal model for this task (async to allow learning-based suggestions)
+ const modelSelection = await selectModelForTask(task, provider);
+ let selectedModel = modelSelection.model;
- // Validate model is compatible with provider
- if (selectedModel && provider.models && provider.models.length > 0) {
- const modelIsValid = provider.models.includes(selectedModel);
- if (!modelIsValid) {
- emitLog('warn', `Model "${selectedModel}" not valid for provider "${provider.id}", falling back to provider default`, {
- taskId: task.id,
- requestedModel: selectedModel,
- providerId: provider.id,
- validModels: provider.models
- });
- selectedModel = modelSelection.tier === 'heavy' ? provider.heavyModel :
- modelSelection.tier === 'light' ? provider.lightModel :
- modelSelection.tier === 'medium' ? provider.mediumModel :
- provider.defaultModel;
+ // Validate model is compatible with provider
+ if (selectedModel && provider.models && provider.models.length > 0) {
+ const modelIsValid = provider.models.includes(selectedModel);
+ if (!modelIsValid) {
+ emitLog('warn', `Model "${selectedModel}" not valid for provider "${provider.id}", falling back to provider default`, {
+ taskId: task.id,
+ requestedModel: selectedModel,
+ providerId: provider.id,
+ validModels: provider.models
+ });
+ selectedModel = modelSelection.tier === 'heavy' ? provider.heavyModel :
+ modelSelection.tier === 'light' ? provider.lightModel :
+ modelSelection.tier === 'medium' ? provider.mediumModel :
+ provider.defaultModel;
+ }
}
- }
-
- const logMessage = modelSelection.learningReason
- ? `Model selection: ${selectedModel} (${modelSelection.reason} - ${modelSelection.learningReason})`
- : `Model selection: ${selectedModel} (${modelSelection.reason})`;
- emitLog('info', logMessage, {
- taskId: task.id,
- model: selectedModel,
- tier: modelSelection.tier,
- reason: modelSelection.reason,
- ...(modelSelection.learningReason && { learningReason: modelSelection.learningReason })
- });
- // Determine workspace path and resolve app name
- const isReadOnly = isTruthyMeta(task.metadata?.readOnly);
- let workspacePath = task.metadata?.app
- ? await getAppWorkspace(task.metadata.app)
- : ROOT_DIR;
- const resolvedAppName = task.metadata?.app
- ? (await getAppById(task.metadata.app).catch(() => null))?.name || null
- : null;
-
- let jiraTicket = null;
- let jiraBranchName = null;
- let worktreeInfo = null;
- const explicitOpenPR = isTruthyMeta(task.metadata?.openPR);
- const explicitWorktree = isTruthyMeta(task.metadata?.useWorktree) || explicitOpenPR;
-
- if (!isReadOnly) {
- // Pull latest from git before starting work
- const pullResult = await git.ensureLatest(workspacePath).catch(err => {
- emitLog('warn', `⚠️ Pre-task git pull failed for ${workspacePath}: ${err.message}`, { taskId: task.id, workspace: workspacePath });
- return { success: false, error: err.message };
+ const logMessage = modelSelection.learningReason
+ ? `Model selection: ${selectedModel} (${modelSelection.reason} - ${modelSelection.learningReason})`
+ : `Model selection: ${selectedModel} (${modelSelection.reason})`;
+ emitLog('info', logMessage, {
+ taskId: task.id,
+ model: selectedModel,
+ tier: modelSelection.tier,
+ reason: modelSelection.reason,
+ ...(modelSelection.learningReason && { learningReason: modelSelection.learningReason })
});
- if (pullResult.skipped) {
- emitLog('debug', `Pre-task git pull skipped: ${pullResult.skipped}`, { taskId: task.id, workspace: workspacePath });
- } else if (pullResult.conflict) {
- emitLog('warn', `🔀 Git conflict in ${workspacePath} (branch: ${pullResult.branch}): ${pullResult.error}`, {
- taskId: task.id, workspace: workspacePath, branch: pullResult.branch
- });
-
- const appId = task.metadata?.app || null;
- const conflictDesc = `Resolve git conflict in ${resolvedAppName || workspacePath} on branch ${pullResult.branch}. `
- + `The branch has diverged from origin and automatic rebase failed. `
- + `Error: ${pullResult.error}`;
-
- await addTask({
- description: conflictDesc,
- priority: 'HIGH',
- app: appId,
- context: `This conflict is blocking task ${task.id}: "${task.description}". `
- + `Resolve the conflict, commit, and push so the blocked task can proceed.`,
- position: 'top'
- }, 'internal').catch(err => {
- emitLog('warn', `Failed to create conflict resolution task: ${err.message}`, { taskId: task.id });
- });
+ // Determine workspace path and resolve app name
+ const isReadOnly = isTruthyMeta(task.metadata?.readOnly);
+ let workspacePath = task.metadata?.app
+ ? await getAppWorkspace(task.metadata.app)
+ : ROOT_DIR;
+ const resolvedAppName = task.metadata?.app
+ ? (await getAppById(task.metadata.app).catch(() => null))?.name || null
+ : null;
- await updateTask(task.id, { status: 'pending' }, task.taskType || 'user').catch(() => {});
- cleanupOnError(`Git conflict blocks task — conflict resolution task created`);
- cosEvents.emit('agent:deferred', { taskId: task.id, reason: 'git-conflict', branch: pullResult.branch });
- return null;
- } else if (pullResult.success && !pullResult.upToDate && !pullResult.skipped) {
- emitLog('info', `📥 Pulled latest for ${resolvedAppName || 'workspace'} (branch: ${pullResult.branch})`, {
- taskId: task.id, workspace: workspacePath, branch: pullResult.branch
+ let jiraTicket = null;
+ let jiraBranchName = null;
+ let worktreeInfo = null;
+ const explicitOpenPR = isTruthyMeta(task.metadata?.openPR);
+ const explicitWorktree = isTruthyMeta(task.metadata?.useWorktree) || explicitOpenPR;
+
+ if (!isReadOnly) {
+ // Pull latest from git before starting work
+ const pullResult = await git.ensureLatest(workspacePath).catch(err => {
+ emitLog('warn', `⚠️ Pre-task git pull failed for ${workspacePath}: ${err.message}`, { taskId: task.id, workspace: workspacePath });
+ return { success: false, error: err.message };
});
- } else if (!pullResult.success) {
- emitLog('warn', `⚠️ Pre-task git pull error: ${pullResult.error}`, { taskId: task.id, workspace: workspacePath });
- }
- // JIRA integration: create ticket + feature branch if app has JIRA enabled and task opted in
- const appData = await getAppDataForTask(task);
-
- if (appData?.jira?.enabled && task.metadata?.createJiraTicket) {
- jiraTicket = await createJiraTicketForTask(task, appData);
-
- if (jiraTicket) {
- const slug = (task.description || 'task')
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, '-')
- .replace(/^-|-$/g, '')
- .substring(0, 40);
- jiraBranchName = `feature/${jiraTicket.ticketId}-${slug}`;
-
- if (task.metadata?.app) {
- await git.fetchOrigin(workspacePath).catch(() => {});
- const { baseBranch: defaultBranch } = await git.getRepoBranches(workspacePath).catch(() => ({ baseBranch: null }));
- if (defaultBranch) {
- await git.checkout(workspacePath, defaultBranch).catch(() => {});
- await execGit(['merge', '--ff-only', `origin/${defaultBranch}`], workspacePath).catch(err => { emitLog('warn', `Fast-forward merge of ${defaultBranch} failed: ${err.message}`, { taskId: task.id }); });
- }
- }
-
- await git.createBranch(workspacePath, jiraBranchName).catch(err => {
- emitLog('warn', `Failed to create JIRA branch ${jiraBranchName}: ${err.message}`, { taskId: task.id });
- jiraBranchName = null;
+ if (pullResult.skipped) {
+ emitLog('debug', `Pre-task git pull skipped: ${pullResult.skipped}`, { taskId: task.id, workspace: workspacePath });
+ } else if (pullResult.conflict) {
+ emitLog('warn', `🔀 Git conflict in ${workspacePath} (branch: ${pullResult.branch}): ${pullResult.error}`, {
+ taskId: task.id, workspace: workspacePath, branch: pullResult.branch
});
- if (jiraBranchName) {
- emitLog('success', `Created feature branch ${jiraBranchName}`, { taskId: task.id, ticketId: jiraTicket.ticketId });
- }
+ const appId = task.metadata?.app || null;
+ const conflictDesc = `Resolve git conflict in ${resolvedAppName || workspacePath} on branch ${pullResult.branch}. `
+ + `The branch has diverged from origin and automatic rebase failed. `
+ + `Error: ${pullResult.error}`;
+
+ await addTask({
+ description: conflictDesc,
+ priority: 'HIGH',
+ app: appId,
+ context: `This conflict is blocking task ${task.id}: "${task.description}". `
+ + `Resolve the conflict, commit, and push so the blocked task can proceed.`,
+ position: 'top'
+ }, 'internal').catch(err => {
+ emitLog('warn', `Failed to create conflict resolution task: ${err.message}`, { taskId: task.id });
+ });
- task.metadata = {
- ...task.metadata,
- jiraTicketId: jiraTicket.ticketId,
- jiraTicketUrl: jiraTicket.ticketUrl,
- jiraBranch: jiraBranchName,
- jiraInstanceId: appData.jira.instanceId,
- jiraCreatePR: appData.jira.createPR !== false
- };
+ await updateTask(task.id, { status: 'pending' }, task.taskType || 'user').catch(() => {});
+ cleanupOnError(`Git conflict blocks task — conflict resolution task created`);
+ cosEvents.emit('agent:deferred', { taskId: task.id, reason: 'git-conflict', branch: pullResult.branch });
+ return null;
+ } else if (pullResult.success && !pullResult.upToDate && !pullResult.skipped) {
+ emitLog('info', `📥 Pulled latest for ${resolvedAppName || 'workspace'} (branch: ${pullResult.branch})`, {
+ taskId: task.id, workspace: workspacePath, branch: pullResult.branch
+ });
+ } else if (!pullResult.success) {
+ emitLog('warn', `⚠️ Pre-task git pull error: ${pullResult.error}`, { taskId: task.id, workspace: workspacePath });
}
- }
- // Feature agent tasks: use persistent worktree instead of creating a new one
- if (task.metadata?.featureAgentRun && task.metadata?.featureAgentId) {
- const { getFeatureAgent } = await import('./featureAgents.js');
- const fa = await getFeatureAgent(task.metadata.featureAgentId).catch(() => null);
- if (fa) {
- const faWorktreePath = join(PATHS.cos, 'feature-agents', fa.id, 'worktree');
- if (existsSync(faWorktreePath)) {
- workspacePath = faWorktreePath;
- worktreeInfo = {
- worktreePath: faWorktreePath,
- branchName: fa.git.branchName,
- baseBranch: fa.git.baseBranch || 'main',
- isPersistentWorktree: true
- };
- const { mergeBaseIntoFeatureWorktree } = await import('./worktreeManager.js');
- if (fa.git.autoMergeBase) {
- await mergeBaseIntoFeatureWorktree(fa.id, fa.git.baseBranch).catch(err => {
- emitLog('warn', `🌳 Feature agent base merge failed: ${err.message}`, { featureAgentId: fa.id });
- });
+ // JIRA integration: create ticket + feature branch if app has JIRA enabled and task opted in
+ const appData = await getAppDataForTask(task);
+
+ if (appData?.jira?.enabled && task.metadata?.createJiraTicket) {
+ jiraTicket = await createJiraTicketForTask(task, appData);
+
+ if (jiraTicket) {
+ const slug = (task.description || 'task')
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, '-')
+ .replace(/^-|-$/g, '')
+ .substring(0, 40);
+ jiraBranchName = `feature/${jiraTicket.ticketId}-${slug}`;
+
+ if (task.metadata?.app) {
+ await git.fetchOrigin(workspacePath).catch(() => {});
+ const { baseBranch: defaultBranch } = await git.getRepoBranches(workspacePath).catch(() => ({ baseBranch: null }));
+ if (defaultBranch) {
+ await git.checkout(workspacePath, defaultBranch).catch(() => {});
+ await execGit(['merge', '--ff-only', `origin/${defaultBranch}`], workspacePath).catch(err => { emitLog('warn', `Fast-forward merge of ${defaultBranch} failed: ${err.message}`, { taskId: task.id }); });
+ }
}
- emitLog('info', `🌳 Feature agent ${fa.name} using persistent worktree: ${fa.git.branchName}`, {
- featureAgentId: fa.id, worktreePath: faWorktreePath
+
+ await git.createBranch(workspacePath, jiraBranchName).catch(err => {
+ emitLog('warn', `Failed to create JIRA branch ${jiraBranchName}: ${err.message}`, { taskId: task.id });
+ jiraBranchName = null;
});
- }
- }
- }
- if (explicitWorktree && !jiraBranchName) {
- const existingBranch = task.metadata?.existingBranch || null;
- const { baseBranch: detectedBase } = await git.getRepoBranches(workspacePath).catch(() => ({ baseBranch: null }));
- if (existingBranch) {
- emitLog('info', `🌳 Worktree requested for task ${task.id} on existing branch ${existingBranch}`, {
- taskId: task.id, app: task.metadata?.app, branch: existingBranch
- });
- } else {
- emitLog('info', `🌳 Worktree requested for task ${task.id} — creating isolated worktree from ${detectedBase || 'default branch'}`, {
- taskId: task.id, app: task.metadata?.app, baseBranch: detectedBase
- });
- }
+ if (jiraBranchName) {
+ emitLog('success', `Created feature branch ${jiraBranchName}`, { taskId: task.id, ticketId: jiraTicket.ticketId });
+ }
- worktreeInfo = await createWorktree(agentId, workspacePath, task.id, {
- baseBranch: detectedBase || undefined,
- existingBranch: existingBranch || undefined,
- planId: task.metadata?.planId || undefined
- }).catch(err => {
- emitLog('warn', `🌳 Worktree creation failed, using shared workspace: ${err.message}`, { taskId: task.id });
- return null;
- });
+ task.metadata = {
+ ...task.metadata,
+ jiraTicketId: jiraTicket.ticketId,
+ jiraTicketUrl: jiraTicket.ticketUrl,
+ jiraBranch: jiraBranchName,
+ jiraInstanceId: appData.jira.instanceId,
+ jiraCreatePR: appData.jira.createPR !== false
+ };
+ }
+ }
- if (worktreeInfo) {
- workspacePath = worktreeInfo.worktreePath;
- emitLog('success', `🌳 Agent ${agentId} will work in worktree: ${worktreeInfo.branchName} (base: ${worktreeInfo.baseBranch})`, {
- agentId, worktreePath: worktreeInfo.worktreePath, branchName: worktreeInfo.branchName, baseBranch: worktreeInfo.baseBranch
- });
+ // Feature agent tasks: use persistent worktree instead of creating a new one
+ if (task.metadata?.featureAgentRun && task.metadata?.featureAgentId) {
+ const { getFeatureAgent } = await import('./featureAgents.js');
+ const fa = await getFeatureAgent(task.metadata.featureAgentId).catch(() => null);
+ if (fa) {
+ const faWorktreePath = join(PATHS.cos, 'feature-agents', fa.id, 'worktree');
+ if (existsSync(faWorktreePath)) {
+ workspacePath = faWorktreePath;
+ worktreeInfo = {
+ worktreePath: faWorktreePath,
+ branchName: fa.git.branchName,
+ baseBranch: fa.git.baseBranch || 'main',
+ isPersistentWorktree: true
+ };
+ const { mergeBaseIntoFeatureWorktree } = await import('./worktreeManager.js');
+ if (fa.git.autoMergeBase) {
+ await mergeBaseIntoFeatureWorktree(fa.id, fa.git.baseBranch).catch(err => {
+ emitLog('warn', `🌳 Feature agent base merge failed: ${err.message}`, { featureAgentId: fa.id });
+ });
+ }
+ emitLog('info', `🌳 Feature agent ${fa.name} using persistent worktree: ${fa.git.branchName}`, {
+ featureAgentId: fa.id, worktreePath: faWorktreePath
+ });
+ }
+ }
}
- } else if (!jiraBranchName && !isFalsyMeta(task.metadata?.useWorktree)) {
- const { getAgents } = await import('./cos.js');
- const allAgents = await getAgents();
- const runningAgents = allAgents.filter(a => a.status === 'running');
-
- const conflictResult = await detectConflicts(task, workspacePath, runningAgents).catch(err => {
- emitLog('warn', `Conflict detection failed: ${err.message}`, { taskId: task.id });
- return { hasConflict: false, recommendation: 'proceed' };
- });
- if (conflictResult.recommendation === 'worktree') {
- emitLog('info', `🌳 Conflict detected for task ${task.id}: ${conflictResult.reason} — creating worktree`, {
- taskId: task.id,
- conflictingAgents: conflictResult.conflictingAgents,
- reason: conflictResult.reason
- });
+ if (explicitWorktree && !jiraBranchName) {
+ const existingBranch = task.metadata?.existingBranch || null;
+ const { baseBranch: detectedBase } = await git.getRepoBranches(workspacePath).catch(() => ({ baseBranch: null }));
+ if (existingBranch) {
+ emitLog('info', `🌳 Worktree requested for task ${task.id} on existing branch ${existingBranch}`, {
+ taskId: task.id, app: task.metadata?.app, branch: existingBranch
+ });
+ } else {
+ emitLog('info', `🌳 Worktree requested for task ${task.id} — creating isolated worktree from ${detectedBase || 'default branch'}`, {
+ taskId: task.id, app: task.metadata?.app, baseBranch: detectedBase
+ });
+ }
worktreeInfo = await createWorktree(agentId, workspacePath, task.id, {
+ baseBranch: detectedBase || undefined,
+ existingBranch: existingBranch || undefined,
planId: task.metadata?.planId || undefined
}).catch(err => {
emitLog('warn', `🌳 Worktree creation failed, using shared workspace: ${err.message}`, { taskId: task.id });
@@ -425,128 +402,158 @@ export async function spawnAgentForTask(task) {
if (worktreeInfo) {
workspacePath = worktreeInfo.worktreePath;
- emitLog('success', `🌳 Agent ${agentId} will work in worktree: ${worktreeInfo.branchName}`, {
- agentId, worktreePath: worktreeInfo.worktreePath, branchName: worktreeInfo.branchName
+ emitLog('success', `🌳 Agent ${agentId} will work in worktree: ${worktreeInfo.branchName} (base: ${worktreeInfo.baseBranch})`, {
+ agentId, worktreePath: worktreeInfo.worktreePath, branchName: worktreeInfo.branchName, baseBranch: worktreeInfo.baseBranch
+ });
+ }
+ } else if (!jiraBranchName && !isFalsyMeta(task.metadata?.useWorktree)) {
+ const { getAgents } = await import('./cos.js');
+ const allAgents = await getAgents();
+ const runningAgents = allAgents.filter(a => a.status === 'running');
+
+ const conflictResult = await detectConflicts(task, workspacePath, runningAgents).catch(err => {
+ emitLog('warn', `Conflict detection failed: ${err.message}`, { taskId: task.id });
+ return { hasConflict: false, recommendation: 'proceed' };
+ });
+
+ if (conflictResult.recommendation === 'worktree') {
+ emitLog('info', `🌳 Conflict detected for task ${task.id}: ${conflictResult.reason} — creating worktree`, {
+ taskId: task.id,
+ conflictingAgents: conflictResult.conflictingAgents,
+ reason: conflictResult.reason
+ });
+
+ worktreeInfo = await createWorktree(agentId, workspacePath, task.id, {
+ planId: task.metadata?.planId || undefined
+ }).catch(err => {
+ emitLog('warn', `🌳 Worktree creation failed, using shared workspace: ${err.message}`, { taskId: task.id });
+ return null;
});
+
+ if (worktreeInfo) {
+ workspacePath = worktreeInfo.worktreePath;
+ emitLog('success', `🌳 Agent ${agentId} will work in worktree: ${worktreeInfo.branchName}`, {
+ agentId, worktreePath: worktreeInfo.worktreePath, branchName: worktreeInfo.branchName
+ });
+ }
+ } else if (conflictResult.recommendation === 'proceed') {
+ emitLog('debug', `No conflicts for task ${task.id}, using shared workspace`, { taskId: task.id });
}
- } else if (conflictResult.recommendation === 'proceed') {
- emitLog('debug', `No conflicts for task ${task.id}, using shared workspace`, { taskId: task.id });
}
- }
- } // end !isReadOnly
+ } // end !isReadOnly
- const isTui = isTuiProvider(provider);
+ const isTui = isTuiProvider(provider);
- // Build the agent prompt. `provider.type` drives the light-vs-full split
- // inside buildAgentPrompt — see its doc comment.
- const prompt = await buildAgentPrompt(task, config, workspacePath, worktreeInfo, isTruthyMeta, {
- providerType: provider.type,
- providerId: provider.id
- });
+ // Build the agent prompt. `provider.type` drives the light-vs-full split
+ // inside buildAgentPrompt — see its doc comment.
+ const prompt = await buildAgentPrompt(task, config, workspacePath, worktreeInfo, isTruthyMeta, {
+ providerType: provider.type,
+ providerId: provider.id
+ });
- // Create agent directory
- const agentDir = join(AGENTS_DIR, agentId);
- if (!existsSync(agentDir)) {
- await ensureDir(agentDir);
- }
+ // Create agent directory
+ const agentDir = join(AGENTS_DIR, agentId);
+ if (!existsSync(agentDir)) {
+ await ensureDir(agentDir);
+ }
- // Save prompt to file
- await writeFile(join(agentDir, 'prompt.txt'), prompt);
+ // Save prompt to file
+ await writeFile(join(agentDir, 'prompt.txt'), prompt);
- // Create run entry for usage tracking
- const { runId } = await createAgentRun(agentId, task, selectedModel, provider, workspacePath, resolvedAppName);
- const executionMode = isTui ? 'tui' : useRunner ? 'runner' : 'direct';
+ // Create run entry for usage tracking
+ const { runId } = await createAgentRun(agentId, task, selectedModel, provider, workspacePath, resolvedAppName);
+ const executionMode = isTui ? 'tui' : useRunner ? 'runner' : 'direct';
- // Register the agent with model info
- await registerAgent(agentId, task.id, {
- workspacePath,
- sourceWorkspace: worktreeInfo ? (task.metadata?.app ? await getAppWorkspace(task.metadata.app) : ROOT_DIR) : null,
- worktreeBranch: worktreeInfo?.branchName || null,
- isWorktree: !!worktreeInfo,
- isPersistentWorktree: !!worktreeInfo?.isPersistentWorktree,
- taskDescription: task.description,
- taskType: task.taskType,
- priority: task.priority,
- providerId: provider.id,
- model: selectedModel,
- modelTier: modelSelection.tier,
- modelReason: modelSelection.reason,
- runId,
- phase: 'initializing',
- useRunner: isTui ? false : useRunner,
- executionMode,
- taskAnalysisType: task.metadata?.analysisType || null,
- taskReviewType: task.metadata?.reviewType || null,
- taskApp: task.metadata?.app || null,
- taskAppName: resolvedAppName,
- selfImprovementType: task.metadata?.selfImprovementType || null,
- jobId: task.metadata?.jobId || null,
- missionName: task.metadata?.missionName || null,
- missionId: task.metadata?.missionId || null,
- jiraTicketId: task.metadata?.jiraTicketId || null,
- jiraTicketUrl: task.metadata?.jiraTicketUrl || null,
- jiraBranch: task.metadata?.jiraBranch || null,
- jiraInstanceId: task.metadata?.jiraInstanceId || null,
- jiraCreatePR: task.metadata?.jiraCreatePR ?? null,
- configOpenPR: isTruthyMeta(task.metadata?.openPR),
- configSimplify: isTruthyMeta(task.metadata?.simplify),
- configReviewLoop: isTruthyMeta(task.metadata?.reviewLoop),
- configReviewer: metaStringOr(task.metadata?.reviewer, null),
- configUseWorktree: !!worktreeInfo,
- configWorktreeAutoDetected: !!worktreeInfo && !explicitWorktree,
- configCodingOnMain: !worktreeInfo && !jiraBranchName
- });
+ // Register the agent with model info
+ await registerAgent(agentId, task.id, {
+ workspacePath,
+ sourceWorkspace: worktreeInfo ? (task.metadata?.app ? await getAppWorkspace(task.metadata.app) : ROOT_DIR) : null,
+ worktreeBranch: worktreeInfo?.branchName || null,
+ isWorktree: !!worktreeInfo,
+ isPersistentWorktree: !!worktreeInfo?.isPersistentWorktree,
+ taskDescription: task.description,
+ taskType: task.taskType,
+ priority: task.priority,
+ providerId: provider.id,
+ model: selectedModel,
+ modelTier: modelSelection.tier,
+ modelReason: modelSelection.reason,
+ runId,
+ phase: 'initializing',
+ useRunner: isTui ? false : useRunner,
+ executionMode,
+ taskAnalysisType: task.metadata?.analysisType || null,
+ taskReviewType: task.metadata?.reviewType || null,
+ taskApp: task.metadata?.app || null,
+ taskAppName: resolvedAppName,
+ selfImprovementType: task.metadata?.selfImprovementType || null,
+ jobId: task.metadata?.jobId || null,
+ missionName: task.metadata?.missionName || null,
+ missionId: task.metadata?.missionId || null,
+ jiraTicketId: task.metadata?.jiraTicketId || null,
+ jiraTicketUrl: task.metadata?.jiraTicketUrl || null,
+ jiraBranch: task.metadata?.jiraBranch || null,
+ jiraInstanceId: task.metadata?.jiraInstanceId || null,
+ jiraCreatePR: task.metadata?.jiraCreatePR ?? null,
+ configOpenPR: isTruthyMeta(task.metadata?.openPR),
+ configSimplify: isTruthyMeta(task.metadata?.simplify),
+ configReviewLoop: isTruthyMeta(task.metadata?.reviewLoop),
+ configReviewer: metaStringOr(task.metadata?.reviewer, null),
+ configUseWorktree: !!worktreeInfo,
+ configWorktreeAutoDetected: !!worktreeInfo && !explicitWorktree,
+ configCodingOnMain: !worktreeInfo && !jiraBranchName
+ });
- emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });
+ emitLog('info', `Agent ${agentId} initializing...${worktreeInfo ? ' (worktree)' : ''}${jiraBranchName ? ` (JIRA: ${jiraTicket?.ticketId})` : ''}`, { agentId, taskId: task.id });
- // Mark the task as in_progress and increment total spawn count
- const newSpawnCount = (Number(task.metadata?.totalSpawnCount) || 0) + 1;
- const updateResult = await updateTask(task.id, {
- status: 'in_progress',
- metadata: {
- ...task.metadata,
- totalSpawnCount: newSpawnCount,
- lastSpawnedAt: new Date().toISOString()
- }
- }, task.taskType || 'user')
- .catch(err => {
- console.error(`❌ Failed to mark task ${task.id} as in_progress: ${err.message}`);
+ // Mark the task as in_progress and increment total spawn count
+ const newSpawnCount = (Number(task.metadata?.totalSpawnCount) || 0) + 1;
+ const updateResult = await updateTask(task.id, {
+ status: 'in_progress',
+ metadata: {
+ ...task.metadata,
+ totalSpawnCount: newSpawnCount,
+ lastSpawnedAt: new Date().toISOString()
+ }
+ }, task.taskType || 'user')
+ .catch(err => {
+ console.error(`❌ Failed to mark task ${task.id} as in_progress: ${err.message}`);
+ return null;
+ });
+ if (!updateResult) {
+ cleanupOnError('Failed to update task status');
return null;
- });
- if (!updateResult) {
- cleanupOnError('Failed to update task status');
- return null;
- }
+ }
- // Record autonomous job execution now that the task is confirmed spawning
- if (task.metadata?.autonomousJob && task.metadata?.jobId) {
- cosEvents.emit('job:spawned', { jobId: task.metadata.jobId });
- }
+ // Record autonomous job execution now that the task is confirmed spawning
+ if (task.metadata?.autonomousJob && task.metadata?.jobId) {
+ cosEvents.emit('job:spawned', { jobId: task.metadata.jobId });
+ }
- const cliConfig = isTui
- ? buildTuiSpawnConfig(provider, selectedModel)
- : buildCliSpawnConfig(provider, selectedModel);
+ const cliConfig = isTui
+ ? buildTuiSpawnConfig(provider, selectedModel)
+ : buildCliSpawnConfig(provider, selectedModel);
- emitLog('success', `Spawning agent for task ${task.id}`, {
- agentId,
- model: selectedModel,
- mode: executionMode,
- cli: cliConfig.command,
- lane: laneName,
- worktree: !!worktreeInfo
- });
+ emitLog('success', `Spawning agent for task ${task.id}`, {
+ agentId,
+ model: selectedModel,
+ mode: executionMode,
+ cli: cliConfig.command,
+ lane: laneName,
+ worktree: !!worktreeInfo
+ });
- // Dedup-window fix: keep the `spawningTasks` guard active across the actual
- // spawn call, not just up to the in_progress flip. Deleting between
- // `updateTask` and `spawnViaRunner`/`spawnDirectly` opened a window where a
- // concurrent `spawnAgentForTask(task)` call (e.g. a re-fired `task:ready`
- // from a follow-up scheduler tick) saw an empty set and a task whose
- // registered agent hadn't yet been queued to the runner, and proceeded to
- // spawn a second agent for the same task id. Awaiting the spawn before
- // releasing the guard — inside try/finally so a throw still releases —
- // closes that race. release() must NOT run here on the success path; the
- // lane is released by the agent-completion handler when the work finishes.
- try {
+ // Dedup-window fix: keep the `spawningTasks` guard active across the actual
+ // spawn call, not just up to the in_progress flip. Deleting between
+ // `updateTask` and `spawnViaRunner`/`spawnDirectly` opened a window where a
+ // concurrent `spawnAgentForTask(task)` call (e.g. a re-fired `task:ready`
+ // from a follow-up scheduler tick) saw an empty set and a task whose
+ // registered agent hadn't yet been queued to the runner, and proceeded to
+ // spawn a second agent for the same task id. The outer try/finally
+ // wrapping this whole function ensures the guard is released whether the
+ // spawn returns normally, throws, or any earlier step throws. release()
+ // must NOT run here on the success path; the lane is released by the
+ // agent-completion handler when the work finishes.
if (isTui) {
return await spawnTuiAgent({
agentId,
@@ -583,6 +590,11 @@ export async function spawnAgentForTask(task) {
cleanupWorktreeFn: cleanupAgentWorktree,
isTruthyMetaFn: isTruthyMeta,
});
+ } catch (err) {
+ emitLog('error', `Agent spawn failed: ${err.message}`, { taskId: task.id, error: err.message });
+ cleanupOnError(err.message);
+ cosEvents.emit('agent:error', { taskId: task.id, error: err.message });
+ return null;
} finally {
spawningTasks.delete(task.id);
}
diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.js
index 420fa0b68a..1b2090b699 100644
--- a/server/services/agentLifecycle.test.js
+++ b/server/services/agentLifecycle.test.js
@@ -22,11 +22,13 @@
*
* 2. `spawnAgentForTask` error recovery (`spawnAgentForTask — cleanupOnError`
* block). Documents which detected-error paths release the guard via
- * `cleanupOnError`, plus a SKIPPED test that pins the partial-coverage
- * gap: a throw between `spawningTasks.add(task.id)` (line 134) and the
- * try/finally (line 536) leaks the guard forever. PLAN.md → Backlog has
- * a separate item to widen the try/finally; the skip flips green once
- * that fix lands.
+ * `cleanupOnError`, plus a set of post-fix tests that simulate uncaught
+ * throws from buildAgentPrompt / writeFile / createAgentRun /
+ * registerAgent and assert the widened try/catch/finally releases the
+ * guard regardless. The earlier partial-coverage gap (throws between
+ * `spawningTasks.add` and the narrow spawn-only try/finally leaking the
+ * guard forever) is closed by the outer try wrapping the whole spawn
+ * path.
*
* 3. `handleAgentCompletion` error recovery (`handleAgentCompletion error
* recovery` block). The completion function has NO try/catch wrapping
@@ -422,71 +424,105 @@ describe('spawnAgentForTask — cleanupOnError error recovery', () => {
expect(spawningTasks.has(task.id)).toBe(false);
});
- // ─── Deferred-fix coverage ──────────────────────────────────────────────
+ // ─── Widened try/catch/finally coverage ─────────────────────────────────
//
- // PLAN.md → Backlog has a separate item: "Widen `spawningTasks`
- // try/finally in `agentLifecycle.js#spawnAgentForTask`". Today's
- // try/finally only wraps the `spawnViaRunner` / `spawnDirectly` calls
- // (lines 536–547). The ~400 LOC above (buildAgentPrompt, writeFile,
- // createAgentRun, registerAgent, etc.) is NOT inside any try/catch. A
- // throw on any of those paths leaves `spawningTasks` registered FOREVER,
- // permanently blocking future spawns of that task id.
+ // Pre-fix, `spawnAgentForTask`'s try/finally only wrapped the final
+ // `spawnViaRunner` / `spawnDirectly` calls. The ~400 LOC above
+ // (buildAgentPrompt, writeFile, createAgentRun, registerAgent, etc.) was
+ // not inside any try/catch — an uncaught throw on any of those paths
+ // leaked `spawningTasks` forever, permanently blocking future spawns of
+ // that task id.
//
- // The detected-error paths above use `cleanupOnError` and are safe. The
- // SKIPPED tests below pin the gap: an uncaught throw from one of those
- // mid-spawn async steps leaks the guard. They flip green when the
- // backlog widen-try-finally fix lands.
-
- it.skip('TODO(plan.md backlog): a throw from buildAgentPrompt leaves the guard set forever', async () => {
- // PRE-FIX: throws from lines ~165–525 are NOT in a try/finally, so the
- // guard leaks. Once the fix widens the try/finally up to the
- // `spawningTasks.add(task.id)` line, this becomes pass-by-construction.
- // Production reference: agentLifecycle.js:443 `buildAgentPrompt` call.
- const task = { id: 'task-prompt-throw' };
- async function simulateProductionPreFix() {
- spawningTasks.add(task.id);
- // The actual production code does not wrap this in a try/catch.
- // We simulate a throw HERE — outside any guard.
- throw new Error('prompt build failed (ENOSPC)');
+ // The fix widens the try to wrap from just after `spawningTasks.add` all
+ // the way through the spawn call, with a `catch` arm that invokes
+ // `cleanupOnError` and a `finally` that releases the guard
+ // unconditionally. These tests replicate the post-fix flow with an
+ // injected throw at each of the four documented async steps and assert
+ // the guard is released. They match the inline-replica convention used
+ // throughout this file (see the file header).
+
+ async function simulateFixedSpawnPath({ taskId, agentId, throwAt }) {
+ spawningTasks.add(taskId);
+ const harness = makeCleanupHarness(taskId, agentId);
+ try {
+ // The injected step is the only thing inside the try. The production
+ // try wraps ~400 LOC; what matters here is that ANY throw lands in
+ // catch and the guard is cleared in finally.
+ await throwAt();
+ return { result: 'spawned', harness };
+ } catch (err) {
+ harness.cleanupOnError(err.message);
+ return { result: null, harness };
+ } finally {
+ spawningTasks.delete(taskId);
}
- await expect(simulateProductionPreFix()).rejects.toThrow('prompt build failed');
- // BUG (today): guard leaks. After the backlog fix this becomes false.
- expect(spawningTasks.has(task.id)).toBe(true);
+ }
+
+ function expectGuardReleased({ result, harness }, message) {
+ expect(result).toBeNull();
+ expect(harness.released).toHaveLength(1);
+ expect(harness.errored[0].message).toBe(message);
+ expect(harness.completed[0].success).toBe(false);
+ }
+
+ it('releases the dedup guard when buildAgentPrompt throws', async () => {
+ // Production reference: `buildAgentPrompt(task, ...)` call.
+ const msg = 'prompt build failed (ENOSPC)';
+ const outcome = await simulateFixedSpawnPath({
+ taskId: 'task-prompt-throw',
+ agentId: 'agent-prompt',
+ throwAt: async () => { throw new Error(msg); },
+ });
+ expect(spawningTasks.has('task-prompt-throw')).toBe(false);
+ expectGuardReleased(outcome, msg);
});
- it.skip('TODO(plan.md backlog): a throw from writeFile(prompt) leaves the guard set forever', async () => {
- // Production reference: agentLifecycle.js:452 `writeFile(join(agentDir, 'prompt.txt'), prompt)`.
- // Same shape as the buildAgentPrompt skip — separate test so the
- // failure surface is easier to read after the fix lands.
- const task = { id: 'task-writefile-throw' };
- async function simulateProductionPreFix() {
- spawningTasks.add(task.id);
- throw new Error('writeFile failed (EACCES)');
- }
- await expect(simulateProductionPreFix()).rejects.toThrow();
- expect(spawningTasks.has(task.id)).toBe(true);
+ it('releases the dedup guard when writeFile(prompt) throws', async () => {
+ // Production reference: `writeFile(join(agentDir, 'prompt.txt'), prompt)`.
+ const msg = 'writeFile failed (EACCES)';
+ const outcome = await simulateFixedSpawnPath({
+ taskId: 'task-writefile-throw',
+ agentId: 'agent-writefile',
+ throwAt: async () => { throw new Error(msg); },
+ });
+ expect(spawningTasks.has('task-writefile-throw')).toBe(false);
+ expectGuardReleased(outcome, msg);
});
- it.skip('TODO(plan.md backlog): a throw from createAgentRun leaves the guard set forever', async () => {
- // Production reference: agentLifecycle.js:455 `createAgentRun(agentId, ...)`.
- const task = { id: 'task-runs-throw' };
- async function simulateProductionPreFix() {
- spawningTasks.add(task.id);
- throw new Error('createAgentRun failed (DB write)');
- }
- await expect(simulateProductionPreFix()).rejects.toThrow();
- expect(spawningTasks.has(task.id)).toBe(true);
+ it('releases the dedup guard when createAgentRun throws', async () => {
+ // Production reference: `createAgentRun(agentId, task, ...)`.
+ const msg = 'createAgentRun failed (DB write)';
+ const outcome = await simulateFixedSpawnPath({
+ taskId: 'task-runs-throw',
+ agentId: 'agent-runs',
+ throwAt: async () => { throw new Error(msg); },
+ });
+ expect(spawningTasks.has('task-runs-throw')).toBe(false);
+ expectGuardReleased(outcome, msg);
});
- it.skip('TODO(plan.md backlog): a throw from registerAgent leaves the guard set forever', async () => {
- // Production reference: agentLifecycle.js:458 `registerAgent(agentId, task.id, {...})`.
- const task = { id: 'task-register-throw' };
- async function simulateProductionPreFix() {
- spawningTasks.add(task.id);
- throw new Error('registerAgent failed (state mutex lost)');
- }
- await expect(simulateProductionPreFix()).rejects.toThrow();
- expect(spawningTasks.has(task.id)).toBe(true);
+ it('releases the dedup guard when registerAgent throws', async () => {
+ // Production reference: `registerAgent(agentId, task.id, {...})`.
+ const msg = 'registerAgent failed (state mutex lost)';
+ const outcome = await simulateFixedSpawnPath({
+ taskId: 'task-register-throw',
+ agentId: 'agent-register',
+ throwAt: async () => { throw new Error(msg); },
+ });
+ expect(spawningTasks.has('task-register-throw')).toBe(false);
+ expectGuardReleased(outcome, msg);
+ });
+
+ // Source-level assertion: the production catch arm exists so any future
+ // refactor that removes it (e.g. accidentally collapsing the try back to
+ // just-the-spawn-call) breaks loudly here instead of silently re-opening
+ // the leak. The companion `finally` shape is asserted in the existing
+ // "agentLifecycle source — spawningTasks delete placement" block above.
+ it('source: spawnAgentForTask has a catch arm that calls cleanupOnError', () => {
+ const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');
+ const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);
+ // Look for catch(err) { ... cleanupOnError(...) ... } anywhere inside.
+ expect(fnBody).toMatch(/catch\s*\(\s*err\s*\)\s*\{[\s\S]{0,800}?cleanupOnError\(/);
});
});