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: preserve checkout incarnation across delayed retirement scans (#13302)

[._.]/ Adam Eivye38aa4e6a1b7
diff --git a/server/lib/reconcileRetirementEvidence.js b/server/lib/reconcileRetirementEvidence.js
index edfdf947d2..565c1213e8 100644
--- a/server/lib/reconcileRetirementEvidence.js
+++ b/server/lib/reconcileRetirementEvidence.js
@@ -1,33 +1,43 @@
/** Exact checkout obligations survive scans until fresh service preservation evidence. */
export const sameRetirementCheckout = (left, right) => left.branch === right.branch && left.path === right.path && left.head === right.head;
-export const hasRetirementReceipt = (outcome, release) => Number.isFinite(Date.parse(release.createdAt))
- && outcome?.retired?.some(row => sameRetirementCheckout(row, release) && row.branchDeleted === true
- && typeof row.archiveDir === 'string' && row.archiveDir.length > 0
- && Date.parse(row.retiredAt) >= Date.parse(release.createdAt)) === true;
+export const sameRetirementObservation = (left, right) => sameRetirementCheckout(left, right)
+ && (left.checkoutIdentity || null) === (right.checkoutIdentity || null);
+
+export const matchingRetirementReceipts = (outcome, release) => [...(outcome?.retired || []), ...Object.values(outcome?.retirementReceiptEvidence || {})].filter(row =>
+ sameRetirementCheckout(row, release) && row.branchDeleted === true
+ && typeof row.archiveDir === 'string' && row.archiveDir.length > 0
+ && Number.isFinite(Date.parse(row.retiredAt)));
+
+export const hasRetirementReceipt = (outcome, release) => matchingRetirementReceipts(outcome, release).some(row => {
+ if (release.checkoutIdentity) return row.checkoutIdentity === release.checkoutIdentity;
+ const observed = Date.parse(release.createdAt || release.observedAt);
+ return Number.isFinite(observed) && Date.parse(row.retiredAt) >= observed;
+});
export function unresolvedRetirements(outcome, additional = []) {
const rows = [...(outcome?.retirementObligations || []), ...(outcome?.remaining || []), ...additional];
const obligations = [];
for (const row of rows) {
if (!['retirement-review-pending', 'retirement-receipt-unverified'].includes(row.reason)
- || hasRetirementReceipt(outcome, row) || obligations.some(previous => sameRetirementCheckout(previous, row))) continue;
+ || hasRetirementReceipt(outcome, row) || obligations.some(previous => sameRetirementObservation(previous, row))) continue;
obligations.push({ ...row, reason: 'retirement-receipt-unverified' });
}
return obligations;
}
-/** Only the serialized schedule writer allocates timestamps. A recreated exact
- * path/head starts after every older matching receipt, even within one clock tick.
+/** New incarnations are admitted by the serialized writer after a live check.
+ * Never replace a producer's observation time with its delayed write time.
*/
export function retainRetirementObligations(outcome, additional, now) {
const existing = unresolvedRetirements(outcome);
- const pending = unresolvedRetirements({ retirementObligations: existing }, additional);
+ const pending = unresolvedRetirements({ ...outcome, retirementObligations: existing }, additional);
return pending.map(row => {
- const previous = existing.find(entry => sameRetirementCheckout(entry, row));
+ const previous = existing.find(entry => sameRetirementObservation(entry, row));
if (Number.isFinite(Date.parse(previous?.createdAt))) return { ...row, createdAt: previous.createdAt };
- const earlier = (outcome?.retired || []).filter(entry => sameRetirementCheckout(entry, row))
- .map(entry => Date.parse(entry.retiredAt)).filter(Number.isFinite);
- return { ...row, createdAt: new Date(Math.max(Date.parse(now), ...earlier.map(time => time + 1))).toISOString() };
+ if (Number.isFinite(Date.parse(row.createdAt))) return row;
+ const earlier = matchingRetirementReceipts(outcome, row).map(entry => Date.parse(entry.retiredAt));
+ const observed = Number.isFinite(Date.parse(row.observedAt)) ? Date.parse(row.observedAt) : Date.parse(now);
+ return { ...row, createdAt: new Date(Math.max(observed, ...earlier.map(time => time + 1))).toISOString() };
});
}
diff --git a/server/lib/retirementCheckoutObservation.js b/server/lib/retirementCheckoutObservation.js
new file mode 100644
index 0000000000..d601f0e146
--- /dev/null
+++ b/server/lib/retirementCheckoutObservation.js
@@ -0,0 +1,25 @@
+/** Filesystem identity distinguishes checkouts recreated at the same path/head. */
+import { lstat } from 'node:fs/promises';
+import { join } from 'node:path';
+import { createHash } from 'node:crypto';
+import { execGit } from './execGit.js';
+
+export async function readRetirementCheckoutIdentity(path) {
+ const info = await lstat(join(path, '.git'), { bigint: true }).catch(() => null);
+ if (!info || (!info.isFile() && !info.isDirectory())) return null;
+ return createHash('sha256').update(JSON.stringify([String(info.dev), String(info.ino), String(info.birthtimeNs)])).digest('hex');
+}
+
+/** Read-only admission; neither a stale inventory nor a pathname grants a new obligation. */
+export async function isCurrentRetirementCheckout(row) {
+ if (!row.checkoutIdentity) return false;
+ const before = await readRetirementCheckoutIdentity(row.path);
+ if (before !== row.checkoutIdentity) return false;
+ const [head, branch] = await Promise.all([
+ execGit(['rev-parse', '--verify', 'HEAD'], row.path),
+ execGit(['symbolic-ref', '--quiet', 'HEAD'], row.path, { ignoreExitCode: true }),
+ ]);
+ return head.stdout.trim() === row.head
+ && (branch.stdout.trim().replace(/^refs\/heads\//, '') || null) === (row.branch || null)
+ && await readRetirementCheckoutIdentity(row.path) === before;
+}
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 887399607c..3ff76af2ac 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -3018,6 +3018,8 @@ export const cosTaskReorderBodySchema = z.object({ taskIds: z.array(nonEmptyStri
export const cosScheduleTargetBodySchema = z.object({ taskType: nonEmptyString, appId: nullishString });
// A scoped release names the exact inventory row the operator saw (#12002).
export const heldCheckoutRetireBodySchema = z.object({
+ checkoutIdentity: z.string().regex(/^[a-f0-9]{64}$/).optional(),
+ observedAt: z.string().datetime({ offset: true }).optional(),
appId: nonEmptyString,
path: nonEmptyString,
head: z.string().regex(/^[0-9a-f]{40}(?:[0-9a-f]{24})?$/),
diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.js
index fd925bad02..ad3854d500 100644
--- a/server/routes/cosScheduleRoutes.test.js
+++ b/server/routes/cosScheduleRoutes.test.js
@@ -47,8 +47,9 @@ describe('CoS Schedule Routes', () => {
vi.clearAllMocks();
});
- it('validates and forwards separate retirement review evidence without including it in checkout identity', async () => {
+ it.each([false, true])('validates retirement review evidence with optional observation identity: %s', async withObservation => {
const tuple = { path: '/synthetic/checkout', head: 'a'.repeat(40), branch: 'claim/42', locked: false, lockReason: null };
+ if (withObservation) Object.assign(tuple, { checkoutIdentity: 'c'.repeat(64), observedAt: '2026-10-23T00:00:00Z' });
const prUrl = 'https://github.com/example/repo/pull/42';
recovery.prepareInventoriedCheckoutRetirement.mockResolvedValue({ ok: true, review: { digest: 'b'.repeat(64) } });
const prepared = await request(app).post('/api/cos/schedule/branch-reconcile/checkouts/review').send({ appId: 'app-1', ...tuple, prUrl });
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.js
index 8f1968b734..f01099e6c8 100644
--- a/server/services/agentRepoStateVerification.js
+++ b/server/services/agentRepoStateVerification.js
@@ -1,6 +1,7 @@
+import { readRetirementCheckoutIdentity } from '../lib/retirementCheckoutObservation.js';
import { MANAGED_WORKTREE_CLEANUP_CONTRACT } from '../lib/mergeGateContract.js';
import { processAuditFingerprint } from '../lib/persistentMindProcessAudit.js';
-import { sameRetirementCheckout } from '../lib/reconcileRetirementEvidence.js';
+import { sameRetirementObservation } from '../lib/reconcileRetirementEvidence.js';
/**
* Agent Repo-State Verification
*
@@ -604,13 +605,15 @@ async function prepareRecoveryRetirement({ app, sourceWorkspace, branchName, wor
return { reason: 'retirement-exact-inventory-unavailable' };
}
const tree = matches[0];
+ const checkoutIdentity = await readRetirementCheckoutIdentity(tree.path);
const release = { branch: branchName, path: tree.path, head: tree.head,
+ ...(checkoutIdentity && { checkoutIdentity, observedAt: new Date().toISOString() }),
locked: tree.locked === true, lockReason: tree.lockReason ?? null };
const { recordBranchReconcileOutcome } = await import('./taskSchedule.js');
const outcome = await recordBranchReconcileOutcome(app.id, { status: 'incomplete', reason: 'retirement-review-pending',
retirementObligations: [{ ...release, reason: 'retirement-review-pending' }],
nextAction: 'Review this exact checkout through the retirement API; require its verified archive receipt.' });
- const obligation = outcome?.retirementObligations?.find(row => sameRetirementCheckout(row, release));
+ const obligation = outcome?.retirementObligations?.find(row => sameRetirementObservation(row, release));
if (!obligation?.createdAt) return { reason: 'retirement-obligation-unavailable' };
if (release.locked) {
await recordBranchReconcileOutcome(app.id, { status: 'incomplete', reason: 'retirement-worktree-locked',
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 5be9c16e29..5070fa1698 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -1,3 +1,4 @@
+import { readRetirementCheckoutIdentity } from '../lib/retirementCheckoutObservation.js';
import { MANAGED_WORKTREE_CLEANUP_CONTRACT } from '../lib/mergeGateContract.js';
/**
* Branch & PR Reconciler — deterministic core (Tier 1).
@@ -1097,6 +1098,8 @@ export function describeIdleReconcilePark(skipped = [], heldLive = [], { wip = [
...((entry.path || entry.worktreePath) && { path: entry.path || entry.worktreePath }),
...(entry.issue && { issue: entry.issue }),
...(entry.head && { head: entry.head }),
+ ...(entry.observedAt && { observedAt: entry.observedAt }),
+ ...(entry.checkoutIdentity && { checkoutIdentity: entry.checkoutIdentity }),
...(entry.locked !== undefined && { locked: entry.locked, lockReason: entry.lockReason ?? null }),
...(entry.detached && { detached: true }),
...(entry.managed !== undefined && { managed: entry.managed }),
@@ -1602,10 +1605,12 @@ const isCommitOnBranch = (repoPath, sha, branch) =>
async function gatherRecoveryWorktrees(repoPath, preloadedTrees = null) {
const trees = preloadedTrees || await listWorktrees(repoPath).catch(() => null);
if (!trees?.length) return null;
- return trees.slice(1).filter(tree => !tree.bare).map(tree => {
+ return Promise.all(trees.slice(1).filter(tree => !tree.bare).map(async tree => {
const managed = worktreeOwnershipReason({ path: tree.path, roots: reconcileWorktreeRoots(repoPath), allowLiveClaim: true }) !== 'worktree-unmanaged-location';
return {
path: tree.path,
+ observedAt: new Date().toISOString(),
+ checkoutIdentity: await readRetirementCheckoutIdentity(tree.path),
...(tree.branch && { branch: tree.branch.replace(/^refs\/heads\//, '') }),
head: tree.head ?? null,
detached: !tree.branch,
@@ -1615,7 +1620,7 @@ async function gatherRecoveryWorktrees(repoPath, preloadedTrees = null) {
reason: tree.prunable ? 'worktree-prunable' : tree.locked ? 'worktree-locked'
: !managed ? 'worktree-unmanaged-location' : 'checkout-retained',
};
- });
+ }));
}
const isStillDetachedOnMerged = async (repoPath, treePath, defaultBranch) => {
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index 66c3091239..cb1740c14d 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -67,6 +67,7 @@ vi.mock('./worktreeManager.js', async () => {
// don't care about age behave as before; set worktreeMtimeMs to pin a specific age.
let worktreeMtimeMs = 0;
vi.mock('node:fs/promises', () => ({
+ lstat: vi.fn(async () => ({ isFile: () => true, dev: 1n, ino: 2n, birthtimeNs: 3n })),
stat: vi.fn(async () => ({ mtimeMs: worktreeMtimeMs })),
}));
const ensureForgeReachableMock = vi.fn(async () => ({ ok: true, status: 'ok', detail: null, remedy: null }));
diff --git a/server/services/branchReconcileCompletion.js b/server/services/branchReconcileCompletion.js
index 5ad0832882..18a334cc25 100644
--- a/server/services/branchReconcileCompletion.js
+++ b/server/services/branchReconcileCompletion.js
@@ -99,7 +99,7 @@ export async function settleRetirementReviewRun(agent) {
await recordCleanupOutcome(agent.id, { status: 'blocked', reason: 'retirement-receipt-unverified', ...target.release });
await recordBranchReconcileOutcome(target.appId, {
status: 'incomplete', reason: 'retirement-receipt-unverified',
- retirementObligations: [{ ...target.release, reason: 'retirement-receipt-unverified' }],
+ retirementObligations: [{ ...target.release, createdAt: target.createdAt, reason: 'retirement-receipt-unverified' }],
nextAction: 'Inspect the scoped cleanup recovery and archive evidence; an agent success report cannot release this obligation.',
});
emitLog('warn', 'Cleanup recovery completed without a verified retirement receipt; exact checkout obligation retained', {
diff --git a/server/services/branchReconcileCompletion.test.js b/server/services/branchReconcileCompletion.test.js
index b327f2c14d..b4bb6b4ff7 100644
--- a/server/services/branchReconcileCompletion.test.js
+++ b/server/services/branchReconcileCompletion.test.js
@@ -145,7 +145,7 @@ describe('scoped retirement recovery completion', () => {
getTaskById.mockResolvedValue({ metadata: { retirementReview: { appId: 'persisted-app', release, createdAt: '2026-10-20T00:00:00Z' } } });
getBranchReconcileOutcome.mockResolvedValue({ retired: [{ ...release, head: 'b'.repeat(40), branchDeleted: true, archiveDir: '/example/other' }] });
expect(await settleRetirementReviewRun(recovery)).toEqual({ verified: false });
- expect(recordBranchReconcileOutcome).toHaveBeenCalledWith('persisted-app', expect.objectContaining({ retirementObligations: [{ ...release, reason: 'retirement-receipt-unverified' }] }));
+ expect(recordBranchReconcileOutcome).toHaveBeenCalledWith('persisted-app', expect.objectContaining({ retirementObligations: [{ ...release, createdAt: '2026-10-20T00:00:00Z', reason: 'retirement-receipt-unverified' }] }));
expect(reconcile).not.toHaveBeenCalled();
for (const retiredAt of ['invalid', '2026-10-19T23:59:00Z']) {
getBranchReconcileOutcome.mockResolvedValue({ retired: [{ ...release, branchDeleted: true, archiveDir: '/example/archive', retiredAt }] });
diff --git a/server/services/branchReconcileRetirement.js b/server/services/branchReconcileRetirement.js
index 6083e4d413..477ba11029 100644
--- a/server/services/branchReconcileRetirement.js
+++ b/server/services/branchReconcileRetirement.js
@@ -25,7 +25,7 @@ export async function prepareReconcileRetirements(app, result, deps = {}) {
if (!tree || tree.managed !== true || tree.locked !== false || tree.head !== branch.tip) continue;
// The open PR ships from another checkout; this one has idled behind it.
if (branch.openPr && !(await isIdleCheckout(tree.path, deps))) continue;
- const release = { branch: tree.branch, path: tree.path, head: tree.head, locked: false, lockReason: tree.lockReason ?? null };
+ const release = { ...(tree.observedAt && { observedAt: tree.observedAt }), ...(tree.checkoutIdentity && { checkoutIdentity: tree.checkoutIdentity }), branch: tree.branch, path: tree.path, head: tree.head, locked: false, lockReason: tree.lockReason ?? null };
// Every commit is already on the default branch, so no PR identity or owner
// history is needed to prove nothing is lost: archive and retire it. The
// service re-proves merge evidence and ownership under its fence.
diff --git a/server/services/branchReconcileRetirement.test.js b/server/services/branchReconcileRetirement.test.js
index 2346b61953..bbc47334a7 100644
--- a/server/services/branchReconcileRetirement.test.js
+++ b/server/services/branchReconcileRetirement.test.js
@@ -21,10 +21,11 @@ describe('historical completed-checkout review obligations', () => {
it('archives and retires a checkout whose commits are all on the default branch without a PR read or dispatch', async () => {
const deps = setup();
deps.retire = vi.fn(async () => ({ ok: true, branchDeleted: true, archiveDir: '/private/verified-archive' }));
- const result = await prepareReconcileRetirements(app, scan({ isMerged: true }), deps);
+ const observation = { observedAt: '2026-10-23T00:00:00Z', checkoutIdentity: 'original-checkout' };
+ const result = await prepareReconcileRetirements(app, scan({ isMerged: true }, observation), deps);
expect(result).toMatchObject({ candidates: [], held: [], retired: [expect.objectContaining({ branch: branch.branch, head })] });
expect(deps.readPr).not.toHaveBeenCalled();
- expect(deps.retire).toHaveBeenCalledWith({ appId: app.id, release: { branch: tree.branch, path: tree.path, head, locked: false, lockReason: null } },
+ expect(deps.retire).toHaveBeenCalledWith({ appId: app.id, release: { ...observation, branch: tree.branch, path: tree.path, head, locked: false, lockReason: null } },
{ beforeMutation: expect.any(Function), settleMergedReviewObligation: true });
});
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index 4403a8c04b..13a6388cf0 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -1,4 +1,4 @@
-import { unresolvedRetirements, sameRetirementCheckout } from '../lib/reconcileRetirementEvidence.js';
+import { unresolvedRetirements, sameRetirementCheckout, sameRetirementObservation } from '../lib/reconcileRetirementEvidence.js';
import { MANAGED_WORKTREE_CLEANUP_CONTRACT } from '../lib/mergeGateContract.js';
import { FORGE_MAINTENANCE_VERSION } from '../lib/forgeMaintenanceTasks.js';
/**
@@ -684,7 +684,7 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
metadata.perpetual = true;
metadata.reconcileRetirements = actionable.filter(branch => branch.retirement).map(branch => ({
...branch.retirement,
- createdAt: dispatchedOutcome.retirementObligations.find(row => sameRetirementCheckout(row, branch.retirement.release))?.createdAt,
+ createdAt: dispatchedOutcome.retirementObligations.find(row => sameRetirementObservation(row, branch.retirement.release))?.createdAt,
}));
const supersededBlock = formatSupersededForPrompt(result.superseded || []);
const block = [
diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.js
index 53962d7910..401f1e4381 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -1,3 +1,4 @@
+import { readRetirementCheckoutIdentity } from '../lib/retirementCheckoutObservation.js';
/**
* Operator-scoped retirement of a merged checkout that branch reconciliation
* reported but cannot retire on its own (#12002): one outside the managed
@@ -138,7 +139,8 @@ export async function prepareInventoriedCheckoutRetirement({ appId, release, prU
const app = await getAppById(appId);
if (!app?.repoPath) return { ok: false, reason: 'app-not-found' };
const outcome = await getBranchReconcileOutcome(appId);
- if (!outcome?.remaining?.some(entry => sameRelease(entry, release))) return { ok: false, reason: 'release-not-in-inventory' };
+ release = bindInventoriedRelease(outcome, release);
+ if (!release) return { ok: false, reason: 'release-not-in-inventory' };
const reviewOptions = { ...opts, forgeAccount: app.forgeAccount ?? null };
const review = () => withClaimOwnershipLock(() => reviewCurrentCheckout({ repoPath: app.repoPath, release, prUrl }, reviewOptions));
let prepared = await review();
@@ -491,6 +493,8 @@ async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {
const first = await matchRelease(repoPath, release);
if (!first.tree) return refuse(first.reason);
const { tree } = first;
+ const checkoutIdentity = await readRetirementCheckoutIdentity(tree.path);
+ if (!checkoutIdentity || (release.checkoutIdentity && release.checkoutIdentity !== checkoutIdentity)) return refuse('checkout-identity-changed');
const merged = branch
? await hasBranchMergeEvidence(repoPath, branch, defaultBranch).catch(() => false)
: await isAncestor(repoPath, tree.head, defaultBranch);
@@ -500,7 +504,7 @@ async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {
if (reviewed?.review.comparison.disposition === 'review-supersession' && review.acceptSuperseded !== true) return refuse('retirement-supersession-not-accepted');
const owner = await ownerReason({ repoPath, tree, branch, readAgents, reviewed: Boolean(review), mergedObligationSettled });
if (owner) return refuse(owner);
- return { fence: { repoPath, path: tree.path, branch }, tree, reviewed };
+ return { fence: { repoPath, path: tree.path, branch }, tree, reviewed, checkoutIdentity };
},
archive: async ({ tree, reviewed }) => {
const archive = await archiveCheckout({ repoPath, tree, branch, defaultBranch, release, cosDir, review: reviewed?.review })
@@ -509,16 +513,20 @@ async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {
console.error(`❌ held-checkout recovery: archive failed for ${tree.path}, checkout kept: ${archive.error.message}`);
return { result: { ok: false, reason: 'archive-failed', detail: archive.error.message } };
},
- finish: ({ tree, reviewed }, archive) => finishHeldCheckoutRetirement({ repoPath, release, review, reviewed, tree, branch, archive, mergedObligationSettled }, opts),
+ finish: async ({ tree, reviewed, checkoutIdentity }, archive) => {
+ const result = await finishHeldCheckoutRetirement({ repoPath, release, review, reviewed, tree, branch, archive, checkoutIdentity, mergedObligationSettled }, opts);
+ return result.ok ? { ...result, checkoutIdentity } : result;
+ },
});
}
/** The second critical section: re-prove the release, ownership and archived bytes, then remove. */
-async function finishHeldCheckoutRetirement({ repoPath, release, review, reviewed, tree, branch, archive, mergedObligationSettled = false }, opts) {
+async function finishHeldCheckoutRetirement({ repoPath, release, review, reviewed, tree, branch, archive, checkoutIdentity, mergedObligationSettled = false }, opts) {
const { readAgents = readClaimOwnershipAgents } = opts;
// Archiving takes time; never unlock a lock that changed hands meanwhile.
const second = await matchRelease(repoPath, release);
if (!second.tree) return { ok: false, reason: second.reason, archiveDir: archive.dir };
+ if (await readRetirementCheckoutIdentity(tree.path) !== checkoutIdentity) return { ok: false, reason: 'checkout-identity-changed', archiveDir: archive.dir };
await opts.beforeMutation?.();
if (release.locked) {
const unlocked = await execGit(['worktree', 'unlock', tree.path], repoPath).then(() => true, () => false);
@@ -526,6 +534,7 @@ async function finishHeldCheckoutRetirement({ repoPath, release, review, reviewe
}
const verifyRemoval = async (holder) => {
if (!holder || holder.head !== tree.head || shortBranch(holder.branch) !== branch) return 'worktree-holder-changed';
+ if (await readRetirementCheckoutIdentity(tree.path) !== checkoutIdentity) return 'checkout-identity-changed';
if (opts.inventoryCurrent && !await opts.inventoryCurrent()) return 'release-not-in-inventory';
const [reason, fresh] = await Promise.all([
ownerReason({ repoPath, tree, branch, readAgents, reviewed: Boolean(review), mergedObligationSettled }),
@@ -573,7 +582,19 @@ async function finishHeldCheckoutRetirement({ repoPath, release, review, reviewe
const sameRelease = (entry, release) => entry.path === release.path && entry.head === release.head
&& (entry.branch ?? null) === (release.branch ?? null) && Boolean(entry.locked) === release.locked
- && (entry.lockReason ?? null) === (release.lockReason ?? null);
+ && (entry.lockReason ?? null) === (release.lockReason ?? null)
+ && (!release.checkoutIdentity || entry.checkoutIdentity === release.checkoutIdentity);
+
+/** Tuple-only clients remain compatible; only persisted observation identity
+ * enters the review digest. Scan times are not incarnation identity.
+ */
+function bindInventoriedRelease(outcome, release) {
+ const entry = outcome?.remaining?.find(row => sameRelease(row, release));
+ if (!entry) return null;
+ return { path: release.path, head: release.head, branch: release.branch ?? null,
+ locked: release.locked, lockReason: release.lockReason ?? null,
+ ...(entry.checkoutIdentity && { checkoutIdentity: entry.checkoutIdentity }) };
+}
// Preview and receipt paths may acquire exact server-verified proof commits
// into the object store, never a branch, index or implicit approval.
@@ -644,7 +665,8 @@ export async function retireInventoriedCheckout({ appId, release, review }, opts
const app = await getAppById(appId);
if (!app?.repoPath) return { ok: false, reason: 'app-not-found' };
const outcome = await taskSchedule.getBranchReconcileOutcome(appId);
- if (!outcome?.remaining?.some?.(entry => sameRelease(entry, release))) return { ok: false, reason: 'release-not-in-inventory' };
+ release = bindInventoriedRelease(outcome, release);
+ if (!release) return { ok: false, reason: 'release-not-in-inventory' };
const inventoryCurrent = async () => (await taskSchedule.getBranchReconcileOutcome(appId))?.remaining?.some(entry => sameRelease(entry, release)) === true;
const result = await retireHeldCheckout({ repoPath: app.repoPath, release, review }, { ...opts, inventoryCurrent, forgeAccount: app.forgeAccount ?? null });
// The row was stale: something else already removed the checkout. That is the
@@ -658,7 +680,7 @@ export async function retireInventoriedCheckout({ appId, release, review }, opts
}
if (result.ok) {
await taskSchedule.recordHeldCheckoutRetirement(appId, {
- path: release.path, branch: release.branch ?? null, head: release.head, branchDeleted: result.branchDeleted, archiveDir: result.archiveDir,
+ path: release.path, branch: release.branch ?? null, head: release.head, branchDeleted: result.branchDeleted, archiveDir: result.archiveDir, checkoutIdentity: result.checkoutIdentity,
});
}
return result;
diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.js
index 81e37689bd..e0da547a27 100644
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@ -9,6 +9,7 @@ import { cp, mkdtemp, mkdir, rm, rename, writeFile, readFile, readdir, symlink,
import { existsSync, realpathSync } from 'fs';
import { tmpdir } from 'os';
import { dirname, join } from 'path';
+import { readRetirementCheckoutIdentity, isCurrentRetirementCheckout } from '../lib/retirementCheckoutObservation.js';
import { execGit } from '../lib/execGit.js';
import { materializeGitRepo, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';
import { cleanupTempDataRoots, lazyTempDataRoot, makePathsProxy } from '../lib/mockPathsDataRoot.js';
@@ -288,11 +289,15 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
await execGit(['merge', '--squash', 'feature/held'], repo);
await execGit(['commit', '-m', 'feat: synthetic feature (squash)'], repo);
} });
+ const checkoutIdentity = await readRetirementCheckoutIdentity(path);
+ const delayed = { ...release, checkoutIdentity, observedAt: new Date().toISOString(), reason: 'retirement-review-pending' };
await recordBranchReconcileOutcome('app-1', {
status: 'incomplete', reason: 'holds-remaining', nextAction: 'Recover held checkouts.',
- remaining: [{ ...release, managed: false, reason: 'worktree-locked' }, { branch: 'other', reason: 'actionable' }],
+ remaining: [{ ...delayed, managed: false, reason: 'worktree-locked' }, { branch: 'other', reason: 'actionable' }],
});
-
+ expect(await retireInventoriedCheckout({ appId: 'app-1', release: { ...release, checkoutIdentity: '0'.repeat(64) } }, { cosDir, readAgents: noOwners }))
+ .toEqual({ ok: false, reason: 'release-not-in-inventory' });
+ expect(await isCurrentRetirementCheckout(delayed)).toBe(true);
const branchArchiveRoot = join(PATHS.cos, 'branch-retirement-archives');
const priorArchives = new Set(await readdir(branchArchiveRoot).catch(() => []));
const originalReflog = await readFile(join(repo, '.git', 'logs', 'refs', 'heads', 'feature', 'held'));
@@ -314,7 +319,20 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
const outcome = await getBranchReconcileOutcome('app-1');
expect(outcome.status).toBe('incomplete');
expect(outcome.remaining).toEqual([{ branch: 'other', reason: 'actionable' }]);
- expect(outcome.retired[0]).toMatchObject({ path: release.path, branch: 'feature/held', branchDeleted: true, archiveDir: result.archiveDir });
+ expect(outcome.retired[0]).toMatchObject({ path: release.path, branch: 'feature/held', branchDeleted: true, archiveDir: result.archiveDir, checkoutIdentity });
+ await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [delayed] });
+ expect((await getBranchReconcileOutcome('app-1')).retirementObligations).toEqual([]);
+ await execGit(['worktree', 'add', '-b', release.branch, path, release.head], repo);
+ const recreated = { ...delayed, checkoutIdentity: await readRetirementCheckoutIdentity(path), observedAt: new Date().toISOString() };
+ expect(recreated.checkoutIdentity).not.toBe(checkoutIdentity);
+ expect(await isCurrentRetirementCheckout(delayed)).toBe(false);
+ expect(await isCurrentRetirementCheckout({ ...recreated, head: '0'.repeat(40) })).toBe(false);
+ // Even while the new tuple is live, the old scan cannot create its obligation.
+ await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [delayed] });
+ expect((await getBranchReconcileOutcome('app-1')).retirementObligations).toEqual([]);
+ await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [recreated] });
+ expect((await getBranchReconcileOutcome('app-1')).retirementObligations)
+ .toEqual([expect.objectContaining({ checkoutIdentity: recreated.checkoutIdentity, reason: 'retirement-receipt-unverified' })]);
});
it('settles a stale inventory row whose checkout was already removed instead of refusing it', async () => {
diff --git a/server/services/initializedCheckoutRecovery.js b/server/services/initializedCheckoutRecovery.js
index e55f8bc749..29c646c899 100644
--- a/server/services/initializedCheckoutRecovery.js
+++ b/server/services/initializedCheckoutRecovery.js
@@ -3,6 +3,7 @@
* quarantined whole, never unlinked. Immutable journal steps and a durable
* repository reservation survive an interrupted request or server restart.
*/
+import { readRetirementCheckoutIdentity } from '../lib/retirementCheckoutObservation.js';
import { spawn } from '../lib/childProcess.js';
import { createHash, randomUUID } from 'node:crypto';
import { link, lstat, mkdir, open, opendir, readFile, readdir } from 'node:fs/promises';
@@ -204,7 +205,10 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
const snapshot = await native({ command: 'inspect', repoPath: ctx.repoPath, release });
const facts = await forge(ctx, release, prUrl);
const base = await comparison(ctx, release, prUrl, snapshot, policy, facts);
- const evidence = { ...base, mode: 'initialized-private-modules', snapshot };
+ const checkoutIdentity = await readRetirementCheckoutIdentity(release.path);
+ if (release.checkoutIdentity && release.checkoutIdentity !== checkoutIdentity) fail('checkout-identity-changed');
+ const evidence = { ...base, mode: 'initialized-private-modules', snapshot,
+ ...(checkoutIdentity && { checkoutIdentity }) };
delete evidence.digest;
return { ctx, review: { digest: hash(evidence), ...evidence } };
};
@@ -378,7 +382,8 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
if (state.phase === 'branch-retired') {
const record = deps.recordRetirement || (await import('./taskSchedule.js')).recordHeldCheckoutRetirement;
await record(state.appId, { path: state.release.path, branch: state.release.branch,
- head: state.release.head, branchDeleted: true, archiveDir: directory });
+ head: state.release.head, branchDeleted: true, archiveDir: directory,
+ ...(state.review.checkoutIdentity && { checkoutIdentity: state.review.checkoutIdentity }) });
state = await appendStep(directory, state, 'retired', { receiptRecorded: true });
}
await beforeMutation();
@@ -447,7 +452,8 @@ export function _createInitializedCheckoutRecovery(deps = {}) {
await beforeMutation();
const record = deps.recordRetirement || (await import('./taskSchedule.js')).recordHeldCheckoutRetirement;
await record(state.appId, { path: state.release.path, branch: state.release.branch,
- head: state.release.head, branchDeleted: true, archiveDir: directory });
+ head: state.release.head, branchDeleted: true, archiveDir: directory,
+ ...(state.review.checkoutIdentity && { checkoutIdentity: state.review.checkoutIdentity }) });
state = await appendStep(directory, state, 'retired', { receiptRecorded: true });
await beforeMutation();
await gate.releaseCheckoutReservation(reservation);
diff --git a/server/services/initializedCheckoutRecovery.test.js b/server/services/initializedCheckoutRecovery.test.js
index 7e7b42b2a1..43bffa3425 100644
--- a/server/services/initializedCheckoutRecovery.test.js
+++ b/server/services/initializedCheckoutRecovery.test.js
@@ -1,3 +1,7 @@
+vi.mock('../lib/retirementCheckoutObservation.js', () => ({
+ readRetirementCheckoutIdentity: vi.fn(async () => null), isCurrentRetirementCheckout: vi.fn(async () => false),
+}));
+import { readRetirementCheckoutIdentity, isCurrentRetirementCheckout } from '../lib/retirementCheckoutObservation.js';
import { pinPlatform } from '../lib/testHelper.js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { mkdir, mkdtemp, open, readFile, readdir, rm, writeFile } from 'node:fs/promises';
@@ -64,6 +68,8 @@ let root, fixture;
const release = { path: '/fixture/checkout', branch: 'claim/42', head: 'a'.repeat(40), locked: false, lockReason: null };
const prUrl = 'https://github.com/example/repo/pull/42';
beforeEach(async () => {
+ readRetirementCheckoutIdentity.mockReset().mockResolvedValue(null);
+ isCurrentRetirementCheckout.mockReset().mockResolvedValue(false);
persisted.hostType = null; persisted.rejectDirectoryOpen = persisted.syntheticModes = false; persisted.fileSyncs = 0;
root = await mkdtemp(join(tmpdir(), 'initialized-recovery-'));
const facts = { prUrl, prHead: release.head, defaultHead: 'b'.repeat(40) };
@@ -953,12 +959,14 @@ describe('initialized checkout transaction', () => {
return { ...bound, review: { prUrl, digest: response.review.digest, acceptSuperseded: fixture.superseded === true } };
};
it('finishes a quarantined branch with a new exact review and records the source checkout receipt', async () => {
+ readRetirementCheckoutIdentity.mockResolvedValue('original-checkout');
const input = await quarantinedReview();
+ readRetirementCheckoutIdentity.mockResolvedValue('later-checkout');
const result = await fixture.service.retireBranch(input);
expect(result).toMatchObject({ ok: true, branchDeleted: true, receiptRecorded: true });
expect(fixture.deps.deleteRef).toHaveBeenCalledWith('/fixture/repo', release.branch, release.head, { beforeMutation: expect.any(Function) });
expect(fixture.deps.recordRetirement).toHaveBeenCalledWith('app', { path: release.path, branch: release.branch,
- head: release.head, branchDeleted: true, archiveDir: join(root, input.transactionId) });
+ head: release.head, branchDeleted: true, archiveDir: join(root, input.transactionId), checkoutIdentity: 'original-checkout' });
expect(fixture.cut).toBeNull();
expect((await fixture.service.status(input)).phase).toBe('retired');
});
@@ -1072,7 +1080,8 @@ describe('initialized checkout transaction', () => {
path: `/later/${index}`, branch: `later/${index}`, head: 'f'.repeat(40),
branchDeleted: true, archiveDir: `/later-archives/${index}`,
});
- const newer = { ...release, reason: 'retirement-review-pending' };
+ const newer = { ...release, checkoutIdentity: 'recreated', reason: 'retirement-review-pending' };
+ isCurrentRetirementCheckout.mockResolvedValueOnce(true);
await recordBranchReconcileOutcome('app', { status: 'actionable', remaining: [newer] });
const saved = JSON.parse(persisted.json);
const outcome = saved.executions['task:branch-reconcile'].perApp.app.branchReconcileOutcome;
@@ -1105,7 +1114,8 @@ describe('initialized checkout transaction', () => {
expect(retired.retirementObligations).toEqual([]);
expect(retired.remaining).toEqual([]);
const originalTimestamp = retired.retired[0].retiredAt;
- const recreated = await recordBranchReconcileOutcome('app', { status: 'actionable', remaining: [pending] });
+ isCurrentRetirementCheckout.mockResolvedValueOnce(true);
+ const recreated = await recordBranchReconcileOutcome('app', { status: 'actionable', remaining: [{ ...pending, checkoutIdentity: 'recreated' }] });
const generation = recreated.retirementObligations[0].createdAt;
expect(Date.parse(generation)).toBeGreaterThan(Date.parse(originalTimestamp));
expect(Date.parse(generation)).toBeGreaterThanOrEqual(Date.parse(firstCreated));
@@ -1116,7 +1126,7 @@ describe('initialized checkout transaction', () => {
vi.useFakeTimers();
try {
vi.setSystemTime(Date.parse(generation) + 1);
- const completed = await recordHeldCheckoutRetirement('app', { ...receipt, archiveDir: '/archive/new-generation' });
+ const completed = await recordHeldCheckoutRetirement('app', { ...receipt, checkoutIdentity: 'recreated', archiveDir: '/archive/new-generation' });
expect(completed.retirementObligations).toEqual([]);
expect(completed.remaining).toEqual([]);
expect(completed.retired.find(row => row.archiveDir === receipt.archiveDir).retiredAt).toBe(originalTimestamp);
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index 6082e5e710..4dac351786 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -20,7 +20,8 @@
*/
import { scheduleExecutionFieldsSchema } from '../lib/scheduleExecutionFieldsValidation.js';
-import { unresolvedRetirements, retainRetirementObligations, sameRetirementCheckout } from '../lib/reconcileRetirementEvidence.js';
+import { unresolvedRetirements, retainRetirementObligations, sameRetirementCheckout, sameRetirementObservation, matchingRetirementReceipts, hasRetirementReceipt } from '../lib/reconcileRetirementEvidence.js';
+import { isCurrentRetirementCheckout } from '../lib/retirementCheckoutObservation.js';
import { findGoneInventoryRows, isObligationRow } from './branchReconcileInventoryPrune.js';
import { createHash, randomUUID } from 'node:crypto';
import { ServerError } from '../lib/errorHandler.js';
@@ -774,13 +775,31 @@ export async function recordBranchReconcileOutcome(appId, { status, reason, rema
const record = ensureExecutionRecord(schedule, 'branch-reconcile', appId);
const now = new Date().toISOString();
const previous = record.branchReconcileOutcome;
- const retirementObligations = retainRetirementObligations(previous, [...(remaining || []), ...additionalObligations], now);
- const inventory = remaining === undefined ? previous?.remaining ?? null : remaining;
+ const existing = unresolvedRetirements(previous);
+ const admitted = [];
+ const rejected = [];
+ for (const row of [...(remaining || []), ...additionalObligations]) {
+ if (!isObligationRow(row)) continue;
+ if (existing.some(entry => sameRetirementObservation(entry, row))) continue;
+ const previousIncarnation = existing.some(entry => sameRetirementCheckout(entry, row));
+ const receipts = matchingRetirementReceipts(previous, row);
+ // Legacy rows without observation identity cannot claim to be recreations.
+ if (hasRetirementReceipt(previous, row)
+ || ((receipts.length || previousIncarnation) && !Number.isFinite(Date.parse(row.createdAt))
+ && (!row.checkoutIdentity || !await isCurrentRetirementCheckout(row).catch(() => false)))) {
+ rejected.push(row);
+ } else admitted.push(row);
+ }
+ const retirementObligations = retainRetirementObligations(previous, admitted, now);
+ const inventory = (remaining === undefined ? previous?.remaining ?? null : remaining)
+ ?.filter(row => !rejected.some(entry => sameRetirementObservation(entry, row))) ?? null;
const current = inventory?.map(row => {
- const obligation = retirementObligations.find(entry => sameRetirementCheckout(entry, row));
- return obligation ? { ...row, createdAt: obligation.createdAt } : row;
+ const obligation = retirementObligations.find(entry => sameRetirementObservation(entry, row));
+ return obligation ? { ...row, createdAt: obligation.createdAt,
+ ...(obligation.checkoutIdentity && { checkoutIdentity: obligation.checkoutIdentity }),
+ ...(obligation.observedAt && { observedAt: obligation.observedAt }) } : row;
}) ?? null;
- const retained = retirementObligations.filter(obligation => !current?.some(row => sameRetirementCheckout(row, obligation)));
+ const retained = retirementObligations.filter(obligation => !current?.some(row => sameRetirementObservation(row, obligation)));
record.branchReconcileOutcome = {
...previous, status, reason, nextAction, updatedAt: now, retirementObligations,
remaining: retained.length ? [...(current || []), ...retained] : current,
@@ -853,38 +872,44 @@ const RETIRED_CHECKOUTS_KEPT = 20;
* where its archive went. Status is untouched: only the next sweep can say the
* repository converged.
*/
-export async function recordHeldCheckoutRetirement(appId, { path, branch, branchDeleted, head, archiveDir }) {
+export async function recordHeldCheckoutRetirement(appId, { path, branch, branchDeleted, head, archiveDir, checkoutIdentity }) {
return updateSchedule(async (schedule) => {
const record = ensureExecutionRecord(schedule, 'branch-reconcile', appId);
const outcome = record.branchReconcileOutcome || {};
- // Display history is bounded; replay identity is durable. A delayed retry
+ // Display history is bounded; receipt evidence and replay identity are durable. A delayed retry
// must not become new evidence after its display row has been evicted.
const identity = receipt => createHash('sha256').update(JSON.stringify([
receipt.archiveDir, receipt.path, receipt.branch ?? null, receipt.head,
receipt.branchDeleted === true,
])).digest('hex');
const receipts = { ...(outcome.retirementReceiptIdentities || {}) };
+ const evidence = { ...(outcome.retirementReceiptEvidence || {}) };
for (const receipt of outcome.retired || []) {
- if (receipt.archiveDir && receipt.retiredAt) receipts[identity(receipt)] ??= receipt.retiredAt;
+ if (receipt.archiveDir && receipt.retiredAt) {
+ receipts[identity(receipt)] ??= receipt.retiredAt;
+ evidence[identity(receipt)] ??= receipt;
+ }
}
const receiptId = archiveDir ? identity({ path, branch, head, archiveDir, branchDeleted }) : null;
if (receiptId && receipts[receiptId]) {
// Keep the original timestamp AND any newer inventory incarnation.
- const changed = JSON.stringify(receipts) !== JSON.stringify(outcome.retirementReceiptIdentities || {});
- if (changed) record.branchReconcileOutcome = { ...outcome, retirementReceiptIdentities: receipts };
+ const changed = JSON.stringify(receipts) !== JSON.stringify(outcome.retirementReceiptIdentities || {})
+ || JSON.stringify(evidence) !== JSON.stringify(outcome.retirementReceiptEvidence || {});
+ if (changed) record.branchReconcileOutcome = { ...outcome, retirementReceiptIdentities: receipts, retirementReceiptEvidence: evidence };
return { result: record.branchReconcileOutcome, changed };
}
const retiredAt = new Date().toISOString();
if (receiptId) receipts[receiptId] = retiredAt;
- const receipt = { path, ...(branch && { branch }), head, branchDeleted, archiveDir, retiredAt };
+ const receipt = { path, ...(branch && { branch }), head, branchDeleted, archiveDir, retiredAt, ...(checkoutIdentity && { checkoutIdentity }) };
const retired = [receipt, ...(outcome.retired || [])].slice(0, RETIRED_CHECKOUTS_KEPT);
- const retirementObligations = unresolvedRetirements({ ...outcome, retired });
+ if (receiptId) evidence[receiptId] = receipt;
+ const retirementObligations = unresolvedRetirements({ ...outcome, retired, retirementReceiptEvidence: evidence });
record.branchReconcileOutcome = {
...outcome, retirementObligations,
- retirementReceiptIdentities: receipts,
+ retirementReceiptIdentities: receipts, retirementReceiptEvidence: evidence,
updatedAt: retiredAt,
remaining: Array.isArray(outcome.remaining)
- ? outcome.remaining.filter(entry => retirementObligations.some(row => sameRetirementCheckout(row, entry))
+ ? outcome.remaining.filter(entry => retirementObligations.some(row => sameRetirementObservation(row, entry))
|| (entry.path !== path && !(branchDeleted && branch && entry.branch === branch)))
: outcome.remaining ?? null,
retired,
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 293228a7a1..22a6422f91 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -1,3 +1,5 @@
+vi.mock('../lib/retirementCheckoutObservation.js', () => ({ isCurrentRetirementCheckout: vi.fn(async () => false) }));
+import { isCurrentRetirementCheckout } from '../lib/retirementCheckoutObservation.js';
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
vi.mock('./branchReconcileInventoryPrune.js', async importOriginal => ({
@@ -3341,13 +3343,93 @@ describe('taskSchedule', () => {
expect(outcome()).toMatchObject({ status: 'drained', retirementObligations: [], remaining: [] });
// A new checkout with identical branch/path/head cannot reuse that receipt.
const retiredAt = outcome().retired[0].retiredAt;
- await recordBranchReconcileOutcome('app-1', { status: 'running', retirementObligations: [release] });
+ isCurrentRetirementCheckout.mockResolvedValueOnce(true);
+ await recordBranchReconcileOutcome('app-1', { status: 'running', retirementObligations: [{ ...release, checkoutIdentity: 'new-incarnation' }] });
const recreatedAt = outcome().retirementObligations[0].createdAt;
expect(Date.parse(recreatedAt)).toBeGreaterThan(Date.parse(retiredAt));
await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [] });
await parkPerpetual('branch-reconcile', 'app-1', { reason: 'no-in-flight-branches' });
- expect(outcome()).toMatchObject({ status: 'incomplete', retirementObligations: [{ ...release, createdAt: recreatedAt, reason: 'retirement-receipt-unverified' }] });
+ expect(outcome()).toMatchObject({ status: 'incomplete', retirementObligations: [{ ...release, checkoutIdentity: 'new-incarnation', createdAt: recreatedAt, reason: 'retirement-receipt-unverified' }] });
+
+ });
+
+ it.each(['scan-first', 'receipt-first'])('does not resurrect a stale scan across serialized %s writes', async order => {
+ let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
+ readJSONFile.mockImplementation(async () => structuredClone(saved));
+ writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(new Date('2026-10-23T00:00:00Z'));
+ const row = { branch: 'fix/example', path: '/example/checkout', head: 'a'.repeat(40),
+ checkoutIdentity: 'original', observedAt: new Date().toISOString(), reason: 'retirement-review-pending' };
+ const receipt = { ...row, branchDeleted: true, archiveDir: '/example/archive' };
+ const outcome = () => saved.executions['task:branch-reconcile'].perApp['app-1'].branchReconcileOutcome;
+ const scan = () => recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [row] });
+ const retire = () => recordHeldCheckoutRetirement('app-1', receipt);
+ // Queue both without awaiting: updateSchedule must merge with the prior write.
+ await Promise.all(order === 'scan-first' ? [scan(), retire()] : [retire(), scan()]);
+ expect(outcome()).toMatchObject({ retirementObligations: [], remaining: [] });
+ const retiredAt = outcome().retired[0].retiredAt;
+ vi.setSystemTime(new Date('2026-10-23T00:00:20Z'));
+ await scan();
+ // A legacy delayed producer has its original timestamp, not filesystem identity.
+ await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [{ ...row, checkoutIdentity: undefined }] });
+ expect(outcome()).toMatchObject({ retirementObligations: [], remaining: [] });
+ expect(isCurrentRetirementCheckout).not.toHaveBeenCalled();
+ // A fresh same-tuple checkout needs a live identity check, even in the same clock tick.
+ vi.setSystemTime(new Date(retiredAt));
+ const recreated = { ...row, checkoutIdentity: 'recreated' };
+ isCurrentRetirementCheckout.mockResolvedValueOnce(true);
+ await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [recreated] });
+ const obligation = outcome().retirementObligations[0];
+ expect(obligation).toMatchObject({ checkoutIdentity: 'recreated' });
+ expect(Date.parse(obligation.createdAt)).toBeGreaterThan(Date.parse(retiredAt));
+ expect(isCurrentRetirementCheckout).toHaveBeenCalledWith(recreated);
+ vi.setSystemTime(new Date('2026-10-23T00:01:00Z'));
+ await retire();
+ expect(outcome().retired[0].retiredAt).toBe(retiredAt);
+ expect(outcome().retirementObligations).toEqual([obligation]);
+ await recordHeldCheckoutRetirement('app-1', { ...receipt, checkoutIdentity: 'recreated', archiveDir: '/example/new-archive' });
+ expect(outcome().retirementObligations).toEqual([]);
+ // A delayed observation of a different, now absent incarnation cannot mint another obligation.
+ await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [{ ...row, checkoutIdentity: 'absent' }] });
+ expect(outcome()).toMatchObject({ retirementObligations: [], remaining: [] });
+ vi.useRealTimers();
+ });
+ it('keeps both incarnations when recreation is observed before the original receipt arrives', async () => {
+ let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
+ readJSONFile.mockImplementation(async () => structuredClone(saved));
+ writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
+ const original = { branch: 'fix/example', path: '/example/checkout', head: 'a'.repeat(40),
+ checkoutIdentity: 'original', reason: 'retirement-review-pending' };
+ const recreated = { ...original, checkoutIdentity: 'recreated' };
+ await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [original] });
+ isCurrentRetirementCheckout.mockResolvedValueOnce(true);
+ const pending = await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [recreated] });
+ expect(pending.retirementObligations.map(row => row.checkoutIdentity)).toEqual(['original', 'recreated']);
+ const retired = await recordHeldCheckoutRetirement('app-1', { ...original, branchDeleted: true, archiveDir: '/example/archive' });
+ expect(retired.retirementObligations).toEqual([expect.objectContaining({ checkoutIdentity: 'recreated' })]);
+ expect(retired.remaining).toEqual([expect.objectContaining({ checkoutIdentity: 'recreated' })]);
+ });
+
+ it('keeps stale-observation evidence after receipt display eviction and refuses duplicate replay', async () => {
+ let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
+ readJSONFile.mockImplementation(async () => structuredClone(saved));
+ writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
+ const row = { branch: 'fix/example', path: '/example/checkout', head: 'a'.repeat(40),
+ createdAt: '2026-01-01T00:00:00Z', reason: 'retirement-review-pending' };
+ const receipt = { ...row, branchDeleted: true, archiveDir: '/example/archive' };
+ const outcome = () => saved.executions['task:branch-reconcile'].perApp['app-1'].branchReconcileOutcome;
+ await recordHeldCheckoutRetirement('app-1', receipt);
+ const evidence = structuredClone(outcome().retirementReceiptEvidence);
+ for (let index = 0; index < 20; index++) {
+ await recordHeldCheckoutRetirement('app-1', { ...receipt, branch: `fix/other-${index}` });
+ }
+ expect(outcome().retired.some(entry => entry.branch === row.branch)).toBe(false);
+ await recordBranchReconcileOutcome('app-1', { status: 'running', remaining: [row] });
+ await recordHeldCheckoutRetirement('app-1', receipt);
+ expect(outcome()).toMatchObject({ retirementObligations: [], remaining: [], retirementReceiptEvidence: evidence });
+ expect(outcome().retired.some(entry => entry.branch === row.branch)).toBe(false);
});
it('persists branch attempts through cap parks and manual resets, clearing only on sweep exhaustion', async () => {