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): complete merged review follow-ups without retries
[._.]/ Adam Eivy19d373907fbe
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex fadbfc18fe..02a993a53e 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -134,8 +134,9 @@ export function releaseAgentLane({ agentId, success, duration, exitCode, executi** @returns {Promise<boolean|null|'skip-learning'>}*/-export async function evaluateSuccessCriteria({ task, terminatedByUser, workspacePath, startedAt = null, success = false, hookResult = null, branchProvenEmpty = false, emptyBranchInconclusiveEvidence = null, claimDisposition = null }) {+export async function evaluateSuccessCriteria({ task, terminatedByUser, workspacePath, startedAt = null, success = false, hookResult = null, branchProvenEmpty = false, emptyBranchInconclusiveEvidence = null, claimDisposition = null, mergedReviewFollowUp = null }) {if (terminatedByUser) return null;+ if (success && mergedReviewFollowUp?.status === 'verified') return true;const taskType = task?.taskType || 'user';// The SCHEDULED type (`metadata.analysisType`) if any, else the queue category —// the same resolution the programmatic-I/O gate uses, reused for the coordinator@@ -1713,8 +1714,24 @@ export async function finalizeAgent({startedAt = null,}) {const executionSuccess = reportedSuccess && (typeof exitCode !== 'number' || exitCode === 0);- const reportedTaskOutcome = !terminatedByUser && !isPrivateSecurityTask(task)+ let reportedTaskOutcome = !terminatedByUser && !isPrivateSecurityTask(task)? await persistCompletionSummary(agentId, { workspacePath, finalSummary }) : null;+ // This task owns one assigned PR, not a new delivery of local corrections.+ // A successful process may report a hold after discovering that PR merged.+ // Verify the exact trusted target before that hold can schedule another run.+ const mergedReviewFollowUp = executionSuccess && !terminatedByUser && !executionInterruption+ && !isPrivateSecurityTask(task) && !reportedErrorAnalysis?.actionable && !reportedErrorAnalysis?.permanent+ ? await (await import('./reviewFollowUpCompletion.js')).verifyMergedReviewFollowUp(task, workspacePath)+ .catch(() => null) : null;+ if (mergedReviewFollowUp) {+ const originalOutcome = reportedTaskOutcome;+ reportedTaskOutcome = {+ status: originalOutcome?.status === 'completed' ? 'completed' : 'no-action-needed',+ reason: `The assigned review/merge target is verified MERGED: ${mergedReviewFollowUp.prUrl}. Preserved corrections and checkout retirement remain separate obligations.`,+ };+ await updateAgent(agentId, { metadata: { taskOutcome: reportedTaskOutcome, taskOutcomeSource: 'forge-verification',+ reportedTaskOutcome: originalOutcome, mergedReviewFollowUp } });+ }const deliveryHeld = ['blocked', 'incomplete'].includes(reportedTaskOutcome?.status);if (deliveryHeld && reportedTaskOutcome.recovery?.mode !== 'cleanup'&& !reportedErrorAnalysis?.actionable && !reportedErrorAnalysis?.permanent) {@@ -1947,6 +1964,7 @@ export async function finalizeAgent({branchProvenEmpty,emptyBranchInconclusiveEvidence: prEvidence.emptyBranchInconclusiveEvidence,claimDisposition,+ mergedReviewFollowUp,}).catch(err => {emitLog('warn', `⚠️ Success-criteria validation failed for ${agentId}: ${err.message}`, { agentId });diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.jsindex bca41edcaa..588ee2b596 100644--- a/server/services/agentFinalization.outputHooks.test.js+++ b/server/services/agentFinalization.outputHooks.test.js@@ -1,6 +1,12 @@import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';vi.mock('../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('portos-finalization-output-') }));afterAll(cleanupTempDataRoots);+const mergedTarget = vi.hoisted(() => ({+ getOriginInfo: vi.fn(),+ probeChangeRequestState: vi.fn(),+}));+vi.mock('../lib/gitRemote.js', () => ({ getOriginInfo: mergedTarget.getOriginInfo }));+vi.mock('./prProbe.js', () => ({ probeChangeRequestState: mergedTarget.probeChangeRequestState }));const claimVerifier = vi.hoisted(() => ({ verifyClaimDisposition: vi.fn() }));vi.mock('./claimDisposition.js', () => claimVerifier);vi.mock('../lib/fileUtils.js', async importOriginal => {@@ -403,6 +409,55 @@ describe('recovery output-hook dispatch (#3182)', () => {}});+ const reviewTask = () => ({ id: TASK.id, taskType: 'internal', status: 'in_progress', metadata: {+ reviewLoopFollowUp: true, reviewLoopPRUrl: 'https://github.com/atomantic/PortOS/pull/123',+ reviewLoopPRBranch: 'fix/example', failureCount: 2,+ } });++ it.each(['blocked', 'incomplete', 'no-action-needed'])('completes a verified merged review target reported as %s without retrying', async status => {+ isProgrammaticIoTaskType.mockReturnValue(false);+ mergedTarget.getOriginInfo.mockResolvedValue({ host: 'github.com', fullName: 'atomantic/PortOS' });+ mergedTarget.probeChangeRequestState.mockResolvedValue({ readable: true, prState: 'MERGED' });+ const task = reviewTask();+ const reported = { status, reason: 'The target is merged; corrections are tracked separately and the checkout is preserved.' };+ const result = await finalizeAgent({ agentId: 'agent-example', runId: 'run-example', task, success: true,+ exitCode: 0, duration: 1000, workspacePath: '/example/repo', outputBuffer: '',+ finalSummary: JSON.stringify({ summary: reported.reason, taskOutcome: reported }) });+ expect(mergedTarget.probeChangeRequestState).toHaveBeenCalledWith('/example/repo', { number: 123, branch: 'fix/example' });+ expect(result).toMatchObject({ success: true, taskOutcome: { status: 'no-action-needed' } });+ expect(updateTask).toHaveBeenCalledWith(task.id, expect.objectContaining({ status: 'completed',+ metadata: expect.objectContaining({ failureCount: 2, taskOutcome: expect.objectContaining({ status: 'no-action-needed' }) }) }), 'internal');+ expect(completeAgent).toHaveBeenCalledWith('agent-example', expect.objectContaining({ success: true, validationPassed: true,+ taskOutcome: expect.objectContaining({ status: 'no-action-needed' }) }));+ expect(persistedAgent.metadata).toMatchObject({ taskOutcomeSource: 'forge-verification', reportedTaskOutcome: reported });+ expect(resolveFailedTaskUpdate).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();+ expect(processAgentCompletion).toHaveBeenCalledWith('agent-example', task, true, '');+ });++ it.each([+ { name: 'an open target', state: { readable: true, prState: 'OPEN' } },+ { name: 'a closed unmerged target', state: { readable: true, prState: 'CLOSED' } },+ { name: 'an unreadable target', state: { readable: false, prState: null } },+ { name: 'a different repository', meta: { reviewLoopPRUrl: 'https://github.com/another/project/pull/123' } },+ { name: 'a leave-open policy', meta: { reviewLoopLeaveOpen: true } },+ { name: 'an ordinary task', meta: { reviewLoopFollowUp: false } },+ { name: 'a failed process', execution: { success: false, exitCode: 1 } },+ { name: 'a provider safety refusal', execution: { executionInterruption: { category: 'content-refusal' } } },+ ])('does not replace a blocked outcome for $name', async ({ state, meta, execution }) => {+ isProgrammaticIoTaskType.mockReturnValue(false);+ mergedTarget.getOriginInfo.mockResolvedValue({ host: 'github.com', fullName: 'atomantic/PortOS' });+ mergedTarget.probeChangeRequestState.mockResolvedValue(state || { readable: true, prState: 'MERGED' });+ const task = reviewTask();+ Object.assign(task.metadata, meta);+ const reported = { status: 'blocked', reason: 'An unmet prerequisite remains.' };+ const result = await finalizeAgent({ agentId: 'agent-example', task, success: true, exitCode: 0,+ duration: 1000, workspacePath: '/example/repo', outputBuffer: '', ...execution,+ finalSummary: JSON.stringify({ summary: reported.reason, taskOutcome: reported }) });+ expect(result).toMatchObject({ success: false, taskOutcome: reported });+ expect(updateTask).not.toHaveBeenCalledWith(task.id, expect.objectContaining({ status: 'completed' }), 'internal');+ });+it('retains explicit approval with choices instead of retrying', async () => {const taskOutcome = { status: 'blocked', reason: 'Continuing would exceed the authorized budget.',recovery: { mode: 'approval', options: ['Increase the budget and retry.', 'Keep the work stopped.'] } };diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txtindex eef973657a..7729ff60a5 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-compact.txt@@ -1,3 +1,6 @@++**Already merged on entry:** Verify the assigned PR/MR state before reviewing. If it is MERGED, this follow-up is a successful `no-action-needed` result: skip reviews, fixes, validation and publication. Preserve local corrections and name their existing follow-up issue; do not reopen this task for separate delivery or unavailable retirement inventory. Request safe reconciliation for retained checkouts, then write the completion sentinel.+## Review-Loop Follow-up (PRIMARY OBJECTIVE)A previous agent finished task **task-example** and opened **PR https://github.com/example-org/example-repo/pull/42** on `feature/example`. Copilot is configured after another reviewer, so the system did NOT pre-request it — request the Copilot review yourself when you reach its turn (after the earlier reviewers’ fixes are pushed), and invoke the other reviewers yourself. Drive the review-and-fix loop to completion and merge.**Reviewers (in order)**: `ollama` → `copilot` → `codex` → `@example-user` (equivalent to `/do:pr --review-with ollama[qwen3-coder]~opt,copilot,codex[gpt-5.6-sol]~max=3,@example-user`).diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txtindex 381c677615..fdbc577607 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-gh-merge-verbose.txt@@ -1,4 +1,6 @@+**Already merged on entry:** Verify the assigned PR/MR state before reviewing. If it is MERGED, this follow-up is a successful `no-action-needed` result: skip reviews, fixes, validation and publication. Preserve local corrections and name their existing follow-up issue; do not reopen this task for separate delivery or unavailable retirement inventory. Request safe reconciliation for retained checkouts, then write the completion sentinel.+## Review-Loop Follow-up (PRIMARY OBJECTIVE)A previous agent finished implementing the work for source task **task-example** and opened **PR https://github.com/example-org/example-repo/pull/42** on branch `feature/example`. Copilot is configured after another reviewer, so the system did NOT pre-request it — request the Copilot review yourself when you reach its turn (after the earlier reviewers’ fixes are pushed), and invoke the other reviewers yourself. **Your job is to drive the review-and-fix loop to completion and merge the PR.**diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txtindex 068f31c36f..7dce7547b7 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-compact.txt@@ -1,3 +1,6 @@++**Already merged on entry:** Verify the assigned PR/MR state before reviewing. If it is MERGED, this follow-up is a successful `no-action-needed` result: skip reviews, fixes, validation and publication. Preserve local corrections and name their existing follow-up issue; do not reopen this task for separate delivery or unavailable retirement inventory. Request safe reconciliation for retained checkouts, then write the completion sentinel.+## Review-Loop Follow-up (PRIMARY OBJECTIVE)A previous agent finished task **task-example** and opened **PR https://github.com/example-org/example-repo/pull/42** on `feature/example`. Copilot is configured after another reviewer, so the system did NOT pre-request it — request the Copilot review yourself when you reach its turn (after the earlier reviewers’ fixes are pushed), and invoke the other reviewers yourself. Drive the review-and-fix loop to completion and merge.**Reviewers (in order)**: `ollama` → `copilot` → `codex` → `@example-user` (equivalent to `/do:pr --review-with ollama[qwen3-coder]~opt,copilot,codex[gpt-5.6-sol]~max=3,@example-user`).diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txtindex 15d07c75e9..d7e7d37ad4 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followUp-glab-merge-verbose.txt@@ -1,4 +1,6 @@+**Already merged on entry:** Verify the assigned PR/MR state before reviewing. If it is MERGED, this follow-up is a successful `no-action-needed` result: skip reviews, fixes, validation and publication. Preserve local corrections and name their existing follow-up issue; do not reopen this task for separate delivery or unavailable retirement inventory. Request safe reconciliation for retained checkouts, then write the completion sentinel.+## Review-Loop Follow-up (PRIMARY OBJECTIVE)A previous agent finished implementing the work for source task **task-example** and opened **PR https://github.com/example-org/example-repo/pull/42** on branch `feature/example`. Copilot is configured after another reviewer, so the system did NOT pre-request it — request the Copilot review yourself when you reach its turn (after the earlier reviewers’ fixes are pushed), and invoke the other reviewers yourself. **Your job is to drive the review-and-fix loop to completion and merge the PR.**diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txtindex 501e080f40..15e4da087d 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/followup-copilot-first.txt@@ -1,3 +1,6 @@++**Already merged on entry:** Verify the assigned PR/MR state before reviewing. If it is MERGED, this follow-up is a successful `no-action-needed` result: skip reviews, fixes, validation and publication. Preserve local corrections and name their existing follow-up issue; do not reopen this task for separate delivery or unavailable retirement inventory. Request safe reconciliation for retained checkouts, then write the completion sentinel.+## Review-Loop Follow-up (PRIMARY OBJECTIVE)A previous agent finished task **task-example** and opened **PR https://github.com/example-org/example-repo/pull/42** on `feature/example`. The system has already requested the initial Copilot code review (Copilot leads the order). Drive the review-and-fix loop to completion and merge.**Reviewers (in order)**: `copilot` → `codex` → `@example-user` (equivalent to `/do:pr --review-with copilot,codex[gpt-5.6-sol]~max=3,@example-user`).diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txtindex 243c42cb83..fe9bf7f31e 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-gh.txt@@ -1,3 +1,5 @@++**Already merged on entry:** Verify the assigned PR/MR state before reviewing. If it is MERGED, this follow-up is a successful `no-action-needed` result: skip reviews, fixes, validation and publication. Preserve local corrections and name their existing follow-up issue; do not reopen this task for separate delivery or unavailable retirement inventory. Request safe reconciliation for retained checkouts, then write the completion sentinel.## Merge Follow-up (PRIMARY OBJECTIVE)A previous agent finished the work for source task **task-example** and opened **PR https://github.com/example-org/example-repo/pull/42** on `feature/example`. **No code review was requested for this task, so nothing else will merge this PR Your job is to land it once CI is green.**diff --git a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-glab.txt b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-glab.txtindex fc670c2e14..cf6298f1c5 100644--- a/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-glab.txt+++ b/server/services/promptSections/__snapshots__/reviewLoopMatrix/mergeonly-followUp-glab.txt@@ -1,3 +1,5 @@++**Already merged on entry:** Verify the assigned PR/MR state before reviewing. If it is MERGED, this follow-up is a successful `no-action-needed` result: skip reviews, fixes, validation and publication. Preserve local corrections and name their existing follow-up issue; do not reopen this task for separate delivery or unavailable retirement inventory. Request safe reconciliation for retained checkouts, then write the completion sentinel.## Merge Follow-up (PRIMARY OBJECTIVE)A previous agent finished the work for source task **task-example** and opened **PR https://github.com/example-org/example-repo/pull/42** on `feature/example`. **No code review was requested for this task, so nothing else will merge this PR Your job is to land it once CI is green.**diff --git a/server/services/promptSections/reviewLifecycle.js b/server/services/promptSections/reviewLifecycle.jsindex 5ace66a218..f756058f1c 100644--- a/server/services/promptSections/reviewLifecycle.js+++ b/server/services/promptSections/reviewLifecycle.js@@ -753,7 +753,10 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,const leaveOpen = isTruthyMeta(metadata.reviewLoopLeaveOpen);const prUrl = metadata.reviewLoopPRUrl || '';const prBranch = metadata.reviewLoopPRBranch || '';- const forkNote = buildForkBranchInstructions(prBranch, metadata.forkHead)+ const completedTargetNote = !inline && !localOnly && !leaveOpen+ ? '\n**Already merged on entry:** Verify the assigned PR/MR state before reviewing. If it is MERGED, this follow-up is a successful `no-action-needed` result: skip reviews, fixes, validation and publication. Preserve local corrections and name their existing follow-up issue; do not reopen this task for separate delivery or unavailable retirement inventory. Request safe reconciliation for retained checkouts, then write the completion sentinel.\n'+ : '';+ const forkNote = completedTargetNote + buildForkBranchInstructions(prBranch, metadata.forkHead)+ buildDefaultBranchHeadInstructions(prBranch, isTruthyMeta(metadata.headIsDefaultBranch));const prNumber = metadata.reviewLoopPRNumber ?? '';const prOwner = metadata.reviewLoopPROwner ?? '';diff --git a/server/services/reviewFollowUpCompletion.js b/server/services/reviewFollowUpCompletion.jsnew file mode 100644index 0000000000..631a85d340--- /dev/null+++ b/server/services/reviewFollowUpCompletion.js@@ -0,0 +1,23 @@+/** A merged assigned PR completes a review/merge follow-up, independently of+ * preserved work that needs a separate delivery. Never infer this from prose,+ * local ancestry, a branch lookup alone, or an unavailable forge.+ */+import { isTruthyMeta } from '../lib/metadataFlags.js';+import { parsePullRequestUrl } from '../lib/gitForge.js';+import { PR_COMPLETIONS, resolvePrCompletion } from '../lib/prDisposition.js';++export async function verifyMergedReviewFollowUp(task, workspacePath) {+ const meta = task?.metadata;+ if (task?.taskType !== 'internal' || !isTruthyMeta(meta?.reviewLoopFollowUp)+ || isTruthyMeta(meta.reviewLoopLeaveOpen) || resolvePrCompletion(meta) === PR_COMPLETIONS.LEAVE_OPEN || !workspacePath+ || typeof meta.reviewLoopPRBranch !== 'string' || !meta.reviewLoopPRBranch.trim()) return null;+ const target = parsePullRequestUrl(meta.reviewLoopPRUrl);+ if (!target) return null;+ const { getOriginInfo } = await import('../lib/gitRemote.js');+ const origin = await getOriginInfo(workspacePath);+ if (origin?.host !== target.host || origin?.fullName !== `${target.owner}/${target.repo}`) return null;+ const { probeChangeRequestState } = await import('./prProbe.js');+ const state = await probeChangeRequestState(workspacePath, { number: target.number, branch: meta.reviewLoopPRBranch });+ return state.readable === true && state.prState === 'MERGED'+ ? { status: 'verified', prUrl: meta.reviewLoopPRUrl } : null;+}