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: bind detached orphan reviews to distinct checkout receipts (#13491)

[._.]/8b8ffd5e847a
diff --git a/server/services/branchCompletionPolicy.js b/server/services/branchCompletionPolicy.js
index 309a7452c3..a8cb4d45d9 100644
--- a/server/services/branchCompletionPolicy.js
+++ b/server/services/branchCompletionPolicy.js
@@ -3,6 +3,7 @@
* shared forge logins never authorize reconciliation. No parallel policy store.
*/
import { readFile, readdir, stat } from 'node:fs/promises';
+import { createHash } from 'node:crypto';
import { isAbsolute, join, resolve } from 'node:path';
import { PATHS } from '../lib/fileUtils.js';
import { isPlainObject } from '../lib/objects.js';
@@ -147,6 +148,23 @@ function reviewedOrphanCheckout(policy, input) {
&& row.head === input.tip && row.incarnation?.pointer && row.incarnation?.gitdir);
}
+// An orphan's captured generation may belong to a different checkout of the
+// same delivered head. It cannot transfer its cleanup obligation to an explicit
+// detached-copy review. Keep its result and original cleanup record unchanged.
+function completedOrphanSibling(policy, input) {
+ const agent = policy.agent;
+ if (!/^[a-f0-9]{64}$/.test(input.detachedCheckoutIdentity || '')
+ || input.verifiedPrHead !== input.tip || !input.tip || retirementPr(policy) !== input.prUrl
+ || (policy.tip && policy.tip !== input.tip) || agent.status !== 'completed' || agent.result?.orphaned !== true
+ || agent.result.validationPassed === false || policy.completion !== PR_COMPLETIONS.REVIEW_THEN_MERGE) return false;
+ return agent.metadata?.completedCheckouts?.some(row => row.version === 2 && completedCheckoutReceiptValid(agent, row)
+ && samePath(row.repoPath, input.repoPath) && row.branch === input.branch && row.head === input.tip
+ && samePath(row.path, agent.metadata.workspacePath) && !samePath(row.path, input.checkoutPath)
+ && !samePath(row.path, input.repoPath) && row.incarnation?.pointer
+ && createHash('sha256').update(JSON.stringify(['dev', 'ino', 'birthtimeNs'].map(key => row.incarnation.pointer[key])))
+ .digest('hex') !== input.detachedCheckoutIdentity) === true;
+}
+
function reviewedIncarnation(input, policies) {
if (!isAbsolute(input.checkoutPath || '') || samePath(input.checkoutPath, input.repoPath)
|| !input.prUrl || input.verifiedPrHead !== input.tip
@@ -215,9 +233,9 @@ 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))
+ if (policies.some(p => p.agent.status !== 'completed' || (p.agent.result?.success !== true && !completedCleanupForRetirement(p, input) && !reviewedOrphanCheckout(p, input) && !completedOrphanSibling(p, input))
|| p.completion !== PR_COMPLETIONS.REVIEW_THEN_MERGE
- || (retirementPr(p) && (!incarnation || retirementPr(p) !== input.prUrl))
+ || (retirementPr(p) && ((!incarnation && !completedOrphanSibling(p, input)) || retirementPr(p) !== input.prUrl))
|| (reviewTarget(p) && (reviewTarget(p).branch !== input.branch || (p.prUrl && p.prUrl !== reviewTarget(p).url)))
|| (incarnation && p.tip && p.tip !== input.tip))) {
return { reason: 'retirement-policy-not-legacy-completed' };
@@ -226,6 +244,7 @@ export function reviewedRetirementPolicy(input) {
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 }),
+ ...(completedOrphanSibling(p, input) && { orphanedSibling: true, detachedCheckoutIdentity: input.detachedCheckoutIdentity }),
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/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.js
index d14bd3d652..e8a5b2cfd0 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -567,6 +567,10 @@ async function reviewCurrentCheckout({ repoPath, release, prUrl, kind, unlocked
if (namedOwner) return { ok: false, reason: namedOwner };
const identity = await integratedPolicyReviewIdentity(repoPath, release, prUrl, forge);
if (!identity) return { ok: false, reason: 'retirement-local-objects-missing' };
+ if (!release.branch) {
+ identity.detachedCheckoutIdentity = await readRetirementCheckoutIdentity(release.path);
+ if (!identity.detachedCheckoutIdentity) return { ok: false, reason: 'checkout-identity-changed' };
+ }
const policy = await retirementPolicy(repoPath, policyBranch, opts, identity);
if (policy.reason) return { ok: false, reason: policy.reason };
return archiveSnapshots(matched.tree, repoPath, null, archiveWork(opts.signal))
diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.js
index bf1ecb2740..62ea7c9115 100644
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@ -2096,6 +2096,53 @@ 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(['confirmed', 'missing-receipt', 'same-incarnation', 'human-handoff', 'active-owner'])('keeps an orphan sibling obligation separate from a detached copy: %s', async scenario => {
+ const c = await reviewedCheckout(`orphan-sibling-${scenario}`);
+ const namedPath = c.path;
+ const namedBranch = c.release.branch;
+ await execGit(['worktree', 'unlock', namedPath], repo);
+ const evidence = await import('./completedCheckoutEvidence.js');
+ const agent = { id: 'sibling-owner', status: 'running', startedAt: new Date(Date.now() - 60_000).toISOString(),
+ metadata: { sourceWorkspace: repo, workspacePath: namedPath, isWorktree: true, worktreeBranch: namedBranch,
+ prCompletionPolicy: 'review-then-merge', reviewLoopMergeTarget: { url: c.forge.prUrl, branch: namedBranch } } };
+ agent.metadata.checkoutSeeds = await evidence.captureCheckoutSeeds(agent);
+ agent.status = 'completed'; agent.completedAt = new Date().toISOString();
+ agent.result = { success: false, executionSuccess: false, orphaned: true, validationPassed: null };
+ agent.metadata.completedCheckouts = await evidence.captureSeededCompletionCheckouts(agent);
+ expect(agent.metadata.completedCheckouts).toHaveLength(1);
+ const path = join(external, `detached-${scenario}`);
+ if (scenario === 'same-incarnation') {
+ const pointerIdentity = await readRetirementCheckoutIdentity(namedPath);
+ await execGit(['worktree', 'move', namedPath, path], repo);
+ await execGit(['switch', '--detach', c.release.head], path);
+ expect(await readRetirementCheckoutIdentity(path)).toBe(pointerIdentity);
+ }
+ else {
+ await execGit(['worktree', 'add', '--detach', path, c.release.head], repo);
+ await writeFile(join(path, 'ignored.txt'), 'distinct detached work\n');
+ }
+ const release = { path, branch: null, head: c.release.head, locked: false, lockReason: null };
+ c.forge.publishedBranch = namedBranch; c.forge.exactAliasHead = release.head;
+ injected.policies = [agent];
+ if (scenario === 'missing-receipt') agent.metadata.completedCheckouts = [];
+ if (scenario === 'human-handoff') agent.metadata.prCompletionPolicy = 'leave-open';
+ if (scenario === 'active-owner') { agent.status = 'running'; c.opts.readAgents = async () => [agent]; }
+ await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [{ ...release, reason: 'worktree-unmanaged-location' }] });
+ const prepared = await prepareInventoriedCheckoutRetirement({ appId: 'app-1', release, prUrl: c.forge.prUrl }, c.opts);
+ if (scenario !== 'confirmed') {
+ expect(prepared.ok).toBe(false); expect(await registered(path)).toBe(true); expect(await archives()).toEqual([]);
+ return;
+ }
+ expect(prepared).toMatchObject({ ok: true, review: { policy: { policies: [{ success: false, orphanedSibling: true }] } } });
+ const result = await retireInventoriedCheckout({ appId: 'app-1', release,
+ review: { prUrl: c.forge.prUrl, digest: prepared.review.digest, acceptSuperseded: false } }, c.opts);
+ expect(result).toMatchObject({ ok: true, branchDeleted: false });
+ expect(await registered(namedPath)).toBe(true);
+ expect((await execGit(['rev-parse', namedBranch], repo)).stdout.trim()).toBe(release.head);
+ expect(agent.result).toEqual({ success: false, executionSuccess: false, orphaned: true, validationPassed: null });
+ expect(await readFile(join(result.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('distinct detached work\n');
+ });
+
it('preserves archive and checkout when fresh forge evidence changes after archiving', async () => {
const c = await reviewedCheckout('late-forge');
const prepared = await c.prepare();