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): drop --auto from review-loop merge, strip prompt boilerplate (#260)
[._.]/ Adam Eivy1436f12399e9
diff --git a/PLAN.md b/PLAN.mdindex b644ba7829..5a15f6ad28 100644--- a/PLAN.md+++ b/PLAN.md@@ -115,6 +115,9 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [DONE.md]- [ ] **Shallow-equal guard in `useMediaAnnotations` socket handler.** Speculative micro-opt; theoretical until observed.- [ ] **Hoist identity lookup out of `liftLegacyEntry` loop in `mediaAnnotations.js#readAll()`.** Pass `localInstanceId`, `defaultAuthorName` in once; make `liftLegacyEntry` synchronous.- [ ] **Bulk reassign helper to collapse N+1 writes in `deleteSeason`.** Add `issuesSvc.bulkReassignSeason(seriesId, fromSeasonId, toSeasonId)` — one readState + N in-memory mutations + one writeState + one renumber.+- [ ] **Extract shared task block + review-loop section in `agentPromptBuilder.js`.** The light path (`buildLightContextPrompt` ~line 510) and full path (`buildAgentPrompt` fallback ~line 425) now emit nearly identical task blocks (`description` + optional `**Target App**:` + optional `**Screenshots**:`). The review-loop follow-up section is duplicated between the full-context block (~line 312-343) and the light-context block (~line 575-602) — same 7-step loop, same `gh pr merge --squash --delete-branch` command, same `gh pr view --json state` verification, same "10 iterations" hard stop. The auto-merge bug fix (PR removing `--auto`) had to be applied in both places. Extract `buildTaskBlock(task, { screenshotsAsList })` + `buildReviewLoopFollowUpSection(metadata, { verbose })` so the next sync edit doesn't drift.+- [ ] **Flatten the giant `isReadOnly ? … : isTui ? … : worktreeInfo && willOpenPR ? …` ternary in `agentPromptBuilder.js` Guidelines bullet (~line 458).** Pre-existing 4-branch one-liner that covers readOnly/TUI/worktree+PR/worktree-only/default-empty. Extract a `buildCompletionGuidelineBullet({ isReadOnly, isTui, tuiCompletionCommand, worktreeInfo, willOpenPR, willReviewLoop })` helper mirroring the pattern the light path already uses (`worktreeCommitGuidance`, `buildTuiCompletionSection`). Returns string or `null`.+- [ ] **Test the untested `worktreeCommitGuidance` branches in `agentPromptBuilder.js`.** Five-branch decision tree at ~line 617; tests don't cover `isWorktreeOnExistingBranch=true` or `hasSlashdo && !willOpenPR`.### v2.1.0 pre-release review residue (deferred from main→release multi-agent review, 2026-05-16)diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex eadea4ff8f..9d367ecb03 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -319,12 +319,14 @@ A previous agent finished implementing the work for source task **${sourceTaskId2. 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:+5. When Copilot returns "0 comments" / no unresolved threads, merge the PR **immediately** with this exact command (flags: \`--squash --delete-branch\`, nothing else):\`\`\`bash- gh pr merge "${prUrl}" --squash --auto --delete-branch+ gh pr merge "${prUrl}" --squash --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).+ ${prOwner && prRepo && prNumber ? `(Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --delete-branch\`.)` : ''}+ You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.+6. Confirm the PR is actually merged before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is \`MERGED\`.+7. Exit. Do **not** run \`/do:push\` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.**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.@@ -421,15 +423,10 @@ ${task.metadata.jiraBranch ? 'Commit your changes to this branch. Do NOT switch${memorySection || ''}-## Task Assignment--### Task Details-- **ID**: ${task.id}-- **Priority**: ${task.priority}-- **Description**: ${task.description}-${task.metadata?.context ? (task.metadata.context.includes('\n') ? `\n### Task Context\n\n${task.metadata.context.trimEnd()}\n` : `- **Context**: ${task.metadata.context}`) : ''}-${task.metadata?.app ? `- **Target App**: ${task.metadata.app}\n- **Target App Directory**: ${workspaceDir}` : ''}-${Array.isArray(task.metadata?.screenshots) && task.metadata.screenshots.length > 0 ? `- **Screenshots**: ${task.metadata.screenshots.join(', ')}` : ''}+${task.description}+${task.metadata?.context ? (task.metadata.context.includes('\n') ? `\n### Task Context\n\n${task.metadata.context.trimEnd()}\n` : `\n### Task Context\n\n${task.metadata.context}\n`) : ''}+${task.metadata?.app ? `**Target App**: ${task.metadata.app}` : ''}+${Array.isArray(task.metadata?.screenshots) && task.metadata.screenshots.length > 0 ? `**Screenshots**: ${task.metadata.screenshots.join(', ')}` : ''}${worktreeSection}${pipelineSection}${jiraSection}@@ -457,7 +454,7 @@ ${skillSection ? `## Task-Type Skill Guidelines\n\n${skillSection}\n` : ''}${too- Do not make unrelated changes- If blocked, explain clearly why- Never update the PortOS changelog (\`.changelog/\`) for work on managed apps — the PortOS changelog tracks PortOS core changes only-${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.` : isTui ? `- On successful completion, YOU run the Completion Workflow above (\`${tuiCompletionCommand}\`, write the sentinel, \`/quit\`). PortOS will NOT push or open a PR on your behalf.` : worktreeInfo && willOpenPR ? `- On successful completion, the system will push your branch and open a pull request — do NOT open a PR manually. (If the task fails, no PR is opened; the worktree is then cleaned up unless a safety check preserves it for manual recovery.)${willReviewLoop ? ' For GitHub PRs, a Copilot code review will also be requested automatically (skipped on GitLab and other non-GitHub forges) — 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.` : ``}+${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.` : isTui ? `- On successful completion, YOU run the Completion Workflow above (\`${tuiCompletionCommand}\`, write the sentinel, \`/quit\`).` : worktreeInfo && willOpenPR ? `- On successful completion, the system will push your branch and open a pull request — do NOT open a PR manually. (If the task fails, no PR is opened; the worktree is then cleaned up unless a safety check preserves it for manual recovery.)${willReviewLoop ? ' For GitHub PRs, a Copilot code review will also be requested automatically (skipped on GitLab and other non-GitHub forges) — 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.@@ -507,15 +504,11 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrutconst sections = [];// --- Task block --------------------------------------------------------- const taskLines = [- '## Task',- `- **ID**: ${task.id}`,- `- **Priority**: ${task.priority}`,- `- **Description**: ${task.description}`- ];- if (task.metadata?.app) taskLines.push(`- **Target App**: ${task.metadata.app}`);- taskLines.push(`- **Working Directory**: \`${workspaceDir}\``);- sections.push(taskLines.join('\n'));+ // cwd is set by the spawner and the agent knows its own id from the+ // runner, so the prompt skips that metadata. Target app is kept because+ // it scopes managed-app work.+ sections.push(task.description);+ if (task.metadata?.app) sections.push(`**Target App**: ${task.metadata.app}`);const context = task.metadata?.context;if (context) {@@ -587,12 +580,14 @@ export function buildLightContextPrompt(task, workspaceDir, worktreeInfo, isTrut'2. If unresolved threads: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push, resolve threads.','3. Re-request a Copilot review.','4. Repeat.',- '5. When clean, merge with:',+ '5. When clean, merge **immediately** with this exact command (flags: `--squash --delete-branch`, nothing else):',' ```bash',- ` gh pr merge "${prUrl}" --squash --auto --delete-branch`,+ ` gh pr merge "${prUrl}" --squash --delete-branch`,' ```',- prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --auto --delete-branch\`.)` : null,- '6. Exit — do NOT run `/do:push` or open a new PR.',+ prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --delete-branch\`.)` : null,+ ' You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.',+ `6. Confirm the merge happened before exiting: \`gh pr view "${prUrl}" --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\`.`,+ '7. Exit — do NOT run `/do:push` or open a new PR.','','**Hard stop:** if not converged after 10 rounds, post a PR comment summarising blockers and exit.','**Repeated comments:** if a round only re-raises feedback you intentionally rejected (with a reply explaining why), treat as clean and merge.'@@ -621,10 +616,10 @@ function worktreeCommitGuidance({ isTui, hasSlashdo, isWorktreeOnExistingBranch,return 'Commit and **push** any review-fix commits to this branch (the PR points at it). Use `git pull --rebase` before pushing if needed.';}if (hasSlashdo && willOpenPR) {- return 'Commit your changes here — the **Completion** section below drives the push and PR. PortOS will NOT push or open a PR on your behalf.';+ return 'Commit your changes here — the **Completion** section below drives the push and PR.';}if (hasSlashdo) {- return 'Commit your changes here — the **Completion** section below drives the push. PortOS will NOT push on your behalf.';+ return 'Commit your changes here — the **Completion** section below drives the push.';}if (willOpenPR) {return 'Commit your changes here. The system will push and open a PR after you exit — do NOT push or open a PR yourself.';@@ -678,23 +673,21 @@ function buildTuiCompletionSection({ willOpenPR, willReviewLoop, simplifyEnabled*/function buildCliCompletionSection({ worktreeInfo, willOpenPR, hasSlashdo = false, simplifyEnabled = false }) {if (hasSlashdo && worktreeInfo && willOpenPR) {- const lines = ['## Completion', 'When finished, run these in order without further user input:'];+ const lines = ['## Completion', 'When finished, run these in order:'];let step = 1;if (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('', 'PortOS will NOT push or open a PR on your behalf.');return lines.join('\n');}if (hasSlashdo && worktreeInfo) {- const lines = ['## Completion', 'When finished, run these in order without further user input:'];+ const lines = ['## Completion', 'When finished, run these in order:'];let step = 1;if (simplifyEnabled) {lines.push(`${step++}. \`/simplify\` — review the changed code for reuse, quality, and efficiency, and fix any findings.`);}lines.push(`${step++}. \`/do:push\` — commits your changes and pushes the branch.`);- lines.push('', 'PortOS will NOT push on your behalf.');return lines.join('\n');}let body;diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 6672b56183..57229d46fa 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -13,7 +13,41 @@* autonomous agent…" preamble are gone from BOTH paths.*/-import { describe, it, expect } from 'vitest';+import { describe, it, expect, vi } from 'vitest';++// Mock heavy dependencies used by the full (api) prompt path so the API-routing+// regression test doesn't try to hit the memory DB, digital-twin services, or+// disk-based slashdo loaders. Light-path tests don't invoke these at all, so+// the mocks are no-ops for them.+vi.mock('./memoryRetriever.js', () => ({+ getMemorySection: vi.fn().mockResolvedValue(null),+}));+vi.mock('./digital-twin.js', () => ({+ getDigitalTwinForPrompt: vi.fn().mockResolvedValue(null),+}));+vi.mock('./tools.js', () => ({+ getToolsSummaryForPrompt: vi.fn().mockResolvedValue(''),+}));+vi.mock('./promptService.js', () => ({+ buildPrompt: vi.fn().mockResolvedValue(null), // force fallback template+}));+vi.mock('./providers.js', () => ({+ getActiveProvider: vi.fn().mockResolvedValue(null),+}));+vi.mock('../lib/promptRunner.js', () => ({+ runPromptThroughProvider: vi.fn().mockResolvedValue(null),+}));+vi.mock('../lib/fileUtils.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ loadSlashdoFile: vi.fn().mockResolvedValue(null),+ };+});+vi.mock('./jira.js', () => ({+ createTicket: vi.fn().mockResolvedValue(null),+}));+import { buildLightContextPrompt, buildAgentPrompt } from './agentPromptBuilder.js';import { isTruthyMeta } from './agentState.js';@@ -59,12 +93,21 @@ describe('buildLightContextPrompt', () => {});describe('what it includes', () => {- it('includes task id/priority/description and working directory', () => {+ it('includes the task description directly without a metadata header', () => {const prompt = buildLightContextPrompt(makeTask(), '/workspaces/foo', null, isTruthyMeta);- expect(prompt).toMatch(/task-test-1/);- expect(prompt).toMatch(/HIGH/);expect(prompt).toMatch(/Add a button to the dashboard/);- expect(prompt).toMatch(/\/workspaces\/foo/);+ // The agent's cwd is set by the spawner; the prompt doesn't repeat metadata.+ expect(prompt).not.toMatch(/task-test-1/);+ expect(prompt).not.toMatch(/\*\*ID\*\*:/);+ expect(prompt).not.toMatch(/\*\*Priority\*\*:/);+ expect(prompt).not.toMatch(/\*\*Working Directory\*\*:/);+ });++ it('shows Target App when set', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: { app: 'comics' } }),+ '/r', null, isTruthyMeta);+ expect(prompt).toMatch(/\*\*Target App\*\*: comics/);});it('renders attached context (multiline and single-line)', () => {@@ -157,7 +200,7 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/^## Completion$/m);expect(prompt).toMatch(/`\/simplify`/);expect(prompt).toMatch(/`\/do:pr`/);- expect(prompt).toMatch(/PortOS will NOT push or open a PR on your behalf/);+ expect(prompt).not.toMatch(/PortOS will NOT push/);expect(prompt).not.toMatch(/`\/quit`/);});@@ -207,7 +250,13 @@ describe('buildLightContextPrompt', () => {isTruthyMeta);expect(prompt).toMatch(/## Review-Loop Follow-up/);expect(prompt).toMatch(/task-src-1/);- expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9"/);+ expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --squash --delete-branch/);+ // --auto must NOT appear inside any `gh pr merge` invocation — it defers+ // the merge and the PR sits open after the agent exits.+ expect(prompt).not.toMatch(/gh pr merge[^\n]*--auto/);+ // Agent must verify the PR is actually merged before exiting.+ expect(prompt).toMatch(/gh pr view "https:\/\/github\.com\/o\/r\/pull\/9" --json state/);+ expect(prompt).toMatch(/MERGED/);expect(prompt).not.toMatch(/## Completion Workflow/);});@@ -228,13 +277,15 @@ describe('buildLightContextPrompt', () => {});describe('buildAgentPrompt — provider type routing', () => {- it('routes TUI provider through the light path (no roleplay preamble)', async () => {+ it('routes TUI provider through the light path (no roleplay preamble or task header)', async () => {const prompt = await buildAgentPrompt(makeTask(), {}, '/r', null, isTruthyMeta,{ providerType: 'tui', tui: true, skipClaudeMd: true });expect(prompt).not.toMatch(/Chief of Staff Agent Briefing/);expect(prompt).not.toMatch(/You are an autonomous agent/);- expect(prompt).toMatch(/^## Task$/m);+ // The Task header block is now gone — task description leads.+ expect(prompt).not.toMatch(/^## Task$/m);+ expect(prompt).toMatch(/Add a button to the dashboard/);});it('routes CLI provider through the light path too', async () => {@@ -246,4 +297,37 @@ describe('buildAgentPrompt — provider type routing', () => {// Light + non-TUI uses the plain "## Completion" block.expect(prompt).toMatch(/^## Completion$/m);});++ it('full-context (api) review-loop follow-up emits merge command WITHOUT --auto and includes MERGED verification', async () => {+ // Regression for Copilot feedback on PR #260: the merge-without-auto ++ // MERGED-state verification instructions live in BOTH the light and full+ // prompt paths, and we lock them in for the full path here so the two+ // paths can't drift independently. The full path goes through the+ // built-in fallback template (review-loop follow-up agents intentionally+ // skip the user-side prompt template — see buildAgentPrompt).+ const prompt = await buildAgentPrompt(+ makeTask({ metadata: {+ reviewLoopFollowUp: true,+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',+ reviewLoopPRBranch: 'b',+ reviewLoopPRNumber: 9,+ reviewLoopPROwner: 'o',+ reviewLoopPRRepo: 'r',+ sourceTaskId: 'task-src-1',+ }}),+ {},+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt' },+ isTruthyMeta,+ { providerType: 'api' });+ expect(prompt).toMatch(/## Review-Loop Follow-up/);+ // Merge command must be present, exactly with --squash --delete-branch.+ expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --squash --delete-branch/);+ // --auto must NOT appear inside any `gh pr merge` invocation — it defers+ // the merge and the PR sits open after the agent exits.+ expect(prompt).not.toMatch(/gh pr merge[^\n]*--auto/);+ // Agent must verify the PR is actually merged before exiting.+ expect(prompt).toMatch(/gh pr view "https:\/\/github\.com\/o\/r\/pull\/9" --json state -q \.state/);+ expect(prompt).toMatch(/MERGED/);+ });});