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): continue Copilot review loop until merge for worktree+PR tasks

Adam Eivyf0043d122081
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index aab2e88bb8..f1a38d9956 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -6,6 +6,7 @@
## Fixed
+- **CoS review-loop tasks now actually loop until clean and merge the PR.** Previously, scheduled or user tasks running with worktree + openPR + reviewLoop only fired one Copilot review request and stopped — the worktree got cleaned up immediately, the PR sat with whatever feedback Copilot returned, and nothing addressed comments or merged. The fix adds a follow-up internal task that the original cleanup hook spawns once the PR is open and the initial Copilot review has been requested. The follow-up agent attaches a fresh worktree to the PR branch (via a new `existingBranch` option on `createWorktree`), runs the full `/do:rpr`-style poll/fix/push/re-request loop until Copilot returns zero unresolved comments (or hits a 10-iteration guardrail), then merges the PR with `gh pr merge --squash --auto --delete-branch`. The follow-up's own cleanup pass passes `skipMerge: true` so the worktree branch isn't re-merged locally on top of the squash-merge gh just executed. GitLab MRs and other non-GitHub forges still skip the loop entirely (Copilot reviewer is GitHub-only). See `server/services/agentLifecycle.js` (`spawnReviewLoopFollowUp`) and `server/services/agentPromptBuilder.js` (`reviewLoopFollowUpSection`).
- **Dashboard form input no longer wipes when rotating between portrait and landscape.** `DashboardGrid` was returning two structurally different render trees on either side of the 640px breakpoint — a flat `<div className="space-y-4">` on mobile and a relative-positioned absolute-grid wrapper on desktop. Crossing the breakpoint (which happens any time you rotate an iPhone, since portrait ~390px is below it and landscape ~844px is above) put the widget at a different DOM depth, so React unmounted every widget and remounted a new one — taking any in-progress `useState` value with it. The Quick Capture text field reset to empty mid-typing. The grid now uses a single render tree across both modes, toggling only `className`/`style` between flow and absolute layouts. Widget components keep their state across rotation.
- **Toast notifications and the eye-exam form no longer overflow on mobile.** The agent-feedback toast had a hard `w-[480px]` when expanded that overflowed past the right edge of a 375px viewport, and the global toast container's `max-w-[520px]` could similarly extend past the screen on narrow viewports. Both now cap at `calc(100vw - 2rem)` on mobile and switch to their full width at the `sm:` breakpoint (640px+). The eye-exam editor on MeatSpace → Body was also unusable on mobile — its `grid-cols-7` layout squeezed seven number inputs into ~42px each at 375px wide; it now reflows to two columns on mobile (with the date field full-width), four on tablet, seven on desktop.
- **Image preview lightbox readable in glass-style day themes.** The MediaLightbox panel (used by Image Gen and Video Gen) inherited `--port-card-alpha: 0.6` from glass themes like Lumen Glass Day, rendering as muddy translucent grey over the modal's `bg-black/90` overlay. Combined with the existing tinted action buttons (`bg-port-accent/20 text-port-accent`), the Remix and Send to Video buttons became nearly invisible. The panel now pins `--port-card-alpha` and `--port-border-alpha` to 1 within the lightbox scope so it renders solid in any theme, and the action buttons switched from translucent-tint to solid-fill (`bg-port-accent text-white`, `bg-port-success text-white`) for high contrast across all day and night themes.
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 6161a36a96..e7e73c0488 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -575,11 +575,14 @@ export async function spawnDirectly(agentId, task, prompt, workspacePath, model,
// Clean up worktree if agent was using one
const directOpenPR = isTruthyMetaFn(task.metadata?.openPR);
+ const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
await cleanupWorktreeFn(agentId, success, {
openPR: directOpenPR,
requestCopilotReview: directOpenPR && isTruthyMetaFn(task.metadata?.reviewLoop),
+ skipMerge: directReviewLoopFollowUp,
description: task.description,
- agentOutput: outputBuffer
+ agentOutput: outputBuffer,
+ originalTask: task
});
unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 1c133cdcdf..d9523f095a 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -379,13 +379,21 @@ export async function spawnAgentForTask(task) {
}
if (explicitWorktree && !jiraBranchName) {
+ const existingBranch = task.metadata?.existingBranch || null;
const { baseBranch: detectedBase } = await git.getRepoBranches(workspacePath).catch(() => ({ baseBranch: null }));
- 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 (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
+ baseBranch: detectedBase || undefined,
+ existingBranch: existingBranch || undefined
}).catch(err => {
emitLog('warn', `🌳 Worktree creation failed, using shared workspace: ${err.message}`, { taskId: task.id });
return null;
@@ -1087,11 +1095,17 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
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);
const cleanupWarnings = await cleanupAgentWorktree(agentId, success, {
openPR: taskOpenPR,
requestCopilotReview: taskOpenPR && taskReviewLoop,
+ skipMerge: taskReviewLoopFollowUp,
description: task?.description,
- agentOutput: outputBuffer
+ agentOutput: outputBuffer,
+ originalTask: task
});
if (cleanupWarnings?.length > 0) {
@@ -1125,10 +1139,15 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
* Clean up a worktree for a completed agent.
* Reads worktree metadata from the agent's registered state and removes the worktree.
* When openPR is true, pushes the branch and creates a PR instead of auto-merging.
- * When requestCopilotReview is also true, requests a Copilot code review on the new PR.
+ * When requestCopilotReview is also true, requests an initial Copilot review on the new
+ * PR and spawns a follow-up internal task that runs the full /do:rpr loop and merges
+ * once the review is clean — that follow-up is the part the user expects to "keep
+ * looping until ready to merge."
+ * When skipMerge is true (review-loop follow-up agents), the cleanup never auto-merges
+ * the worktree branch into the source workspace because `gh pr merge` already handled it.
* Otherwise, merges the worktree branch back to the source branch on success.
*/
-export async function cleanupAgentWorktree(agentId, success, { openPR = false, requestCopilotReview: shouldRequestCopilot = false, description = null, agentOutput = null } = {}) {
+export async function cleanupAgentWorktree(agentId, success, { openPR = false, requestCopilotReview: shouldRequestCopilot = false, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {
const { getAgent: getAgentState } = await import('./cos.js');
const agentState = await getAgentState(agentId).catch(() => null);
if (!agentState?.metadata?.isWorktree) return [];
@@ -1208,19 +1227,41 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
const cliName = prResult.cli || 'gh';
emitLog('success', `🌳 Created PR: ${prResult.url} (${cliName}${prResult.account ? ` authed as ${prResult.account}` : ''})`, { agentId, branchName: worktreeBranch, cli: prResult.cli, account: prResult.account, owner: prResult.owner, host: prResult.host });
+ let copilotReviewOk = false;
+ let copilotReviewSkipped = false;
if (shouldRequestCopilot) {
const reviewResult = await git.requestCopilotReview(worktreePath, prResult.url).catch(err => ({ success: false, error: err.message }));
if (reviewResult.success && reviewResult.skipped) {
// Non-GitHub forge (e.g. GitLab MR) — Copilot reviewer doesn't exist there. Log info, no warning.
emitLog('info', `🤖 Skipping Copilot review request for ${prResult.url} (non-GitHub forge)`, { agentId, prUrl: prResult.url });
+ copilotReviewSkipped = true;
} else if (reviewResult.success) {
emitLog('success', `🤖 Requested Copilot review on ${prResult.url}`, { agentId, prUrl: prResult.url });
+ copilotReviewOk = true;
} else {
emitLog('warn', `🤖 Failed to request Copilot review on ${prResult.url}: ${reviewResult.error}`, { agentId, prUrl: prResult.url });
warnings.push(`Copilot review request failed for ${prResult.url}: ${reviewResult.error}`);
}
}
+ // Spawn the review-loop follow-up agent that runs /do:rpr until clean and merges.
+ // Without this, the loop stops after the initial review request — the user-reported
+ // "they only handle one review loop and then finish" bug.
+ // Only spawn for GitHub PRs (Copilot reviewer is GitHub-only) and only when the
+ // initial review request succeeded — otherwise the follow-up has nothing to wait for.
+ if (shouldRequestCopilot && copilotReviewOk && !copilotReviewSkipped) {
+ await spawnReviewLoopFollowUp({
+ originalAgentId: agentId,
+ originalTask,
+ prUrl: prResult.url,
+ prBranch: worktreeBranch,
+ sourceWorkspace
+ }).catch(err => {
+ emitLog('warn', `🤖 Failed to spawn review-loop follow-up for ${prResult.url}: ${err.message}`, { agentId, prUrl: prResult.url });
+ warnings.push(`Review-loop follow-up spawn failed for ${prResult.url}: ${err.message}`);
+ });
+ }
+
const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {
emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });
return { warnings: [`Worktree cleanup failed: ${err.message}`] };
@@ -1235,12 +1276,16 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
return warnings;
}
- // Default: auto-merge on success, just cleanup on failure
- emitLog('info', `🌳 Cleaning up worktree for agent ${agentId} (merge: ${success})`, {
- agentId, branchName: worktreeBranch, merge: success
+ // Default: auto-merge on success, just cleanup on failure.
+ // Review-loop follow-up agents pass skipMerge: true because gh pr merge already
+ // handled the merge upstream — re-merging the worktree branch into the local
+ // source workspace would duplicate the squashed commits.
+ const shouldMerge = success && !skipMerge;
+ emitLog('info', `🌳 Cleaning up worktree for agent ${agentId} (merge: ${shouldMerge})`, {
+ agentId, branchName: worktreeBranch, merge: shouldMerge
});
- const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: success }).catch(err => {
+ const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: shouldMerge }).catch(err => {
emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });
return { warnings: [`Worktree cleanup failed: ${err.message}`] };
});
@@ -1248,6 +1293,73 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, r
return warnings;
}
+/**
+ * Spawn an internal follow-up task that runs the Copilot review-and-fix loop
+ * (per /do:rpr) on the just-created PR until it has zero unresolved comments,
+ * then merges the PR. This is what makes the user-facing "review loop" actually
+ * loop — the original agent only requests the *initial* Copilot review and
+ * exits; without this follow-up, the loop ends after one iteration and the PR
+ * is never merged.
+ *
+ * The follow-up task uses an isolated worktree attached to the existing PR
+ * branch (via createWorktree's `existingBranch` option) so it can fix-and-push
+ * without trampling concurrent agents.
+ */
+export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, sourceWorkspace }) {
+ if (!prUrl || !prBranch) return null;
+
+ const parsedPr = git.parsePullRequestUrl(prUrl);
+ // Copilot loop is only meaningful on GitHub — on other forges, skip silently
+ if (parsedPr && parsedPr.host && parsedPr.host !== 'github.com') return null;
+
+ const appId = originalTask?.metadata?.app || null;
+ const sourceTaskDesc = originalTask?.description || 'CoS automated task';
+ const firstLine = sourceTaskDesc.split(/[\r\n]/).find(l => l.trim()) || sourceTaskDesc;
+ const followUpTitle = `[Review Loop] ${firstLine.trim().substring(0, 80)} (${prUrl})`;
+
+ const followUpTaskId = `sys-rl-${Date.now().toString(36)}`;
+ const followUpTask = {
+ id: followUpTaskId,
+ status: 'pending',
+ priority: (originalTask?.priority || 'MEDIUM').toUpperCase(),
+ priorityValue: 2,
+ description: followUpTitle,
+ metadata: {
+ app: appId,
+ // useWorktree is required so the follow-up runs in isolation; existingBranch
+ // tells createWorktree to attach to the PR branch instead of cutting a new one.
+ useWorktree: true,
+ existingBranch: prBranch,
+ // openPR/reviewLoop must stay false so cleanup doesn't try to create another PR
+ // or request another initial review (the agent itself drives the loop)
+ openPR: false,
+ reviewLoop: false,
+ simplify: false,
+ // Marker flags consumed by the agent prompt + completion handler
+ reviewLoopFollowUp: true,
+ reviewLoopPRUrl: prUrl,
+ reviewLoopPRBranch: prBranch,
+ reviewLoopPRNumber: parsedPr?.number ?? null,
+ reviewLoopPRHost: parsedPr?.host ?? null,
+ reviewLoopPROwner: parsedPr?.owner ?? null,
+ reviewLoopPRRepo: parsedPr?.repo ?? null,
+ sourceTaskId: originalTask?.id || null,
+ sourceAgentId: originalAgentId || null,
+ // skipCommitCheck: this task may exit cleanly with zero new commits if the
+ // initial Copilot review came back clean. Don't false-positive that as failure.
+ readOnly: false
+ },
+ autoApproved: true,
+ section: 'pending'
+ };
+
+ await addTask(followUpTask, 'internal', { raw: true });
+ emitLog('info', `🔁 Spawned Copilot review-loop follow-up task ${followUpTaskId} for PR ${prUrl}`, {
+ taskId: followUpTaskId, prUrl, prBranch, sourceAgentId: originalAgentId, sourceTaskId: originalTask?.id
+ });
+ return followUpTask;
+}
+
/**
* 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.
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 16fdc20b3d..812b348eab 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -169,14 +169,17 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo
// Build worktree context section if applicable
const willOpenPR = isTruthyMetaFn(task.metadata?.openPR);
const willReviewLoop = isTruthyMetaFn(task.metadata?.reviewLoop);
+ const isWorktreeOnExistingBranch = worktreeInfo?.existingBranch === true;
const worktreeSection = worktreeInfo ? `
## Git Worktree Context
You are working in an **isolated git worktree** to avoid conflicts with other agents working concurrently.
-- **Branch**: \`${worktreeInfo.branchName}\`
+- **Branch**: \`${worktreeInfo.branchName}\`${isWorktreeOnExistingBranch ? ' *(pre-existing PR branch)*' : ''}
- **Worktree Path**: \`${worktreeInfo.worktreePath}\`
${worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\` (latest from origin)` : ''}
-**Important**: Commit your changes to this branch.${willOpenPR ? ' When your task completes, the system will push this branch and open a pull request against the default branch — do NOT push or open a PR yourself.' : ' Your commits will be automatically merged back to the main development branch when your task completes.'} Do NOT manually switch branches or modify the worktree configuration.
+**Important**: ${isWorktreeOnExistingBranch
+ ? 'Commit and **push** any review-fix commits to this branch — the PR points at it, so pushed commits are how Copilot sees your fixes. Use `git pull --rebase` before pushing if needed.'
+ : `Commit your changes to this branch.${willOpenPR ? ' When your task completes, the system will push this branch and open a pull request against the default branch — do NOT push or open a PR yourself.' : ' Your commits will be automatically merged back to the main development branch when your task completes.'}`} Do NOT manually switch branches or modify the worktree configuration.
` : '';
// Build pipeline context section if this is a pipeline stage
@@ -210,9 +213,55 @@ After completing your work and before committing, run \`/simplify\` to review th
// PR URL.
const reviewLoopSection = willReviewLoop && willOpenPR ? `
## Code Review
-After your task completes, the system will request a Copilot code review automatically for GitHub PRs (the step is skipped for GitLab MRs and other non-GitHub forges). You do not need to open the PR or trigger the review yourself — focus on producing high-quality, well-tested code so the review pass goes cleanly.
+After your task completes, the system will request a Copilot code review automatically for GitHub PRs (the step is skipped for GitLab MRs and other non-GitHub forges). The system will then spawn a follow-up agent that runs the full review-and-fix loop until Copilot returns zero comments and merges the PR. You do not need to open the PR, trigger the review, or address feedback yourself — focus on producing high-quality, well-tested code so the review pass goes cleanly.
` : '';
+ // Build review-loop follow-up section. This is the agent that addresses Copilot's
+ // feedback iteratively and merges the PR — spawned by the previous agent's cleanup
+ // hook (see spawnReviewLoopFollowUp in agentLifecycle.js). It needs the full /do:rpr
+ // procedure inlined because the agent runs in a one-shot session and won't trigger
+ // a slash command itself.
+ const isReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);
+ let reviewLoopFollowUpSection = '';
+ if (isReviewLoopFollowUp) {
+ const prUrl = task.metadata?.reviewLoopPRUrl || '';
+ const prBranch = task.metadata?.reviewLoopPRBranch || '';
+ const prNumber = task.metadata?.reviewLoopPRNumber ?? '';
+ const prOwner = task.metadata?.reviewLoopPROwner ?? '';
+ const prRepo = task.metadata?.reviewLoopPRRepo ?? '';
+ const sourceTaskId = task.metadata?.sourceTaskId || 'unknown';
+ const rprBody = await loadSlashdoFile('rpr').catch(() => null);
+
+ reviewLoopFollowUpSection = `
+## Review-Loop Follow-up (PRIMARY OBJECTIVE)
+A previous agent finished implementing the work for source task **${sourceTaskId}** and opened **PR ${prUrl}** on branch \`${prBranch}\`. The system has already requested an initial Copilot code review. **Your job is to drive the review-and-fix loop to completion and merge the PR.**
+
+**Run this loop UNTIL the PR has zero unresolved Copilot comments OR you hit the iteration cap of 10:**
+
+1. Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round).
+2. If there are unresolved review threads, fix them in this worktree, run the project's tests, commit (\`feat:\`/\`fix:\` prefix, no Co-Authored-By), push, and resolve the addressed threads.
+3. Re-request a Copilot review.
+4. Repeat from step 1.
+5. When Copilot returns "0 comments" / no unresolved threads, merge the PR with:
+ \`\`\`bash
+ gh pr merge "${prUrl}" --squash --auto --delete-branch
+ \`\`\`
+ ${prOwner && prRepo && prNumber ? `(Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --auto --delete-branch\`.)` : ''}
+6. Exit. Do **not** run \`/do:push\` or open a new PR — the merge handles everything. The system will clean up your worktree on exit (no auto-merge will be re-attempted because \`gh pr merge\` already merged on the remote).
+
+**Hard stop:** if the loop hasn't converged after 10 iterations, post a PR comment summarising the unresolved blockers and exit. Do not loop indefinitely.
+
+**Repeated comments:** If a new Copilot round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on to merge.
+
+PR Details:
+- **URL**: ${prUrl}
+- **Branch**: \`${prBranch}\`
+${prNumber !== '' ? `- **Number**: ${prNumber}` : ''}
+${prOwner && prRepo ? `- **Repo**: ${prOwner}/${prRepo}` : ''}
+- **Source task**: ${sourceTaskId}
+${rprBody ? `\n### /do:rpr Reference (full procedure)\n\n${rprBody}\n` : ''}`;
+ }
+
// Build JIRA context section if applicable
const jiraSection = task.metadata?.jiraTicketId ? `
## JIRA Integration
@@ -260,8 +309,12 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch
}
}
- // Try to use the prompt template system
- const promptData = await buildPrompt('cos-agent-briefing', {
+ // Try to use the prompt template system. Skip the template path for
+ // review-loop follow-up agents because the user-side template usually
+ // predates the {{reviewLoopFollowUpSection}} placeholder; the built-in
+ // fallback is the source of truth for that section, and silently dropping
+ // it would leave the agent with no instructions and the loop would not run.
+ const promptData = isReviewLoopFollowUp ? null : await buildPrompt('cos-agent-briefing', {
task,
config,
memorySection,
@@ -272,6 +325,7 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch
jiraSection,
simplifySection,
reviewLoopSection,
+ reviewLoopFollowUpSection,
compactionSection,
skillSection,
planningContextSection,
@@ -306,6 +360,7 @@ ${pipelineSection}
${jiraSection}
${simplifySection}
${reviewLoopSection}
+${reviewLoopFollowUpSection}
${compactionSection}
${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${toolsSection ? `\n${toolsSection}\n` : ''}${planningContextSection}
## Instructions
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index c0f5e58840..3fa2718d27 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -161,7 +161,13 @@ vi.mock('./git.js', () => ({
generatePRDescription: vi.fn(),
deleteBranch: vi.fn().mockResolvedValue(undefined),
requestCopilotReview: vi.fn().mockResolvedValue({ success: true }),
- resolveForgeForRepo: vi.fn().mockResolvedValue({ cli: 'gh', env: process.env, host: 'github.com', owner: null, account: null })
+ resolveForgeForRepo: vi.fn().mockResolvedValue({ cli: 'gh', env: process.env, host: 'github.com', owner: null, account: null }),
+ parsePullRequestUrl: vi.fn((url) => {
+ // Minimal stand-in: extract host/owner/repo/number from GitHub PR URLs
+ const match = url?.match?.(/^https:\/\/([^/]+)\/([^/]+)\/([^/]+)\/(?:pull|merge_requests|-\/merge_requests)\/(\d+)/);
+ if (!match) return null;
+ return { host: match[1], owner: match[2], repo: match[3], number: Number(match[4]) };
+ })
}));
vi.mock('./runner.js', () => ({
@@ -172,7 +178,7 @@ vi.mock('./runner.js', () => ({
// --- Import the function under test and the mocked dependencies ---
-import { cleanupAgentWorktree, spawnMergeRecoveryTask } from './subAgentSpawner.js';
+import { cleanupAgentWorktree, spawnMergeRecoveryTask, spawnReviewLoopFollowUp } from './subAgentSpawner.js';
import { getAgent, addTask } from './cos.js';
import { removeWorktree } from './worktreeManager.js';
import * as git from './git.js';
@@ -456,6 +462,148 @@ describe('cleanupAgentWorktree - openPR path', () => {
expect(warnings.some(w => w.includes('Copilot review'))).toBe(false);
expect(removeWorktree).toHaveBeenCalled();
});
+
+ // --- Review-loop follow-up spawn tests (the user-reported bug:
+ // "they are only handling one review loop and then finishing,
+ // they are not continuing the loop ... until ready to merge") ---
+
+ it('should spawn a review-loop follow-up task after a successful Copilot review request on a GitHub PR', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/42' });
+ git.requestCopilotReview.mockResolvedValue({ success: true });
+ addTask.mockResolvedValue({ id: 'sys-rl-x' });
+
+ await cleanupAgentWorktree('agent-1', true, {
+ openPR: true,
+ requestCopilotReview: true,
+ description: 'Build the thing',
+ originalTask: { id: 'task-orig', priority: 'HIGH', metadata: { app: 'sparsetree' }, description: 'Build the thing' }
+ });
+
+ expect(addTask).toHaveBeenCalledTimes(1);
+ const [followUp, taskType, opts] = addTask.mock.calls[0];
+ expect(taskType).toBe('internal');
+ expect(opts).toEqual({ raw: true });
+ expect(followUp.metadata.reviewLoopFollowUp).toBe(true);
+ expect(followUp.metadata.reviewLoopPRUrl).toBe('https://github.com/test/repo/pull/42');
+ expect(followUp.metadata.reviewLoopPRBranch).toBe('cos/task-abc123');
+ expect(followUp.metadata.reviewLoopPRNumber).toBe(42);
+ expect(followUp.metadata.reviewLoopPROwner).toBe('test');
+ expect(followUp.metadata.reviewLoopPRRepo).toBe('repo');
+ expect(followUp.metadata.existingBranch).toBe('cos/task-abc123');
+ expect(followUp.metadata.useWorktree).toBe(true);
+ expect(followUp.metadata.openPR).toBe(false); // must not chain another PR
+ expect(followUp.metadata.reviewLoop).toBe(false); // must not chain another loop
+ expect(followUp.metadata.sourceTaskId).toBe('task-orig');
+ expect(followUp.metadata.sourceAgentId).toBe('agent-1');
+ expect(followUp.priority).toBe('HIGH');
+ expect(followUp.autoApproved).toBe(true);
+ });
+
+ it('should NOT spawn a review-loop follow-up when Copilot review request fails', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/43' });
+ git.requestCopilotReview.mockResolvedValue({ success: false, error: 'gh exited 1' });
+
+ await cleanupAgentWorktree('agent-1', true, {
+ openPR: true, requestCopilotReview: true, description: 'X',
+ originalTask: { id: 'task-orig', metadata: {}, description: 'X' }
+ });
+
+ // No follow-up because the initial review never landed — nothing to wait on
+ expect(addTask).not.toHaveBeenCalled();
+ expect(removeWorktree).toHaveBeenCalled();
+ });
+
+ it('should NOT spawn a review-loop follow-up on non-GitHub forges (Copilot is GitHub-only)', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://gitlab.com/group/proj/-/merge_requests/12' });
+ git.requestCopilotReview.mockResolvedValue({ success: true, skipped: true });
+
+ await cleanupAgentWorktree('agent-1', true, {
+ openPR: true, requestCopilotReview: true, description: 'X',
+ originalTask: { id: 'task-orig', metadata: {}, description: 'X' }
+ });
+
+ expect(addTask).not.toHaveBeenCalled();
+ expect(removeWorktree).toHaveBeenCalled();
+ });
+
+ it('should NOT spawn a review-loop follow-up when requestCopilotReview is false', async () => {
+ git.push.mockResolvedValue(undefined);
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/44' });
+
+ await cleanupAgentWorktree('agent-1', true, {
+ openPR: true, requestCopilotReview: false, description: 'X',
+ originalTask: { id: 'task-orig', metadata: {}, description: 'X' }
+ });
+
+ expect(git.requestCopilotReview).not.toHaveBeenCalled();
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ // --- skipMerge tests for review-loop follow-up cleanup ---
+
+ it('should pass merge: false in the auto-merge fallback when skipMerge is true (review-loop follow-up cleanup)', async () => {
+ // The follow-up agent already merged via `gh pr merge`; re-merging the worktree
+ // branch into source workspace would duplicate the squashed commits.
+ await cleanupAgentWorktree('agent-1', true, { openPR: false, skipMerge: true });
+
+ expect(removeWorktree).toHaveBeenCalledWith(
+ 'agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false }
+ );
+ });
+
+ it('should still pass merge: true in the auto-merge fallback when skipMerge is false on success', async () => {
+ await cleanupAgentWorktree('agent-1', true, { openPR: false, skipMerge: false });
+
+ expect(removeWorktree).toHaveBeenCalledWith(
+ 'agent-1', '/mock/workspace', 'cos/task-abc123', { merge: true }
+ );
+ });
+});
+
+describe('spawnReviewLoopFollowUp', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ addTask.mockResolvedValue({ id: 'sys-rl-x' });
+ });
+
+ it('should not spawn when prUrl is missing', async () => {
+ const result = await spawnReviewLoopFollowUp({
+ originalAgentId: 'agent-1', originalTask: { id: 'task-1' },
+ prUrl: null, prBranch: 'cos/x/agent-1', sourceWorkspace: '/ws'
+ });
+ expect(result).toBeNull();
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('should not spawn when prBranch is missing', async () => {
+ const result = await spawnReviewLoopFollowUp({
+ originalAgentId: 'agent-1', originalTask: { id: 'task-1' },
+ prUrl: 'https://github.com/o/r/pull/1', prBranch: null, sourceWorkspace: '/ws'
+ });
+ expect(result).toBeNull();
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('should skip spawning for GitLab MR URLs (Copilot is GitHub-only)', async () => {
+ const result = await spawnReviewLoopFollowUp({
+ originalAgentId: 'agent-1', originalTask: { id: 'task-1' },
+ prUrl: 'https://gitlab.com/group/proj/-/merge_requests/5', prBranch: 'feat/x', sourceWorkspace: '/ws'
+ });
+ expect(result).toBeNull();
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('should default priority to MEDIUM when originalTask omits it', async () => {
+ await spawnReviewLoopFollowUp({
+ originalAgentId: 'agent-1',
+ originalTask: { id: 'task-1', metadata: {}, description: 'X' },
+ prUrl: 'https://github.com/o/r/pull/9', prBranch: 'cos/task-1/agent-1', sourceWorkspace: '/ws'
+ });
+ expect(addTask.mock.calls[0][0].priority).toBe('MEDIUM');
+ });
});
describe('spawnMergeRecoveryTask', () => {
diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.js
index 7725faaff4..a94a6c44b3 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, spawnMergeRecoveryTask } from './agentLifecycle.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';
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 2092f625e2..66f441c587 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -28,19 +28,23 @@ const AUTO_GENERATED_LOCKFILES = ['package-lock.json', 'yarn.lock', 'pnpm-lock.y
* For managed apps, the worktree is based on the latest remote default branch
* (main/master) to ensure a clean starting point free from other agents' changes.
*
+ * When `options.existingBranch` is provided, the worktree tracks that pre-existing
+ * branch instead of creating a new one — used for the Copilot review-loop follow-up
+ * agent that needs to address comments on a PR branch the previous agent just pushed.
+ *
* @param {string} agentId - The agent identifier (used for branch/directory naming)
* @param {string} sourceWorkspace - The original git repository path
* @param {string} taskId - Task identifier (included in branch name for traceability)
* @param {object} options - Optional configuration
* @param {string} options.baseBranch - Branch to base the worktree on (auto-detected if omitted)
- * @returns {{ worktreePath: string, branchName: string, baseBranch: string }} paths for the new worktree
+ * @param {string} options.existingBranch - Pre-existing branch to attach (creates from origin/<branch> if no local copy)
+ * @returns {{ worktreePath: string, branchName: string, baseBranch: string|null, existingBranch?: boolean }} paths for the new worktree
*/
export async function createWorktree(agentId, sourceWorkspace, taskId, options = {}) {
if (!existsSync(WORKTREES_DIR)) {
await ensureDir(WORKTREES_DIR);
}
- const branchName = `cos/${taskId}/${agentId}`;
const worktreePath = join(WORKTREES_DIR, agentId);
// Fetch latest from origin so we base off up-to-date refs
@@ -51,6 +55,23 @@ export async function createWorktree(agentId, sourceWorkspace, taskId, options =
return false;
});
+ // Existing-branch path: attach the worktree to a branch that already lives on
+ // the remote (e.g. the PR branch from the previous agent in a review loop).
+ if (options.existingBranch) {
+ const branchName = options.existingBranch;
+ const localExists = (await execGit(['branch', '--list', branchName], sourceWorkspace, { ignoreExitCode: true })).stdout.trim();
+ if (localExists) {
+ await execGit(['worktree', 'add', worktreePath, branchName], sourceWorkspace);
+ } else {
+ // Use -B (force-create) so we don't fail if a stale local ref exists; track origin
+ await execGit(['worktree', 'add', '-B', branchName, worktreePath, `origin/${branchName}`], sourceWorkspace);
+ }
+ console.log(`🌳 Created worktree for ${agentId} at ${worktreePath} on existing branch ${branchName}`);
+ return { worktreePath, branchName, baseBranch: null, existingBranch: true };
+ }
+
+ const branchName = `cos/${taskId}/${agentId}`;
+
// Determine the base: explicit option > remote default branch > current HEAD
let baseBranch = options.baseBranch;
if (!baseBranch) {