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: review superseded and detached local checkouts (#13488)

[._.]/d68f0615154a
diff --git a/client/src/pages/GitHub.test.jsx b/client/src/pages/GitHub.test.jsx
index c67d307d5a..9bc1e3f189 100644
--- a/client/src/pages/GitHub.test.jsx
+++ b/client/src/pages/GitHub.test.jsx
@@ -444,6 +444,7 @@ async function renderInbox(tab = 'inbox') {
describe('GitHub inbox tab', () => {
beforeEach(() => {
vi.clearAllMocks();
+ mock.getProviders.mockResolvedValue({ providers: [] });
mock.getGitHubAccounts.mockResolvedValue([IMPLICIT]);
mock.syncGitHubNotifications.mockResolvedValue({ results: [] });
mock.getGitHubNotifications.mockResolvedValue({ notifications: [NOTIFICATION], sync: {} });
diff --git a/docs/features/branch-reconciliation.md b/docs/features/branch-reconciliation.md
index 0962f07864..b14d681cb2 100644
--- a/docs/features/branch-reconciliation.md
+++ b/docs/features/branch-reconciliation.md
@@ -68,6 +68,32 @@ immediately before removal; if that recheck refuses, the original lock is
restored. A retired row leaves the inventory and appears under *Recently
retired* with its archive path; only the next sweep can report convergence.
+### Explicit delivery reviews
+
+`POST /api/cos/schedule/branch-reconcile/checkouts/review` accepts the exact
+inventory tuple and `prUrl`. A detached checkout may name its merged PR only
+when its HEAD exactly equals the published PR head. The published branch's
+saved completion policy and live owners still apply. Retirement preserves the
+detached checkout and records checkout-only completion; it never deletes the
+published branch.
+
+Sometimes a completed local branch was delivered through a replacement PR
+instead of its original tip. For that case, add `kind: "source-supersession"`
+to the review request and name the replacement merged PR. The server verifies
+the same repository and default branch, refuses an open delivery for the
+original branch, and binds both original and replacement heads plus current
+source differences. This does not claim that the original commits were merged.
+Inspect the original unique patch and its current replacement before accepting;
+wanted unfinished work still needs delivery. Unknown/active owners, failed or
+manual-handoff completion policies, and changed evidence remain holds.
+
+Confirm through `checkouts/retire` with the same inventory tuple and
+`review: { prUrl, digest, kind: "source-supersession", acceptSuperseded: true }`.
+Explicit acceptance is required even when the affected file bytes now match.
+The existing full archive, private Git proof, ownership/content rechecks and
+persisted receipt remain prerequisites to removal. Initialized checkouts retain
+their separate workflow; this mode does not bypass its preservation guards.
+
### Held archive work budgets
Patch capture preserves original Git output bytes, including non-UTF-8 content. Metadata names and symlink targets must round-trip losslessly through UTF-8; unsupported encodings refuse preservation before removal.
diff --git a/server/lib/validation.js b/server/lib/validation.js
index 3ff76af2ac..41baec6096 100644
--- a/server/lib/validation.js
+++ b/server/lib/validation.js
@@ -3030,9 +3030,10 @@ export const heldCheckoutRetireBodySchema = z.object({
prUrl: z.string().url(),
digest: z.string().regex(/^[a-f0-9]{64}$/),
acceptSuperseded: z.boolean(),
+ kind: z.literal('source-supersession').optional(),
}).optional(),
});
-export const heldCheckoutReviewBodySchema = heldCheckoutRetireBodySchema.omit({ review: true }).extend({ prUrl: z.string().url() });
+export const heldCheckoutReviewBodySchema = heldCheckoutRetireBodySchema.omit({ review: true }).extend({ prUrl: z.string().url(), kind: z.literal('source-supersession').optional() });
export const initializedCheckoutRetireBodySchema = heldCheckoutRetireBodySchema.extend({
review: heldCheckoutRetireBodySchema.shape.review.unwrap(),
}).strict();
diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.js
index 8167893b3d..81da4ec2e2 100644
--- a/server/routes/cosScheduleRoutes.js
+++ b/server/routes/cosScheduleRoutes.js
@@ -298,9 +298,9 @@ router.post('/schedule/branch-reconcile/refresh', asyncHandler(async (req, res)
// Prepare evidence only; the separate confirmation binds its digest to fresh facts.
router.post('/schedule/branch-reconcile/checkouts/review', asyncHandler(async (req, res) => {
- const { appId, prUrl, ...release } = validateRequest(heldCheckoutReviewBodySchema, req.body);
+ const { appId, prUrl, kind, ...release } = validateRequest(heldCheckoutReviewBodySchema, req.body);
const { prepareInventoriedCheckoutRetirement } = await import('../services/heldCheckoutRecovery.js');
- const result = await prepareInventoriedCheckoutRetirement({ appId, release, prUrl });
+ const result = await prepareInventoriedCheckoutRetirement({ appId, release, prUrl, ...(kind && { kind }) });
if (!result.ok) throw new ServerError(`Checkout review refused: ${result.reason}`, {
status: 409, code: 'CHECKOUT_REVIEW_REFUSED', context: { reason: result.reason, ...(result.archiveLimit && { archiveLimit: result.archiveLimit }), ...(result.nextAction && { nextAction: result.nextAction }) },
});
@@ -324,7 +324,7 @@ router.post('/schedule/branch-reconcile/checkouts/retire', asyncHandler(async (r
// Initial retirement remains explicit. Only existing proof-bound journals can be
// continued by the deterministic daemon; ordinary cleanup keeps its module guard.
router.post('/schedule/branch-reconcile/initialized-checkouts/review', asyncHandler(async (req, res) => {
- const { appId, prUrl, ...release } = validateRequest(heldCheckoutReviewBodySchema.strict(), req.body);
+ const { appId, prUrl, ...release } = validateRequest(heldCheckoutReviewBodySchema.omit({ kind: true }).strict(), req.body);
const { reviewInitializedCheckout } = await import('../services/initializedCheckoutRecovery.js');
const result = await reviewInitializedCheckout({ appId, release, prUrl });
res.status(result.ok ? 200 : 409).json(result);
diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.js
index b14b6d179a..e3face121b 100644
--- a/server/routes/cosScheduleRoutes.test.js
+++ b/server/routes/cosScheduleRoutes.test.js
@@ -64,6 +64,20 @@ describe('CoS Schedule Routes', () => {
expect(refreshInventory).not.toHaveBeenCalled();
});
+ it('keeps replacement-source mode out of the released inventory tuple and binds it on confirmation', async () => {
+ const tuple = { path: '/synthetic/checkout', head: 'a'.repeat(40), branch: 'original', locked: false, lockReason: null };
+ const prUrl = 'https://github.com/example/repo/pull/42';
+ recovery.prepareInventoriedCheckoutRetirement.mockResolvedValue({ ok: true, review: { digest: 'b'.repeat(64) } });
+ expect((await request(app).post('/api/cos/schedule/branch-reconcile/checkouts/review')
+ .send({ appId: 'app-1', ...tuple, prUrl, kind: 'source-supersession' })).status).toBe(200);
+ expect(recovery.prepareInventoriedCheckoutRetirement).toHaveBeenCalledWith({ appId: 'app-1', release: tuple, prUrl, kind: 'source-supersession' });
+ const review = { prUrl, digest: 'b'.repeat(64), acceptSuperseded: true, kind: 'source-supersession' };
+ recovery.retireInventoriedCheckout.mockResolvedValue({ ok: true });
+ expect((await request(app).post('/api/cos/schedule/branch-reconcile/checkouts/retire').send({ appId: 'app-1', ...tuple, review })).status).toBe(200);
+ expect(recovery.retireInventoriedCheckout).toHaveBeenCalledWith({ appId: 'app-1', release: tuple, review });
+ expect((await request(app).post('/api/cos/schedule/branch-reconcile/checkouts/review').send({ appId: 'app-1', ...tuple, prUrl, kind: 'force' })).status).toBe(400);
+ });
+
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' });
diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.js
index df36509d42..d14bd3d652 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -542,30 +542,42 @@ async function integratedPolicyReviewIdentity(repoPath, release, prUrl, forge) {
? forge.defaultHead : null };
}
-async function reviewCurrentCheckout({ repoPath, release, prUrl, unlocked = false }, opts = {}) {
- if (!release.branch || PROTECTED_BRANCHES.includes(release.branch)) return { ok: false, reason: 'protected-branch' };
+const reviewForgeOptions = (release, kind, opts) => ({ forgeAccount: opts.forgeAccount,
+ ...(!release.branch && { exactAliasHead: release.head }),
+ ...(kind === 'source-supersession' && { sourceSupersessionHead: release.head }) });
+
+async function reviewCurrentCheckout({ repoPath, release, prUrl, kind, unlocked = false }, opts = {}) {
+ if (kind && kind !== 'source-supersession') return { ok: false, reason: 'retirement-review-kind-unavailable' };
+ if (kind && !release.branch) return { ok: false, reason: 'retirement-source-branch-required' };
+ if (PROTECTED_BRANCHES.includes(release.branch)) return { ok: false, reason: 'protected-branch' };
const matched = await matchRelease(repoPath, unlocked ? { ...release, locked: false, lockReason: null } : release);
if (!matched.tree) return { ok: false, reason: matched.reason };
const owner = await ownerReason({ repoPath, tree: matched.tree, branch: release.branch,
readAgents: opts.readAgents || readClaimOwnershipAgents, reviewed: true });
if (owner) return { ok: false, reason: owner };
const { buildCheckoutRetirementReview, readRetirementForgeEvidence } = await import('./heldCheckoutReview.js');
- const forge = await (opts.readForge || readRetirementForgeEvidence)(repoPath, release.branch, prUrl, { forgeAccount: opts.forgeAccount })
+ const forge = await (opts.readForge || readRetirementForgeEvidence)(repoPath, release.branch, prUrl, reviewForgeOptions(release, kind, opts))
.catch(error => ({ error }));
if (forge?.error) return { ok: false, reason: /^retirement-[a-z-]+$/.test(forge.error.message) ? forge.error.message : 'retirement-forge-unavailable' };
+ if (kind && forge?.sourceSupersessionHead !== release.head) return { ok: false, reason: 'retirement-source-head-unverified' };
+ if (!release.branch && (forge?.prHead !== release.head || !forge.publishedBranch)) return { ok: false, reason: 'retirement-detached-head-unverified' };
+ const policyBranch = release.branch || forge.publishedBranch;
+ const namedOwner = !release.branch && await ownerReason({ repoPath, tree: matched.tree, branch: policyBranch,
+ readAgents: opts.readAgents || readClaimOwnershipAgents, reviewed: true });
+ 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' };
- const policy = await retirementPolicy(repoPath, release.branch, opts, identity);
+ 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))
- .then(([content, administration]) => buildCheckoutRetirementReview({ repoPath, release, prUrl,
+ .then(([content, administration]) => buildCheckoutRetirementReview({ repoPath, release, prUrl, kind,
contentFingerprint: content.fingerprint, administrationFingerprint: administration.fingerprint, policy }, { ...opts, readForge: async () => forge }))
.then(review => ({ ok: true, review }), error => archiveLimitRefusal(error) || ({ ok: false,
reason: /^retirement-[a-z-]+$/.test(error.message) ? error.message : 'retirement-local-evidence-unavailable' }));
}
/** Host-control-gated preview of one inventory row; may fetch missing proof objects. */
-export async function prepareInventoriedCheckoutRetirement({ appId, release, prUrl }, opts = {}) {
+export async function prepareInventoriedCheckoutRetirement({ appId, release, prUrl, kind }, opts = {}) {
const [{ getAppById }, { getBranchReconcileOutcome }] = await Promise.all([import('./apps.js'), import('./taskSchedule.js')]);
const app = await getAppById(appId);
if (!app?.repoPath) return { ok: false, reason: 'app-not-found' };
@@ -573,16 +585,16 @@ export async function prepareInventoriedCheckoutRetirement({ appId, release, prU
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));
+ const review = () => withClaimOwnershipLock(() => reviewCurrentCheckout({ repoPath: app.repoPath, release, prUrl, kind }, reviewOptions));
let prepared = await review();
if (prepared.reason === 'retirement-local-objects-missing') {
// A remote default may advance while local refs stay put. Acquire only its
// validated proof objects; then repeat every owner/policy/content check.
- const fetched = await fetchRetirementProofObjects(app.repoPath, release, prUrl, null, reviewOptions);
+ const fetched = await fetchRetirementProofObjects(app.repoPath, release, prUrl, null, { ...reviewOptions, ...reviewForgeOptions(release, kind, reviewOptions) });
if (!fetched.ok) return fetched;
prepared = await review();
}
- if (prepared.reason === 'retirement-policy-not-legacy-completed') {
+ if (!kind && release.branch && prepared.reason === 'retirement-policy-not-legacy-completed') {
// Recover only a previously registered physical generation after fresh
// merged exact-head proof. Never promote an orphan's execution to success.
const { readRetirementForgeEvidence } = await import('./heldCheckoutReview.js');
@@ -1154,7 +1166,7 @@ async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {
? await hasBranchMergeEvidence(repoPath, branch, defaultBranch).catch(() => false)
: await isAncestor(repoPath, tree.head, defaultBranch);
if (!merged && !review) return refuse('not-merged-on-recheck');
- const reviewed = review ? await reviewCurrentCheckout({ repoPath, release, prUrl: review.prUrl }, opts) : null;
+ const reviewed = review ? await reviewCurrentCheckout({ repoPath, release, prUrl: review.prUrl, kind: review.kind }, opts) : null;
if (reviewed && (!reviewed.ok || reviewed.review.digest !== review.digest)) return refuse(reviewed.reason || 'retirement-review-changed', reviewed.archiveLimit, reviewed.nextAction);
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 });
@@ -1199,7 +1211,7 @@ async function finishHeldCheckoutRetirement({ repoPath, release, review, reviewe
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 }),
- review ? reviewCurrentCheckout({ repoPath, release, prUrl: review.prUrl, unlocked: release.locked }, opts) : null,
+ review ? reviewCurrentCheckout({ repoPath, release, prUrl: review.prUrl, kind: review.kind, unlocked: release.locked }, opts) : null,
]);
if (fresh && !fresh.ok) { capacityRefusal = fresh; return fresh.reason; }
if (fresh && fresh.review.digest !== review.digest) return 'retirement-review-changed';
@@ -1231,7 +1243,7 @@ async function finishHeldCheckoutRetirement({ repoPath, release, review, reviewe
if (hold) return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: hold };
if (review) {
const { readRetirementForgeEvidence } = await import('./heldCheckoutReview.js');
- const forge = await (opts.readForge || readRetirementForgeEvidence)(repoPath, branch, review.prUrl, { forgeAccount: opts.forgeAccount }).catch(() => null);
+ 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 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)) {
diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.js
index 7b284bae97..bf1ecb2740 100644
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@ -2024,6 +2024,78 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
expect(await registered(c.release.path)).toBe(true);
});
+ it.each(['confirmed', 'unconfirmed', 'human-handoff', 'active-owner', 'changed-default', 'changed-source'])('reviews source-superseded local work through the existing archive fence: %s', async scenario => {
+ const c = await reviewedCheckout(`source-${scenario}`, { superseded: scenario !== 'unconfirmed' });
+ c.forge.prHead = c.forge.firstCommit = c.forge.mergeCommit;
+ c.forge.changeBase = (await execGit(['rev-parse', `${c.forge.firstCommit}^`], repo)).stdout.trim();
+ c.forge.sourceSupersessionHead = c.release.head;
+ const prepare = () => prepareInventoriedCheckoutRetirement({ appId: 'app-1', release: c.release,
+ prUrl: c.forge.prUrl, kind: 'source-supersession' }, c.opts);
+ if (scenario === 'human-handoff') injected.policies[0].metadata.prCompletionPolicy = 'leave-open';
+ if (scenario === 'active-owner') c.opts.readAgents = async () => [{ id: 'live', status: 'running', metadata: { workspacePath: repo, claimBranches: [c.release.branch] } }];
+ const prepared = await prepare();
+ if (['human-handoff', 'active-owner'].includes(scenario)) {
+ expect(prepared.ok).toBe(false);
+ expect(await archives()).toEqual([]);
+ expect(await registered(c.path)).toBe(true);
+ return;
+ }
+ expect(prepared).toMatchObject({ ok: true, review: { kind: 'source-supersession',
+ forge: { sourceSupersessionHead: c.release.head }, comparison: { disposition: 'review-supersession' } } });
+ if (scenario === 'changed-source') await writeFile(join(c.path, 'ignored.txt'), 'new local work\n');
+ if (scenario === 'changed-default') {
+ await writeFile(join(repo, 'later.txt'), 'new default\n');
+ await execGit(['add', 'later.txt'], repo);
+ await execGit(['commit', '-m', 'later default'], repo);
+ c.forge.defaultHead = (await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim();
+ }
+ const result = await retireInventoriedCheckout({ appId: 'app-1', release: c.release, review: {
+ prUrl: c.forge.prUrl, digest: prepared.review.digest, kind: 'source-supersession', acceptSuperseded: scenario !== 'unconfirmed',
+ } }, c.opts);
+ if (scenario !== 'confirmed') {
+ expect(result).toMatchObject({ ok: false, reason: scenario === 'unconfirmed' ? 'retirement-supersession-not-accepted' : 'retirement-review-changed' });
+ expect(await registered(c.path)).toBe(true);
+ expect(await archives()).toEqual([]);
+ return;
+ }
+ expect(result).toMatchObject({ ok: true, branchDeleted: true });
+ const manifest = JSON.parse(await readFile(join(result.archiveDir, 'manifest.json'), 'utf8'));
+ expect(manifest).toMatchObject({ head: c.release.head, review: { kind: 'source-supersession' } });
+ expect(await readFile(join(result.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('ignored work\n');
+ expect(await registered(c.path)).toBe(false);
+ expect((await getBranchReconcileOutcome('app-1')).retired).toEqual(expect.arrayContaining([expect.objectContaining({ head: c.release.head, archiveDir: result.archiveDir })]));
+ const restored = join(scratch, 'standalone-source.git');
+ await execGit(['init', '--bare', restored], scratch);
+ await execGit(['bundle', 'unbundle', join(result.archiveDir, 'commits.bundle')], restored);
+ await execGit(['fsck', '--full', '--strict', '--no-reflogs', c.release.head], restored);
+ expect((await execGit(['show', `${c.release.head}:feature.txt`], restored)).stdout).toBe('original feature\n');
+ });
+
+ it.each(['confirmed', 'human-handoff', 'published-owner'])('reviews an exact merged detached checkout without borrowing branch retirement: %s', async scenario => {
+ const c = await reviewedCheckout(`detached-review-${scenario}`);
+ const publishedBranch = c.release.branch;
+ await execGit(['switch', '--detach', c.release.head], c.path);
+ c.release.branch = null;
+ c.forge.publishedBranch = publishedBranch;
+ c.forge.exactAliasHead = c.release.head;
+ await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [{ ...c.release, reason: 'worktree-unmanaged-location' }] });
+ if (scenario === 'human-handoff') injected.policies[0].metadata.prCompletionPolicy = 'leave-open';
+ if (scenario === 'published-owner') c.opts.readAgents = async () => [{ id: 'live', status: 'running', metadata: { workspacePath: repo, claimBranches: [publishedBranch] } }];
+ const prepared = await c.prepare();
+ if (scenario !== 'confirmed') {
+ expect(prepared.ok).toBe(false);
+ expect(await registered(c.path)).toBe(true);
+ expect(await archives()).toEqual([]);
+ return;
+ }
+ expect(prepared.ok).toBe(true);
+ const result = await c.confirm(prepared.review);
+ expect(result).toMatchObject({ ok: true, branchDeleted: false });
+ expect(await registered(c.path)).toBe(false);
+ expect((await execGit(['rev-parse', publishedBranch], repo)).stdout.trim()).toBe(c.release.head);
+ expect(await readFile(join(result.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('ignored 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();
diff --git a/server/services/heldCheckoutReview.js b/server/services/heldCheckoutReview.js
index 3492d4e6dc..51f6e23667 100644
--- a/server/services/heldCheckoutReview.js
+++ b/server/services/heldCheckoutReview.js
@@ -59,7 +59,7 @@ export async function findMergedPullRequest(repoPath, branch, tip, { forgeAccoun
return { url: historical[0].url, mergedAt: null };
}
-export async function readRetirementForgeEvidence(repoPath, branch, prUrl, { forgeAccount = null, exactAliasHead = null } = {}) {
+export async function readRetirementForgeEvidence(repoPath, branch, prUrl, { forgeAccount = null, exactAliasHead = null, sourceSupersessionHead = null } = {}) {
const origin = await getOriginInfo(repoPath);
const parsed = parsePullRequestUrl(prUrl);
if (!origin || !parsed || parsed.host !== origin.host || `${parsed.owner}/${parsed.repo}` !== origin.fullName) {
@@ -72,13 +72,21 @@ export async function readRetirementForgeEvidence(repoPath, branch, prUrl, { for
const remote = await read(['pr', 'view', prUrl, '--json', 'url,state,headRefName,headRefOid,isCrossRepository,mergeCommit,baseRefName']);
const repository = await api(`repos/${origin.fullName}`);
const defaultBranch = repository.default_branch;
+ const supersession = typeof branch === 'string' && oid(sourceSupersessionHead);
// Explicit whole-checkout review may name a local repair alias, but only
// when its exact tip is the merged PR head. Similar names are never evidence.
const alias = remote.headRefName !== branch && oid(exactAliasHead) && exactAliasHead === remote.headRefOid;
- if (remote.url !== prUrl || remote.state !== 'MERGED' || (remote.headRefName !== branch && !alias)
+ if (remote.url !== prUrl || remote.state !== 'MERGED' || (remote.headRefName !== branch && !alias && !supersession)
|| remote.isCrossRepository !== false || remote.baseRefName !== defaultBranch || !oid(remote.headRefOid) || !oid(remote.mergeCommit?.oid)) {
throw new Error('retirement-pr-not-matching-merged');
}
+ if (supersession) {
+ // A replacement delivery never authorizes abandoning an open delivery of
+ // the original local branch. Unavailable/uncertain forge reads retain it.
+ const open = await api(`repos/${origin.fullName}/pulls?state=open&head=${encodeURIComponent(`${origin.fullName.split('/')[0]}:${branch}`)}&per_page=100`);
+ if (!Array.isArray(open)) throw new Error('retirement-forge-unavailable');
+ if (open.length) throw new Error('retirement-source-delivery-open');
+ }
// A current-main merge base loses the original scope after a normal merge.
// Use complete original PR metadata, and refuse API caps or ambiguous roots.
const pullPath = `repos/${origin.fullName}/pulls/${parsed.number}`;
@@ -109,21 +117,22 @@ export async function readRetirementForgeEvidence(repoPath, branch, prUrl, { for
const target = await api(`repos/${origin.fullName}/git/ref/heads/${encodeURIComponent(defaultBranch)}`);
if (!oid(target.object?.sha)) throw new Error('retirement-default-unreadable');
// ls-remote returns an empty successful result only for actual ref absence.
- const remoteHead = (await git(['ls-remote', '--heads', 'origin', `refs/heads/${branch}`], repoPath)
- .catch(() => { throw new Error('retirement-remote-ref-unreadable'); })).trim();
- if (remoteHead && remoteHead !== `${remote.headRefOid}\trefs/heads/${branch}`) throw new Error('retirement-remote-head-changed');
- const publishedRemoteHead = alias ? (await git(['ls-remote', '--heads', 'origin', `refs/heads/${remote.headRefName}`], repoPath)
+ const remoteHead = branch ? (await git(['ls-remote', '--heads', 'origin', `refs/heads/${branch}`], repoPath)
+ .catch(() => { throw new Error('retirement-remote-ref-unreadable'); })).trim() : '';
+ if (remoteHead && remoteHead !== `${supersession ? sourceSupersessionHead : remote.headRefOid}\trefs/heads/${branch}`) throw new Error('retirement-remote-head-changed');
+ const publishedRemoteHead = alias || supersession ? (await git(['ls-remote', '--heads', 'origin', `refs/heads/${remote.headRefName}`], repoPath)
.catch(() => { throw new Error('retirement-remote-ref-unreadable'); })).trim() : null;
if (publishedRemoteHead && publishedRemoteHead !== `${remote.headRefOid}\trefs/heads/${remote.headRefName}`) throw new Error('retirement-remote-head-changed');
return { repository: `${origin.host}/${origin.fullName}`, prUrl, prHead: remote.headRefOid,
mergeCommit: remote.mergeCommit.oid, changedPaths, changeBase, firstCommit, defaultBranch, defaultHead: target.object.sha, remoteHead: remoteHead || null,
- ...(alias ? { exactAliasHead, publishedBranch: remote.headRefName, publishedRemoteHead: publishedRemoteHead || null } : {}) };
+ ...(alias || supersession ? { ...(alias && { exactAliasHead }), ...(supersession && { sourceSupersessionHead }),
+ publishedBranch: remote.headRefName, publishedRemoteHead: publishedRemoteHead || null } : {}) };
}
/** Returned differences are review material, not executable instructions or an
* automated supersession verdict. Every byte and identity participates in digest.
*/
-export async function buildCheckoutRetirementReview({ repoPath, release, prUrl, contentFingerprint, administrationFingerprint, policy }, {
+export async function buildCheckoutRetirementReview({ repoPath, release, prUrl, kind, contentFingerprint, administrationFingerprint, policy }, {
readForge = readRetirementForgeEvidence, forgeAccount = null,
} = {}) {
const forge = await readForge(repoPath, release.branch, prUrl, { forgeAccount });
@@ -145,8 +154,8 @@ export async function buildCheckoutRetirementReview({ repoPath, release, prUrl,
const parent = parents.value.trim().split(/\s+/);
if (parent.length !== 2 || parent[1] !== forge.changeBase) throw new Error('retirement-original-scope-unavailable');
if (inPr.status === 'rejected') throw new Error('retirement-original-scope-unavailable');
- const base = (await git(['merge-base', release.head, forge.changeBase], repoPath)).trim();
- if (base === release.head) throw new Error('retirement-original-scope-unavailable');
+ const base = (await git(['merge-base', release.head, kind ? forge.defaultHead : forge.changeBase], repoPath)).trim();
+ if (base === release.head && !kind) throw new Error('retirement-original-scope-unavailable');
const [localPathsOut, localPatch] = await Promise.all([
git(['diff', '--name-only', '-z', base, release.head], repoPath),
git(['diff', '--binary', '--no-ext-diff', '--no-textconv', base, release.head], repoPath),
@@ -158,8 +167,9 @@ export async function buildCheckoutRetirementReview({ repoPath, release, prUrl,
// code still implements the original work (it may have been strengthened or
// reverted). Exact affected-file equality is the mechanical case; differences
// require the operator's explicit supersession judgment on the displayed diff.
- const mechanicallyEquivalent = difference === '';
+ const mechanicallyEquivalent = difference === '' && kind !== 'source-supersession';
const evidence = { repoPath, release, forge, contentFingerprint, administrationFingerprint, policy,
+ ...(kind && { kind }),
comparison: { base, paths, localPatch, difference, disposition: mechanicallyEquivalent ? 'integrated' : 'review-supersession' } };
return { digest: createHash('sha256').update(JSON.stringify(evidence)).digest('hex'), ...evidence };
}
diff --git a/server/services/heldCheckoutReview.test.js b/server/services/heldCheckoutReview.test.js
index 87ca1c6130..9dfb523e25 100644
--- a/server/services/heldCheckoutReview.test.js
+++ b/server/services/heldCheckoutReview.test.js
@@ -13,8 +13,10 @@ describe('retirement forge verification', () => {
let detail;
let files;
let commits;
+ let open;
beforeEach(() => {
vi.clearAllMocks();
+ open = [];
pr = { url: prUrl, state: 'MERGED', headRefName: 'claim/42', headRefOid: 'a'.repeat(40),
mergeCommit: { oid: 'b'.repeat(40) }, isCrossRepository: false, baseRefName: 'main' };
detail = { merged: true, head: { sha: 'a'.repeat(40) }, base: { ref: 'main' }, changed_files: 1, commits: 1 };
@@ -24,7 +26,7 @@ describe('retirement forge verification', () => {
mock.git.mockResolvedValue({ stdout: '', exitCode: 0 });
mock.gh.mockImplementation(async args => JSON.stringify(args[0] === 'pr' ? pr
: args.at(-1).includes('/files?') ? files : args.at(-1).includes('/commits?') ? commits
- : args.at(-1).includes('/pulls/') ? detail
+ : args.at(-1).includes('/pulls?') ? open : args.at(-1).includes('/pulls/') ? detail
: args.at(-1).includes('/git/ref/') ? { object: { sha: 'c'.repeat(40) } } : { default_branch: 'main' }));
});
@@ -63,6 +65,26 @@ describe('retirement forge verification', () => {
expect(mock.gh).toHaveBeenCalledWith(expect.arrayContaining(['--paginate', '--slurp']), undefined, expect.any(Object));
});
+ it('binds detached evidence to the exact published PR head without querying a null branch', async () => {
+ expect(await readRetirementForgeEvidence('/synthetic/repo', null, prUrl, { exactAliasHead: pr.headRefOid }))
+ .toMatchObject({ exactAliasHead: pr.headRefOid, publishedBranch: 'claim/42' });
+ expect(mock.git.mock.calls.every(([args]) => args.at(-1) === 'refs/heads/claim/42')).toBe(true);
+ await expect(readRetirementForgeEvidence('/synthetic/repo', null, prUrl, { exactAliasHead: 'e'.repeat(40) }))
+ .rejects.toThrow('retirement-pr-not-matching-merged');
+ });
+
+ it.each(['closed-original', 'open-original', 'unreadable', 'advanced-original'])('reviews a replacement PR without abandoning a %s source delivery', async state => {
+ const source = 'e'.repeat(40);
+ if (state === 'open-original') open = [{ head: { sha: source } }];
+ if (state === 'unreadable') open = null;
+ if (state === 'advanced-original') mock.git.mockResolvedValueOnce({ stdout: `${'f'.repeat(40)}\trefs/heads/original\n` });
+ const review = readRetirementForgeEvidence('/synthetic/repo', 'original', prUrl, { sourceSupersessionHead: source });
+ if (state === 'closed-original') {
+ expect(await review).toMatchObject({ sourceSupersessionHead: source, prHead: pr.headRefOid, publishedBranch: 'claim/42' });
+ } else await expect(review).rejects.toThrow(state === 'open-original' ? 'retirement-source-delivery-open'
+ : state === 'unreadable' ? 'retirement-forge-unavailable' : 'retirement-remote-head-changed');
+ });
+
it.each(['file-count', 'commit-count', 'duplicate', 'missing-previous', 'ambiguous-base', 'wrong-tip', 'cap', 'bad-path', 'unpaginated'])('refuses incomplete or ambiguous original scope: %s', async change => {
if (change === 'file-count') detail.changed_files = 2;
if (change === 'commit-count') detail.commits = 2;