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: verify claim PR closing trailers (#5186)
[._.]/ Adam Eivy12a5b13f2512
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 558edbb6b5..37cfd0688a 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -41,6 +41,7 @@ import { canRunTaskOutputHookWithoutPayload, getTaskOutputPayloadPredicate, isPrimport { processAgentCompletion } from './agentCompletion.js';import { extractSimplifySummaries } from './agentSummaryExtraction.js';import { usesCreativeDirectorScratchCwd, removeCreativeDirectorScratchCwd } from '../lib/spawnCwd.js';+import { issueNumberFromRef } from './issueReconcile.js';/*** Release the execution lane and complete tool-execution tracking for a@@ -241,6 +242,15 @@ const HOOK_ABORTED_BEFORE_EVALUATION = new Set(['no-app', 'app-not-found']);*/export const PR_MISSING_CATEGORY = 'pr-missing';export const FORGE_UNREACHABLE_CATEGORY = 'forge-unreachable';+export const ISSUE_TRAILER_MISSING_CATEGORY = 'issue-trailer-missing';++function hasIssueClosingTrailer(body, issueNumber) {+ return new RegExp(`\\b(clos(e|es|ed)|fix(e[sd])?|resolv(e|es|ed))\\s+#${issueNumber}\\b`, 'i').test(body);+}++function hasIssuePartialTrailer(body, issueNumber) {+ return new RegExp(`\\b(refs?|part of)\\s+#${issueNumber}\\b`, 'i').test(body);+}function isVerifiedNoChangeTask(task) {const isPersistedTrue = (value) => value === true || value === 'true';@@ -316,7 +326,7 @@ async function countCommitsAhead(workspacePath) {* would fail and record every correct MR run as `forge-unreachable`.** Four outcomes, never collapsed:- * - `ok: true` — a PR exists, or there was nothing to check+ * - `ok: true` — a PR exists with a valid claim trailer, or there was nothing to check* - `ok: true, noChangesToShip: 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@@ -326,9 +336,9 @@ async function countCommitsAhead(workspacePath) {** @returns {Promise<{ ok: boolean, category?: string, message?: string, branch?: string|null, noChangesToShip?: boolean, commitsAhead?: number|null, inconclusive?: boolean }>}* `inconclusive: true` is set for every requested check that cannot reach an- * unambiguous answer about an empty branch (no resolvable branch, unreachable- * forge, or unreadable commit count). It is omitted for a found PR, a proven- * empty branch, and a readable non-empty branch missing its PR.+ * 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 }) {// Only a run that CLAIMED success has a claim to verify; a failed run is@@ -352,7 +362,33 @@ export async function verifyPrClaim({ task, workspacePath, success, prExpected }: await (await import('./github.js')).findPullRequestForBranch(branch, { cwd: workspacePath, env: env || null });const noun = cli === 'glab' ? 'merge request' : 'pull request';- if (found.status === 'found') return { ok: true, branch };+ if (found.status === 'found') {+ const issueNumber = issueNumberFromRef(branch);+ if (issueNumber === null) return { ok: true, branch };+ if (typeof found.body !== 'string') {+ return {+ ok: false,+ branch,+ category: FORGE_UNREACHABLE_CATEGORY,+ message: `Could not read the ${noun} body for branch ${branch} to verify issue #${issueNumber}`,+ inconclusive: true,+ };+ }+ if (hasIssueClosingTrailer(found.body, issueNumber)) return { ok: true, branch };+ if (hasIssuePartialTrailer(found.body, issueNumber)) {+ return {+ ok: true,+ branch,+ advisory: `${noun[0].toUpperCase()}${noun.slice(1)} for branch ${branch} partially ships issue #${issueNumber}; reconcile the remaining scope after merge.`,+ };+ }+ return {+ ok: false,+ branch,+ category: ISSUE_TRAILER_MISSING_CATEGORY,+ message: `${noun[0].toUpperCase()}${noun.slice(1)} for branch ${branch} does not contain a closing trailer for issue #${issueNumber}`,+ };+ }if (found.status === 'none') {// "No PR" is only a MISS if there was something to open one for. An agent// that investigated its task, found the defect already fixed on main, anddiff --git a/server/services/agentFinalization.prVerification.test.js b/server/services/agentFinalization.prVerification.test.jsindex eb07a2290c..eb95bd9892 100644--- a/server/services/agentFinalization.prVerification.test.js+++ b/server/services/agentFinalization.prVerification.test.js@@ -96,6 +96,7 @@ import {finalizeAgent,PR_MISSING_CATEGORY,FORGE_UNREACHABLE_CATEGORY,+ ISSUE_TRAILER_MISSING_CATEGORY,} from './agentFinalization.js';/**@@ -129,8 +130,8 @@ beforeEach(() => {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' });- findMergeRequestForBranchMock.mockResolvedValue({ status: 'found', number: 12, url: 'https://example.com/mr/12' });+ 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' });resolveForgeForRepoMock.mockResolvedValue({ cli: 'gh' });});@@ -142,6 +143,43 @@ describe('verifyPrClaim (#3358)', () => {expect(findPullRequestForBranchMock).toHaveBeenCalledWith('claim/issue-1', { cwd: '/w', env: null });});+ it('fails claim branches with a dedicated category when the PR body lacks a closing trailer', async () => {+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'https://example.com/pr/7', body: 'Summary only' });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(verdict).toMatchObject({ ok: false, category: ISSUE_TRAILER_MISSING_CATEGORY, branch: 'claim/issue-1' });+ expect(verdict.message).toMatch(/issue #1/i);+ });++ it.each(['Closes #1', 'Fixes #1', 'Resolves #1'])('accepts a closing trailer: %s', async (body) => {+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'https://example.com/pr/7', body });+ await expect(verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true }))+ .resolves.toMatchObject({ ok: true, branch: 'claim/issue-1' });+ });++ it.each(['Refs #1', 'Part of #1'])('permits a partial-ship trailer with an advisory: %s', async (body) => {+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'https://example.com/pr/7', body });+ await expect(verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true }))+ .resolves.toMatchObject({ ok: true, branch: 'claim/issue-1', advisory: expect.stringMatching(/partially ships/i) });+ });++ it('skips trailer verification for a non-claim branch', async () => {+ onBranch('feature/pr-body-verification');+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'https://example.com/pr/7', body: null });+ await expect(verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true }))+ .resolves.toMatchObject({ ok: true, branch: 'feature/pr-body-verification' });+ });++ it('is inconclusive rather than reporting a trailer miss when the PR body is unreadable', async () => {+ onBranch('claim/issue-1');+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'https://example.com/pr/7', body: null });+ const verdict = await verifyPrClaim({ task: prTask(), workspacePath: '/w', success: true, prExpected: true });+ expect(verdict).toMatchObject({ ok: false, category: FORGE_UNREACHABLE_CATEGORY, inconclusive: true });+ expect(verdict.category).not.toBe(ISSUE_TRAILER_MISSING_CATEGORY);+ });+it('threads the repo-pinned gh credential into the lookup', async () => {// The agent opened its PR as the repo-owner-matched account; querying as the// ambient one may not even see it on a multi-login host.@@ -459,7 +497,7 @@ describe('finalizeAgent — a PR-shaped run with no PR is not a success (#3358)'findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });await expect(finalize()).resolves.toMatchObject({ success: false });- findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'u' });+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'u', body: 'Closes #1' });await expect(finalize()).resolves.toMatchObject({ success: true });});@@ -623,7 +661,7 @@ describe('finalizeAgent — the PR verdict is only recorded when one was reachedonBranch('claim/issue-1');findPullRequestForBranchMock.mockResolvedValue({ status: 'none', number: null, url: null, detail: null });await finalize();- findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'https://example.com/pr/7' });+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', number: 7, url: 'https://example.com/pr/7', body: 'Closes #1' });await finalize();expect(prVerified().map((e) => e.data.verified)).toEqual([false, true]);diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 3b4d548df4..4745d01517 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -428,7 +428,7 @@ For EACH picked issue, spawn a subagent that runs the single-issue **Phases 2–**Each fan-out agent gets its OWN scratch subdirectory — the scratchpad root is off-limits.** Every agent in this run shares one session scratchpad path, and every agent runs these byte-identical instructions, so left to themselves two agents pick the same obvious filename (\`pr-body.md\`) and silently clobber each other — last writer wins, the command still exits 0, and the wrong text lands on the wrong ${pr}. So: **each fan-out agent writes ALL temp files under \`<scratchpad>/issue-<num>/\` (its own issue number), and NEVER writes to the scratchpad root** (the root stays the orchestrator's). That covers ${pr} body drafts, review notes, diff dumps, test output — every scratch artifact, not just the body file. Create the directory before first use (\`mkdir -p\`). Filenames inside it may be as obvious as you like; the directory is what makes them unique. **If your environment gives you no scratchpad path at all**, use \`$(mktemp -d)/issue-<num>\` instead — never a path inside the source repo or inside your worktree, where it would show up as untracked cruft or get swept into a commit.-**Verify the ${pr} body's issue trailer after create AND after every edit.** The ${pr}-body flow is create-then-edit — the file is written once, then re-read minutes later during the review loop — which is a wide window for a stale or foreign body to land. Belt to the namespacing's braces: immediately after \`create\` and after each body \`edit\`, re-read the published body with \`${bodyCmd}\` — **note it takes no number: both CLIs resolve the ${pr} from your checked-out \`claim/issue-<num>\` branch, and passing an ISSUE number where a ${pr} number belongs is how you end up reading (and then "correcting") someone else's ${pr}** — and confirm the body carries this agent's own trailer (\`Closes #<num>\` or \`Refs #<num>\` for ITS issue number). If it does not, rewrite the body from this agent's own scratch file and re-verify. **Cap this at 2 rewrites:** if the trailer still doesn't match, the scratch file itself is suspect — re-derive the body from your own branch's commits/diff for one final attempt, and if that also fails, STOP, leave the ${pr} open, and say so in the result you hand back. Never loop on it: Phase C waits for every agent to finish, so one agent stuck re-publishing blocks the whole batch's merges. And never assume a zero exit code means the right body was published.+**Verify the ${pr} body's issue trailer after create AND after every edit.** The ${pr}-body flow is create-then-edit — the file is written once, then re-read minutes later during the review loop — which is a wide window for a stale or foreign body to land. Belt to the namespacing's braces: immediately after \`create\` and after each body \`edit\`, re-read the published body with \`${bodyCmd}\` — **note it takes no number: both CLIs resolve the ${pr} from your checked-out \`claim/issue-<num>\` branch, and passing an ISSUE number where a ${pr} number belongs is how you end up reading (and then "correcting") someone else's ${pr}** — and confirm the body carries this agent's own trailer. A full-scope ship MUST carry \`Closes #<num>\` for this issue; \`Refs #<num>\` is permitted ONLY for a deliberate partial ship that also records the required \`Done ✓ / Remaining ▢\` reconciliation comment. If it does not, rewrite the body from this agent's own scratch file and re-verify. **Cap this at 2 rewrites:** if the trailer still doesn't match, the scratch file itself is suspect — re-derive the body from your own branch's commits/diff for one final attempt, and if that also fails, STOP, leave the ${pr} open, and say so in the result you hand back. Never loop on it: Phase C waits for every agent to finish, so one agent stuck re-publishing blocks the whole batch's merges. And never assume a zero exit code means the right body was published.## Phase C — Serialize the merges (orchestrator, after all agents finish)Merge the ready ${pr}s ONE AT A TIME. For each: re-sync onto the latest default branch, gate on **required** CI (one re-run on a flaky required check, then proceed; a real failure or an irreconcilable conflict leaves that ${pr} OPEN and recorded — move to the next), then \`${mergeCmd}\`. After all merges, run Phase 7 cleanup once per merged worktree.diff --git a/server/services/github.ghHealth.test.js b/server/services/github.ghHealth.test.jsindex 153c47abcc..64877b3e74 100644--- a/server/services/github.ghHealth.test.js+++ b/server/services/github.ghHealth.test.js@@ -255,8 +255,8 @@ describe('findPullRequestForBranch (#3358)', () => {};it('reports `found` with the PR number', async () => {- spawnMock.mockImplementation(() => ghChild({ stdout: '[{"number":7,"url":"https://example.com/pr/7","state":"OPEN"}]' }));- await expect(findPullRequestForBranch('claim/issue-1')).resolves.toMatchObject({ status: 'found', number: 7 });+ spawnMock.mockImplementation(() => ghChild({ stdout: '[{"number":7,"url":"https://example.com/pr/7","body":"Closes #1","state":"OPEN"}]' }));+ await expect(findPullRequestForBranch('claim/issue-1')).resolves.toMatchObject({ status: 'found', number: 7, body: 'Closes #1' });});it('reports `none` for an ANSWERED empty list', async () => {diff --git a/server/services/github.js b/server/services/github.jsindex b9d9febd5c..1108267d0d 100644--- a/server/services/github.js+++ b/server/services/github.js@@ -538,12 +538,12 @@ export async function ensureForgeReachable(label, { hostname = null } = {}) {* `resolveForgeForRepo` so the lookup authenticates as the SAME repo-owner-* pinned account that opened the PR — on a multi-login host the ambient* account may not even see it, which would read as "no PR".- * @returns {Promise<{ status: 'found'|'none'|'unavailable', number: number|null, url: string|null, detail: string|null }>}+ * @returns {Promise<{ status: 'found'|'none'|'unavailable', number: number|null, url: string|null, body: string|null, detail: string|null }>}*/export async function findPullRequestForBranch(branch, { cwd = null, env = null } = {}) {if (!branch) return { status: 'unavailable', number: null, url: null, detail: 'no branch name' };const raw = await execGh(- ['pr', 'list', '--head', branch, '--state', 'all', '--limit', '1', '--json', 'number,url,state'],+ ['pr', 'list', '--head', branch, '--state', 'all', '--limit', '1', '--json', 'number,url,body,state'],DEFAULT_EXEC_GH_TIMEOUT_MS,{ cwd, env }).catch(err => err);@@ -558,7 +558,7 @@ export async function findPullRequestForBranch(branch, { cwd = null, env = null}const pr = parsed[0];if (!pr) return { status: 'none', number: null, url: null, detail: null };- return { status: 'found', number: pr.number ?? null, url: pr.url || null, detail: pr.state || null };+ return { status: 'found', number: pr.number ?? null, url: pr.url || null, body: typeof pr.body === 'string' ? pr.body : null, detail: pr.state || null };}/**diff --git a/server/services/gitlab.js b/server/services/gitlab.jsindex bb0c19aa2a..2e525d7a53 100644--- a/server/services/gitlab.js+++ b/server/services/gitlab.js@@ -97,7 +97,7 @@ export async function execGlabJson(args, cwd, timeoutMs = DEFAULT_EXEC_GLAB_TIME** @param {string} branch - source branch name* @param {string} cwd - repo root (glab resolves the project from its cwd)- * @returns {Promise<{ status: 'found'|'none'|'unavailable', number: number|null, url: string|null, detail: string|null }>}+ * @returns {Promise<{ status: 'found'|'none'|'unavailable', number: number|null, url: string|null, body: string|null, detail: string|null }>}*/export async function findMergeRequestForBranch(branch, cwd) {if (!branch || !cwd) return { status: 'unavailable', number: null, url: null, detail: 'no branch or repo path' };@@ -110,5 +110,5 @@ export async function findMergeRequestForBranch(branch, cwd) {}const mr = rows[0];if (!mr) return { status: 'none', number: null, url: null, detail: null };- return { status: 'found', number: mr.iid ?? null, url: mr.web_url || null, detail: mr.state || 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 };}diff --git a/server/services/gitlab.test.js b/server/services/gitlab.test.jsindex 9957f906b4..0d55efbee5 100644--- a/server/services/gitlab.test.js+++ b/server/services/gitlab.test.js@@ -38,10 +38,10 @@ beforeEach(() => {describe('findMergeRequestForBranch (#3358)', () => {it('reports `found` with the MR iid', async () => {spawnMock.mockImplementationOnce(() => glabChild({- stdout: '[{"iid":12,"web_url":"https://gitlab.example/g/p/-/merge_requests/12","state":"opened"}]'+ stdout: '[{"iid":12,"web_url":"https://gitlab.example/g/p/-/merge_requests/12","description":"Closes #1","state":"opened"}]'}));await expect(findMergeRequestForBranch('claim/issue-1', '/repo'))- .resolves.toMatchObject({ status: 'found', number: 12 });+ .resolves.toMatchObject({ status: 'found', number: 12, body: 'Closes #1' });});it('queries by source branch across every state, asking for JSON with the long --output form', async () => {