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: retire delivered checkouts from incomplete claim batches (#13534)

picodotdddbaa2dae7c
diff --git a/docs/features/branch-reconciliation.md b/docs/features/branch-reconciliation.md
index 4cd58ad493..6af70d5de7 100644
--- a/docs/features/branch-reconciliation.md
+++ b/docs/features/branch-reconciliation.md
@@ -480,10 +480,18 @@ ancestor of the captured completion head, and that capture is an ancestor of the
currently reviewed delivery. The captured pointer and private-administration
generation must match exactly. Missing evidence, changed generations, active
owners and human handoffs remain held. The original agent result and policy are
-never rewritten; the new proof is bound into the retirement review and archive.
-After removal, only that archive-bound generation can finish branch retirement;
+never rewritten; the new proof is bound into the retirement review and removal receipt.
+Cleanup creates no checkout archive. Only that reviewed generation can finish branch retirement;
a recreated checkout path or new branch holder still refuses.
+An incomplete multi-claim batch does not prevent cleanup of a separately
+verified merged checkout. Its completed execution must have a valid capture of
+that same generation, and the captured head must be included in the exact
+merged delivery. Failed execution or validation, missing captures and unmerged
+delivery remain held. Cleanup preserves the batch's incomplete result, every
+capture and unfinished sibling checkout; it does not reset or resume exhausted
+retry budgets.
+
## Whole-checkout preservation
For a reviewed checkout that exceeds the ordinary archive byte bounds, the
diff --git a/server/services/branchCompletionPolicy.js b/server/services/branchCompletionPolicy.js
index eb1de517aa..a06d22ffa8 100644
--- a/server/services/branchCompletionPolicy.js
+++ b/server/services/branchCompletionPolicy.js
@@ -136,10 +136,12 @@ const reviewTarget = policy => policy.agent.metadata?.reviewLoopMergeTarget;
const retirementPr = policy => policy.prUrl || reviewTarget(policy)?.url;
function continuedDelivery(policy, input) {
- if (policy.agent.status !== 'completed' || policy.agent.result?.success !== true || policy.agent.result.validationPassed === false
+ if (policy.agent.status !== 'completed'
+ || (policy.agent.result?.success !== true && policy.agent.result?.executionSuccess !== true)
+ || policy.agent.result?.executionSuccess === false || policy.agent.result?.validationPassed === false
|| policy.completion !== PR_COMPLETIONS.REVIEW_THEN_MERGE || input.verifiedPrHead !== input.tip) return null;
return input.deliveryContinuations?.find(proof => proof.agentId === policy.agent.id
- && proof.originalPrUrl === retirementPr(policy) && proof.originalPrUrl !== input.prUrl
+ && proof.originalPrUrl === (retirementPr(policy) ?? null)
&& proof.prUrl === input.prUrl && proof.tip === input.tip
&& (!policy.tip || [proof.originalPrHead, proof.capturedHead].includes(policy.tip))
&& policy.agent.metadata?.completedCheckouts?.some(row => completedCheckoutReceiptValid(policy.agent, row)
@@ -188,7 +190,8 @@ function reviewedIncarnation(input, policies) {
if (!isAbsolute(input.checkoutPath || '') || samePath(input.checkoutPath, input.repoPath)
|| !input.prUrl || input.verifiedPrHead !== input.tip
|| !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(input.tip || '')) return null;
- const owners = policies.filter(policy => policy.agent.status === 'completed' && (policy.agent.result?.success === true || completedCleanupForRetirement(policy, input) || reviewedOrphanCheckout(policy, input))
+ const owners = policies.filter(policy => policy.agent.status === 'completed' && (policy.agent.result?.success === true
+ || completedCleanupForRetirement(policy, input) || reviewedOrphanCheckout(policy, input) || continuedDelivery(policy, input))
&& policy.completion === PR_COMPLETIONS.REVIEW_THEN_MERGE
&& (samePath(policy.agent.metadata?.workspacePath, input.checkoutPath) || completedCleanupForRetirement(policy, input)
|| reviewedOrphanCheckout(policy, input) || continuedDelivery(policy, input))
@@ -255,7 +258,8 @@ export function reviewedRetirementPolicy(input) {
const incarnation = reviewedIncarnation(input, decision.policies || []);
const policies = incarnation?.current || decision.policies || [];
if (policies.some(p => p.completion === PR_COMPLETIONS.LEAVE_OPEN)) return { reason: held };
- if (policies.some(p => p.agent.status !== 'completed' || (p.agent.result?.success !== true && !completedCleanupForRetirement(p, input) && !reviewedOrphanCheckout(p, input) && !completedOrphanSibling(p, input))
+ if (policies.some(p => p.agent.status !== 'completed' || (p.agent.result?.success !== true && !completedCleanupForRetirement(p, input)
+ && !reviewedOrphanCheckout(p, input) && !completedOrphanSibling(p, input) && !continuedDelivery(p, input))
|| p.completion !== PR_COMPLETIONS.REVIEW_THEN_MERGE
|| (retirementPr(p) && !continuedDelivery(p, input)
&& ((!incarnation && !completedOrphanSibling(p, input)) || retirementPr(p) !== input.prUrl))
diff --git a/server/services/checkoutDeliveryContinuation.js b/server/services/checkoutDeliveryContinuation.js
index 533fb0ab2f..2916b12e53 100644
--- a/server/services/checkoutDeliveryContinuation.js
+++ b/server/services/checkoutDeliveryContinuation.js
@@ -1,4 +1,4 @@
-/** Fresh delivery evidence for a later merged PR on one captured checkout.
+/** Fresh delivery evidence for one captured checkout, including partial batches.
* This never changes the producing agent, its result, or its original policy.
*/
import { execGit } from '../lib/execGit.js';
@@ -33,8 +33,9 @@ export async function readCheckoutDeliveryContinuations(input, agents, opts = {}
if (!Array.isArray(agents) || !checkoutIncarnation?.pointer || !checkoutIncarnation.gitdir
|| verifiedPrHead !== tip || !oid(tip) || retirementForge?.prUrl !== prUrl
|| retirementForge.prHead !== tip || !oid(retirementForge.defaultHead)) return [];
- const candidates = agents.filter(agent => agent?.status === 'completed' && agent.result?.success === true
- && agent.result.validationPassed !== false
+ const candidates = agents.filter(agent => agent?.status === 'completed'
+ && (agent.result?.success === true || agent.result?.executionSuccess === true)
+ && agent.result.executionSuccess !== false && agent.result.validationPassed !== false
&& Array.isArray(agent.metadata?.completedCheckouts)
&& agent.metadata.completedCheckouts.some(row => samePath(row?.repoPath, repoPath) && samePath(row.path, checkoutPath) && row.branch === branch));
if (candidates.length > 25) return [];
@@ -42,16 +43,26 @@ export async function readCheckoutDeliveryContinuations(input, agents, opts = {}
const ancestor = (older, newer) => oid(older) && oid(newer)
? execGit(['--no-replace-objects', '-c', 'core.commitGraph=false', 'merge-base', '--is-ancestor', older, newer],
repoPath, { env: proofEnv }).then(() => true, () => false) : false;
+ if (!await ancestor(retirementForge.mergeCommit, retirementForge.defaultHead)) return [];
const evidence = [];
const historical = new Map();
- // Bounded sequential forge reads, only for a physically matching successful
- // owner whose known PR differs. Unknown or unreadable history remains held.
+ // Bounded sequential forge reads, only for a matching completed execution
+ // whose known PR differs. The aggregate task outcome is never promoted.
for (const agent of candidates) {
- const originalPrUrl = agent.metadata.branchCompletionPolicy?.prUrl || agent.metadata.reviewLoopMergeTarget?.url;
- if (!originalPrUrl || originalPrUrl === prUrl) continue;
+ const policyUrl = agent.metadata.branchCompletionPolicy?.prUrl;
+ const target = agent.metadata.reviewLoopMergeTarget;
+ if ((policyUrl != null && !parsePullRequestUrl(policyUrl))
+ || (target != null && (!parsePullRequestUrl(target.url) || target.branch !== branch))) continue;
+ const originalPrUrl = policyUrl ?? target?.url ?? null;
const rows = agent.metadata.completedCheckouts.filter(row => samePath(row?.repoPath, repoPath) && samePath(row.path, checkoutPath)
&& row.branch === branch && completedCheckoutReceiptValid(agent, row) && isDeepStrictEqual(row.incarnation, checkoutIncarnation));
if (rows.length !== 1 || !await ancestor(rows[0].head, tip)) continue;
+ if (!originalPrUrl || originalPrUrl === prUrl) {
+ evidence.push({ kind: 'captured-merged-delivery', agentId: agent.id, originalPrUrl,
+ originalPrHead: originalPrUrl ? retirementForge.prHead : null, originalMergeCommit: originalPrUrl ? retirementForge.mergeCommit : null,
+ capturedHead: rows[0].head, capturedAt: rows[0].capturedAt, prUrl, tip, checkoutIncarnation });
+ continue;
+ }
if (!historical.has(originalPrUrl)) historical.set(originalPrUrl,
(opts.readHistoricalMerge || historicalMerge)(repoPath, originalPrUrl, opts.forgeAccount));
const old = await historical.get(originalPrUrl);
@@ -59,7 +70,7 @@ export async function readCheckoutDeliveryContinuations(input, agents, opts = {}
|| old.headRefName !== branch || old.baseRefName !== retirementForge.defaultBranch
|| !await ancestor(old.headRefOid, rows[0].head)
|| !await ancestor(old.mergeCommit?.oid, retirementForge.defaultHead)) continue;
- evidence.push({ agentId: agent.id, originalPrUrl, originalPrHead: old.headRefOid,
+ evidence.push({ kind: 'continued-merged-delivery', agentId: agent.id, originalPrUrl, originalPrHead: old.headRefOid,
originalMergeCommit: old.mergeCommit.oid, capturedHead: rows[0].head,
capturedAt: rows[0].capturedAt, prUrl, tip, checkoutIncarnation });
}
diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.js
index 8b17d54fe8..f59630228f 100644
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@ -1176,7 +1176,8 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
return checkout;
}
- it.each(['delivered', 'recreated-after-removal', 'different-generation', 'unmerged-original', 'unreadable-original', 'unrelated-capture', 'human-handoff', 'failed-validation'])(
+ it.each(['delivered', 'recreated-after-removal', 'different-generation', 'unmerged-original', 'unreadable-original', 'unrelated-capture',
+ 'human-handoff', 'failed-validation', 'batch-with-target', 'batch-without-target', 'failed-execution', 'batch-unmerged-current'])(
'binds a later merged delivery to its captured owner without rewriting history: %s', async scenario => {
const c = await reviewedCheckout(`continued-${scenario}`, { normalMerge: true });
const { readCompletedCheckoutIdentity } = await import('./completedCheckoutEvidence.js');
@@ -1194,6 +1195,27 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
completedCheckouts: [{ version: 1, agentId: 'agent-continued', startedAt: '2026-01-01T00:00:00.000Z',
capturedAt: '2026-01-01T00:02:00.000Z', ...captured }],
} };
+ let unfinished;
+ if (['batch-with-target', 'batch-without-target', 'failed-execution', 'failed-validation', 'batch-unmerged-current'].includes(scenario)) {
+ agent.result = { success: false, executionSuccess: scenario !== 'failed-execution',
+ taskOutcome: { status: 'incomplete', reason: 'Another claim remains unfinished' } };
+ agent.metadata.sourceWorkspace = null;
+ agent.metadata.workspacePath = repo;
+ agent.metadata.claimBranches = [c.release.branch];
+ delete agent.metadata.worktreeBranch;
+ agent.metadata.reviewLoopMergeTarget = scenario === 'batch-with-target' ? { branch: c.release.branch, url: c.forge.prUrl } : null;
+ }
+ if (scenario === 'batch-without-target') {
+ unfinished = await heldCheckout('batch-unfinished', { branch: 'feature/batch-unfinished', beforeLock: async tree => {
+ await writeFile(join(tree, 'pending.txt'), 'unfinished unique work\n');
+ await execGit(['add', 'pending.txt'], tree);
+ await execGit(['commit', '-m', 'unfinished claim'], tree);
+ } });
+ const pendingCapture = await readCompletedCheckoutIdentity({ repoPath: repo, ...unfinished.release, allowLocked: true });
+ agent.metadata.claimBranches.push(unfinished.release.branch);
+ agent.metadata.completedCheckouts.push({ version: 1, agentId: agent.id, startedAt: agent.startedAt,
+ capturedAt: '2026-01-01T00:02:00.000Z', ...pendingCapture });
+ }
if (scenario === 'failed-validation') agent.result.validationPassed = false;
if (scenario === 'different-generation') agent.metadata.completedCheckouts[0].incarnation.gitdir.ino += '0';
if (scenario === 'unrelated-capture') {
@@ -1214,6 +1236,10 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
}
Object.assign(c.forge, { prHead: c.release.head, mergeCommit: c.release.head, defaultHead: c.release.head,
changedPaths: ['continued.txt', 'feature.txt'] });
+ if (scenario === 'batch-unmerged-current') {
+ const tree = (await execGit(['rev-parse', `${oldHead}^{tree}`], repo)).stdout.trim();
+ c.forge.mergeCommit = (await execGit(['commit-tree', tree, '-m', 'unintegrated delivery'], repo)).stdout.trim();
+ }
c.opts.readHistoricalMerge = async () => scenario === 'unreadable-original' ? null : ({ url: oldUrl,
state: scenario === 'unmerged-original' ? 'OPEN' : 'MERGED', isCrossRepository: false,
headRefName: c.release.branch, headRefOid: oldHead, mergeCommit: { oid: oldHead }, baseRefName: 'main' });
@@ -1227,17 +1253,17 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [{ ...c.release, reason: 'pr-completion-review-required' }] });
const original = structuredClone(agent);
const prepared = await c.prepare();
- if (!['delivered', 'recreated-after-removal'].includes(scenario)) {
+ if (!['delivered', 'recreated-after-removal', 'batch-with-target', 'batch-without-target'].includes(scenario)) {
expect(prepared).toMatchObject({ ok: false, reason: scenario === 'human-handoff'
? 'pr-completion-human-handoff' : 'retirement-policy-not-legacy-completed' });
expect(await registered(c.path)).toBe(true);
expect(await archives()).toEqual([]);
} else {
expect(prepared).toMatchObject({ ok: true, review: { policy: { policies: [{ continuedDelivery: {
- originalPrUrl: oldUrl, capturedHead: oldHead, tip: c.release.head,
+ originalPrUrl: agent.metadata.reviewLoopMergeTarget?.url ?? null, capturedHead: oldHead, tip: c.release.head,
} }] } } });
const retired = await c.confirm(prepared.review);
- expect(retired).toMatchObject({ ok: true, branchDeleted: scenario === 'delivered' });
+ expect(retired).toMatchObject({ ok: true, branchDeleted: scenario !== 'recreated-after-removal' });
if (scenario === 'recreated-after-removal') {
expect(retired.branchRetainedReason).toBe('retirement-evidence-changed');
expect(await readFile(join(c.path, 'new-owner.txt'), 'utf8')).toBe('unrelated new work\n');
@@ -1245,8 +1271,14 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
}
expect(retired.archiveDir).toBeUndefined();
expect(await archives()).toEqual([]);
- if (scenario === 'delivered') expect(await registered(c.path)).toBe(false);
+ if (scenario !== 'recreated-after-removal') expect(await registered(c.path)).toBe(false);
expect((await c.prepare()).ok).toBe(false);
+ if (unfinished) {
+ expect(await registered(unfinished.path)).toBe(true);
+ expect(await lockText(unfinished.path)).toBe(unfinished.release.lockReason);
+ expect(await readFile(join(unfinished.path, 'pending.txt'), 'utf8')).toBe('unfinished unique work\n');
+ expect((await execGit(['rev-parse', unfinished.release.branch], repo)).stdout.trim()).toBe(unfinished.release.head);
+ }
}
expect(agent).toEqual(original);
});