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): make CoS agents merge PR + delete branch after Copilot review goes clean (#280)
[._.]/ Adam Eivy9d3115a2a5d3
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 2936273915..7091b2b2c3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -18,6 +18,7 @@## Fixed+- **CoS agents with Open PR enabled now merge their PR + delete the branch after Copilot review goes clean.** Claude Code CLI/TUI agents drive their own `/do:pr` flow, which opens the PR and runs the Copilot review loop but exits without merging — leaving the PR open and the worktree branch leaking. The CoS completion sections (`buildCliCompletionSection`, `buildTuiCompletionSection`, and the inline TUI block in the full/api path) now append an explicit `gh pr merge "<PR_URL>" --squash --delete-branch` step plus a `gh pr view ... -q .state` MERGED-verification step. The merge is skipped when the review loop ended `timeout`/`error`/`guardrail`, mirroring the contract the review-loop follow-up agent already uses.- **CoS Workflow tab now renders cleanly on desktop and mobile.** The stage columns had only `min-w-[12rem]` with no max — long stage descriptions stretched each column past 300px and forced horizontal scroll even on wide monitors. Columns now use responsive flex sizing on `2xl+` (`2xl:flex-1 2xl:basis-0 2xl:min-w-[11rem] 2xl:max-w-[15rem]`) so descriptions wrap predictably without forcing fixed widths, and the whole pipeline stacks vertically below `2xl` (with arrows hidden) for phones, tablets, and standard-density laptops where 7 stages won't fit horizontally. Cards inside each stage flow into a 2-column grid on `sm`–`2xl` so single-column stages don't waste tablet width. (Follow-up after the initial PR's squash-merge mixed `lg:` children with a `2xl:` parent wrapper — Copilot review flagged the breakpoint mismatch.)- **Volume cover-concept generation no longer 500s on upgraded installs.** The per-season "generate volume cover concepts" LLM step was shipped with its prompt template but missing from `stage-config.json`, so existing installs hit `Stage pipeline-volume-cover-concepts not found`. Added the config entry and a migration that seeds both the template and the config on next launch — fresh installs were already fine.- **Pending data migrations now apply automatically on every server start.** Previously only `update.sh` ran `scripts/run-migrations.js`, so a plain pull-and-restart (or `pm2 restart` after manual git pull) left shipped migrations un-applied — new prompt stages, settings renames, and seed data sat in the queue until the user explicitly ran update or `npm run migrations`. The server now invokes the migration runner during boot, before the AI toolkit loads `stage-config.json`, and continues on failure with an error log instead of refusing to start.diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex a2486ea8b5..e693f6e124 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -405,36 +405,18 @@ 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 ${worktreeInfo && willOpenPR ? 'commit your changes (do NOT push — on a successful run the system will push and open the PR after you exit; if the run fails, no push or PR happens)' : 'commit and push using `/do:push`'}.` : '';- // TUI Completion Workflow. Claude Code TUI has direct access to the- // slashdo commands (the submodule mounts them as project-level slash- // commands), so the agent runs the whole tail end itself instead of- // having PortOS drive push/PR creation from cleanup. The sentinel file- // (.agent-done) is what PortOS polls for to know the agent has finished- // — write it AFTER /do:pr/push succeeds, then /quit exits Claude Code- // and the spawn's handleExit fires.+ // TUI completion section — delegate to the shared light-path builder so+ // both prompt paths emit byte-identical workflows. (Background: TUI owns+ // its own `/simplify` → `/do:pr|/do:push` → sentinel → `/quit` sequence+ // because the slashdo submodule mounts those commands at project level —+ // see `buildTuiCompletionSection` below for the full contract.)const tuiCompletionCommand = willOpenPR ? '/do:pr' : '/do:push';- const tuiCompletionSection = isTui ? `-## Completion Workflow-When the task is complete, run these in order:--1. ${simplifyEnabled ? '`/simplify`' : '(simplify is disabled — skip)'}-2. \`${tuiCompletionCommand}\`${willReviewLoop && willOpenPR ? ' — after the PR opens, request a Copilot review (e.g. via `gh`).' : ''}-3. Write a short markdown summary (~5–15 lines) to the completion sentinel — PortOS polls this every 2s; without it the agent sits idle until a 3-minute fallback fires.-- \`\`\`bash- cat > "${worktreeInfo?.worktreePath || workspaceDir}/.agent-done" <<'EOF'- ## Summary- <one-sentence statement of what was accomplished>-- ## Changes- - <key file or area>: <what changed and why>- - <…>-- ${willOpenPR ? '## PR\n <PR URL>' : '## Branch\n <branch name>'}- EOF- \`\`\`-4. \`/quit\`.-` : '';+ const tuiCompletionSection = isTui+ ? buildTuiCompletionSection({+ willOpenPR, willReviewLoop, simplifyEnabled,+ sentinelPath: `${worktreeInfo?.worktreePath || workspaceDir}/.agent-done`+ })+ : '';// 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.@@ -726,6 +708,28 @@ function worktreeCommitGuidance({ isTui, hasSlashdo, isWorktreeOnExistingBranch,return 'Commit your changes here. Your branch will be merged back automatically when the task completes.';}+/**+ * Build the merge-and-verify steps that follow `/do:pr` in completion blocks.+ * Returns `{ lines, nextStep }` — append `lines` to the workflow array and+ * assign `nextStep` back to the caller's step counter so any subsequent+ * numbered steps stay continuous.+ *+ * The agent must drive the merge itself — `/do:pr` runs the Copilot review+ * loop but exits without merging, so without this step the PR sits open and+ * the branch leaks. Mirrors the merge contract in the review-loop follow-up+ * section so both agent flows converge on the same final state.+ */+function buildPostPRMergeSteps(startStep) {+ const lines = [+ `${startStep}. **Merge the PR immediately when the Copilot review loop reports \`clean\` (or \`too-large\`)** — \`/do:pr\` opens the PR and runs the review loop but does NOT merge. Capture the PR URL printed by \`/do:pr\` and run the exact command below (flags: \`--squash --delete-branch\`, nothing else — any merge-deferral flag leaves the PR open after you exit). Skip the merge if the loop ended \`timeout\`, \`error\`, or \`guardrail\`; leave the PR open for human follow-up.`,+ ' ```bash',+ ' gh pr merge "<PR_URL>" --squash --delete-branch',+ ' ```',+ `${startStep + 1}. Confirm the merge before exiting: \`gh pr view "<PR_URL>" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (failing check, unresolved thread, branch protection), fix, and retry. Do NOT exit until state is \`MERGED\` (or you have explicitly decided not to merge per the rule above).`+ ];+ return { lines, nextStep: startStep + 2 };+}+/*** TUI completion-workflow block. The TUI owns its own commit → push → PR* pipeline via slashdo commands and signals "done" with a sentinel file.@@ -736,6 +740,9 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled? ' — after the PR opens, request a Copilot review (e.g. via `gh`).' : '';const simplifyStep = simplifyEnabled ? '1. `/simplify`' : '1. (simplify disabled — skip)';const sentinelTail = willOpenPR ? ' ## PR\n <PR URL>' : ' ## Branch\n <branch name>';+ const merge = willOpenPR ? buildPostPRMergeSteps(3) : { lines: [], nextStep: 3 };+ const sentinelStep = merge.nextStep;+ const quitStep = sentinelStep + 1;return ['## Completion Workflow',@@ -743,7 +750,8 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled'',simplifyStep,`2. \`${cmd}\`${reviewSuffix}`,- '3. Write a short markdown summary (~5–15 lines) to the completion sentinel — PortOS polls this every 2s; without it the agent sits idle until a 3-minute fallback fires.',+ ...merge.lines,+ `${sentinelStep}. Write a short markdown summary (~5–15 lines) to the completion sentinel — PortOS polls this every 2s; without it the agent sits idle until a 3-minute fallback fires.`,'',' ```bash',` cat > "${sentinelPath}" <<'EOF'`,@@ -756,7 +764,7 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabledsentinelTail,' EOF',' ```',- '4. `/quit`.'+ `${quitStep}. \`/quit\`.`].join('\n');}@@ -777,7 +785,10 @@ function buildCliCompletionSection({ worktreeInfo, willOpenPR, hasSlashdo = falsif (simplifyEnabled) {lines.push(`${step++}. \`/simplify\` — review the changed code for reuse, quality, and efficiency, and fix any findings.`);}- lines.push(`${step++}. \`/do:pr\` — commits your changes, pushes the branch, and opens a pull request against the default branch.`);+ lines.push(`${step++}. \`/do:pr\` — commits your changes, pushes the branch, opens a pull request against the default branch, and drives the Copilot review loop until clean.`);+ const merge = buildPostPRMergeSteps(step);+ lines.push(...merge.lines);+ step = merge.nextStep;return lines.join('\n');}if (hasSlashdo && worktreeInfo) {diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 628b12e871..c6830e2567 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -167,6 +167,12 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/`\/do:pr`/);expect(prompt).toMatch(/\.agent-done/);expect(prompt).toMatch(/\/quit/);+ // After /do:pr drives the Copilot review loop clean, the agent must+ // merge and verify — otherwise the PR sits open after the agent exits.+ expect(prompt).toMatch(/gh pr merge "<PR_URL>" --squash --delete-branch/);+ expect(prompt).not.toMatch(/gh pr merge[^\n]*--auto/);+ expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);+ expect(prompt).toMatch(/MERGED/);});it('renders the Completion Workflow with /do:push when openPR is false', () => {@@ -175,6 +181,8 @@ describe('buildLightContextPrompt', () => {'/r', null, isTruthyMeta, { isTui: true });expect(prompt).toMatch(/`\/do:push`/);expect(prompt).not.toMatch(/`\/do:pr`/);+ // /do:push doesn't open a PR — no merge step should be emitted.+ expect(prompt).not.toMatch(/gh pr merge/);});it('emits a non-TUI "Completion" block (no slashdo) for non-Claude CLI agents', () => {@@ -202,6 +210,13 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/`\/do:pr`/);expect(prompt).not.toMatch(/PortOS will NOT push/);expect(prompt).not.toMatch(/`\/quit`/);+ // After /do:pr drives the Copilot review loop clean, the agent must+ // merge and verify — without these steps the PR sits open after the+ // agent exits (the original "agent abandoned the PR" bug).+ expect(prompt).toMatch(/gh pr merge "<PR_URL>" --squash --delete-branch/);+ expect(prompt).not.toMatch(/gh pr merge[^\n]*--auto/);+ expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);+ expect(prompt).toMatch(/MERGED/);});it('skips /simplify in the slashdo Completion block when simplify is disabled', () => {@@ -213,6 +228,8 @@ describe('buildLightContextPrompt', () => {{ isTui: false, providerId: 'claude-code' });expect(prompt).toMatch(/`\/do:pr`/);expect(prompt).not.toMatch(/`\/simplify`/);+ // Merge guidance still applies when /simplify is skipped.+ expect(prompt).toMatch(/gh pr merge "<PR_URL>" --squash --delete-branch/);});it('uses /do:push (not /do:pr) for Claude Code CLI when openPR is false', () => {@@ -224,6 +241,8 @@ describe('buildLightContextPrompt', () => {{ isTui: false, providerId: 'claude-code' });expect(prompt).toMatch(/`\/do:push`/);expect(prompt).not.toMatch(/`\/do:pr`/);+ // /do:push doesn't open a PR — no merge step should be emitted.+ expect(prompt).not.toMatch(/gh pr merge/);});it('suppresses the completion block and warns when readOnly is set', () => {