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: remove the worktree a failed agent spawn setup cut instead of leaving one checkout per retry

[._.]/ Adam Eivybed92a57febd
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 9820efbd8c..28a6363c67 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -279,10 +279,15 @@ async function runAgentSpawn(task) {
// "in review" until the next daemon restart (issue #989). The release is a
// no-op when the task carries no `metadata.app` or the marker is a real
// `agent-*` id from a different live agent.
+ // The throwaway worktree this attempt cut (set once prepareAgentWorkspace
+ // returns one), so every setup failure after that point removes it. Without
+ // this each failed spawn left a full checkout behind: the task stayed pending
+ // and every retry cut another.
+ let spawnWorktree = null;
const cleanupOnError = async (error) => {
// The spawn-dedup guard is released by withSpawnDedupGuard's finally around
// this whole body (see spawnAgentForTask) — cleanupOnError only owns the
- // lane, tool-execution, claim, and app-review marker releases.
+ // lane, tool-execution, claim, app-review marker, and setup-worktree releases.
release(agentId);
errorExecution(toolExecution.id, { message: error });
completeExecution(toolExecution.id, { success: false });
@@ -295,6 +300,14 @@ async function runAgentSpawn(task) {
await releaseAppReviewMarker(task.metadata?.app).catch(err => {
emitLog('warn', `Failed to release app review marker for ${task.metadata?.app}: ${err.message}`, { taskId: task.id });
});
+ if (spawnWorktree) {
+ // No agent ever ran in it, so nothing in it is worth keeping.
+ const { removeWorktree } = await import('./worktreeManager.js');
+ const sourceWorkspace = task.metadata?.app ? await getAppWorkspace(task.metadata.app).catch(() => ROOT_DIR) : ROOT_DIR;
+ await removeWorktree(agentId, sourceWorkspace, spawnWorktree.branchName, { discardDirt: true }).catch((cleanupErr) => {
+ emitLog('warn', `Failed to remove the worktree of failed spawn ${agentId}: ${cleanupErr.message}`, { agentId, taskId: task.id });
+ });
+ }
};
// Acquire the federation lease BEFORE any spawn setup (issue #1563, addressing
@@ -528,6 +541,9 @@ async function runAgentSpawn(task) {
return null;
}
const { workspacePath, resolvedAppName, worktreeInfo, jiraTicket, jiraBranchName, explicitWorktree } = prep;
+ if (worktreeInfo?.branchName && !worktreeInfo.existingBranch && !worktreeInfo.isPersistentWorktree) {
+ spawnWorktree = { branchName: worktreeInfo.branchName };
+ }
if (publicReview) {
const allowedPullRequestNumbers = publicReviewActions
diff --git a/server/services/agentLifecycle.postureGate.test.js b/server/services/agentLifecycle.postureGate.test.js
index cc0b641ffb..75ea24eb13 100644
--- a/server/services/agentLifecycle.postureGate.test.js
+++ b/server/services/agentLifecycle.postureGate.test.js
@@ -78,6 +78,7 @@ vi.mock('./agentWorktreeCleanup.js', () => ({
cleanupAgentWorktree: vi.fn(),
releaseRetryHold: vi.fn().mockResolvedValue({}),
}));
+vi.mock('./worktreeManager.js', () => ({ removeWorktree: vi.fn().mockResolvedValue({ removed: true }) }));
vi.mock('./agentCompletionCleanup.js', () => ({ runAgentCompletionCleanup: vi.fn() }));
vi.mock('./agentSummaryExtraction.js', () => ({ extractFinalSummary: vi.fn() }));
vi.mock('./agentManagement.js', () => ({ handleOrphanedTask: vi.fn() }));
@@ -108,6 +109,9 @@ vi.mock('./modelAbuseGuard.js', () => ({
}));
import { spawnAgentForTask } from './agentLifecycle.js';
+import { prepareAgentWorkspace } from './agentWorkspacePrep.js';
+import { materializePublicReviewInput } from './modelAbuseGuard.js';
+import { removeWorktree } from './worktreeManager.js';
import { resolveAgentProviderAndModel } from './agentProviderResolution.js';
import { updateTask } from './cos.js';
import { spawningTasks, runnerAgents } from './agentState.js';
@@ -133,6 +137,32 @@ beforeEach(() => {
});
});
+describe('spawn setup failure after the worktree exists', () => {
+ // Every failed Stage 2 spawn used to leave its checkout behind: the task
+ // stayed pending and each retry cut another worktree.
+ it('removes the worktree this attempt cut', async () => {
+ vi.mocked(prepareAgentWorkspace).mockResolvedValueOnce({
+ outcome: 'ready',
+ workspacePath: '/tmp/worktrees/agent-x',
+ worktreeInfo: { worktreePath: '/tmp/worktrees/agent-x', branchName: 'cos/task-public-review/agent-x' },
+ });
+ vi.mocked(materializePublicReviewInput).mockRejectedValueOnce(new Error('The "cb" argument must be of type function'));
+
+ await spawnAgentForTask({
+ id: 'task-public-review',
+ metadata: {
+ executionProfile: 'public-review-gate',
+ pipeline: { securityScan: { completed: true, status: 'passed', safePrCount: 1 }, reviewInputKey: 'a'.repeat(64) },
+ },
+ });
+
+ expect(removeWorktree).toHaveBeenCalledTimes(1);
+ const [, , branchName, options] = vi.mocked(removeWorktree).mock.calls[0];
+ expect(branchName).toBe('cos/task-public-review/agent-x');
+ expect(options).toEqual({ discardDirt: true });
+ });
+});
+
describe('public-review posture gate — spawn behavior (#5866)', () => {
// THE regression. An ordinary task declares no execution profile, so it
// requests no posture and the gate must not fire. When it did, every CoS