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: honor a verified parallel-claim stand-down instead of retrying it as pr-missing
Adam Eivyb91809d04da2
diff --git a/server/services/agentFinalization.goalFidelity.test.js b/server/services/agentFinalization.goalFidelity.test.jsindex 3b1a792ac5..9ee7bae4c1 100644--- a/server/services/agentFinalization.goalFidelity.test.js+++ b/server/services/agentFinalization.goalFidelity.test.js@@ -87,7 +87,7 @@ vi.mock('./goalFidelityFollowUp.js', () => ({}));vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async () => null) }));-vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null) }));+vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null), extractFinalSummary: vi.fn(() => null) }));const getGoalFidelityConfigMock = vi.fn(async () => ({ enabled: true, backend: 'ollama', model: 'example-model', effort: null }));const runLocalGoalFidelityReviewMock = vi.fn();diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex b845a90789..f1a8f47f95 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -58,7 +58,7 @@ import { SKIP_LEARNING_VERDICT } from '../lib/learningVerdict.js';import { detectPrimaryCheckoutDrift, PRIMARY_CHECKOUT_MUTATED_ESCALATION, PRIMARY_CHECKOUT_MUTATED_REASON } from '../lib/primaryCheckoutGuard.js';import { canRunTaskOutputHookWithoutPayload, getTaskOutputPayloadPredicate, isProgrammaticIoTaskType, resolveTaskHookType, declaresNoCommitCriterion, isClaimFlowDispatch } from './taskTypeHooks.js';import { processAgentCompletion } from './agentCompletion.js';-import { extractSimplifySummaries } from './agentSummaryExtraction.js';+import { extractFinalSummary, extractSimplifySummaries } from './agentSummaryExtraction.js';import { usesCreativeDirectorScratchCwd, removeCreativeDirectorScratchCwd } from '../lib/spawnCwd.js';import { issueNumberFromRef } from './issueReconcile.js';@@ -288,6 +288,60 @@ function hasIssuePartialTrailer(body, issueNumber) {return new RegExp(`\\b(refs?|part of)\\s+#${issueNumber}\\b`, 'i').test(body);}+/**+ * Does the agent's own completion summary declare that this task's work+ * already landed through a DIFFERENT change request — the stand-down a retry+ * reaches when a parallel claim merged the same issue first?+ *+ * The resume briefing (`buildResumeSection`) tells a retry exactly this: "If a+ * PR is already **merged**, the work is done — go straight to your completion+ * step and report that." Without a finalize outcome that HONORS the report, a+ * correct stand-down fails as `pr-missing` (non-actionable), the task retries,+ * the next agent reads the same guidance, reaches the same conclusion, and+ * fails again — a loop no retry can break (task-mupxru13, three identical+ * failures).+ *+ * Mirrors `mergeGateContract.js`'s `summaryStatesLeaveOpen`: the agent's own+ * words are read as a DECISION, but never trusted alone — the caller must+ * verify the named change request is actually merged before this excuses a+ * missing PR. Two signals, not one:+ * - "already merged/landed/completed" language tied to the work, AND+ * - a change-request reference (PR/MR #N or a forge URL) the caller can ask+ * the forge about.+ *+ * @param {string|null|undefined} summary - the run's completion summary text+ * @returns {boolean}+ */+const LANDED_ELSEWHERE_DECLARATION = /\b(?:already|previously)\s+(?:been\s+)?(?:merged|landed|completed|shipped|fixed|implemented)\b/i;+const CHANGE_REQUEST_REFERENCE = /\b(?:pr|pull request|mr|merge request)\s*#(\d+)\b|\b(?:pr|mr)\/(\d+)\b|(?:\/(?:pull|merge_requests)\/(\d+))/i;++function summaryDeclaresWorkLanded(summary) {+ if (typeof summary !== 'string' || !summary.trim()) return false;+ return LANDED_ELSEWHERE_DECLARATION.test(summary) && CHANGE_REQUEST_REFERENCE.test(summary);+}++/**+ * The change-request identifiers a landed-elsewhere summary names, in the+ * order the patterns found them — `#N` first, then a URL path. Returns [] when+ * the summary names none, which is the caller's signal that nothing can be+ * verified (and the miss must stand).+ *+ * @param {string|null|undefined} summary+ * @returns {string[]} forge-native references (bare numbers) to probe+ */+function landedChangeRequestRefs(summary) {+ if (typeof summary !== 'string' || !summary.trim()) return [];+ const refs = [];+ const push = (n) => {+ const id = Number(n);+ if (Number.isSafeInteger(id) && id > 0 && !refs.includes(String(id))) refs.push(String(id));+ };+ for (const m of summary.matchAll(new RegExp(CHANGE_REQUEST_REFERENCE.source, 'gi'))) {+ push(m[1] ?? m[2] ?? m[3]);+ }+ return refs;+}+/*** The branch a finished agent's workspace is sitting on, or null when the* workspace is gone / not a repo / detached. Read at finalize time, while the@@ -367,6 +421,13 @@ const PR_OBSERVATION = Object.freeze({EMPTY_BRANCH: 'empty-branch',/** The forge holds no change request for a branch that does (or may) hold commits. */MISSING_PR: 'missing-pr',+ /**+ * The forge holds no change request for this branch, but the run's own+ * completion summary declares the work already landed via a change request+ * PortOS VERIFIED is merged — a parallel claim shipped the same issue first+ * and this run correctly stood down rather than opening a duplicate.+ */+ WORK_LANDED_ELSEWHERE: 'work-landed-elsewhere',/** The change request exists but does not close the issue its branch names. */INVALID_TRAILER: 'invalid-trailer',/** We could not ask, or could not read the answer. Says nothing about the PR. */@@ -401,6 +462,11 @@ const PR_OBSERVATION_POLICY = Object.freeze({[PR_OBSERVATION.VERIFIED_CLAIM]: Object.freeze({ completionOk: true, observed: true, namesBranch: true, recordable: true, category: null }),[PR_OBSERVATION.EMPTY_BRANCH]: Object.freeze({ completionOk: true, observed: true, namesBranch: true, recordable: true, category: null }),[PR_OBSERVATION.MISSING_PR]: Object.freeze({ completionOk: false, observed: true, namesBranch: true, recordable: true, category: PR_MISSING_CATEGORY }),+ // `work-landed-elsewhere` is a VERIFIED terminal state, not an excuse: the+ // agent's summary named a merged change request and the forge confirmed it,+ // so the run stands as reported. `recordable` so the ledger carries the+ // stand-down (verified: true) rather than silently omitting the transition.+ [PR_OBSERVATION.WORK_LANDED_ELSEWHERE]: Object.freeze({ completionOk: true, observed: true, namesBranch: true, recordable: true, category: null }),[PR_OBSERVATION.INVALID_TRAILER]: Object.freeze({ completionOk: false, observed: true, namesBranch: true, recordable: true, category: ISSUE_TRAILER_MISSING_CATEGORY }),[PR_OBSERVATION.FORGE_UNAVAILABLE]: Object.freeze({ completionOk: false, observed: true, namesBranch: true, recordable: false, category: FORGE_UNREACHABLE_CATEGORY }),});@@ -421,6 +487,42 @@ const prObservation = (outcome, fields = {}) => ({...fields,});+/**+ * Verify that a change request the agent's summary named is actually MERGED.+ *+ * The declaration alone is not evidence — an agent that shipped nothing can+ * write "already merged in PR #7" just as easily as one that checked. So the+ * stand-down is honored only when the forge CONFIRMS a named change request is+ * merged. Fail-safe polarity throughout: an unreachable forge or an unreadable+ * state is `null` (could not verify), never "verified", and the caller leaves+ * the miss standing rather than taking the agent's word for it.+ *+ * Probes every reference the summary names and accepts the FIRST merged one —+ * a stand-down summary typically names the parallel claim's PR plus the issue's+ * other landed work, and any one merged change request establishes that this+ * run's task outcome exists on the default branch.+ *+ * @param {string[]} refs - forge-native change-request numbers, from `landedChangeRequestRefs`+ * @param {{ cli: 'gh'|'glab', env: object|null }} forge - the resolved forge for this repo+ * @param {string} workspacePath+ * @returns {Promise<{ ref: string, state: string }|null>} null when no named change request could be verified merged+ */+async function verifyLandedChangeRequest(refs, forge, workspacePath) {+ for (const ref of refs) {+ if (forge.cli === 'glab') {+ const { getMergeRequestState } = await import('./gitlab.js');+ const view = await getMergeRequestState(ref, workspacePath).catch(() => ({ status: 'unavailable', state: null }));+ if (view.status === 'known' && view.state === 'MERGED') return { ref, state: view.state };+ } else {+ const { getPullRequestState } = await import('./github.js');+ const view = await getPullRequestState(ref, { cwd: workspacePath, env: forge.env || null })+ .catch(() => ({ status: 'unavailable', state: null }));+ if (view.status === 'known' && view.state === 'MERGED') return { ref, state: view.state };+ }+ }+ return null;+}+/*** Project an observation onto the historical `verifyPrClaim` result shape.*@@ -474,7 +576,7 @@ function prVerdictFromObservation(observation) {** @returns {Promise<{ outcome: string, branch: string|null, message: string|null, advisory: string|null, commitsAhead: number|null, inconclusive: boolean }>}*/-async function observePrClaim({ task, workspacePath, success, prExpected }) {+async function observePrClaim({ task, workspacePath, success, prExpected, agentSummary = null }) {// Only a run that CLAIMED success has a claim to verify; a failed run is// already recorded as failed.if (!prExpected || !success || !workspacePath) return prObservation(PR_OBSERVATION.SKIPPED);@@ -532,6 +634,23 @@ async function observePrClaim({ task, workspacePath, success, prExpected }) {// of an empty branch, so it leaves the miss standing.const ahead = await countCommitsAhead(workspacePath).catch(() => null);if (ahead === 0) return prObservation(PR_OBSERVATION.EMPTY_BRANCH, { branch });+ // The stand-down a parallel claim produces: the branch holds this run's+ // (now redundant) commits, the forge holds no change request for it, and+ // the agent's own summary says the work already landed elsewhere. The+ // resume briefing TELLS a retry to conclude exactly this — honor the report+ // only when the forge confirms a change request the summary names is+ // actually merged; the agent's word alone never excuses a miss.+ if (summaryDeclaresWorkLanded(agentSummary)) {+ const landed = await verifyLandedChangeRequest(+ landedChangeRequestRefs(agentSummary), { cli, env }, workspacePath+ ).catch(() => null);+ if (landed) {+ return prObservation(PR_OBSERVATION.WORK_LANDED_ELSEWHERE, {+ branch,+ advisory: `Work for this task already landed via ${noun} #${landed.ref} — this run stood down rather than opening a duplicate`,+ });+ }+ }return prObservation(PR_OBSERVATION.MISSING_PR, {branch,commitsAhead: ahead,@@ -555,18 +674,22 @@ async function observePrClaim({ task, workspacePath, success, prExpected }) {* - `ok: true, branchProvenEmpty: true` — the forge answered "no PR" and the* branch holds no commits, so there was nothing a PR could have been opened* for; the run concluded that no change was warranted+ * - `ok: true, advisory: …` — the forge answered "no PR" for a branch that+ * holds commits, but the run's summary declared the work already landed via+ * a change request the forge confirmed is MERGED (a parallel claim shipped+ * first; this run correctly stood down)* - `ok: false, category: 'pr-missing'` — the forge answered "no PR" for a* branch that DOES hold commits* - `ok: false, category: 'forge-unreachable'` — we could not ask*- * @returns {Promise<{ ok: boolean, category?: string, message?: string, branch?: string|null, branchProvenEmpty?: boolean, commitsAhead?: number|null, inconclusive?: boolean }>}+ * @returns {Promise<{ ok: boolean, category?: string, message?: string, advisory?: string, branch?: string|null, branchProvenEmpty?: boolean, commitsAhead?: number|null, inconclusive?: boolean }>}* `inconclusive: true` is set for every requested check that cannot reach an* unambiguous answer (no resolvable branch, unreachable forge, unreadable claim* body, or unreadable commit count). It is omitted for a proven empty branch and* a readable non-empty branch missing its PR.*/-export async function verifyPrClaim({ task, workspacePath, success, prExpected }) {- return prVerdictFromObservation(await observePrClaim({ task, workspacePath, success, prExpected }));+export async function verifyPrClaim({ task, workspacePath, success, prExpected, agentSummary = null }) {+ return prVerdictFromObservation(await observePrClaim({ task, workspacePath, success, prExpected, agentSummary }));}/**@@ -1142,12 +1265,12 @@ export async function stampLiExecutionVerdict(taskUpdate, task, { success, valid// scoring a correct no-op as a commit miss.async function resolveNoChangeObservation({noChangeAudit, prExpected, primaryObservation,- task, workspacePath, success, agentId,+ task, workspacePath, success, agentId, agentSummary = null,}) {if (!noChangeAudit) return null;const unproven = prObservation(PR_OBSERVATION.FORGE_UNAVAILABLE, { inconclusive: true });if (prExpected) return primaryObservation.outcome === PR_OBSERVATION.CHECK_THREW ? unproven : primaryObservation;- return observePrClaim({ task, workspacePath, success, prExpected: true })+ return observePrClaim({ task, workspacePath, success, prExpected: true, agentSummary }).catch(err => {emitLog('warn', `⚠️ No-change verification failed for ${agentId}: ${err.message}`, { agentId });return unproven;@@ -1241,9 +1364,16 @@ export async function finalizeAgent({// than manufacturing a failure out of a check that never ran, and say so by// NAME so the ledger gate below doesn't have to infer it from an empty result.const noChangeAudit = !terminatedByUser && reportedSuccess && permitsNoChangeCompletion(task);+ // The agent's own completion summary — the sentinel text when one was+ // ingested, the transcript tail otherwise. The PR check reads it for exactly+ // one purpose: recognizing the stand-down a parallel claim produces ("the+ // work already landed via PR #N"), which the resume briefing itself tells a+ // retry to report. Never trusted alone — the named change request is verified+ // against the forge before it excuses anything.+ const agentSummary = terminatedByUser ? null : extractFinalSummary(outputBuffer);const primaryPrObservation = terminatedByUser? prObservation(PR_OBSERVATION.SKIPPED)- : await observePrClaim({ task, workspacePath, success: reportedSuccess, prExpected })+ : await observePrClaim({ task, workspacePath, success: reportedSuccess, prExpected, agentSummary }).catch(err => {emitLog('warn', `⚠️ PR verification failed for ${agentId}: ${err.message}`, { agentId });return prObservation(PR_OBSERVATION.CHECK_THREW);@@ -1256,7 +1386,7 @@ export async function finalizeAgent({// a clean exit can satisfy its no-change success criterion.const noChangeObservation = await resolveNoChangeObservation({noChangeAudit, prExpected, primaryObservation: primaryPrObservation,- task, workspacePath, success: reportedSuccess, agentId,+ task, workspacePath, success: reportedSuccess, agentId, agentSummary,});const prEvidence = resolvePrEvidence({ primaryObservation: primaryPrObservation, noChangeObservation });const branchProvenEmpty = prEvidence.branchProvenEmpty;@@ -1363,6 +1493,14 @@ export async function finalizeAgent({emitLog('info', `🫧 ${agentId} opened no change request and committed nothing to ${prEvidence.evidenceBranch} — recording the run as complete with no change warranted`, {agentId, taskId: task?.id, branch: prEvidence.evidenceBranch});+ } else if (primaryPrObservation.outcome === PR_OBSERVATION.WORK_LANDED_ELSEWHERE) {+ // The parallel-claim stand-down: this run's commits are redundant, the work+ // itself is on the default branch via a change request the forge confirmed+ // merged. Worth surfacing — the branch cleanup below will discard the+ // duplicate commits, and the human should know why.+ emitLog('info', `🤝 ${agentId} opened no change request for ${prEvidence.evidenceBranch} but its summary's landed work was verified merged — recording the run as complete`, {+ agentId, taskId: task?.id, branch: prEvidence.evidenceBranch+ });}// #5994: the run shipped — but did it ship what was asked? Runs only on a rundiff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.jsindex 84abc99526..96dc49f9bd 100644--- a/server/services/agentFinalization.prVerification.test.js+++ b/server/services/agentFinalization.prVerification.test.js@@ -26,14 +26,19 @@ vi.mock('../lib/execGit.js', () => ({}));const findPullRequestForBranchMock = vi.fn();+const getPullRequestStateMock = vi.fn();vi.mock('./github.js', () => ({findPullRequestForBranch: (...args) => findPullRequestForBranchMock(...args),+ // The landed-elsewhere stand-down verifies a summary-named PR is merged.+ getPullRequestState: (...args) => getPullRequestStateMock(...args),ensureForgeReachable: vi.fn(async () => ({ ok: true, status: 'ok' })),}));const findMergeRequestForBranchMock = vi.fn();+const getMergeRequestStateMock = vi.fn();vi.mock('./gitlab.js', () => ({findMergeRequestForBranch: (...args) => findMergeRequestForBranchMock(...args),+ getMergeRequestState: (...args) => getMergeRequestStateMock(...args),}));const resolveForgeForRepoMock = vi.fn(async () => ({ cli: 'gh' }));@@ -98,7 +103,12 @@ vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async ()// ledger, and so the boundary assertions below can read the envelope (#4540).const { appendRunEvent } = vi.hoisted(() => ({ appendRunEvent: vi.fn(async () => ({ appended: true })) }));vi.mock('./agentRunEventLog.js', () => ({ appendRunEvent }));-vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null) }));+vi.mock('./agentSummaryExtraction.js', () => ({+ extractSimplifySummaries: vi.fn(() => null),+ // The landed-elsewhere check reads the run's own completion summary; the+ // default mock yields none, so a test opts in by setting `summaryText`.+ extractFinalSummary: vi.fn(() => summaryText),+}));import {verifyPrClaim,@@ -115,6 +125,9 @@ import {* answers, and feeding a branch name to the counter reads as "unknown".*/const git = { branch: 'claim/issue-1', ahead: 3, hasOriginRef: true };+// The completion summary `extractFinalSummary` is mocked to return — set by a+// test exercising the landed-elsewhere stand-down, null otherwise.+let summaryText = null;const ok = (stdout) => ({ stdout, stderr: '', exitCode: 0 });const routeGit = (args) => {if (args[0] === 'rev-parse' && args.includes('--abbrev-ref')) return ok(`${git.branch}\n`);@@ -136,11 +149,16 @@ const prTask = () => ({beforeEach(() => {vi.clearAllMocks();+ summaryText = null;Object.assign(git, { branch: 'claim/issue-1', ahead: 3, hasOriginRef: true });execGitMock.mockImplementation(async (args) => routeGit(args));getDefaultBranchMock.mockResolvedValue('main');findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'https://example.com/pr/7', body: 'Closes #1' });findMergeRequestForBranchMock.mockResolvedValue({ status: 'found', number: 12, url: 'https://example.com/mr/12', body: 'Closes #1' });+ // Default: a summary-named change request confirms as merged. A fail-safe+ // test overrides this with OPEN / unavailable / a throw.+ getPullRequestStateMock.mockResolvedValue({ status: 'known', state: 'MERGED', detail: null });+ getMergeRequestStateMock.mockResolvedValue({ status: 'known', state: 'MERGED', detail: null });resolveForgeForRepoMock.mockResolvedValue({ cli: 'gh' });});@@ -287,6 +305,97 @@ describe('verifyPrClaim (#3358)', () => {expect(getDefaultBranchMock).not.toHaveBeenCalled();});+ // ─── The parallel-claim stand-down (task-mupxru13) ──────────────────────+ // A swarm claim merged the issue's PR first; the resume briefing tells this+ // run "if a PR is already merged, the work is done — report that and stop."+ // The run commits, pushes, opens no duplicate PR, and reports success. The+ // branch holds commits and the forge holds no PR for it, which used to read+ // as pr-missing — a non-actionable failure that auto-retried into the same+ // conclusion three times. The stand-down is honored only when the forge+ // CONFIRMS a change request the summary names is merged.++ it('passes when the summary declares landed work and the forge confirms the named PR is merged', async () => {+ onBranch('claim/issue-1');+ git.ahead = 3;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ const summary = 'The work for this task already landed via PR #879 — this run stood down rather than opening a duplicate.';+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true, agentSummary: summary });+ expect(verdict.ok).toBe(true);+ expect(verdict.branch).toBe('claim/issue-1');+ expect(verdict.category).toBeUndefined();+ expect(verdict.advisory).toMatch(/pull request #879/i);+ expect(getPullRequestStateMock).toHaveBeenCalledWith('879', { cwd: '/w', env: null });+ });++ it('keeps pr-missing when the summary declares nothing — the miss stands', async () => {+ onBranch('claim/issue-1');+ git.ahead = 3;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true, agentSummary: 'Investigated the task; the branch holds my commits but I could not open a PR.' });+ expect(verdict.ok).toBe(false);+ expect(verdict.category).toBe(PR_MISSING_CATEGORY);+ expect(getPullRequestStateMock).not.toHaveBeenCalled();+ });++ it('keeps pr-missing when the summary names no change request — nothing can be verified', async () => {+ onBranch('claim/issue-1');+ git.ahead = 3;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true, agentSummary: 'The work was already merged by a parallel claim, so I stood down.' });+ expect(verdict.ok).toBe(false);+ expect(verdict.category).toBe(PR_MISSING_CATEGORY);+ expect(getPullRequestStateMock).not.toHaveBeenCalled();+ });++ it.each([+ ['an OPEN change request', { status: 'known', state: 'OPEN', detail: null }],+ ['an unavailable forge', { status: 'unavailable', state: null, detail: 'connect: refused' }],+ ])('keeps pr-missing when the named PR verifies as %s — the agent\'s word alone never excuses a miss', async (_label, state) => {+ onBranch('claim/issue-1');+ git.ahead = 3;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ getPullRequestStateMock.mockResolvedValue(state);+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true, agentSummary: 'The work already landed via PR #879 — standing down.' });+ expect(verdict.ok).toBe(false);+ expect(verdict.category).toBe(PR_MISSING_CATEGORY);+ });++ it('keeps pr-missing when the state probe itself throws', async () => {+ onBranch('claim/issue-1');+ git.ahead = 3;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ getPullRequestStateMock.mockRejectedValue(new Error('gh exploded'));+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true, agentSummary: 'The work already landed via PR #879 — standing down.' });+ expect(verdict.ok).toBe(false);+ expect(verdict.category).toBe(PR_MISSING_CATEGORY);+ });++ it('accepts the first MERGED reference the summary names on a GitLab repo, via glab', async () => {+ onBranch('claim/issue-1');+ git.ahead = 3;+ resolveForgeForRepoMock.mockResolvedValue({ cli: 'glab' });+ findMergeRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ getMergeRequestStateMock+ .mockResolvedValueOnce({ status: 'known', state: 'OPEN', detail: null })+ .mockResolvedValueOnce({ status: 'known', state: 'MERGED', detail: null });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true, agentSummary: 'The work already landed via MR #12 and MR #15 — standing down.' });+ expect(verdict.ok).toBe(true);+ expect(verdict.advisory).toMatch(/merge request #15/i);+ expect(getMergeRequestStateMock).toHaveBeenCalledWith('12', '/w');+ expect(getMergeRequestStateMock).toHaveBeenCalledWith('15', '/w');+ expect(getPullRequestStateMock).not.toHaveBeenCalled();+ });++ it('does not consult the summary on the empty-branch path — that proof needs no corroboration', async () => {+ onBranch('cos/sys-1/agent-1');+ git.ahead = 0;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true, agentSummary: 'Nothing to do; the work already landed via PR #879.' });+ expect(verdict.ok).toBe(true);+ expect(verdict.branchProvenEmpty).toBe(true);+ expect(getPullRequestStateMock).not.toHaveBeenCalled();+ });+it('fails with forge-unreachable — NOT pr-missing — when we could not ask', async () => {onBranch('claim/issue-1');findPullRequestForBranchMock.mockResolvedValue({@@ -393,6 +502,38 @@ describe('finalizeAgent — a PR-shaped run with no PR is not a success (#3358)'expect(resolveFailedTaskUpdateMock).not.toHaveBeenCalled();});+ it('records "completed" for a parallel-claim stand-down whose landed work the forge confirms', async () => {+ // task-mupxru13: the resume briefing tells a retry "if a PR is already+ // merged, the work is done — report that and stop." Three runs did exactly+ // that, and each was failed as pr-missing (non-actionable → auto-retry →+ // same conclusion). The stand-down must complete the run.+ onBranch('claim/issue-1');+ git.ahead = 3;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ summaryText = 'The work for this task already landed via PR #879 — this run stood down rather than opening a duplicate.';+ await finalize();++ expect(completeAgentMock).toHaveBeenCalledWith('agent-1', expect.objectContaining({ success: true }));+ expect(updateTaskMock).toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'completed' }), 'internal');+ expect(resolveFailedTaskUpdateMock).not.toHaveBeenCalled();+ });++ it('still fails a stand-down whose named PR the forge cannot confirm merged', async () => {+ // The fail-safe polarity: the declaration alone is not evidence. A summary+ // naming an OPEN (or unreachable) change request leaves the miss standing.+ onBranch('claim/issue-1');+ git.ahead = 3;+ findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });+ getPullRequestStateMock.mockResolvedValue({ status: 'known', state: 'OPEN', detail: null });+ summaryText = 'The work already landed via PR #879 — standing down.';+ await finalize();++ const [, result] = completeAgentMock.mock.calls[0];+ expect(result.success).toBe(false);+ expect(result.completionReason).toBe(PR_MISSING_CATEGORY);+ expect(updateTaskMock).not.toHaveBeenCalledWith('task-1', expect.objectContaining({ status: 'completed' }), 'internal');+ });+it.each(['autonomousJob', 'isInvestigation'])('proves a marked no-op %s even when cleanup owns PR creation', async (marker) => {onBranch('cos/sys-1/agent-1');git.ahead = 0;@@ -768,6 +909,18 @@ describe('finalizeAgent — completion, ledger and cleanup evidence agree per oucleanupEvidence: { ok: false, branch: 'claim/issue-1', category: PR_MISSING_CATEGORY, message: anyMessage, commitsAhead: null, inconclusive: true },ledger: { verified: false, branch: 'claim/issue-1', category: PR_MISSING_CATEGORY, branchProvenEmpty: false },},+ {+ name: 'work-landed-elsewhere — a verified parallel-claim stand-down completes, records verified, and carries its advisory to cleanup',+ arrange: () => {+ onBranch('claim/issue-1');+ git.ahead = 3;+ findPullRequestForBranchMock.mockResolvedValue(noPr);+ summaryText = 'The work already landed via PR #879 — this run stood down rather than opening a duplicate.';+ },+ success: true,+ cleanupEvidence: { ok: true, branch: 'claim/issue-1', advisory: expect.stringMatching(/pull request #879/i) },+ ledger: { verified: true, branch: 'claim/issue-1', category: null, branchProvenEmpty: false },+ },{name: 'empty-branch — a PROVEN empty branch completes, and cleanup must not open a PR for it',arrange: () => {diff --git a/server/services/agentFinalization.primaryCheckoutDrift.test.js b/server/services/agentFinalization.primaryCheckoutDrift.test.jsindex a63986360d..397cdef87c 100644--- a/server/services/agentFinalization.primaryCheckoutDrift.test.js+++ b/server/services/agentFinalization.primaryCheckoutDrift.test.js@@ -81,7 +81,7 @@ vi.mock('./taskTypeHooks.js', () => ({getTaskOutputPayloadPredicate: vi.fn(async () => null),}));vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async () => null) }));-vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null) }));+vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null), extractFinalSummary: vi.fn(() => null) }));import { checkPrimaryCheckoutDrift, finalizeAgent } from './agentFinalization.js';import { emitLog } from './cosEvents.js';diff --git a/server/services/agentFinalization.providerBench.test.js b/server/services/agentFinalization.providerBench.test.jsindex 1e77852094..65a051b717 100644--- a/server/services/agentFinalization.providerBench.test.js+++ b/server/services/agentFinalization.providerBench.test.js@@ -83,7 +83,7 @@ vi.mock('./taskTypeHooks.js', () => ({getTaskOutputPayloadPredicate: vi.fn(async () => null),}));vi.mock('./agentCompletion.js', () => ({ processAgentCompletion: vi.fn(async () => null) }));-vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null) }));+vi.mock('./agentSummaryExtraction.js', () => ({ extractSimplifySummaries: vi.fn(() => null), extractFinalSummary: vi.fn(() => null) }));import { finalizeAgent } from './agentFinalization.js';// The real detector and the real cooldown table supply the analysis shape anddiff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 754a010868..27ada3ae1c 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -184,10 +184,16 @@ async function worktreeCleanupContext(agentId, options) {async function probeWorktreePr(context, success) {if (!context.isWorktree || context.discardWorktree || context.prCreation !== PR_CREATION.IF_MISSING) return null;- const { worktreePath, worktreeBranch } = context;+ const { worktreePath, worktreeBranch, agentOutput } = context;if (success) {const { verifyPrClaim } = await import('./agentFinalization.js');- return verifyPrClaim({ workspacePath: worktreePath, success: true, prExpected: true })+ // `agentOutput` (the run's output buffer) rides along so the probe can+ // recognize the parallel-claim stand-down the same way finalize did —+ // without it, cleanup would re-ask the forge, see "no PR", and open a+ // DUPLICATE of the change request the summary says already landed.+ const { extractFinalSummary } = await import('./agentSummaryExtraction.js');+ const agentSummary = extractFinalSummary(agentOutput);+ return verifyPrClaim({ workspacePath: worktreePath, success: true, prExpected: true, agentSummary }).catch(err => ({ ok: false, category: 'forge-unreachable', message: err.message }));}const { findPullRequestForBranch } = await import('./github.js');diff --git a/server/services/gitlab.js b/server/services/gitlab.jsindex db97dd375b..5ef3004e86 100644--- a/server/services/gitlab.js+++ b/server/services/gitlab.js@@ -1,6 +1,6 @@import { spawn } from '../lib/childProcess.js';import { safeJSONParse } from '../lib/fileUtils.js';-import { withGlabJson } from '../lib/glabArgs.js';+import { GLAB_JSON_ARGS, withGlabJson } from '../lib/glabArgs.js';import { withSpawnCwdEnv } from '../lib/spawnCwd.js';// Mirrors execGh's DEFAULT_EXEC_GH_TIMEOUT_MS. `glab` hits the network, so a@@ -125,3 +125,31 @@ export async function findMergeRequestForBranch(branch, cwd) {if (!mr) return { status: 'none', number: null, url: null, detail: null };return { status: 'found', number: mr.iid ?? null, url: mr.web_url || null, body: typeof mr.description === 'string' ? mr.description : null, detail: mr.state || null };}++/**+ * Read ONE merge request's state by iid — the GitLab mirror of+ * `github.js#getPullRequestState`, with the same two-not-three-answers+ * discipline: `known` is a real forge answer, `unavailable` means we could not+ * ask (glab failed, not installed, or answered exit-0 without JSON), and a+ * caller must never read `unavailable` as "not merged".+ *+ * `glab mr view <iid>` answers a single OBJECT (not a list), so this goes+ * through `execGlab` + `safeJSONParse` rather than `execGlabJson`, whose+ * array-only salvage would misread it. `--output json` is the one correct+ * spelling (lib/glabArgs.js).+ *+ * @param {number|string} mrIid - the project-local MR iid+ * @param {string} cwd - repo root glab resolves the project from+ * @returns {Promise<{ status: 'known'|'unavailable', state: string|null, detail: string|null }>}+ * `state` is upper-cased (`MERGED` / `OPENED` / `CLOSED`) when status is `known`.+ */+export async function getMergeRequestState(mrIid, cwd) {+ if (!mrIid || !cwd) return { status: 'unavailable', state: null, detail: 'no MR reference or repo path' };+ const raw = await execGlab(['mr', 'view', String(mrIid), ...GLAB_JSON_ARGS], cwd).catch(() => null);+ if (raw === null) return { status: 'unavailable', state: null, detail: 'glab call failed' };+ const parsed = safeJSONParse(raw, null);+ const state = typeof parsed?.state === 'string' && parsed.state.trim() ? parsed.state.toUpperCase() : null;+ // A zero-exit glab that emitted nothing parseable told us nothing.+ if (!state) return { status: 'unavailable', state: null, detail: 'glab returned unparseable output' };+ return { status: 'known', state, detail: null };+}diff --git a/server/services/gitlab.test.js b/server/services/gitlab.test.jsindex 0d55efbee5..5b4fd877ca 100644--- a/server/services/gitlab.test.js+++ b/server/services/gitlab.test.js@@ -16,7 +16,7 @@ vi.mock('../lib/childProcess.js', () => ({execFile: () => { throw new Error('execFile is not used by gitlab.js'); },}));-const { findMergeRequestForBranch, execGlabJson } = await import('./gitlab.js');+const { findMergeRequestForBranch, getMergeRequestState, execGlabJson } = await import('./gitlab.js');/** A fake `glab` child that writes `stdout` then exits with `code`. */const glabChild = ({ code = 0, stdout = '' } = {}) => {@@ -75,6 +75,50 @@ describe('findMergeRequestForBranch (#3358)', () => {});});+describe('getMergeRequestState — the landed-elsewhere stand-down probe', () => {+ // The parallel-claim stand-down (task-mupxru13) honors an agent's "the work+ // already landed via MR #N" report only when the forge CONFIRMS the named MR+ // is merged. Same two-answers discipline as the GitHub mirror+ // (`getPullRequestState`): `unavailable` means we could not ask and must+ // never read as "not merged".+ it('reports `known` with the upper-cased state', async () => {+ spawnMock.mockImplementationOnce(() => glabChild({ stdout: '{"state":"merged"}' }));+ await expect(getMergeRequestState(12, '/repo'))+ .resolves.toEqual({ status: 'known', state: 'MERGED', detail: null });+ });++ it('views the MR by iid with the JSON output flag, inside the repo', async () => {+ await getMergeRequestState(12, '/repo');+ const [, args, opts] = spawnMock.mock.calls[0];+ expect(args).toEqual(['mr', 'view', '12', '--output', 'json']);+ expect(opts.cwd).toBe('/repo');+ });++ it('reports `unavailable` — never a state — when glab fails', async () => {+ spawnMock.mockImplementationOnce(() => glabChild({ code: 1 }));+ await expect(getMergeRequestState(12, '/repo'))+ .resolves.toEqual({ status: 'unavailable', state: null, detail: 'glab call failed' });+ });++ it('reports `unavailable` when a zero-exit glab emits unparseable output', async () => {+ spawnMock.mockImplementationOnce(() => glabChild({ stdout: 'not json' }));+ await expect(getMergeRequestState(12, '/repo'))+ .resolves.toEqual({ status: 'unavailable', state: null, detail: 'glab returned unparseable output' });+ });++ it('reports `unavailable` for a JSON object with no state field', async () => {+ spawnMock.mockImplementationOnce(() => glabChild({ stdout: '{"message":"404 Not Found"}' }));+ await expect(getMergeRequestState(12, '/repo'))+ .resolves.toEqual({ status: 'unavailable', state: null, detail: 'glab returned unparseable output' });+ });++ it('never spawns without an MR reference or a repo path', async () => {+ await expect(getMergeRequestState('', '/repo')).resolves.toMatchObject({ status: 'unavailable' });+ await expect(getMergeRequestState(12, '')).resolves.toMatchObject({ status: 'unavailable' });+ expect(spawnMock).not.toHaveBeenCalled();+ });+});+describe('execGlab timeout (#3358)', () => {it('kills a stalled glab and resolves null instead of hanging the caller', async () => {// Without this bound, the agent PR-claim verification that awaits an MR