Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([agent-spawn-widen-try-finally-guard]): scope catch to pre-spawn only
[._.]/ Adam Eivy08958afb47a5
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex d0cb9c7b02..bf2b831f45 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -154,12 +154,15 @@ export async function spawnAgentForTask(task) {completeExecution(toolExecution.id, { success: false });};- // 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+ // try/catch wraps the pre-spawn setup so any uncaught throw from+ // buildAgentPrompt / writeFile / createAgentRun / registerAgent /+ // worktree + JIRA provisioning 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.+ // id until process restart. Spawn-handoff failures (the helpers after+ // this block) are handled separately because they may reject AFTER a+ // live runner agent or child process exists; those helpers own their+ // own cleanup via the child's `on('error')` handler.try {// Get configurationconst config = await getConfig();@@ -542,18 +545,37 @@ export async function spawnAgentForTask(task) {lane: laneName,worktree: !!worktreeInfo});+ } catch (err) {+ // Pre-spawn setup threw — the agent has NOT been handed to the runner /+ // child process yet, so it's safe to release the lane, execution state,+ // and the dedup guard here. Spawn-handoff failures (the helpers below)+ // are deliberately NOT caught here because they may reject AFTER a live+ // runner agent or child process exists; those helpers own their own+ // cleanup via the child's `on('error')` handler.+ emitLog('error', `Agent spawn setup failed: ${err.message}`, { taskId: task.id, error: err.message });+ cleanupOnError(err.message);+ cosEvents.emit('agent:error', { taskId: task.id, error: err.message });+ // Preserve the autonomous-job retry contract. Pre-widening, an uncaught+ // throw here propagated to subAgentSpawner's `task:ready` listener,+ // which emitted `job:spawn-failed` so cos.js could clear+ // `spawningJobIds` and re-register the cron schedule.+ if (task.metadata?.jobId) {+ cosEvents.emit('job:spawn-failed', { jobId: task.metadata.jobId });+ }+ return null;+ }- // 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.+ // 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 {if (isTui) {return await spawnTuiAgent({agentId,@@ -590,20 +612,6 @@ 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 });- // Preserve the autonomous-job retry contract. Pre-widening, an uncaught- // throw here propagated to subAgentSpawner's `task:ready` listener,- // which emitted `job:spawn-failed` so cos.js could clear- // `spawningJobIds` and re-register the cron schedule. Now that the- // throw is consumed locally, emit the same event ourselves — otherwise- // the job-level guard sticks until its 5-minute safety timeout.- if (task.metadata?.jobId) {- cosEvents.emit('job:spawn-failed', { jobId: task.metadata.jobId });- }- return null;} finally {spawningTasks.delete(task.id);}diff --git a/server/services/agentLifecycle.test.js b/server/services/agentLifecycle.test.jsindex 6007b4dbaf..cd4534d81e 100644--- a/server/services/agentLifecycle.test.js+++ b/server/services/agentLifecycle.test.js@@ -546,21 +546,42 @@ describe('spawnAgentForTask — cleanupOnError error recovery', () => {expect(outcome.jobSpawnFailedEmissions).toEqual([]);});- // Source-level assertions: the catch arm exists, calls cleanupOnError,- // AND emits job:spawn-failed when task.metadata?.jobId is set — so any- // future refactor that drops the autonomous-job retry contract breaks- // loudly here. The companion `finally` shape is asserted in the+ // Source-level assertions: the pre-spawn catch arm exists, calls+ // cleanupOnError, AND emits job:spawn-failed when task.metadata?.jobId+ // is set — so any future refactor that drops the autonomous-job retry+ // contract breaks loudly here. The companion inner `finally` shape+ // (dedup-race guard around the spawn helpers) is asserted in the// "agentLifecycle source — spawningTasks delete placement" block above.- it('source: spawnAgentForTask catch arm calls cleanupOnError and re-emits job:spawn-failed', () => {+ it('source: spawnAgentForTask pre-spawn catch calls cleanupOnError and re-emits job:spawn-failed', () => {const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);- const catchMatch = fnBody.match(/catch\s*\(\s*err\s*\)\s*\{([\s\S]{0,2000}?)\}\s*finally/);- expect(catchMatch, 'spawnAgentForTask must have a catch arm before its finally').not.toBeNull();+ const catchMatch = fnBody.match(/catch\s*\(\s*err\s*\)\s*\{([\s\S]{0,2000}?)\n\s{2}\}/);+ expect(catchMatch, 'spawnAgentForTask must have a catch arm with cleanupOnError').not.toBeNull();const catchBody = catchMatch[1];expect(catchBody).toMatch(/cleanupOnError\(/);expect(catchBody).toMatch(/job:spawn-failed/);expect(catchBody).toMatch(/task\.metadata\??\.jobId/);});++ // Source-level assertion: the spawn-handoff calls (spawnTuiAgent /+ // spawnViaRunner / spawnDirectly) must remain OUTSIDE the pre-spawn+ // catch. Catching their rejections here would double-clean a partially+ // launched live agent (lane release, execution-state error mark)+ // alongside the spawn helper's own `on('error')` cleanup. The pre-spawn+ // catch must close before the spawn `if (isTui)` branch.+ it('source: spawn helpers are invoked outside the pre-spawn catch', () => {+ const fnStart = AGENT_LIFECYCLE_SRC.indexOf('export async function spawnAgentForTask');+ const fnBody = AGENT_LIFECYCLE_SRC.slice(fnStart, fnStart + 60_000);+ const catchIdx = fnBody.indexOf('catch (err)');+ const catchClose = fnBody.indexOf('return null;', catchIdx);+ expect(catchIdx, 'pre-spawn catch must exist').toBeGreaterThan(-1);+ expect(catchClose, 'pre-spawn catch must contain `return null;`').toBeGreaterThan(catchIdx);+ // The spawn helper calls must appear AFTER the pre-spawn catch closes.+ for (const helper of ['spawnTuiAgent(', 'spawnViaRunner(', 'spawnDirectly(']) {+ const idx = fnBody.indexOf(helper, catchClose);+ expect(idx, `${helper} must appear AFTER the pre-spawn catch arm`).toBeGreaterThan(-1);+ }+ });});// ─── handleAgentCompletion error recovery ──────────────────────────────────