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(cos): always open PR + request copilot review when openPR is set
Adam Eivy8444d040e31f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6072276714..94b483b5a3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -8,3 +8,7 @@## Changed- **Worktree policy** clarified in `CLAUDE.md`: TUI sessions edit the main repo directly; worktrees are reserved for unattended CoS sub-agents.++## Fixed++- **CoS agents now reliably open PRs and request Copilot reviews when configured.** Previously, when both `openPR` and `reviewLoop` were enabled on a task, the worktree-cleanup logic's gate (`taskOpenPR && !taskReviewLoop`) skipped PR creation — falling through to auto-merge the agent's branch into main with no PR, no review, and contradictory wording in the agent prompt about whether it should open the PR itself. The cleanup now always opens the PR when `openPR` is set; when `reviewLoop` is also set, it requests a Copilot review on the new PR via the new `git.requestCopilotReview()` helper. The agent prompt is updated to consistently tell the agent the system handles PR creation and review requests.diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex 5c01d9981e..45fe3fb27f 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -1108,9 +1108,10 @@ 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.* Otherwise, merges the worktree branch back to the source branch on success.*/-export async function cleanupAgentWorktree(agentId, success, { openPR = false, description = null, agentOutput = null } = {}) {+export async function cleanupAgentWorktree(agentId, success, { openPR = false, requestCopilotReview: shouldRequestCopilot = false, description = null, agentOutput = null } = {}) {const { getAgent: getAgentState } = await import('./cos.js');const agentState = await getAgentState(agentId).catch(() => null);if (!agentState?.metadata?.isWorktree) return [];@@ -1186,6 +1187,16 @@ export async function cleanupAgentWorktree(agentId, success, { openPR = false, dconst 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 });+ if (shouldRequestCopilot) {+ const reviewResult = await git.requestCopilotReview(worktreePath, prResult.url).catch(err => ({ success: false, error: err.message }));+ if (reviewResult.success) {+ emitLog('success', `🤖 Requested Copilot review on ${prResult.url}`, { agentId, prUrl: prResult.url });+ } 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}`);+ }+ }+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}`] };diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 4051b7488d..6afcad880d 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -169,8 +169,6 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfo// Build worktree context section if applicableconst willOpenPR = isTruthyMetaFn(task.metadata?.openPR);const willReviewLoop = isTruthyMetaFn(task.metadata?.reviewLoop);- // When reviewLoop is enabled alongside openPR, the agent opens the PR during its run- const prHandledByAgent = willReviewLoop && willOpenPR;const worktreeSection = worktreeInfo ? `## Git Worktree ContextYou are working in an **isolated git worktree** to avoid conflicts with other agents working concurrently.@@ -178,7 +176,7 @@ You are working in an **isolated git worktree** to avoid conflicts with other ag- **Worktree Path**: \`${worktreeInfo.worktreePath}\`${worktreeInfo.baseBranch ? `- **Based on**: \`${worktreeInfo.baseBranch}\` (latest from origin)` : ''}-**Important**: Commit your changes to this branch.${willOpenPR && !prHandledByAgent ? ' Your commits will be submitted as a pull request to the default branch when your task completes.' : ' 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**: 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@@ -200,10 +198,12 @@ Use the findings from the previous stage to inform your work. If the previous stAfter completing your work and before committing, run \`/simplify\` to review the changed code for reuse, quality, and efficiency. Fix any issues found, then commit and push using \`/do:push\`.` : '';- // Build review loop section if enabled+ // Build review loop section if enabled. The agent itself does NOT open the PR+ // or run /do:rpr — by the time the PR exists, the agent has already exited.+ // The system requests Copilot review automatically after PR creation.const reviewLoopSection = willReviewLoop ? `-## Review Loop-After opening the PR, run \`/do:rpr\` to resolve PR review feedback and complete the merge validation. Continue running the review loop until all checks pass and the PR is approved.+## Code Review+After your task completes, the system will request a Copilot code review on the PR automatically. 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.` : '';// Build JIRA context section if applicable@@ -316,7 +316,7 @@ ${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${too- If blocked, explain clearly why- Never update the PortOS changelog (\`.changelog/\`) for work on managed apps — the PortOS changelog tracks PortOS core changes only- **BTW Messages**: The user may send you additional context while you work. Check for a \`BTW.md\` file in your working directory root — if it exists, read it for important messages from the user. Incorporate that context into your work. Do not delete or modify BTW.md.-${isTruthyMetaFn(task.metadata?.readOnly) ? `- **This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.` : task.metadata?.app && worktreeInfo && willOpenPR ? `- A pull request will be automatically created when your task completes — do NOT open a PR manually.` : task.metadata?.app && worktreeInfo ? `- Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.` : ``}+${isTruthyMetaFn(task.metadata?.readOnly) ? `- **This is a read-only task.** Do NOT commit, push, or modify any files in the repository. Only read data and generate reports.` : worktreeInfo && willOpenPR ? `- A pull request will be automatically created when your task completes — do NOT open a PR manually.${willReviewLoop ? ' A Copilot code review will also be requested automatically — do NOT run \`/do:rpr\` or attempt to address review comments yourself; you will have already exited.' : ''}` : worktreeInfo ? `- Your worktree branch will be automatically merged back to the source branch when your task completes — do NOT open a PR.` : ``}## Git Hygiene (CRITICAL)- **Before starting work**, run \`git status\` to verify a clean working tree. Do NOT stash or discard uncommitted changes — other agents may be working concurrently and expecting those changes to be present. If the tree is dirty, only commit files YOU changed for this task.diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 7c100d2687..5b9ec94be7 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -159,6 +159,7 @@ vi.mock('./git.js', () => ({createPR: vi.fn(),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 })}));@@ -385,6 +386,49 @@ describe('cleanupAgentWorktree - openPR path', () => {expect(git.push).not.toHaveBeenCalled();expect(removeWorktree).not.toHaveBeenCalled();});++ // --- requestCopilotReview flag tests (regression for the openPR && !reviewLoop bug) ---++ it('should request a Copilot review after PR creation when requestCopilotReview is true', async () => {+ git.push.mockResolvedValue(undefined);+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/7' });++ await cleanupAgentWorktree('agent-1', true, { openPR: true, requestCopilotReview: true, description: 'Test' });++ expect(git.requestCopilotReview).toHaveBeenCalledWith('/mock/root/data/cos/worktrees/agent-1', 'https://github.com/test/repo/pull/7');+ });++ it('should NOT request a Copilot review when requestCopilotReview is false', async () => {+ git.push.mockResolvedValue(undefined);+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/8' });++ await cleanupAgentWorktree('agent-1', true, { openPR: true, requestCopilotReview: false, description: 'Test' });++ expect(git.requestCopilotReview).not.toHaveBeenCalled();+ });++ it('should still create PR (not auto-merge) when both openPR and requestCopilotReview are true — regression', async () => {+ // Regression for the bug where `openPR: taskOpenPR && !taskReviewLoop` skipped+ // PR creation when both flags were set, causing auto-merge into main with no PR/review.+ git.push.mockResolvedValue(undefined);+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/9' });++ await cleanupAgentWorktree('agent-1', true, { openPR: true, requestCopilotReview: true, description: 'Test' });++ expect(git.createPR).toHaveBeenCalled();+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });+ });++ it('should record warning but still complete cleanup when Copilot review request fails', async () => {+ git.push.mockResolvedValue(undefined);+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/10' });+ git.requestCopilotReview.mockResolvedValue({ success: false, error: 'gh exited with code 1' });++ const warnings = await cleanupAgentWorktree('agent-1', true, { openPR: true, requestCopilotReview: true, description: 'Test' });++ expect(warnings.some(w => w.includes('Copilot review request failed'))).toBe(true);+ expect(removeWorktree).toHaveBeenCalled();+ });});describe('spawnMergeRecoveryTask', () => {diff --git a/server/services/git.js b/server/services/git.jsindex 369a28df0a..82459f3db7 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -481,6 +481,56 @@ export async function createPR(dir, { title, body, base, head }) {});}+/**+ * Parse a PR / MR URL into { host, owner, repo, number }. Returns null on bad input.+ * Handles GitHub (`/pull/N`) and GitLab (`/-/merge_requests/N`) URLs.+ */+export function parsePullRequestUrl(url) {+ if (!url || typeof url !== 'string') return null;+ const ghMatch = url.match(/^https?:\/\/([^/]+)\/([^/]+)\/([^/]+)\/pull\/(\d+)/);+ if (ghMatch) return { host: ghMatch[1], owner: ghMatch[2], repo: ghMatch[3], number: Number(ghMatch[4]) };+ const glMatch = url.match(/^https?:\/\/([^/]+)\/([^/]+)\/([^/]+)\/-\/merge_requests\/(\d+)/);+ if (glMatch) return { host: glMatch[1], owner: glMatch[2], repo: glMatch[3], number: Number(glMatch[4]) };+ return null;+}++/**+ * Request a Copilot code review on a GitHub PR. The reviewer login MUST include+ * the `[bot]` suffix or GitHub returns 422 "must be a collaborator". GitLab has+ * no equivalent — this is a GitHub-only no-op there.+ *+ * @param {string} dir - Working directory used to resolve gh auth+ * @param {string} prUrl - PR URL returned by createPR+ * @returns {Promise<{success: boolean, error?: string}>}+ */+export async function requestCopilotReview(dir, prUrl) {+ const parsed = parsePullRequestUrl(prUrl);+ if (!parsed) return { success: false, error: `unparseable PR URL: ${prUrl}` };++ const { cli, env } = await resolveForgeForRepo(dir);+ if (cli !== 'gh') return { success: false, error: `Copilot reviewer is GitHub-only (got ${cli})` };++ const args = [+ 'api',+ `repos/${parsed.owner}/${parsed.repo}/pulls/${parsed.number}/requested_reviewers`,+ '-X', 'POST',+ '-f', 'reviewers[]=copilot-pull-request-reviewer[bot]'+ ];++ return new Promise((resolve) => {+ const child = spawn(cli, args, { cwd: dir, env, shell: false, windowsHide: true });+ let stderr = '';+ child.stderr.on('data', (data) => { stderr += data.toString(); });+ child.on('close', (code) => {+ if (code === 0) resolve({ success: true });+ else resolve({ success: false, error: stderr.trim() || `gh exited with code ${code}` });+ });+ child.on('error', (err) => {+ resolve({ success: false, error: `gh not available: ${err.message}` });+ });+ });+}+/*** Generate a rich PR description from the agent's output summary.* Extracts the implementation summary from the tail of the agent output,diff --git a/server/services/git.test.js b/server/services/git.test.jsindex ccfb5cead0..aab10f41dc 100644--- a/server/services/git.test.js+++ b/server/services/git.test.js@@ -1,5 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';-import { createPR, extractAgentSummary, parseGitHubOwnerFromRemote, pickGhAccountForOwner, parseGitRemote, detectForgeCli } from './git.js';+import { createPR, extractAgentSummary, parseGitHubOwnerFromRemote, pickGhAccountForOwner, parseGitRemote, detectForgeCli, parsePullRequestUrl, requestCopilotReview } from './git.js';describe('parseGitRemote', () => {it('parses GitHub SSH urls', () => {@@ -115,6 +115,46 @@ describe('createPR', () => {});});+describe('parsePullRequestUrl', () => {+ it('parses GitHub PR URLs', () => {+ expect(parsePullRequestUrl('https://github.com/atomantic/PortOS/pull/185')).toEqual({+ host: 'github.com', owner: 'atomantic', repo: 'PortOS', number: 185+ });+ expect(parsePullRequestUrl('http://github.example.com/org/repo/pull/1')).toEqual({+ host: 'github.example.com', owner: 'org', repo: 'repo', number: 1+ });+ });++ it('parses GitLab MR URLs', () => {+ expect(parsePullRequestUrl('https://gitlab.com/group/project/-/merge_requests/42')).toEqual({+ host: 'gitlab.com', owner: 'group', repo: 'project', number: 42+ });+ });++ it('returns null for invalid input', () => {+ expect(parsePullRequestUrl(null)).toBeNull();+ expect(parsePullRequestUrl('')).toBeNull();+ expect(parsePullRequestUrl(undefined)).toBeNull();+ expect(parsePullRequestUrl('https://github.com/atomantic/PortOS')).toBeNull();+ expect(parsePullRequestUrl('not a url')).toBeNull();+ });+});++describe('requestCopilotReview', () => {+ it('returns structured failure for unparseable URL without invoking gh', async () => {+ const result = await requestCopilotReview('/nonexistent-path-for-test', 'not a url');+ expect(result).toEqual({ success: false, error: expect.stringContaining('unparseable PR URL') });+ });++ it('does not throw on a parseable URL when gh is unavailable (graceful failure)', async () => {+ // We can't easily mock spawn here, but we can confirm the function returns+ // a structured failure rather than throwing when invoked end-to-end.+ const result = await requestCopilotReview('/nonexistent-path-for-test', 'https://github.com/test/repo/pull/1');+ expect(result).toHaveProperty('success');+ if (!result.success) expect(typeof result.error).toBe('string');+ });+});+describe('extractAgentSummary', () => {it('returns null for short output', () => {expect(extractAgentSummary(null)).toBeNull();