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(cos): handle no-commit PRs silently and auto-spawn recovery for PR failures

Adam Eivy6cf78db0417b
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 7bb7cddde3..a020ed6a11 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -1058,6 +1058,8 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
}).catch(err => {
emitLog('warn', `Failed to create cleanup warning notification: ${err.message}`, { agentId });
});
+
+ spawnMergeRecoveryTask(cleanupWarnings, agentId, task, appName, currentAgent?.metadata?.sourceWorkspace);
}
}
@@ -1114,6 +1116,17 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, d
if (!prResult?.success) {
const reason = prResult?.error || 'unknown error (createPR returned null or threw)';
+
+ // "No commits between X and Y" means the agent made no code changes.
+ // Clean up the worktree silently — nothing to review or merge.
+ if (reason.includes('No commits between')) {
+ emitLog('info', `🌳 No commits on ${worktreeBranch} vs ${targetBranch} — agent made no changes, cleaning up`, { agentId });
+ await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {
+ emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });
+ });
+ return warnings;
+ }
+
emitLog('error', `🌳 PR creation failed for ${worktreeBranch}: ${reason}`, { agentId, branchName: worktreeBranch });
warnings.push(`PR creation failed for branch ${worktreeBranch}: ${reason}. Worktree preserved for manual PR creation.`);
return warnings;
@@ -1147,3 +1160,58 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, d
warnings.push(...(result?.warnings || []));
return warnings;
}
+
+/**
+ * Auto-create a recovery task when a worktree merge or PR creation fails, so stale
+ * branches don't accumulate in managed app repos and block future agent work.
+ */
+export async function spawnMergeRecoveryTask(cleanupWarnings, agentId, task, appName, sourceWorkspace) {
+ let staleBranch = null;
+ let isMergeFail = false;
+
+ for (const w of cleanupWarnings) {
+ const mergeMatch = w.match(/Auto-merge failed for branch (\S+)/);
+ if (mergeMatch) { staleBranch = mergeMatch[1]; isMergeFail = true; break; }
+
+ const prMatch = w.match(/PR creation failed for branch (\S+?):/);
+ if (prMatch) { staleBranch = prMatch[1]; break; }
+ }
+
+ if (!staleBranch || !sourceWorkspace) return;
+
+ const appId = task?.metadata?.app;
+
+ if (isMergeFail) {
+ addTask({
+ description: `[Recovery] Resolve merge conflict and clean up stale branch ${staleBranch} in ${appName}`,
+ priority: 'HIGH',
+ app: appId,
+ context: `An agent failed to auto-merge branch "${staleBranch}" back to main in ${sourceWorkspace}. `
+ + `Resolve this by: (1) checking if the branch's changes are already on main (superseded by other commits), `
+ + `and if so, delete the branch with "git branch -D ${staleBranch}"; `
+ + `(2) if the changes are NOT on main, attempt "git merge ${staleBranch} --no-edit" from main, resolve any conflicts, and commit; `
+ + `(3) after merging or determining the branch is stale, delete it with "git branch -D ${staleBranch}". `
+ + `Original agent: ${agentId}, original task: ${task?.description || 'unknown'}.`,
+ useWorktree: false,
+ }, 'user').catch(err => {
+ emitLog('warn', `Failed to create merge recovery task: ${err.message}`, { agentId, staleBranch });
+ });
+ emitLog('info', `🔧 Auto-created merge recovery task for stale branch ${staleBranch}`, { agentId, appName });
+ } else {
+ // PR creation failed — spawn an agent to investigate and retry
+ addTask({
+ description: `[Recovery] Investigate and retry failed PR for branch ${staleBranch} in ${appName}`,
+ priority: 'HIGH',
+ app: appId,
+ context: `An agent pushed branch "${staleBranch}" to ${sourceWorkspace} but automated PR creation failed. `
+ + `Investigate by: (1) checking if a PR already exists for this branch: "gh pr list --head ${staleBranch}"; `
+ + `(2) if no PR exists, review the branch changes and create one: "gh pr create --head ${staleBranch} --base main --title '...' --body '...'"; `
+ + `(3) if the branch is stale or changes are already on main, delete the remote branch: "git push origin --delete ${staleBranch}". `
+ + `Original agent: ${agentId}, original task: ${task?.description || 'unknown'}.`,
+ useWorktree: false,
+ }, 'user').catch(err => {
+ emitLog('warn', `Failed to create PR recovery task: ${err.message}`, { agentId, staleBranch });
+ });
+ emitLog('info', `🔧 Auto-created PR recovery task for branch ${staleBranch}`, { agentId, appName });
+ }
+}
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 7b72c16b87..797a80cb9a 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -170,8 +170,8 @@ vi.mock('./runner.js', () => ({
// --- Import the function under test and the mocked dependencies ---
-import { cleanupAgentWorktree } from './subAgentSpawner.js';
-import { getAgent } from './cos.js';
+import { cleanupAgentWorktree, spawnMergeRecoveryTask } from './subAgentSpawner.js';
+import { getAgent, addTask } from './cos.js';
import { removeWorktree } from './worktreeManager.js';
import * as git from './git.js';
@@ -252,6 +252,18 @@ describe('cleanupAgentWorktree - openPR path', () => {
expect(removeWorktree).not.toHaveBeenCalled();
});
+ it('should silently clean up worktree when createPR fails with "No commits between"', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: false, error: 'GraphQL: No commits between main and cos/task-abc123 (createPullRequest)' });
+
+ const warnings = await cleanupAgentWorktree('agent-1', true, { openPR: true, description: 'Test task' });
+
+ expect(git.createPR).toHaveBeenCalled();
+ // Agent made no changes — clean up silently without a warning
+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });
+ expect(warnings).toHaveLength(0);
+ });
+
it('should use auto-merge path when openPR is false (success)', async () => {
await cleanupAgentWorktree('agent-1', true, { openPR: false });
@@ -373,3 +385,130 @@ describe('cleanupAgentWorktree - openPR path', () => {
expect(removeWorktree).not.toHaveBeenCalled();
});
});
+
+describe('spawnMergeRecoveryTask', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ addTask.mockResolvedValue({ id: 'task-recovery' });
+ });
+
+ it('should create a recovery task when merge failure warning is present', async () => {
+ const warnings = ['Auto-merge failed for branch cos/task-abc123/agent-1 — branch preserved for manual recovery'];
+ const task = { id: 'task-original', description: 'Fix deps', metadata: { app: 'sparsetree' } };
+
+ await spawnMergeRecoveryTask(warnings, 'agent-1', task, 'SparseTree', '/mock/workspace');
+
+ expect(addTask).toHaveBeenCalledTimes(1);
+ expect(addTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ description: expect.stringContaining('[Recovery]'),
+ priority: 'HIGH',
+ app: 'sparsetree',
+ context: expect.stringContaining('cos/task-abc123/agent-1'),
+ useWorktree: false,
+ }),
+ 'user'
+ );
+ });
+
+ it('should include branch name and repo path in recovery context', async () => {
+ const warnings = ['Auto-merge failed for branch feature/my-branch — branch preserved for manual recovery'];
+ const task = { id: 'task-1', description: 'Original task', metadata: { app: 'myapp' } };
+
+ await spawnMergeRecoveryTask(warnings, 'agent-1', task, 'MyApp', '/mock/workspace');
+
+ const call = addTask.mock.calls[0];
+ expect(call[0].context).toContain('feature/my-branch');
+ expect(call[0].context).toContain('/mock/workspace');
+ expect(call[0].context).toContain('agent-1');
+ expect(call[0].description).toContain('feature/my-branch');
+ expect(call[0].description).toContain('MyApp');
+ });
+
+ it('should not create a task when no merge failure warning exists', async () => {
+ const warnings = ['Worktree cleanup failed: some other error'];
+
+ await spawnMergeRecoveryTask(warnings, 'agent-1', {}, 'TestApp', '/mock/workspace');
+
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('should not create a task when warnings array is empty', async () => {
+ await spawnMergeRecoveryTask([], 'agent-1', {}, 'TestApp', '/mock/workspace');
+
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('should not create a task when sourceWorkspace is undefined', async () => {
+ const warnings = ['Auto-merge failed for branch cos/task-abc/agent-1 — branch preserved'];
+
+ await spawnMergeRecoveryTask(warnings, 'agent-1', {}, 'TestApp', undefined);
+
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('should not create a task when sourceWorkspace is null', async () => {
+ const warnings = ['Auto-merge failed for branch cos/task-abc/agent-1 — branch preserved'];
+
+ await spawnMergeRecoveryTask(warnings, 'agent-1', {}, 'TestApp', null);
+
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('should handle addTask failure gracefully', async () => {
+ addTask.mockRejectedValue(new Error('write failed'));
+ const warnings = ['Auto-merge failed for branch cos/task-abc/agent-1 — branch preserved'];
+
+ // Should not throw
+ await spawnMergeRecoveryTask(warnings, 'agent-1', { metadata: {} }, 'TestApp', '/mock/workspace');
+ });
+
+ it('should use "unknown" for task description when not provided', async () => {
+ const warnings = ['Auto-merge failed for branch cos/branch-1 — branch preserved'];
+
+ await spawnMergeRecoveryTask(warnings, 'agent-1', { metadata: {} }, 'TestApp', '/mock/workspace');
+
+ const call = addTask.mock.calls[0];
+ expect(call[0].context).toContain('original task: unknown');
+ });
+
+ it('should create a PR recovery task when a PR creation failure warning is present', async () => {
+ const warnings = ['PR creation failed for branch cos/task-xyz/agent-1: GraphQL: some error. Worktree preserved for manual PR creation.'];
+ const task = { id: 'task-original', description: 'Add feature', metadata: { app: 'myapp' } };
+
+ await spawnMergeRecoveryTask(warnings, 'agent-1', task, 'MyApp', '/mock/workspace');
+
+ expect(addTask).toHaveBeenCalledTimes(1);
+ expect(addTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ description: expect.stringContaining('[Recovery]'),
+ priority: 'HIGH',
+ app: 'myapp',
+ context: expect.stringContaining('cos/task-xyz/agent-1'),
+ useWorktree: false,
+ }),
+ 'user'
+ );
+ });
+
+ it('should include branch name and workspace in PR recovery context', async () => {
+ const warnings = ['PR creation failed for branch feature/my-pr-branch: gh exited with code 1. Worktree preserved for manual PR creation.'];
+ const task = { id: 'task-1', description: 'Original task', metadata: { app: 'myapp' } };
+
+ await spawnMergeRecoveryTask(warnings, 'agent-1', task, 'MyApp', '/mock/workspace');
+
+ const call = addTask.mock.calls[0];
+ expect(call[0].context).toContain('feature/my-pr-branch');
+ expect(call[0].context).toContain('/mock/workspace');
+ expect(call[0].description).toContain('feature/my-pr-branch');
+ expect(call[0].description).toContain('MyApp');
+ });
+
+ it('should not create a PR recovery task when sourceWorkspace is missing', async () => {
+ const warnings = ['PR creation failed for branch cos/task-xyz/agent-1: some error. Worktree preserved for manual PR creation.'];
+
+ await spawnMergeRecoveryTask(warnings, 'agent-1', {}, 'TestApp', null);
+
+ expect(addTask).not.toHaveBeenCalled();
+ });
+});
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 39a29b7a3b..7725faaff4 100644
--- a/server/services/subAgentSpawner.js
+++ b/server/services/subAgentSpawner.js
@@ -25,7 +25,7 @@ export { createAgentRun, completeAgentRun, checkForTaskCommit, extractErrorFromO
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 { syncRunnerAgents, spawnAgentForTask, waitForRunnerStability, spawnViaRunner, extractFinalSummary, extractPipelineOutputSummary, handlePipelineProgression, handleAgentCompletion, cleanupAgentWorktree } from './agentLifecycle.js';
+export { syncRunnerAgents, spawnAgentForTask, waitForRunnerStability, spawnViaRunner, extractFinalSummary, extractPipelineOutputSummary, handlePipelineProgression, handleAgentCompletion, cleanupAgentWorktree, spawnMergeRecoveryTask } from './agentLifecycle.js';
export { terminateAgent, getActiveAgents, killAgent, getAgentProcessStats, killAllAgents, isPidAlive, cleanupOrphanedAgents, handleOrphanedTask } from './agentManagement.js';
export { processAgentCompletion } from './agentCompletion.js';