Skip to content

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

fix: verify selected claim stand-downs against their tracker (#13373)

Adam Eivyf9fa01960ae5
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index 76fa974a3c..635075af5b 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -20,6 +20,24 @@ is `completed`, `no-action-needed`, `blocked`, or `incomplete`. Reasons describe
the delivery evidence, remaining work, or unmet prerequisite. A reported no-op
requires the task's existing delivery checks or permitted empty-branch proof.
+Claim workflows can also settle a reported `no-action-needed` result from a
+read-only tracker proof. The server resolves the configured app and repository,
+checks the agent's task and source checkout binding, then verifies the pinned
+`claimTarget` or every server-persisted selected `claimBranches` issue. On
+GitHub, a closed `NOT_PLANNED` issue with a verified repository operator closure
+is a stand-down, not code delivery. A `COMPLETED` issue needs an exact closing
+relationship to a merged PR in the same repository's current default branch,
+with its merge commit recorded. GitLab supports the corresponding delivered
+case through the MR's `closes_issues` relationship. GitLab closure without that
+proof, Jira and file trackers, open or mismatched issues, unreadable responses,
+and arbitrary agent prose remain unverified. Bounded tracker reads may refuse
+when the relevant history or closing relationship is outside their result window.
+
+Normal completion and restart recovery use the same verifier, perform no tracker
+writes, and retain the scoped evidence in the agent's `claimDisposition` result.
+This proof does not bypass existing PR, drift or fidelity checks, or erase a
+recorded failed validation gate during recovery.
+
Agent results and run history retain `executionSuccess` independently of the
validated `taskOutcome`; task metadata retains the outcome too. Explicit blocked
or incomplete reports park the task and preserve work for continuation. Cards
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index 0ae51664d6..c1202f9c8f 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -1,3 +1,4 @@
+import { hasClaimFlowContract } from '../lib/claimFlowTaskTypes.js';
import { isLegacyDeepAudit } from '../lib/auditWorkflow.js';
import { retryHoldMetadata, isDeliveryCleanupHeld } from '../lib/taskRetryHold.js';
import { PR_COMPLETIONS, resolvePrCompletion, PR_MISSING_CATEGORY, prClaimWasVerified } from '../lib/prDisposition.js';
@@ -130,7 +131,7 @@ 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 }) {
+export async function evaluateSuccessCriteria({ task, terminatedByUser, workspacePath, startedAt = null, success = false, hookResult = null, branchProvenEmpty = false, emptyBranchInconclusiveEvidence = null, claimDisposition = null }) {
if (terminatedByUser) return null;
const taskType = task?.taskType || 'user';
// The SCHEDULED type (`metadata.analysisType`) if any, else the queue category —
@@ -150,6 +151,9 @@ export async function evaluateSuccessCriteria({ task, terminatedByUser, workspac
if (isProgrammaticIoTaskType(scheduledType)) {
return resolveProgrammaticIoVerdict({ success, hookResult });
}
+ // Only the server-owned selected-issue verifier supplies this proof. Ordinary
+ // claim shipping keeps its existing PR/fidelity gates and undeclared criterion.
+ if (success && hasClaimFlowContract(task) && claimDisposition?.status === 'verified') return true;
// Interactive/user tasks declare no machine-checkable criterion; neither does
// a run missing the task id or workspace needed to validate.
if (taskType === 'user' || !task?.id || !workspacePath) return null;
@@ -1167,6 +1171,13 @@ export function dispatchRecoveredTaskOutputHook({ agentId, task, success, worksp
});
}
+async function completionClaimDisposition({ task, agent, agentId, reportedOutcome, success }) {
+ if (!success || reportedOutcome?.status !== 'no-action-needed' || !hasClaimFlowContract(task)) return null;
+ return import('./claimDisposition.js').then(async ({ verifyClaimDisposition }) =>
+ verifyClaimDisposition({ task, agent: agent || await getAgentRecord(agentId), reportedOutcome, success }))
+ .catch(() => ({ status: 'unverified', reason: 'tracker-unavailable' }));
+}
+
/**
* Retire an agent whose process is gone — the one step list both recovery
* paths now share (issue #8440). Before this, the orphan sweep
@@ -1234,9 +1245,15 @@ export async function retireDeadAgent({ agent, task, success, exitCode, duration
});
if (Number(task?.metadata?.auditDispositionVersion) === 1 && recoveredHook?.auditDisposition?.status !== 'complete') effectiveSuccess = false;
- const validationPassed = isProgrammaticIoTaskType(resolveTaskHookType(task))
+ const claimDisposition = await completionClaimDisposition({ task, agent, reportedOutcome, success: effectiveSuccess && executionSuccess });
+ const recoveredValidation = isProgrammaticIoTaskType(resolveTaskHookType(task))
? resolveProgrammaticIoVerdict({ success: effectiveSuccess, hookResult: recoveredHook })
: agent.result?.validationPassed ?? null;
+ // A disposition never erases a recorded failed delivery gate. A saved pass,
+ // however, cannot replace a fresh selected-issue proof on no-op recovery.
+ const validationPassed = claimDisposition && recoveredValidation !== false
+ ? claimDisposition.status === 'verified' ? true : null
+ : recoveredValidation;
const taskOutcome = reportedOutcome ? resolveTaskOutcome({ reported: reportedOutcome,
success: effectiveSuccess, validationPassed }) : null;
if (['blocked', 'incomplete'].includes(taskOutcome?.status)) effectiveSuccess = false;
@@ -1275,6 +1292,7 @@ export async function retireDeadAgent({ agent, task, success, exitCode, duration
...(savedCleanup ? { cleanupDeliveryVerified: true } : {}),
taskOutcome,
validationPassed,
+ ...(claimDisposition ? { claimDisposition } : {}),
exitCode,
duration,
orphaned: true,
@@ -1914,6 +1932,8 @@ export async function finalizeAgent({
// exit-code `success`, so task-learning telemetry can distinguish "ran clean
// but produced nothing" from a genuine success. Best-effort — a validation
// check failure must never block finalize (falls back to the null sentinel).
+ const claimDisposition = await completionClaimDisposition({ task, agentId,
+ reportedOutcome: reportedTaskOutcome, success: verdict.success && executionSuccess && !terminatedByUser });
const validationPassed = await evaluateSuccessCriteria({
task,
terminatedByUser,
@@ -1923,6 +1943,7 @@ export async function finalizeAgent({
hookResult,
branchProvenEmpty,
emptyBranchInconclusiveEvidence: prEvidence.emptyBranchInconclusiveEvidence,
+ claimDisposition,
})
.catch(err => {
emitLog('warn', `⚠️ Success-criteria validation failed for ${agentId}: ${err.message}`, { agentId });
@@ -1969,6 +1990,7 @@ export async function finalizeAgent({
await completeAgent(agentId, { ...completionRecord({
task, verdict: deliveryVerdict, hookResult, fidelity, executionInterruption, exitCode, duration, outputBuffer, validationPassed,
}), executionSuccess, taskOutcome,
+ ...(claimDisposition ? { claimDisposition } : {}),
...(['task-approval', 'task-recovery-exhausted'].includes(taskUpdate.metadata?.blockedCategory)
|| taskUpdate.metadata?.retryPendingCleanup === agentId || taskUpdate.metadata?.deliveryRecoveryAgentId === agentId
? { deliveryRecoveryOwned: true } : {}),
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index 92ec52c1cb..05c625375d 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -1,3 +1,5 @@
+const claimVerifier = vi.hoisted(() => ({ verifyClaimDisposition: vi.fn() }));
+vi.mock('./claimDisposition.js', () => claimVerifier);
vi.mock('../lib/fileUtils.js', async importOriginal => {
const actual = await importOriginal();
return { ...actual, tryReadFile: vi.fn(actual.tryReadFile) };
@@ -423,6 +425,61 @@ describe('recovery output-hook dispatch (#3182)', () => {
expect(addTask).not.toHaveBeenCalled();
});
+ it.each(['normal', 'restart'])('settles a selected claim no-op from the shared verifier during %s completion', async mode => {
+ isProgrammaticIoTaskType.mockReturnValue(false);
+ const task = { id: 'claim-example', taskType: 'user', metadata: { app: 'app-example', claimFlow: true, claimTarget: '42' } };
+ const taskOutcome = { status: 'no-action-needed', reason: 'Selected issue no longer requires a change.' };
+ const claimDisposition = { status: 'verified', taskId: task.id, issues: [{ issue: 42, disposition: 'not-planned' }] };
+ persistedAgent.taskId = task.id;
+ persistedAgent.metadata.taskOutcome = taskOutcome;
+ persistedAgent.metadata.taskOutcomeSource = 'terminal-result';
+ claimVerifier.verifyClaimDisposition.mockResolvedValue(claimDisposition);
+ try {
+ if (mode === 'normal') await finalizeAgent({ agentId: persistedAgent.id, task, success: true, exitCode: 0,
+ finalSummary: JSON.stringify({ summary: 'Claim stood down.', taskOutcome }) });
+ else await retireDeadAgent({ agent: persistedAgent, task, success: true, exitCode: 0, duration: 100 });
+ expect(claimVerifier.verifyClaimDisposition).toHaveBeenLastCalledWith(expect.objectContaining({ task,
+ agent: expect.objectContaining({ id: persistedAgent.id, taskId: task.id }), reportedOutcome: taskOutcome, success: true }));
+ expect(completeAgent).toHaveBeenLastCalledWith(persistedAgent.id, expect.objectContaining({ success: true,
+ validationPassed: true, taskOutcome, claimDisposition }));
+ expect(hook).not.toHaveBeenCalled();
+ } finally { isProgrammaticIoTaskType.mockReturnValue(true); }
+ });
+
+ it.each(['normal', 'restart'])('keeps an unreadable tracker unverified during %s completion even with a saved validation pass', async mode => {
+ isProgrammaticIoTaskType.mockReturnValue(false);
+ const task = { id: 'claim-example', taskType: 'user', metadata: { app: 'app-example', claimFlow: true, claimTarget: '42' } };
+ const taskOutcome = { status: 'no-action-needed', reason: 'Agent says done.' };
+ persistedAgent.taskId = task.id;
+ persistedAgent.result = { validationPassed: true };
+ persistedAgent.metadata.taskOutcome = taskOutcome;
+ persistedAgent.metadata.taskOutcomeSource = 'terminal-result';
+ claimVerifier.verifyClaimDisposition.mockRejectedValue(new Error('Invented forge outage'));
+ try {
+ if (mode === 'normal') await finalizeAgent({ agentId: persistedAgent.id, task, success: true, exitCode: 0,
+ finalSummary: JSON.stringify({ summary: 'Claim stood down.', taskOutcome }) });
+ else await retireDeadAgent({ agent: persistedAgent, task, success: true, exitCode: 0, duration: 100 });
+ expect(completeAgent).toHaveBeenLastCalledWith(persistedAgent.id, expect.objectContaining({ success: false,
+ validationPassed: null, taskOutcome: { status: 'incomplete', reason: 'The reported no-action-needed result was not verified.' },
+ claimDisposition: { status: 'unverified', reason: 'tracker-unavailable' } }));
+ } finally { isProgrammaticIoTaskType.mockReturnValue(true); }
+ });
+
+ it('preserves a failed delivery gate during claim no-op recovery', async () => {
+ isProgrammaticIoTaskType.mockReturnValue(false);
+ const task = { id: 'claim-example', taskType: 'user', metadata: { claimFlow: true, claimTarget: '42' } };
+ persistedAgent.taskId = task.id;
+ persistedAgent.result = { validationPassed: false };
+ persistedAgent.metadata.taskOutcome = { status: 'no-action-needed', reason: 'Issue was closed.' };
+ persistedAgent.metadata.taskOutcomeSource = 'terminal-result';
+ claimVerifier.verifyClaimDisposition.mockResolvedValue({ status: 'verified' });
+ try {
+ await retireDeadAgent({ agent: persistedAgent, task, success: true, exitCode: 0, duration: 100 });
+ expect(completeAgent).toHaveBeenLastCalledWith(persistedAgent.id, expect.objectContaining({ success: false,
+ validationPassed: false, taskOutcome: { status: 'incomplete', reason: 'Delivery checks did not pass.' } }));
+ } finally { isProgrammaticIoTaskType.mockReturnValue(true); }
+ });
+
it('holds an unverified no-op', async () => {
isProgrammaticIoTaskType.mockReturnValue(false);
try {
diff --git a/server/services/claimDisposition.js b/server/services/claimDisposition.js
new file mode 100644
index 0000000000..cbcfba528f
--- /dev/null
+++ b/server/services/claimDisposition.js
@@ -0,0 +1,139 @@
+/** Read-only completion evidence for a selected claim, never agent prose. */
+import { resolve } from 'node:path';
+import { hasClaimFlowContract } from '../lib/claimFlowTaskTypes.js';
+import { expandHome, safeJSONParse } from '../lib/fileUtils.js';
+import { resolveAppForgeTarget } from '../lib/workTracker.js';
+import { getAppDataForTask } from './agentAppWorkspace.js';
+
+const unverified = reason => ({ status: 'unverified', reason });
+const sameRepo = (a, b) => typeof a === 'string' && typeof b === 'string' && a.toLowerCase() === b.toLowerCase();
+const positiveIssue = value => /^[1-9]\d*$/.test(String(value ?? '')) && Number.isSafeInteger(Number(value)) ? Number(value) : null;
+
+function selectedIssues(task, agent) {
+ const branches = agent?.metadata?.claimBranches;
+ if (Array.isArray(branches) && branches.length) {
+ // Every bound child must be accounted for; never settle an entire swarm by
+ // presenting one convenient closed issue. Unknown branch formats refuse.
+ const numbers = branches.map(branch => typeof branch === 'string'
+ ? positiveIssue(branch.match(/^claim\/issue-([1-9]\d*)$/)?.[1]) : null);
+ return numbers.every(Boolean) ? [...new Set(numbers)] : null;
+ }
+ const number = positiveIssue(task.metadata?.claimTarget);
+ return number ? [number] : null;
+}
+
+const PR_FIELDS = `number merged mergedAt baseRefName baseRepository { nameWithOwner }
+ mergeCommit { oid } closingIssuesReferences(first:100) { nodes { number repository { nameWithOwner } } }`;
+const CLAIM_QUERY = `query($owner:String!,$name:String!,$number:Int!) {
+ repository(owner:$owner,name:$name) { nameWithOwner defaultBranchRef { name }
+ issue(number:$number) { number state stateReason repository { nameWithOwner }
+ timelineItems(last:100,itemTypes:[CLOSED_EVENT,CROSS_REFERENCED_EVENT]) { nodes {
+ ... on ClosedEvent { actor { login } createdAt closer { __typename ... on PullRequest { ${PR_FIELDS} } } }
+ ... on CrossReferencedEvent { source { __typename ... on PullRequest { ${PR_FIELDS} } } }
+ } }
+ }
+ }
+}`;
+
+function deliveredPr(pr, number, target, defaultBranch, closedAt) {
+ return pr?.__typename === 'PullRequest' && pr.merged === true
+ && Number.isSafeInteger(pr.number) && pr.number > 0
+ && /^[a-f0-9]{40,64}$/i.test(pr.mergeCommit?.oid || '')
+ && sameRepo(pr.baseRepository?.nameWithOwner, target.fullName) && pr.baseRefName === defaultBranch
+ && Number.isFinite(Date.parse(pr.mergedAt)) && Date.parse(pr.mergedAt) <= Date.parse(closedAt)
+ && pr.closingIssuesReferences?.nodes?.some(issue => issue.number === number
+ && sameRepo(issue.repository?.nameWithOwner, target.fullName));
+}
+
+async function githubDisposition({ number, target, run }) {
+ const [owner, name] = target.fullName.split('/');
+ const raw = await run(['api', 'graphql', '--hostname', target.apiHost, '-f', `query=${CLAIM_QUERY}`,
+ '-f', `owner=${owner}`, '-f', `name=${name}`, '-F', `number=${number}`]);
+ const response = safeJSONParse(raw, null, { logError: false });
+ const repository = response?.data?.repository;
+ const issue = repository?.issue;
+ if (response?.errors || !sameRepo(repository?.nameWithOwner, target.fullName)
+ || issue?.number !== number || !sameRepo(issue.repository?.nameWithOwner, target.fullName)
+ || issue.state !== 'CLOSED') return unverified('issue-not-closed-or-mismatched');
+ const events = issue.timelineItems?.nodes;
+ if (!Array.isArray(events)) return unverified('closure-unavailable');
+ const closed = events.filter(event => event?.createdAt).at(-1);
+ if (!closed || !Number.isFinite(Date.parse(closed.createdAt))) return unverified('closure-unavailable');
+ if (issue.stateReason === 'NOT_PLANNED') {
+ // A typed stand-down is distinct from delivery. Only a repository operator
+ // may invalidate work: arbitrary contributor labels/comments grant nothing.
+ const { createGithubActorTrust } = await import('./forgeActorTrust.js');
+ const trust = await createGithubActorTrust({ runGh: run, host: target.apiHost, repoFullName: target.fullName });
+ if (!await trust.isTrusted(closed.actor?.login)) return unverified('closure-authority-unverified');
+ return { status: 'verified', disposition: 'not-planned', issue: number, closedAt: closed.createdAt };
+ }
+ if (issue.stateReason !== 'COMPLETED') return unverified('closure-reason-unverified');
+ const defaultBranch = repository.defaultBranchRef?.name;
+ if (typeof defaultBranch !== 'string' || !defaultBranch) return unverified('default-branch-unavailable');
+ const candidates = [closed.closer, ...events.map(event => event?.source)];
+ const pr = candidates.find(candidate => deliveredPr(candidate, number, target, defaultBranch, closed.createdAt));
+ return pr ? { status: 'verified', disposition: 'delivered', issue: number, closedAt: closed.createdAt,
+ changeRequest: pr.number, mergeCommit: pr.mergeCommit.oid, defaultBranch }
+ : unverified('merged-delivery-unverified');
+}
+
+async function gitlabDisposition({ number, target, run }) {
+ const project = `projects/${encodeURIComponent(target.fullName)}`;
+ const read = async endpoint => safeJSONParse(await run(['api', '--hostname', target.webHost,
+ '--method', 'GET', endpoint]), null, { logError: false });
+ const repository = await read(project);
+ const issue = await read(`${project}/issues/${number}`);
+ if (!sameRepo(repository?.path_with_namespace, target.fullName) || !Number.isSafeInteger(repository?.id)
+ || issue?.iid !== number || issue.project_id !== repository.id || issue.state !== 'closed'
+ || !Number.isFinite(Date.parse(issue.closed_at))) return unverified('issue-not-closed-or-mismatched');
+ const requests = await read(`${project}/issues/${number}/related_merge_requests?per_page=100`);
+ if (!Array.isArray(requests)) return unverified('merged-delivery-unavailable');
+ for (const mr of requests) {
+ if (!Number.isSafeInteger(mr?.iid) || mr.iid < 1 || mr.project_id !== repository.id
+ || mr.target_project_id !== repository.id || mr.state !== 'merged'
+ || !repository.default_branch || mr.target_branch !== repository.default_branch
+ || !/^[a-f0-9]{40,64}$/i.test(mr.merge_commit_sha || '')
+ || !Number.isFinite(Date.parse(mr.merged_at)) || Date.parse(mr.merged_at) > Date.parse(issue.closed_at)) continue;
+ const closes = await read(`${project}/merge_requests/${mr.iid}/closes_issues?per_page=100`);
+ if (Array.isArray(closes) && closes.some(row => row.iid === number && row.project_id === repository.id)) {
+ return { status: 'verified', disposition: 'delivered', issue: number, closedAt: issue.closed_at,
+ changeRequest: mr.iid, mergeCommit: mr.merge_commit_sha, defaultBranch: repository.default_branch };
+ }
+ }
+ // GitLab has no equivalent typed NOT_PLANNED closure in this API. Closed
+ // without a proven merged relationship stays unverified, even with labels.
+ return unverified('merged-delivery-unverified');
+}
+
+/**
+ * Uses the persisted task and agent, not supplied issue URLs or the sentinel's
+ * reason. The app registry owns tracker/remote resolution. Reads only, so both
+ * live finalization and restart recovery can safely repeat the same check.
+ */
+export async function verifyClaimDisposition({ task, agent, reportedOutcome, success }) {
+ if (!success || reportedOutcome?.status !== 'no-action-needed' || !hasClaimFlowContract(task)) return null;
+ if (!task?.id || agent?.taskId !== task.id) return unverified('task-binding-unverified');
+ const app = await getAppDataForTask(task);
+ const source = agent.metadata?.sourceWorkspace || agent.metadata?.workspacePath;
+ if (!app?.repoPath || typeof source !== 'string'
+ || resolve(expandHome(app.repoPath)) !== resolve(source)) return unverified('repository-binding-unverified');
+ const numbers = selectedIssues(task, agent);
+ if (!numbers?.length || numbers.length > 50) return unverified('selected-issue-unverified');
+ const { tracker, target } = await resolveAppForgeTarget(app);
+ if (!['github', 'gitlab'].includes(tracker) || target?.forge !== tracker || !target?.fullName?.includes('/')) {
+ return unverified('tracker-unsupported');
+ }
+ const { resolveForgeForRepo } = await import('./forgeAuth.js');
+ const forge = await resolveForgeForRepo(source, { forgeAccount: app.forgeAccount || null });
+ if (forge?.cli !== (tracker === 'github' ? 'gh' : 'glab')) return unverified('forge-mismatched');
+ const run = tracker === 'github'
+ ? async args => (await import('./github.js')).execGh(args, undefined, { cwd: source, env: forge.env || null, backoffKey: target.repoSpec })
+ : async args => (await import('./gitlab.js')).execGlab(args, source, undefined, { env: forge.env || null });
+ const issues = [];
+ for (const number of numbers) {
+ const result = await (tracker === 'github' ? githubDisposition : gitlabDisposition)({ number, target, run });
+ if (result.status !== 'verified') return result;
+ issues.push(result);
+ }
+ return { status: 'verified', tracker, repository: `${target.webHost}/${target.fullName}`, taskId: task.id, issues };
+}
diff --git a/server/services/claimDisposition.test.js b/server/services/claimDisposition.test.js
new file mode 100644
index 0000000000..1040d2539e
--- /dev/null
+++ b/server/services/claimDisposition.test.js
@@ -0,0 +1,148 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('./agentAppWorkspace.js', () => ({ getAppDataForTask: vi.fn() }));
+vi.mock('../lib/workTracker.js', () => ({ resolveAppForgeTarget: vi.fn() }));
+vi.mock('./forgeAuth.js', () => ({ resolveForgeForRepo: vi.fn() }));
+vi.mock('./github.js', () => ({ execGh: vi.fn() }));
+vi.mock('./gitlab.js', () => ({ execGlab: vi.fn() }));
+
+import { getAppDataForTask } from './agentAppWorkspace.js';
+import { resolveAppForgeTarget } from '../lib/workTracker.js';
+import { resolveForgeForRepo } from './forgeAuth.js';
+import { execGh } from './github.js';
+import { execGlab } from './gitlab.js';
+import { verifyClaimDisposition } from './claimDisposition.js';
+
+const target = { forge: 'github', fullName: 'example/project', webHost: 'github.example.test', apiHost: 'github.example.test', repoSpec: 'github.example.test/example/project' };
+const task = { id: 'task-example', taskType: 'internal', metadata: { app: 'example', claimFlow: true, claimTarget: '42' } };
+const agent = { id: 'agent-example', taskId: task.id, metadata: { sourceWorkspace: '/example/project' } };
+const reportedOutcome = { status: 'no-action-needed', reason: 'Untrusted reason says this was delivered.' };
+const merged = () => ({ __typename: 'PullRequest', number: 7, merged: true, mergedAt: '2026-10-01T10:00:00Z',
+ baseRefName: 'main', baseRepository: { nameWithOwner: 'example/project' }, mergeCommit: { oid: 'a'.repeat(40) },
+ closingIssuesReferences: { nodes: [{ number: 42, repository: { nameWithOwner: 'example/project' } }] } });
+const closure = () => ({ actor: { login: 'example' }, createdAt: '2026-10-01T11:00:00Z', closer: null });
+let repository;
+const verify = (extra = {}) => verifyClaimDisposition({ task, agent, reportedOutcome, success: true, ...extra });
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ getAppDataForTask.mockResolvedValue({ repoPath: '/example/project', forgeAccount: 'configured-account' });
+ resolveAppForgeTarget.mockResolvedValue({ tracker: 'github', target });
+ resolveForgeForRepo.mockResolvedValue({ cli: 'gh', env: { GH_TOKEN: 'invented-test-token' } });
+ repository = { nameWithOwner: 'example/project', defaultBranchRef: { name: 'main' },
+ issue: { number: 42, state: 'CLOSED', stateReason: 'COMPLETED', repository: { nameWithOwner: 'example/project' },
+ timelineItems: { nodes: [{ source: merged() }, closure()] } } };
+ execGh.mockImplementation(async args => args[1] === 'graphql' ? JSON.stringify({ data: { repository } })
+ : JSON.stringify({ login: 'configured-account' }));
+});
+
+describe('selected claim tracker completion', () => {
+ it('verifies an exact closing PR merged into the configured default branch, including manual issue closure', async () => {
+ expect(await verify()).toMatchObject({ status: 'verified', repository: 'github.example.test/example/project', taskId: task.id,
+ issues: [{ disposition: 'delivered', issue: 42, changeRequest: 7, mergeCommit: 'a'.repeat(40), defaultBranch: 'main' }] });
+ expect(resolveForgeForRepo).toHaveBeenCalledWith('/example/project', { forgeAccount: 'configured-account' });
+ expect(execGh).toHaveBeenCalledWith(expect.arrayContaining(['--hostname', target.apiHost, 'number=42']), undefined,
+ expect.objectContaining({ cwd: '/example/project', env: { GH_TOKEN: 'invented-test-token' } }));
+ expect(execGh.mock.calls.every(([args]) => args[0] === 'api' && !args.includes('POST') && !args.includes('PATCH'))).toBe(true);
+ });
+
+ it('accepts an operator NOT_PLANNED disposition without manufacturing code delivery', async () => {
+ repository.issue.stateReason = 'NOT_PLANNED';
+ repository.issue.timelineItems.nodes = [closure()];
+ expect(await verify()).toMatchObject({ status: 'verified', issues: [{ issue: 42, disposition: 'not-planned' }] });
+ expect((await verify()).issues[0]).not.toHaveProperty('mergeCommit');
+ });
+
+ it('preserves delegated collaborator closure authority and rejects an untrusted invalidation', async () => {
+ repository.issue.stateReason = 'NOT_PLANNED';
+ repository.issue.timelineItems.nodes = [{ ...closure(), actor: { login: 'delegated-agent' } }];
+ execGh.mockImplementation(async args => args[1] === 'graphql' ? JSON.stringify({ data: { repository } })
+ : JSON.stringify(args.at(-1).includes('permission')
+ ? { permission: 'write', user: { login: 'delegated-agent' } } : { login: 'configured-account' }));
+ expect(await verify()).toMatchObject({ status: 'verified' });
+ execGh.mockImplementation(async args => args[1] === 'graphql' ? JSON.stringify({ data: { repository } }) : '{}');
+ expect(await verify()).toMatchObject({ status: 'unverified', reason: 'closure-authority-unverified' });
+ });
+
+ it.each([
+ ['open issue', r => { r.issue.state = 'OPEN'; }],
+ ['other issue', r => { r.issue.number = 43; }],
+ ['other repository', r => { r.issue.repository.nameWithOwner = 'other/project'; }],
+ ['unknown closure reason', r => { r.issue.stateReason = null; }],
+ ['missing closure', r => { r.issue.timelineItems.nodes = []; }],
+ ['unmerged PR', r => { r.issue.timelineItems.nodes[0].source.merged = false; }],
+ ['PR targeting another branch', r => { r.issue.timelineItems.nodes[0].source.baseRefName = 'release'; }],
+ ['PR targeting another repository', r => { r.issue.timelineItems.nodes[0].source.baseRepository.nameWithOwner = 'other/project'; }],
+ ['mere cross-reference', r => { r.issue.timelineItems.nodes[0].source.closingIssuesReferences.nodes = []; }],
+ ['closing another issue', r => { r.issue.timelineItems.nodes[0].source.closingIssuesReferences.nodes[0].number = 43; }],
+ ['unproven merge commit', r => { r.issue.timelineItems.nodes[0].source.mergeCommit = null; }],
+ ['closure before merge', r => { r.issue.timelineItems.nodes[0].source.mergedAt = '2026-10-02T00:00:00Z'; }],
+ ])('refuses %s despite affirmative agent prose', async (_name, mutate) => {
+ mutate(repository);
+ expect(await verify()).toMatchObject({ status: 'unverified' });
+ });
+
+ it.each([
+ ['missing target', { task: { ...task, metadata: { ...task.metadata, claimTarget: undefined } } }],
+ ['a URL supplied as target', { task: { ...task, metadata: { ...task.metadata, claimTarget: 'https://github.example.test/other/project/issues/42' } } }],
+ ['different task', { agent: { ...agent, taskId: 'other-task' } }],
+ ['different source checkout', { agent: { ...agent, metadata: { sourceWorkspace: '/other/project' } } }],
+ ])('refuses %s before querying the forge', async (_name, options) => {
+ expect(await verify(options)).toMatchObject({ status: 'unverified' });
+ expect(execGh).not.toHaveBeenCalled();
+ });
+
+ it('uses persisted selected child branches instead of a closed parent or arbitrary result target', async () => {
+ const selected = { ...agent, metadata: { ...agent.metadata, claimBranches: ['claim/issue-43'] } };
+ expect(await verify({ agent: selected, reportedOutcome: { ...reportedOutcome, issue: 42 } })).toMatchObject({ status: 'unverified' });
+ expect(execGh.mock.calls[0][0]).toContain('number=43');
+ expect(await verify({ task: { ...task, metadata: { ...task.metadata, claimTarget: undefined } },
+ agent: { ...agent, metadata: { ...agent.metadata, claimBranches: ['claim/issue-42'] } } })).toMatchObject({ status: 'verified' });
+ });
+
+ it('requires all selected swarm issues, and refuses unrecognized bound branches', async () => {
+ expect(await verify({ agent: { ...agent, metadata: { ...agent.metadata, claimBranches: ['claim/issue-42', 'claim/issue-43'] } } })).toMatchObject({ status: 'unverified' });
+ expect(await verify({ agent: { ...agent, metadata: { ...agent.metadata, claimBranches: ['claim/unrecognized'] } } })).toMatchObject({ status: 'unverified' });
+ });
+
+ it('leaves unsupported trackers, malformed replies and GraphQL partial errors unverified', async () => {
+ execGh.mockResolvedValue('not JSON');
+ expect(await verify()).toMatchObject({ status: 'unverified' });
+ execGh.mockResolvedValue(JSON.stringify({ data: { repository }, errors: [{ message: 'Partial data' }] }));
+ expect(await verify()).toMatchObject({ status: 'unverified' });
+ resolveAppForgeTarget.mockResolvedValue({ tracker: 'jira', target });
+ expect(await verify()).toMatchObject({ status: 'unverified', reason: 'tracker-unsupported' });
+ });
+
+ it('does not grant ordinary shipping or failed runs a claim no-op criterion', async () => {
+ expect(await verify({ reportedOutcome: { status: 'completed' } })).toBeNull();
+ expect(await verify({ success: false })).toBeNull();
+ expect(await verify({ task: { ...task, metadata: { app: 'example' } } })).toBeNull();
+ expect(execGh).not.toHaveBeenCalled();
+ });
+});
+
+describe('GitLab selected claim delivery', () => {
+ const project = { id: 5, path_with_namespace: 'example/project', default_branch: 'main' };
+ const issue = { iid: 42, project_id: 5, state: 'closed', closed_at: '2026-10-01T11:00:00Z' };
+ const mr = { iid: 7, project_id: 5, target_project_id: 5, state: 'merged', target_branch: 'main',
+ merge_commit_sha: 'b'.repeat(40), merged_at: '2026-10-01T10:00:00Z' };
+
+ it('requires a same-project merged MR that explicitly closes this issue, and refuses unsupported closure-only claims', async () => {
+ resolveAppForgeTarget.mockResolvedValue({ tracker: 'gitlab', target: { ...target, forge: 'gitlab' } });
+ resolveForgeForRepo.mockResolvedValue({ cli: 'glab', env: { GITLAB_TOKEN: 'invented-token' } });
+ let closes = [issue];
+ execGlab.mockImplementation(async args => {
+ const endpoint = args.at(-1);
+ return JSON.stringify(endpoint.includes('closes_issues') ? closes
+ : endpoint.includes('related_merge_requests') ? [mr] : endpoint.endsWith('/42') ? issue : project);
+ });
+ expect(await verify()).toMatchObject({ status: 'verified', tracker: 'gitlab', issues: [{ issue: 42, disposition: 'delivered', changeRequest: 7 }] });
+ expect(execGlab.mock.calls[0]).toEqual([expect.arrayContaining(['--hostname', target.webHost, '--method', 'GET']),
+ '/example/project', undefined, { env: { GITLAB_TOKEN: 'invented-token' } }]);
+ closes = [{ ...issue, project_id: 6 }];
+ expect(await verify()).toMatchObject({ status: 'unverified', reason: 'merged-delivery-unverified' });
+ closes = [];
+ expect(await verify()).toMatchObject({ status: 'unverified' });
+ });
+});