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: recover exact orphan checkout evidence for retirement (#13486)
[._.]/ab9bc9f0ced1
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.jsindex 61b57329c2..ca69afdc57 100644--- a/server/services/agentRepoStateVerification.js+++ b/server/services/agentRepoStateVerification.js@@ -261,7 +261,14 @@ export async function verifyAgentRepoState(input) {const verify = async () => {if (input.agentState?.metadata?.completionSentinel&& await completionSentinelPresent(input.agentId, input.agentState.metadata.workspacePath)) return skipped('completion-sentinel-generation-pending');- if (input.agentState?.metadata?.checkoutCapture?.status === 'pending') return skipped('checkout-capture-pending');+ if (input.agentState?.metadata?.checkoutCapture?.status === 'pending') {+ const { retryCompletionCheckoutCapture, getAgentRecord } = await import('./cosAgentLifecycle.js');+ if (!await retryCompletionCheckoutCapture(input.agentId).catch(() => false)) return skipped('checkout-capture-pending');+ const recovered = await getAgentRecord(input.agentId).catch(() => null);+ if (!recovered || recovered.status !== 'completed' || recovered.startedAt !== input.agentState.startedAt+ || recovered.metadata?.checkoutCapture?.status !== 'captured') return skipped('checkout-capture-pending');+ input = { ...input, agentState: recovered };+ }if (cleanupPending) {const { getTaskById } = await import('./cosTaskStore.js');const original = await getTaskById(input.task.id);diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.jsindex 81db0e80a4..c0268fcd07 100644--- a/server/services/agentRepoStateVerification.test.js+++ b/server/services/agentRepoStateVerification.test.js@@ -30,7 +30,7 @@ vi.mock('./heldCheckoutReview.js', () => ({ readRetirementForgeEvidence: vi.fn(avi.mock('./completedCheckoutEvidence.js', async original => ({ ...await original(), readCompletedCheckoutIdentity: vi.fn() }));vi.mock('./cos.js', () => ({}));vi.mock('./agentCompletionCleanup.js', () => ({ replayAgentCompletionCleanup: vi.fn(async () => {}) }));-vi.mock('./cosAgentLifecycle.js', () => ({ reserveRepoCleanupRecovery: vi.fn(async () => ({ admitted: true, attempt: 1 })), recordRepoCleanupRecovery: vi.fn(async () => true), recordCleanupOutcome: vi.fn(async () => true), updateAgent: vi.fn().mockResolvedValue({}), recordRepoStateRecovery: vi.fn().mockResolvedValue(true), recordRepoStateVerification: vi.fn().mockResolvedValue(true), getAgentRecord: vi.fn(async () => null), recordCompletionCleanup: vi.fn(async () => true) }));+vi.mock('./cosAgentLifecycle.js', () => ({ retryCompletionCheckoutCapture: vi.fn(async () => false), reserveRepoCleanupRecovery: vi.fn(async () => ({ admitted: true, attempt: 1 })), recordRepoCleanupRecovery: vi.fn(async () => true), recordCleanupOutcome: vi.fn(async () => true), updateAgent: vi.fn().mockResolvedValue({}), recordRepoStateRecovery: vi.fn().mockResolvedValue(true), recordRepoStateVerification: vi.fn().mockResolvedValue(true), getAgentRecord: vi.fn(async () => null), recordCompletionCleanup: vi.fn(async () => true) }));vi.mock('./cosClaimOwnership.js', () => ({ readClaimOwnershipAgents: vi.fn().mockResolvedValue([]), withClaimOwnershipLock: fn => fn() }));vi.mock('./taskSchedule.js', () => ({ recordBranchReconcileOutcome: vi.fn().mockResolvedValue({}) }));vi.mock('./heldCheckoutRecovery.js', () => ({@@ -79,7 +79,7 @@ import { inspectOrQueueCompletedReview } from './repoCleanupRecovery.js';import { readLocalBranchPresence, readCheckoutPathPresence } from './repoCleanupObservation.js';import { readCompletedCheckoutIdentity } from './completedCheckoutEvidence.js';import { readClaimOwnershipAgents } from './cosClaimOwnership.js';-import { recordCleanupOutcome, reserveRepoCleanupRecovery, recordRepoStateRecovery, recordRepoStateVerification } from './cosAgentLifecycle.js';+import { retryCompletionCheckoutCapture, getAgentRecord, recordCleanupOutcome, reserveRepoCleanupRecovery, recordRepoStateRecovery, recordRepoStateVerification } from './cosAgentLifecycle.js';import { verifyAgentRepoState, sweepRepoStateVerifications, REPO_STATE_REMEDIATIONS } from './agentRepoStateVerification.js';import { readBranchCompletionPolicies } from './branchCompletionPolicy.js';import { releaseRetryHold } from './agentWorktreeCleanup.js';@@ -146,6 +146,8 @@ const run = (overrides = {}) => verifyAgentRepoState({beforeEach(() => {vi.clearAllMocks();+ retryCompletionCheckoutCapture.mockReset().mockResolvedValue(false);+ getAgentRecord.mockReset().mockResolvedValue(null);findMissingCheckoutPreservation.mockResolvedValue(null);inspectOrQueueCompletedReview.mockResolvedValue({ disposition: 'held', reason: 'delivery-ci-or-review-pending' });readBranchCompletionPolicies.mockResolvedValue([]);@@ -176,6 +178,20 @@ beforeEach(() => {});describe('verifyAgentRepoState — clean runs', () => {+ it.each(['pending', 'captured', 'lost-record'])('retries failed-run identity capture without promoting delivery or cleanup: %s', async scenario => {+ const state = { ...agentState({ checkoutCapture: { status: 'pending' }, repoStateVerification: { status: 'pending' } }),+ id: 'agent-1', status: 'completed', startedAt: CREATED_AT, result: { success: false, executionSuccess: false, orphaned: true } };+ retryCompletionCheckoutCapture.mockResolvedValue(scenario !== 'pending');+ if (scenario === 'captured') getAgentRecord.mockResolvedValue({ ...state,+ metadata: { ...state.metadata, checkoutCapture: { status: 'captured' }, completedCheckouts: [RELEASE] } });+ expect(await run({ success: false, agentState: state })).toMatchObject({+ skipReason: scenario === 'captured' ? REPO_STATE_SKIPS.FAILED_RUN : 'checkout-capture-pending',+ });+ expect(state.result).toEqual({ success: false, executionSuccess: false, orphaned: true });+ expect(addTask).not.toHaveBeenCalled();+ expect(retireInventoriedCheckout).not.toHaveBeenCalled();+ });+it('retains unresolved verification after an explicit retry without adopting its task or touching Git', async () => {getTaskById.mockResolvedValue({ ...task(), status: 'pending' });const state = { ...agentState({ repoStateVerification: { status: 'pending' } }), result: { cleanupPending: true } };diff --git a/server/services/branchCompletionPolicy.js b/server/services/branchCompletionPolicy.jsindex 885ecd0e34..32b1dcfd4a 100644--- a/server/services/branchCompletionPolicy.js+++ b/server/services/branchCompletionPolicy.js@@ -133,13 +133,27 @@ function completionDecision({ repoPath, branch, prUrl, tip, agents }) {const reviewTarget = policy => policy.agent.metadata?.reviewLoopMergeTarget;const retirementPr = policy => policy.prUrl || reviewTarget(policy)?.url;+/** A process interruption is not a code-delivery verdict. Only a fresh merged+ * exact-head PR and a server-captured original physical generation admit this+ * owner to explicit retirement review. Its execution failure remains unchanged.+ */+function reviewedOrphanCheckout(policy, input) {+ const agent = policy.agent;+ return agent.status === 'completed' && agent.result?.orphaned === true+ && agent.result.validationPassed !== false && retirementPr(policy) === input.prUrl+ && input.verifiedPrHead === input.tip && !!input.tip+ && agent.metadata?.completedCheckouts?.some(row => completedCheckoutReceiptValid(agent, row)+ && row.repoPath === input.repoPath && row.branch === input.branch && row.path === input.checkoutPath+ && row.head === input.tip && row.incarnation?.pointer && row.incarnation?.gitdir);+}+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))+ const owners = policies.filter(policy => policy.agent.status === 'completed' && (policy.agent.result?.success === true || completedCleanupForRetirement(policy, input) || reviewedOrphanCheckout(policy, input))&& policy.completion === PR_COMPLETIONS.REVIEW_THEN_MERGE- && (samePath(policy.agent.metadata?.workspacePath, input.checkoutPath) || completedCleanupForRetirement(policy, input))+ && (samePath(policy.agent.metadata?.workspacePath, input.checkoutPath) || completedCleanupForRetirement(policy, input) || reviewedOrphanCheckout(policy, input))&& retirementPr(policy) === input.prUrl && (!policy.tip || policy.tip === input.tip)&& (!reviewTarget(policy) || (reviewTarget(policy).branch === input.branch && reviewTarget(policy).url === input.prUrl))&& Number.isFinite(Date.parse(policy.agent.startedAt))@@ -201,7 +215,7 @@ 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))+ if (policies.some(p => p.agent.status !== 'completed' || (p.agent.result?.success !== true && !completedCleanupForRetirement(p, input) && !reviewedOrphanCheckout(p, input))|| p.completion !== PR_COMPLETIONS.REVIEW_THEN_MERGE|| (retirementPr(p) && (!incarnation || retirementPr(p) !== input.prUrl))|| (reviewTarget(p) && (reviewTarget(p).branch !== input.branch || (p.prUrl && p.prUrl !== reviewTarget(p).url)))@@ -211,6 +225,7 @@ export function reviewedRetirementPolicy(input) {return { reason: null, ...(input.integratedCleanupHead && { integratedCleanupHead: input.integratedCleanupHead }), policies: policies.map(p => ({id: p.agent.id || p.agent.agentId, startedAt: p.agent.startedAt,completedAt: p.agent.completedAt, status: p.agent.status, success: p.agent.result.success,+ ...(reviewedOrphanCheckout(p, input) && { orphanedExecution: true }),branch: p.branch, completion: p.completion,...(incarnation && { prUrl: retirementPr(p) ?? null, tip: p.tip ?? null, workspacePath: p.agent.metadata?.workspacePath ?? null }),})).sort((a, b) => String(a.id).localeCompare(String(b.id))),diff --git a/server/services/completedCheckoutEvidence.js b/server/services/completedCheckoutEvidence.jsindex b9f6ea27a7..f67a49e66b 100644--- a/server/services/completedCheckoutEvidence.js+++ b/server/services/completedCheckoutEvidence.js@@ -135,8 +135,10 @@ export async function captureSeededCompletionCheckouts(agent) {return receipts;}-/** Called under the agent-state lock while the successful run still owns its- * current claim bindings. Never manufacture evidence for historical releases.+/** Called under the agent-state lock while the run still owns its current+ * bindings. The caller's success flag enables identity capture, as at initial+ * registration; it never changes the provider's execution/delivery verdict.+ * Never manufacture evidence for historical releases.* Capture errors withhold cleanup authority without breaking completion.*/export async function captureCompletedCheckouts(agent, { success, strict = false, allowUncreated = false } = {}) {diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.jsindex 551a2a0584..21312623b7 100644--- a/server/services/cosAgentLifecycle.js+++ b/server/services/cosAgentLifecycle.js@@ -321,14 +321,23 @@ export async function recordCompletionCleanup(agentId, startedAt, patch) {/** Retry capture ONLY against preterminal snapshots. Unknown originals remain* explicit holds; a completed record can never discover a replacement by name.*/-export async function retryCompletionCheckoutCapture(agentId) {+export async function retryCompletionCheckoutCapture(agentId, { retirement } = {}) {const { withClaimOwnershipLock, readClaimOwnershipAgents } = await import('./cosClaimOwnership.js');const { claimCheckoutOwner } = await import('../lib/claimContinuation.js');const { readCompletedCheckoutIdentity, captureSeededCompletionCheckouts } = await import('./completedCheckoutEvidence.js');return withClaimOwnershipLock(async () => {+ if (retirement) {+ const [repoPath, path] = await Promise.all([realpath(retirement.repoPath).catch(() => null), realpath(retirement.path).catch(() => null)]);+ if (!repoPath || !path || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(retirement.head || '')) return false;+ retirement = { ...retirement, repoPath, path };+ }const agent = await getAgentRecord(agentId);const pending = agent?.metadata?.checkoutCapture;- if (agent?.status !== 'completed' || pending?.status !== 'pending') return false;+ const seededOrphan = retirement && agent?.result?.orphaned === true && agent.result.validationPassed !== false+ && pending?.status === 'captured' && agent.metadata.completedCheckouts?.length === 0+ && agent.metadata.checkoutSeeds?.some(seed => seed.repoPath === retirement.repoPath+ && seed.branch === retirement.branch && seed.path === retirement.path);+ if (agent?.status !== 'completed' || (pending?.status !== 'pending' && !seededOrphan)) return false;const owners = await readClaimOwnershipAgents().catch(() => null);const { readBranchCompletionPolicies } = await import('./branchCompletionPolicy.js');const history = await readBranchCompletionPolicies({ repairIndex: false }).catch(() => null);@@ -358,6 +367,8 @@ export async function retryCompletionCheckoutCapture(agentId) {}const captured = seeds.length ? await captureSeededCompletionCheckouts(agent).catch(() => null) : targets;if (!captured?.length) return false;+ if (retirement && !captured.some(row => row.repoPath === retirement.repoPath && row.branch === retirement.branch+ && row.path === retirement.path && row.head === retirement.head)) return false;let recorded = false;const saved = await updateCompletionReceipt(agentId, (metadata, current) => {if (current.startedAt !== agent.startedAt || JSON.stringify(metadata.checkoutCapture) !== JSON.stringify(pending)@@ -415,15 +426,17 @@ export async function completeAgent(agentId, result = {}) {let checkoutCapture;if (hasClaimCheckoutBindings(agent.metadata) || agent.metadata?.isWorktree) {completedCheckouts = [];- if (result.success === true || result.cleanupPending === true) {- const { captureCompletedCheckouts } = await import('./completedCheckoutEvidence.js');- try { completedCheckouts = await captureCompletedCheckouts(agent, { success: true, strict: true }); }- catch (error) {- // Ingestion remains terminal. Retry only an originally captured exact- // generation, never finalize/output hooks or historical branch names.- checkoutCapture = { status: 'pending', reason: 'checkout-evidence-unavailable',- targets: error.checkoutCapture?.targets || [], unknown: error.checkoutCapture?.unknown !== false,- observedAt: new Date().toISOString() };+ // Identity capture describes the owned physical checkout, not a passing+ // execution verdict. Failed/orphaned runs may already have delivered code.+ const { captureCompletedCheckouts } = await import('./completedCheckoutEvidence.js');+ try { completedCheckouts = await captureCompletedCheckouts(agent, { success: true, strict: true }); }+ catch (error) {+ // Ingestion remains terminal. Retry only an originally captured exact+ // generation, never finalize/output hooks or historical branch names.+ checkoutCapture = { status: 'pending', reason: 'checkout-evidence-unavailable',+ targets: error.checkoutCapture?.targets || [], unknown: error.checkoutCapture?.unknown !== false,+ observedAt: new Date().toISOString() };+ if (result.success === true || result.cleanupPending === true) {result = { ...result, success: false, executionSuccess: result.executionSuccess ?? result.success,cleanupPending: true, deliveryRecoveryOwned: true,taskOutcome: { status: 'incomplete', reason: 'Original checkout identity capture is pending; delivery and preservation remain unverified.',@@ -451,7 +464,7 @@ export async function completeAgent(agentId, result = {}) {status: cleanupContext ? cleanup.status || 'pending' : 'abandoned',...(!cleanupContext && { reason: 'completion-context-unavailable' }) },...(completedCheckouts ? { checkoutCapture: checkoutCapture || { status: 'captured' } } : {}),- ...((result.success || result.cleanupPending === true) && (agent.metadata?.isWorktree || hasClaimCheckoutBindings(agent.metadata))+ ...((result.success || result.cleanupPending === true || checkoutCapture?.status === 'pending') && (agent.metadata?.isWorktree || hasClaimCheckoutBindings(agent.metadata))? { repoStateVerification: { status: 'pending' } } : {}),};state.agents[agentId] = {diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.jsindex fe23d4b8dd..a44ae75b58 100644--- a/server/services/cosAgentLifecycle.test.js+++ b/server/services/cosAgentLifecycle.test.js@@ -625,11 +625,30 @@ describe('completeAgent idempotence (#3384)', () => {metadata: { claimPicksOwnBranch: true, completedCheckouts: [{ stale: true }] }, output: [] };const failed = await completeAgent('claim-failed', { success: false });expect(failed.metadata.completedCheckouts).toEqual([]);- expect(captureCompletedCheckouts).toHaveBeenCalledTimes(1);+ expect(captureCompletedCheckouts).toHaveBeenCalledTimes(2);+ });++ it('archives owned checkout identity on execution failure without claiming delivery success', async () => {+ const id = 'failed-owned-checkout';+ const evidence = { version: 1, agentId: id, branch: 'feature/failed-owned' };+ mockCosState.state.agents[id] = { id, status: 'running', startedAt: '2026-01-01T00:00:00Z', output: [],+ metadata: { isWorktree: true, worktreeBranch: evidence.branch } };+ captureCompletedCheckouts.mockImplementationOnce(async agent => {+ expect(agent.status).toBe('running');+ return [evidence];+ });+ const failed = await completeAgent(id, { success: false, executionSuccess: false, orphaned: true });+ expect(failed.result).toMatchObject({ success: false, executionSuccess: false, orphaned: true });+ expect(failed.result.cleanupPending).not.toBe(true);+ expect(failed.metadata).toMatchObject({ completedCheckouts: [evidence], checkoutCapture: { status: 'captured' } });+ const persisted = JSON.parse(await readFile(join(mockCosState.agentsDir, failed.completedAt.slice(0, 10), id, 'metadata.json'), 'utf8'));+ expect(persisted.result).toEqual(failed.result);+ expect(persisted.metadata.completedCheckouts).toEqual([evidence]);});- it.each(['unchanged', 'physical-generation', 'new-owner'])('retries the first completion Git-read failure from the early registered physical seed after restart, scenario=%s', async scenario => {- const changed = scenario !== 'unchanged';+ it.each(['unchanged', 'physical-generation', 'new-owner', 'orphan-empty', 'orphan-physical-generation', 'orphan-new-owner'])('recovers only the original completion physical seed after restart, scenario=%s', async scenario => {+ const orphan = scenario.startsWith('orphan-');+ const changed = !['unchanged', 'orphan-empty'].includes(scenario);const scratch = await mkdtemp(join(tmpdir(), 'portos-completion-capture-seed-'));let failFirstRead;try {@@ -649,31 +668,36 @@ describe('completeAgent idempotence (#3384)', () => {await execGit(['add', 'delivery.txt'], checkout);await execGit(['-c', 'user.name=Test', '-c', '[email protected]', 'commit', '-m', 'final delivered head'], checkout);const head = (await execGit(['rev-parse', 'HEAD'], checkout)).stdout.trim();- failFirstRead = vi.spyOn(await import('./worktreeManager.js'), 'listWorktrees').mockRejectedValueOnce(new Error('first completion Git read unavailable'));- const completed = await completeAgent(agentId, { success: true });- expect(completed).toMatchObject({ status: 'completed', result: { cleanupPending: true, executionSuccess: true },+ if (orphan) captureCompletedCheckouts.mockReset().mockResolvedValueOnce([]); // Historical failed-run empty capture.+ else failFirstRead = vi.spyOn(await import('./worktreeManager.js'), 'listWorktrees').mockRejectedValueOnce(new Error('first completion Git read unavailable'));+ const completed = await completeAgent(agentId, orphan ? { success: false, executionSuccess: false, orphaned: true } : { success: true });+ if (orphan) expect(completed).toMatchObject({ result: { success: false, executionSuccess: false, orphaned: true },+ metadata: { completedCheckouts: [], checkoutCapture: { status: 'captured' } } });+ else expect(completed).toMatchObject({ status: 'completed', result: { cleanupPending: true, executionSuccess: true },metadata: { checkoutCapture: { status: 'pending', unknown: true } } });expect(cosEvents.listenerCount('agent:completed')).toBeGreaterThan(0);delete mockCosState.state.agents[agentId]; // Restart: only the real archived metadata remains.- if (scenario === 'new-owner') {+ if (scenario.endsWith('new-owner')) {mockCosState.state.agents['new-owner'] = { id: 'new-owner', status: 'completed', startedAt: new Date().toISOString(),metadata: { sourceWorkspace: repo, workspacePath: checkout, worktreeBranch: 'feature/seeded' } };}- if (scenario === 'physical-generation') {+ if (scenario.endsWith('physical-generation')) {const pointer = join(checkout, '.git');const bytes = await readFile(pointer);await rename(pointer, join(scratch, 'original-git-pointer'));await writeFile(pointer, bytes);}- expect(await retryCompletionCheckoutCapture(agentId)).toBe(!changed);+ const options = orphan ? { retirement: { repoPath: repo, branch: 'feature/seeded', path: checkout, head } } : {};+ expect(await retryCompletionCheckoutCapture(agentId, options)).toBe(!changed);const recovered = await getAgent(agentId);- if (changed) expect(recovered.metadata.checkoutCapture.status).toBe('pending');+ if (changed) expect(recovered.metadata.checkoutCapture.status).toBe(orphan ? 'captured' : 'pending');else {const receipt = recovered.metadata.completedCheckouts[0];expect(receipt).toMatchObject({ version: 2, head, seededAt: seed.seededAt });expect(Date.parse(receipt.capturedAt)).toBeGreaterThanOrEqual(Date.parse(completed.completedAt));expect(completedCheckoutReceiptValid(recovered, receipt)).toBe(true);}+ if (orphan) expect(recovered.result).toEqual(completed.result);expect(await readFile(join(checkout, 'delivery.txt'), 'utf8')).toBe('wanted original work');expect((await execGit(['rev-parse', 'HEAD'], checkout)).stdout.trim()).toBe(head);expect(emittedCompletions).toHaveLength(1);diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.jsindex ac099d6d44..932d8014a1 100644--- a/server/services/heldCheckoutRecovery.js+++ b/server/services/heldCheckoutRecovery.js@@ -582,6 +582,28 @@ export async function prepareInventoriedCheckoutRetirement({ appId, release, prUif (!fetched.ok) return fetched;prepared = await review();}+ if (prepared.reason === 'retirement-policy-not-legacy-completed') {+ // Recover only a previously registered physical generation after fresh+ // merged exact-head proof. Never promote an orphan's execution to success.+ const { readRetirementForgeEvidence } = await import('./heldCheckoutReview.js');+ const forge = await (opts.readForge || readRetirementForgeEvidence)(app.repoPath, release.branch, prUrl,+ { forgeAccount: app.forgeAccount ?? null }).catch(() => null);+ if (forge?.prUrl === prUrl && forge.prHead === release.head) {+ const { readBranchCompletionPolicies } = await import('./branchCompletionPolicy.js');+ const policies = await (opts.readPolicies || (() => readBranchCompletionPolicies({ repairIndex: false })))().catch(() => null);+ const retry = opts.recoverCheckoutCapture || (await import('./cosAgentLifecycle.js')).retryCompletionCheckoutCapture;+ let recovered = false;+ for (const agent of Array.isArray(policies) ? policies : []) {+ const meta = agent.metadata || {};+ const knownPr = meta.branchCompletionPolicy?.prUrl || meta.reviewLoopMergeTarget?.url;+ if (agent.status !== 'completed' || agent.result?.orphaned !== true || agent.result.validationPassed === false+ || knownPr !== prUrl || meta.checkoutCapture?.status !== 'captured' || meta.completedCheckouts?.length !== 0+ || !meta.checkoutSeeds?.some(seed => seed.repoPath === app.repoPath && seed.branch === release.branch && seed.path === release.path)) continue;+ recovered = await retry(agent.id || agent.agentId, { retirement: { repoPath: app.repoPath, ...release } }).catch(() => false) || recovered;+ }+ if (recovered) prepared = await review();+ }+ }return prepared;}diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.jsindex cb4ea521e9..1556db7bf5 100644--- a/server/services/heldCheckoutRecovery.test.js+++ b/server/services/heldCheckoutRecovery.test.js@@ -1555,6 +1555,68 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()expect(await readFile(join(result.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('ignored work\n');});+ it.each(['original', 'recreated-pointer', 'active-owner', 'different-pr-head', 'failed-validation'])('recovers a merged orphan only from its exact early generation: %s', async scenario => {+ const c = await reviewedCheckout(`orphan-${scenario}`);+ await execGit(['worktree', 'unlock', c.path], repo);+ Object.assign(c.release, { locked: false, lockReason: null });+ await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [{ ...c.release, reason: 'pr-completion-review-required' }] });+ const evidence = await import('./completedCheckoutEvidence.js');+ const agent = { id: 'original-orphan', status: 'running', startedAt: new Date(Date.now() - 60_000).toISOString(),+ result: { success: false, executionSuccess: false, orphaned: true, validationPassed: null },+ metadata: { isWorktree: true, sourceWorkspace: repo, workspacePath: c.path, worktreeBranch: c.release.branch,+ prCompletionPolicy: 'review-then-merge', reviewLoopMergeTarget: { url: c.forge.prUrl, branch: c.release.branch } } };+ agent.metadata.checkoutSeeds = await evidence.captureCheckoutSeeds(agent);+ agent.status = 'completed';+ agent.completedAt = new Date().toISOString();+ agent.metadata.completedCheckouts = [];+ agent.metadata.checkoutCapture = { status: 'captured' };+ if (scenario === 'failed-validation') agent.result.validationPassed = false;+ injected.policies = [agent];+ const originalResult = structuredClone(agent.result);+ let recoveries = 0;+ c.opts.recoverCheckoutCapture = async (id, { retirement }) => {+ expect(id).toBe(agent.id);+ expect(retirement).toMatchObject({ repoPath: repo, ...c.release });+ const captured = await evidence.captureSeededCompletionCheckouts(agent);+ if (!captured) return false;+ agent.metadata.completedCheckouts = captured;+ recoveries++;+ return true;+ };+ if (scenario === 'recreated-pointer') {+ const bytes = await readFile(join(c.path, '.git'));+ await rename(join(c.path, '.git'), join(scratch, 'original-pointer'));+ await writeFile(join(c.path, '.git'), bytes);+ }+ if (scenario === 'active-owner') c.opts.readAgents = async () => [{ id: 'other', status: 'running', workspacePath: c.path }];+ if (scenario === 'different-pr-head') c.forge.prHead = 'b'.repeat(40);+ const prepared = await c.prepare();+ expect(agent.result).toEqual(originalResult);+ if (scenario !== 'original') {+ expect(prepared.ok).toBe(false);+ expect(await registered(c.path)).toBe(true);+ expect(await archives()).toEqual([]);+ expect(recoveries).toBe(0);+ return;+ }+ expect(prepared).toMatchObject({ ok: true, review: { policy: { policies: [{ success: false, orphanedExecution: true }] } } });+ const receipt = agent.metadata.completedCheckouts[0];+ expect(receipt).toMatchObject({ version: 2, head: c.release.head });+ expect(evidence.completedCheckoutReceiptValid(agent, receipt)).toBe(true);+ const retired = await c.confirm(prepared.review);+ expect(retired).toMatchObject({ ok: true, branchDeleted: true });+ expect(await readFile(join(retired.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('ignored work\n');+ const restored = join(scratch, 'independent-orphan.git');+ await execGit(['init', '--bare', restored], scratch);+ await execGit(['bundle', 'unbundle', join(retired.archiveDir, 'commits.bundle')], restored);+ await execGit(['fsck', '--full', '--strict', '--no-reflogs', c.release.head], restored);+ expect(await registered(c.path)).toBe(false);+ expect((await c.prepare()).ok).toBe(false);+ expect(await archives()).toHaveLength(1);+ expect(recoveries).toBe(1);+ expect(agent.result).toEqual(originalResult);+ });+it('requires supersession acceptance after an ancestral merged tip is later changed', async () => {const c = await reviewedCheckout('ancestral', { normalMerge: true, superseded: true });const prepared = await c.prepare();