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

Recover retirement across merged deliveries on one checkout (#13517)

picodotd38367dc9e57
diff --git a/docs/features/branch-reconciliation.md b/docs/features/branch-reconciliation.md
index f4c397b93f..3d51d3b8e3 100644
--- a/docs/features/branch-reconciliation.md
+++ b/docs/features/branch-reconciliation.md
@@ -457,6 +457,19 @@ by replaying an older retirement. Interrupted transactions outside the machine-v
require explicit status and recovery; ambiguous identities remain held. The
private journal and all copies remain available after success or recovery.
+## Later deliveries on a captured checkout
+
+A later merged PR on the same captured checkout generation can satisfy an
+earlier completed review obligation. Explicit retirement review must prove that
+both PRs merged on this repository's default branch, the earlier PR head is an
+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;
+a recreated checkout path or new branch holder still refuses.
+
## 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 be2d7fd6fa..eb1de517aa 100644
--- a/server/services/branchCompletionPolicy.js
+++ b/server/services/branchCompletionPolicy.js
@@ -11,6 +11,7 @@ import { isTruthyMeta } from '../lib/metadataFlags.js';
import { PR_COMPLETIONS, explicitPrCompletion } from '../lib/prDisposition.js';
import { parsePullRequestUrl } from '../lib/gitForge.js';
import { completedCheckoutReceiptValid } from './completedCheckoutEvidence.js';
+import { isDeepStrictEqual } from 'node:util';
const samePath = (a, b) => typeof a === 'string' && typeof b === 'string'
&& (process.platform === 'win32' ? resolve(a).toLowerCase() === resolve(b).toLowerCase() : resolve(a) === resolve(b));
@@ -134,6 +135,20 @@ function completionDecision({ repoPath, branch, prUrl, tip, agents }) {
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
+ || 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.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)
+ && samePath(row.repoPath, input.repoPath) && row.branch === input.branch && samePath(row.path, input.checkoutPath)
+ && row.head === proof.capturedHead && row.capturedAt === proof.capturedAt
+ && isDeepStrictEqual(row.incarnation, proof.checkoutIncarnation)
+ && isDeepStrictEqual(row.incarnation, input.checkoutIncarnation))) || null;
+}
+
/** 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.
@@ -175,9 +190,12 @@ function reviewedIncarnation(input, policies) {
|| !/^[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))
&& policy.completion === PR_COMPLETIONS.REVIEW_THEN_MERGE
- && (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))
+ && (samePath(policy.agent.metadata?.workspacePath, input.checkoutPath) || completedCleanupForRetirement(policy, input)
+ || reviewedOrphanCheckout(policy, input) || continuedDelivery(policy, input))
+ && (retirementPr(policy) === input.prUrl || continuedDelivery(policy, input))
+ && (!policy.tip || policy.tip === input.tip || continuedDelivery(policy, input))
+ && (!reviewTarget(policy) || (reviewTarget(policy).branch === input.branch
+ && (reviewTarget(policy).url === input.prUrl || continuedDelivery(policy, input))))
&& Number.isFinite(Date.parse(policy.agent.startedAt))
&& Date.parse(policy.agent.completedAt) >= Date.parse(policy.agent.startedAt));
if (!owners.length) return null;
@@ -239,14 +257,16 @@ export function reviewedRetirementPolicy(input) {
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))
|| p.completion !== PR_COMPLETIONS.REVIEW_THEN_MERGE
- || (retirementPr(p) && ((!incarnation && !completedOrphanSibling(p, input)) || retirementPr(p) !== input.prUrl))
+ || (retirementPr(p) && !continuedDelivery(p, input)
+ && ((!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))) {
+ || (incarnation && p.tip && p.tip !== input.tip && !continuedDelivery(p, input)))) {
return { reason: 'retirement-policy-not-legacy-completed' };
}
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,
+ ...(continuedDelivery(p, input) && { continuedDelivery: continuedDelivery(p, input) }),
...(reviewedOrphanCheckout(p, input) && { orphanedExecution: true }),
...(completedOrphanSibling(p, input) && { orphanedSibling: true, detachedCheckoutIdentity: input.detachedCheckoutIdentity }),
branch: p.branch, completion: p.completion,
diff --git a/server/services/checkoutDeliveryContinuation.js b/server/services/checkoutDeliveryContinuation.js
new file mode 100644
index 0000000000..533fb0ab2f
--- /dev/null
+++ b/server/services/checkoutDeliveryContinuation.js
@@ -0,0 +1,67 @@
+/** Fresh delivery evidence for a later merged PR on one captured checkout.
+ * This never changes the producing agent, its result, or its original policy.
+ */
+import { execGit } from '../lib/execGit.js';
+import { getOriginInfo } from '../lib/gitRemote.js';
+import { parsePullRequestUrl } from '../lib/gitForge.js';
+import { completedCheckoutReceiptValid } from './completedCheckoutEvidence.js';
+import { isDeepStrictEqual } from 'node:util';
+import { devNull } from 'node:os';
+import { resolve } from 'node:path';
+
+const oid = value => typeof value === 'string' && /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(value);
+const samePath = (a, b) => typeof a === 'string' && typeof b === 'string'
+ && (process.platform === 'win32' ? resolve(a).toLowerCase() === resolve(b).toLowerCase() : resolve(a) === resolve(b));
+
+async function historicalMerge(repoPath, prUrl, forgeAccount) {
+ const origin = await getOriginInfo(repoPath);
+ const parsed = parsePullRequestUrl(prUrl);
+ if (!origin || !parsed || parsed.host !== origin.host || `${parsed.owner}/${parsed.repo}` !== origin.fullName) return null;
+ const [{ execGh }, { resolveForgeExecOptions }] = await Promise.all([import('./github.js'), import('./forgeExecOptions.js')]);
+ const options = await resolveForgeExecOptions(repoPath, { forgeAccount });
+ return execGh(['pr', 'view', prUrl, '--json', 'url,state,headRefName,headRefOid,isCrossRepository,mergeCommit,baseRefName'],
+ 10000, options).then(JSON.parse).catch(() => null);
+}
+
+/** Only callers that freshly verified the current PR and captured the exact
+ * pointer AND private-administration generation supply this input. A native
+ * transaction reuses that bound generation after independently verifying its
+ * original/quarantine placements; no missing-path inference is performed here.
+ */
+export async function readCheckoutDeliveryContinuations(input, agents, opts = {}) {
+ const { repoPath, branch, checkoutPath, tip, prUrl, verifiedPrHead, checkoutIncarnation, retirementForge } = input;
+ 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
+ && 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 [];
+ const proofEnv = { ...process.env, GIT_NO_REPLACE_OBJECTS: '1', GIT_NO_LAZY_FETCH: '1', GIT_GRAFT_FILE: devNull };
+ 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;
+ 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.
+ for (const agent of candidates) {
+ const originalPrUrl = agent.metadata.branchCompletionPolicy?.prUrl || agent.metadata.reviewLoopMergeTarget?.url;
+ if (!originalPrUrl || originalPrUrl === prUrl) continue;
+ 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 (!historical.has(originalPrUrl)) historical.set(originalPrUrl,
+ (opts.readHistoricalMerge || historicalMerge)(repoPath, originalPrUrl, opts.forgeAccount));
+ const old = await historical.get(originalPrUrl);
+ if (old?.url !== originalPrUrl || old.state !== 'MERGED' || old.isCrossRepository !== false
+ || 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,
+ originalMergeCommit: old.mergeCommit.oid, capturedHead: rows[0].head,
+ capturedAt: rows[0].capturedAt, prUrl, tip, checkoutIncarnation });
+ }
+ return evidence;
+}
diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.js
index 393e76aea8..b42c17d5a0 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -596,7 +596,22 @@ async function retirementPolicy(repoPath, branch, opts, reviewIdentity = {}) {
}
}
}
- return reviewedRetirementPolicy({ repoPath, branch, agents: policies, ...reviewIdentity, checkoutIdentities });
+ const initial = reviewedRetirementPolicy({ repoPath, branch, agents: policies, ...reviewIdentity, checkoutIdentities });
+ if (initial.reason !== 'retirement-policy-not-legacy-completed' || !reviewIdentity.retirementForge) return initial;
+ let identity = reviewIdentity;
+ if (!identity.checkoutIncarnation) {
+ const { readCompletedCheckoutIdentity } = await import('./completedCheckoutEvidence.js');
+ // The caller has already checked the released lock and registration. This
+ // fact-read grants no unlock authority; ordinary matching policies avoid it.
+ const generation = await readCompletedCheckoutIdentity({ repoPath, branch, path: identity.checkoutPath,
+ head: identity.tip, allowLocked: true }).catch(() => null);
+ if (!generation) return initial;
+ identity = { ...identity, checkoutIncarnation: generation.incarnation };
+ }
+ const { readCheckoutDeliveryContinuations } = await import('./checkoutDeliveryContinuation.js');
+ const deliveryContinuations = await readCheckoutDeliveryContinuations({ repoPath, branch, ...identity }, policies, opts);
+ return deliveryContinuations.length
+ ? reviewedRetirementPolicy({ repoPath, branch, agents: policies, ...identity, checkoutIdentities, deliveryContinuations }) : initial;
}
const policyReviewIdentity = (release, prUrl, forge) => ({
@@ -604,9 +619,14 @@ const policyReviewIdentity = (release, prUrl, forge) => ({
verifiedPrHead: forge?.prUrl === prUrl ? forge.prHead : null,
});
-async function integratedPolicyReviewIdentity(repoPath, release, prUrl, forge) {
+async function integratedPolicyReviewIdentity(repoPath, release, prUrl, forge, archivedIncarnation = null) {
if (!forge || !await execGit(['cat-file', '-e', `${forge.defaultHead}^{commit}`], repoPath).then(() => true, () => false)) return null;
- return { ...policyReviewIdentity(release, prUrl, forge),
+ // Only the post-removal caller supplies a generation already bound into the
+ // verified archive/review. A recreated path is never an absent original.
+ const absent = archivedIncarnation && await lstat(release.path).then(() => false, error => error.code === 'ENOENT');
+ const checkoutIncarnation = absent ? archivedIncarnation : null;
+ return { ...policyReviewIdentity(release, prUrl, forge), retirementForge: forge,
+ ...(checkoutIncarnation && { checkoutIncarnation }),
// Older pinned claims missed completion capture. Fresh inclusion of every
// commit settles cleanup-only outcomes without manufacturing receipts.
integratedCleanupHead: forge?.prHead === release.head && await isAncestor(repoPath, release.head, forge.defaultHead)
@@ -1200,14 +1220,14 @@ async function matchRelease(repoPath, release) {
/** Shared live policy/owner check for the explicit whole-checkout transaction.
* It does not archive, unlock or infer integration.
*/
-export async function inspectCheckoutRetirementOwnership({ repoPath, release, registration = true }, opts = {}) {
+export async function inspectCheckoutRetirementOwnership({ repoPath, release, registration = true, reviewIdentity = {}, forgeAccount = null }, opts = {}) {
if (!release.branch || PROTECTED_BRANCHES.includes(release.branch)) return { ok: false, reason: 'protected-branch' };
const matched = registration ? await matchRelease(repoPath, release) : { tree: release };
if (!matched.tree) return { ok: false, reason: matched.reason };
const reason = await ownerReason({ repoPath, tree: matched.tree, branch: release.branch,
readAgents: opts.readAgents || readClaimOwnershipAgents, reviewed: true });
if (reason) return { ok: false, reason };
- const policy = await retirementPolicy(repoPath, release.branch, opts);
+ const policy = await retirementPolicy(repoPath, release.branch, { ...opts, forgeAccount: opts.forgeAccount ?? forgeAccount }, reviewIdentity);
return policy.reason ? { ok: false, reason: policy.reason } : { ok: true, tree: matched.tree, policy };
}
@@ -1323,7 +1343,8 @@ async function finishHeldCheckoutRetirement({ repoPath, release, review, reviewe
if (review) {
const { readRetirementForgeEvidence } = await import('./heldCheckoutReview.js');
const forge = await (opts.readForge || readRetirementForgeEvidence)(repoPath, branch, review.prUrl, reviewForgeOptions(release, review.kind, opts)).catch(() => null);
- const identity = await integratedPolicyReviewIdentity(repoPath, release, review.prUrl, forge);
+ const captured = reviewed.review.policy?.policies?.find(row => row.continuedDelivery)?.continuedDelivery.checkoutIncarnation;
+ const identity = await integratedPolicyReviewIdentity(repoPath, release, review.prUrl, forge, captured);
const policy = identity ? await retirementPolicy(repoPath, branch, opts, identity) : null;
if (JSON.stringify(policy) !== JSON.stringify(reviewed.review.policy) || JSON.stringify(forge) !== JSON.stringify(reviewed.review.forge)) {
return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: 'retirement-evidence-changed' };
diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.js
index 1d55dd6829..cbe70a6844 100644
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@ -1240,6 +1240,85 @@ 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'])(
+ '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');
+ const captured = await readCompletedCheckoutIdentity({ repoPath: repo, ...c.release, allowLocked: true });
+ expect(captured).not.toBeNull();
+ // Persisted JSON object key order is not part of physical generation.
+ captured.incarnation = { gitdir: { ...captured.incarnation.gitdir }, pointer: { ...captured.incarnation.pointer } };
+ const oldHead = c.release.head;
+ const oldUrl = 'https://github.com/example/repo/pull/41';
+ const agent = { id: 'agent-continued', status: 'completed', startedAt: '2026-01-01T00:00:00.000Z',
+ completedAt: '2026-01-01T00:03:00.000Z', result: { success: true }, metadata: {
+ sourceWorkspace: repo, workspacePath: captured.path, worktreeBranch: c.release.branch,
+ prCompletionPolicy: scenario === 'human-handoff' ? 'leave-open' : 'review-then-merge',
+ reviewLoopMergeTarget: { branch: c.release.branch, url: oldUrl },
+ completedCheckouts: [{ version: 1, agentId: 'agent-continued', startedAt: '2026-01-01T00:00:00.000Z',
+ capturedAt: '2026-01-01T00:02:00.000Z', ...captured }],
+ } };
+ if (scenario === 'failed-validation') agent.result.validationPassed = false;
+ if (scenario === 'different-generation') agent.metadata.completedCheckouts[0].incarnation.gitdir.ino += '0';
+ if (scenario === 'unrelated-capture') {
+ const tree = (await execGit(['rev-parse', `${oldHead}^{tree}`], repo)).stdout.trim();
+ agent.metadata.completedCheckouts[0].head = (await execGit(['commit-tree', tree, '-m', 'unrelated captured history'], repo)).stdout.trim();
+ }
+ injected.policies = [agent];
+ await writeFile(join(c.path, 'continued.txt'), 'later delivered change\n');
+ await execGit(['add', 'continued.txt'], c.path);
+ await execGit(['commit', '-m', 'later delivery on the same checkout'], c.path);
+ c.release.head = (await execGit(['rev-parse', 'HEAD'], c.path)).stdout.trim();
+ await execGit(['merge', '--ff-only', c.release.branch], repo);
+ if (scenario === 'unrelated-capture') {
+ const unrelated = agent.metadata.completedCheckouts[0].head;
+ // Virtual replacement history must not turn missing delivery into proof.
+ await execGit(['replace', '--graft', unrelated, oldHead], repo);
+ await execGit(['replace', '--graft', c.release.head, unrelated], repo);
+ }
+ Object.assign(c.forge, { prHead: c.release.head, mergeCommit: c.release.head, defaultHead: c.release.head,
+ changedPaths: ['continued.txt', 'feature.txt'] });
+ 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' });
+ if (scenario === 'recreated-after-removal') c.opts.readForge = async () => {
+ if (!existsSync(c.path)) {
+ await mkdir(c.path);
+ await writeFile(join(c.path, 'new-owner.txt'), 'unrelated new work\n');
+ }
+ return c.forge;
+ };
+ 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)) {
+ 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,
+ } }] } } });
+ const retired = await c.confirm(prepared.review);
+ expect(retired).toMatchObject({ ok: true, branchDeleted: scenario === 'delivered' });
+ 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');
+ expect((await execGit(['rev-parse', c.release.branch], repo)).stdout.trim()).toBe(c.release.head);
+ }
+ expect(await readFile(join(retired.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('ignored work\n');
+ const restore = join(scratch, 'continued-standalone.git');
+ await execGit(['init', '--bare', restore], scratch);
+ await execGit(['bundle', 'unbundle', join(retired.archiveDir, 'commits.bundle')], restore);
+ await execGit(['fsck', '--full', '--strict', '--no-reflogs', c.release.head], restore);
+ expect(await registered(c.path)).toBe(false);
+ expect((await c.prepare()).ok).toBe(false);
+ expect(await archives()).toHaveLength(1);
+ }
+ expect(agent).toEqual(original);
+ });
+
it('preserves the checkout when escaped review evidence exceeds the recovery manifest limit', async () => {
const c = await reviewedCheckout('manifest-byte-limit', {
superseded: true, featurePath: 'tabs.txt', featureBody: '\t'.repeat(4 * 1024 * 1024 - 512) + '\n',
diff --git a/server/services/initializedCheckoutRecovery.js b/server/services/initializedCheckoutRecovery.js
index b42df1b667..89ec499f65 100644
--- a/server/services/initializedCheckoutRecovery.js
+++ b/server/services/initializedCheckoutRecovery.js
@@ -195,14 +195,30 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
throw error;
}
});
- const ensureOwner = async (ctx, release, registration = true) => {
- const result = await ownership({ repoPath: ctx.repoPath, release, registration });
- if (!result.ok) fail(result.reason);
- return result.policy;
+ const ensureOwner = async (ctx, release, registration = true, reviewed = null) => {
+ const input = { repoPath: ctx.repoPath, release, registration };
+ const result = await ownership(input);
+ if (result.ok) return result.policy;
+ if (result.reason !== 'retirement-policy-not-legacy-completed' || !reviewed?.checkoutIncarnation) fail(result.reason);
+ const facts = await forge(ctx, release, reviewed.forge.prUrl);
+ const continued = await ownership({ ...input, forgeAccount: ctx.forgeAccount, reviewIdentity: {
+ checkoutPath: release.path, tip: release.head, prUrl: facts.prUrl, verifiedPrHead: facts.prHead,
+ retirementForge: facts, checkoutIncarnation: reviewed.checkoutIncarnation,
+ } });
+ if (!continued.ok || !continued.policy?.policies?.some(row => row.continuedDelivery)) fail(continued.reason || result.reason);
+ return continued.policy;
};
const makeReview = async ({ appId, release, prUrl, wholeCheckout = false }) => {
const ctx = await context(appId, release);
- const policy = await ensureOwner(ctx, release);
+ let checkoutIncarnation;
+ const policy = await ensureOwner(ctx, release).catch(async error => {
+ if (error.message !== 'retirement-policy-not-legacy-completed') throw error;
+ const read = deps.readCompletedIdentity || (await import('./completedCheckoutEvidence.js')).readCompletedCheckoutIdentity;
+ const generation = await read({ repoPath: ctx.repoPath, ...release, allowLocked: release.locked === true }).catch(() => null);
+ if (!generation) throw error;
+ checkoutIncarnation = generation.incarnation;
+ return ensureOwner(ctx, release, true, { forge: { prUrl }, checkoutIncarnation });
+ });
const snapshot = await native({ command: 'inspect', repoPath: ctx.repoPath, release, requireOwnership: true,
...(wholeCheckout && { wholeCheckout: true }) });
const facts = await forge(ctx, release, prUrl);
@@ -210,7 +226,7 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
const checkoutIdentity = await readRetirementCheckoutIdentity(release.path);
if (release.checkoutIdentity && release.checkoutIdentity !== checkoutIdentity) fail('checkout-identity-changed');
const evidence = { ...base, mode: wholeCheckout ? 'whole-checkout' : 'initialized-private-modules', snapshot,
- ...(checkoutIdentity && { checkoutIdentity }) };
+ ...(checkoutIdentity && { checkoutIdentity }), ...(checkoutIncarnation && { checkoutIncarnation }) };
delete evidence.digest;
return { ctx, review: { digest: hash(evidence), ...evidence } };
};
@@ -223,7 +239,7 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
if (current.comparison.disposition === 'review-supersession' && accepted.acceptSuperseded !== true) fail('retirement-supersession-not-accepted');
};
const verifyFacts = async (ctx, state, registration) => {
- const policy = await ensureOwner(ctx, state.release, registration);
+ const policy = await ensureOwner(ctx, state.release, registration, state.review);
const facts = await forge(ctx, state.release, state.review.forge.prUrl);
if (JSON.stringify(policy) !== JSON.stringify(state.review.policy)
|| JSON.stringify(facts) !== JSON.stringify(state.review.forge)) fail('retirement-evidence-changed');
@@ -304,7 +320,7 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
const branchReview = async ({ directory, state, ctx }) => {
const transitioned = Boolean(state.quarantineResumptionReview);
if (!['quarantined', 'quarantined-with-metadata-transitions', 'branch-retirement-prepared'].includes(state.phase) || state.branchDeleted) fail('retirement-branch-phase-not-ready');
- const policy = await ensureOwner(ctx, state.release, false);
+ const policy = await ensureOwner(ctx, state.release, false, state.review);
const proof = await native(transitioned
? { command: 'verify-completed-quarantine', ...quarantineProofInput({ directory, state, ctx }) }
: { command: 'verify', manifestSha256: state.proof?.manifestSha256, transactionDir: directory, mode: 'restore' });
@@ -317,7 +333,7 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
if (head.exitCode !== 0 || head.stdout.trim() !== state.release.head) fail('branch-ref-changed');
const facts = await forge(ctx, state.release, state.review.forge.prUrl);
const base = await comparison(ctx, state.release, facts.prUrl, state.review.snapshot, policy, facts);
- if (JSON.stringify(await ensureOwner(ctx, state.release, false)) !== JSON.stringify(policy)) fail('retirement-evidence-changed');
+ if (JSON.stringify(await ensureOwner(ctx, state.release, false, state.review)) !== JSON.stringify(policy)) fail('retirement-evidence-changed');
const evidence = { ...base, mode: 'quarantined-branch', transactionId: state.id,
journalDigest: hash(state), archiveFingerprint: proof.fingerprint,
...(transitioned ? { quarantineResumptionReview: state.quarantineResumptionReview,
@@ -353,7 +369,7 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
if (hash(await readJournal(directory)) !== hash(state)) fail('retirement-journal-changed');
const verify = async () => {
executor.assertHeld();
- await ensureOwner(ctx, state.release, false);
+ await ensureOwner(ctx, state.release, false, state.review);
let placement;
if (state.quarantineResumptionReview) {
placement = await native({ command: 'verify-retired-quarantine', ...quarantineProofInput({ directory, state, ctx }),
@@ -370,7 +386,7 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
manifestSha256: state.proof?.manifestSha256, confirmedDeletion: { journalDigest: hash(state),
branch: state.release.branch, head: state.release.head, phase: state.phase } });
if (absence.verified !== true || absence.branchAbsent !== true) fail('retirement-deleted-branch-not-absent');
- await ensureOwner(ctx, state.release, false);
+ await ensureOwner(ctx, state.release, false, state.review);
executor.assertHeld();
};
const reservation = await gate.readCheckoutReservation(ctx.repoPath, state.id).catch(error => {
@@ -439,7 +455,7 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
let receiverAuthorized = false;
const deleted = await remove(ctx.repoPath, state.release.branch, state.release.head, { beforeMutation: async () => {
executor.assertHeld();
- if (JSON.stringify(await ensureOwner(ctx, state.release, false)) !== JSON.stringify(current.policy)
+ if (JSON.stringify(await ensureOwner(ctx, state.release, false, state.review)) !== JSON.stringify(current.policy)
|| JSON.stringify(await forge(ctx, state.release, state.review.forge.prUrl)) !== JSON.stringify(current.forge)) fail('retirement-evidence-changed');
await beforeMutation();
executor.assertHeld();
@@ -563,7 +579,7 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
|| (state.phase === 'restored' && state.cancelledUnboundPreservation === true)))) fail('retirement-cancellation-phase-invalid');
const ctx = await context(input.appId);
if (state.appId !== input.appId || state.repoPath !== ctx.repoPath) fail('retirement-transaction-app-mismatch');
- await ensureOwner(ctx, state.release, false);
+ await ensureOwner(ctx, state.release, false, state.review);
// A completed quarantine released its cut. An interrupted one retains it.
let newReservation = false;
const reservation = await gate.readCheckoutReservation(ctx.repoPath, state.id).catch(async error => {
@@ -601,7 +617,7 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
if (cancellationProof.verified !== true || cancellationProof.originalsUnmoved !== true) fail('retirement-source-changed');
}
}
- await ensureOwner(ctx, state.release, true);
+ await ensureOwner(ctx, state.release, true, state.review);
executor.assertHeld();
state = await appendStep(directory, state, 'restored', { reservation,
cancelledUnboundPreservation: !state.proof?.manifestSha256,
@@ -633,7 +649,7 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
}).catch(error => ({ ok: false, reason: error.message, transactionId: input.transactionId, recoveryRequired: true }));
const metadataRestoreSafety = async ({ ctx, state }) => {
- const policy = await ensureOwner(ctx, state.release, false);
+ const policy = await ensureOwner(ctx, state.release, false, state.review);
const list = deps.listWorktrees || (await import('./worktreeManager.js')).listWorktrees;
if ((await list(ctx.repoPath)).some(tree => String(tree.branch || '').replace(/^refs\/heads\//, '') === state.release.branch
&& tree.path !== state.release.path)) fail('branch-has-new-holder');
diff --git a/server/services/initializedCheckoutRecovery.test.js b/server/services/initializedCheckoutRecovery.test.js
index 64860fd6d5..b2e854f115 100644
--- a/server/services/initializedCheckoutRecovery.test.js
+++ b/server/services/initializedCheckoutRecovery.test.js
@@ -201,6 +201,29 @@ const reviewed = async () => {
};
describe('initialized checkout transaction', () => {
+ it('replays a bound continued-delivery generation after quarantine without recapturing absent originals', async () => {
+ const incarnation = { pointer: { dev: '1', ino: '2', birthtimeNs: '3' },
+ gitdir: { path: '/fixture/private', dev: '1', ino: '4', birthtimeNs: '5' } };
+ const policy = { reason: null, policies: [{ id: 'agent-continued', continuedDelivery: { capturedHead: '1'.repeat(40) } }] };
+ const deps = { ...fixture.deps, readCompletedIdentity: async () => {
+ if (fixture.placement.working !== 'original') throw new Error('original-checkout-already-quarantined');
+ return { incarnation };
+ }, ownership: async input => JSON.stringify(input.reviewIdentity?.checkoutIncarnation) === JSON.stringify(incarnation)
+ ? { ok: true, policy } : { ok: false, reason: 'retirement-policy-not-legacy-completed' } };
+ const service = _createInitializedCheckoutRecovery(deps);
+ const prepared = await service.review({ appId: 'app', release, prUrl });
+ expect(prepared).toMatchObject({ ok: true, review: { checkoutIncarnation: incarnation } });
+ const retired = await service.retire({ appId: 'app', release,
+ review: { prUrl, digest: prepared.review.digest, acceptSuperseded: false } });
+ expect(retired).toMatchObject({ ok: true, originalsQuarantined: true });
+ const restarted = _createInitializedCheckoutRecovery(deps);
+ const status = await restarted.status({ appId: 'app', transactionId: retired.transactionId });
+ const input = { appId: 'app', transactionId: retired.transactionId, journalDigest: status.journalDigest };
+ const branch = await restarted.reviewBranch(input);
+ expect(branch.ok).toBe(true);
+ expect(await restarted.retireBranch({ ...input, review: { digest: branch.review.digest } }))
+ .toMatchObject({ ok: true, branchDeleted: true, receiptRecorded: true });
+ });
it('binds whole-checkout admission to a distinct review before the existing durable retirement flow', async () => {
const native = vi.fn(async input => {
const result = await fixture.deps.native(input);