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: retire merged manual-claim checkouts on forge-merged exact-head proof (#12849)

[._.]/ Adam Eivy4967fc2a89b0
diff --git a/server/services/README.md b/server/services/README.md
index fdeb62b35c..9c02fed31f 100644
--- a/server/services/README.md
+++ b/server/services/README.md
@@ -12,7 +12,7 @@ image-generation paths below are useful entry points when tracing render jobs.
| `repoCleanupObservation.js` | Read-only exact-ref presence/absence accounting; malformed, changing or unsupported metadata remains unknown. |
| `branchReconcileCompletion.js` | Runs ownership-checked merged and superseded cleanup on coordinator completion, independent of perpetual scheduling. |
| `initializedCheckoutRecovery.js` | Explicit macOS private-module checkout archive, standalone recovery proof, durable reservation, reversible whole-directory quarantine and transaction-bound branch finalization/receipt replay; automatic module cleanup remains blocked. |
-| `heldCheckoutReview.js` | Computes fresh forge identity, merged PR/default refs and exact code comparisons for a digest-bound operator retirement; no saved consent or policy rewrites. |
+| `heldCheckoutReview.js` | Selects the merged PR for an exact local head and computes fresh forge identity, merged PR/default refs and exact code comparisons for a digest-bound operator retirement; no saved consent or policy rewrites. |
| `heldCheckoutRecovery.js` | Prepares scoped retirement reviews and preserves checkout content, empty gitlinks and private Git administration before ownership-checked removal and expected-head local ref deletion. Pending-merge receipts use `retirePendingMergeCheckout`, which independently verifies the merged head and refuses locks, supersession and initialized submodules. |
| `cosClaimOwnershipState.js` | Shared ownership lock, per-checkout retirement fence with `retireWithUnlockedArchive` (archives run between two lock sections), and fail-closed live-agent reader used by claim binding and worktree cleanup. Re-exported by `cosClaimOwnership.js` for existing callers; does not import reconciliation. |
| `systemActivityNotify.js` | Coalesced activity invalidation signal and LLM lifecycle adapters; producers do not import media execution. |
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 215757801a..a9ea411458 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -1117,7 +1117,9 @@ async function retainedClaimMarkers(repoPath, branch, { origin } = {}) {
* 2. the branch's worktree (if any) has no real uncommitted changes.
* 3. that worktree (if any) lives in a managed root and is unlocked.
* 4. fresh ownership and completion policy permit retirement under the claim
- * binding lock; manual claims have an exact successful checkout receipt.
+ * binding lock; a claim checkout has an exact successful run receipt, or
+ * the forge reports its exact head merged and it has idled past
+ * SHIPPED_CLAIM_IDLE_MS (see manualClaimShippedHold).
* 5. recovery archives verify before removal and exact-head ref deletion.
* A failed gate skips the branch with a reason. Age, an absent upstream, and
* a cached merged flag never substitute for successful completion evidence.
@@ -1146,6 +1148,7 @@ export async function cleanupMerged(repoPath, defaultBranch, merged, { activeAge
claimOwners,
mergedRetirement: true,
mergeTarget: defaultBranch,
+ forgeAccount,
label: `🔀 branch-reconcile: remove worktree for ${b.branch}`,
});
if (!retired.ok) {
@@ -1347,7 +1350,7 @@ async function retireBranch(repoPath, b, opts) {
}
/** Every gate before the archive. Returns `{ result }` to stop, else the context removal needs. */
-async function admitBranchRetirement(repoPath, b, { activeAgentIds = new Set(), staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, label, requireCleanWorktree = true, unmanagedIdleMs, prepare, claimOwners, mergedRetirement = false, mergeTarget }) {
+async function admitBranchRetirement(repoPath, b, { activeAgentIds = new Set(), staleClaimIdleMs = STALE_CLAIM_IDLE_MS, allowLiveClaim = false, label, requireCleanWorktree = true, unmanagedIdleMs, prepare, claimOwners, mergedRetirement = false, mergeTarget, forgeAccount = null }) {
const stop = result => ({ result });
if (PROTECTED_BRANCHES.includes(b.branch)) return stop({ ok: false, reason: 'protected-branch' });
const defaultBranch = await getDefaultBranch(repoPath, { strict: true }).catch(() => null);
@@ -1358,6 +1361,7 @@ async function admitBranchRetirement(repoPath, b, { activeAgentIds = new Set(),
const policyHold = await readPolicyHold();
if (policyHold) return stop({ ok: false, reason: policyHold });
let archiveTree = null;
+ let claimCompletion = null;
const expectedHead = (await execGit(['rev-parse', '--verify', `refs/heads/${b.branch}`], repoPath).catch(() => null))?.stdout?.trim();
if (!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(expectedHead || '')) return stop({ ok: false, reason: mergedRetirement ? 'not-merged-on-recheck' : 'branch-head-unavailable' });
if (mergedRetirement) {
@@ -1403,25 +1407,50 @@ async function admitBranchRetirement(repoPath, b, { activeAgentIds = new Set(),
const { readBranchCompletionPolicies } = await import('./branchCompletionPolicy.js');
const records = await readBranchCompletionPolicies({ repairIndex: false }).catch(() => null);
// Registry absence cannot prove a manual CLI or external task finished.
- // Require a recorded completed owner before waiving its claim hold.
+ // Waive the claim hold only on a recorded completed owner or, for a
+ // manual session that records none, the forge's merged exact head.
const { hasCompletedCheckoutEvidence } = await import('./completedCheckoutEvidence.js');
- const completed = records && await hasCompletedCheckoutEvidence(records, {
+ if (!records) return stop({ ok: false, reason: 'claim-ownership-unreadable' });
+ if (await hasCompletedCheckoutEvidence(records, {
repoPath, branch: b.branch, path: b.worktreePath, head: expectedHead,
- });
- if (!completed) return stop({ ok: false, reason: records ? 'claim-completion-unverified' : 'claim-ownership-unreadable' });
+ })) claimCompletion = 'receipt';
+ else {
+ const hold = await manualClaimShippedHold(repoPath, b, expectedHead, forgeAccount);
+ if (hold) return stop(hold);
+ claimCompletion = 'forge-merged';
+ }
}
const tree = (await listWorktrees(repoPath)).find(wt => wt.path === b.worktreePath);
if (!tree || tree.head !== expectedHead) return stop({ ok: false, reason: 'worktree-holder-changed' });
archiveTree = tree;
}
- return { b, expectedHead, readPolicyHold, archiveTree, mergeTarget, label, requireCleanWorktree, prepare, claimOwners, mergedRetirement };
+ return { b, expectedHead, readPolicyHold, archiveTree, mergeTarget, label, requireCleanWorktree, prepare, claimOwners, mergedRetirement, claimCompletion };
+}
+
+/**
+ * Why a merged manual `claim-*` checkout without a run receipt is still held, or
+ * null once the forge proves it shipped (#12849). A manual /claim session never
+ * records the receipt a CoS claim run does, so without this its checkouts were
+ * held forever. The forge must report a merged PR whose head is exactly
+ * `head`; the clean-tree, lock, owner and merge gates have already run. What
+ * neither proof shows is a session still tearing down, so SHIPPED_CLAIM_IDLE_MS
+ * must have passed since the checkout was created AND since the merge.
+ */
+async function manualClaimShippedHold(repoPath, b, head, forgeAccount) {
+ // No retryAt: the idle window is not the only gate, so no clock lifts this.
+ const unverified = { ok: false, reason: 'claim-completion-unverified' };
+ if (!Number.isFinite(b.worktreeAgeMs) || b.worktreeAgeMs < SHIPPED_CLAIM_IDLE_MS) return unverified;
+ const { readMergedClaimEvidence } = await import('./completedCheckoutEvidence.js');
+ const merged = await readMergedClaimEvidence({ repoPath, branch: b.branch, head, forgeAccount }).catch(() => null);
+ if (!merged || Date.now() - Date.parse(merged.mergedAt) < SHIPPED_CLAIM_IDLE_MS) return unverified;
+ return null;
}
/**
* Removal and branch deletion. `preservation` is the archive and `prepared` the
* `prepare` backup, each taken after admission with the ownership lock released.
*/
-async function finishBranchRetirement(repoPath, { b, expectedHead, readPolicyHold, mergeTarget, label, requireCleanWorktree, claimOwners, mergedRetirement }, { prepared = null, preservation = null } = {}) {
+async function finishBranchRetirement(repoPath, { b, expectedHead, readPolicyHold, mergeTarget, label, requireCleanWorktree, claimOwners, mergedRetirement, claimCompletion }, { prepared = null, preservation = null } = {}) {
if (b.worktreePath) {
const verifyRemoval = async (holder) => {
if (!holder || holder.branch !== `refs/heads/${b.branch}` || holder.head !== expectedHead) return 'worktree-holder-changed';
@@ -1432,7 +1461,9 @@ async function finishBranchRetirement(repoPath, { b, expectedHead, readPolicyHol
}
const policyHold = await readPolicyHold();
if (policyHold) return policyHold;
- if (mergedRetirement && isHumanClaimWorktree(worktreeAgentId(b.worktreePath))) {
+ // A forge-merged exact head cannot un-merge, and the holder check above
+ // pins that head; only a run receipt can be superseded by a later owner.
+ if (mergedRetirement && isHumanClaimWorktree(worktreeAgentId(b.worktreePath)) && claimCompletion !== 'forge-merged') {
const { readBranchCompletionPolicies } = await import('./branchCompletionPolicy.js');
const { hasCompletedCheckoutEvidence } = await import('./completedCheckoutEvidence.js');
const records = await readBranchCompletionPolicies({ repairIndex: false }).catch(() => null);
diff --git a/server/services/branchReconcile.ownership.test.js b/server/services/branchReconcile.ownership.test.js
index 157a1aa69e..ede3bca439 100644
--- a/server/services/branchReconcile.ownership.test.js
+++ b/server/services/branchReconcile.ownership.test.js
@@ -25,7 +25,7 @@ vi.mock('../lib/paths.js', async importOriginal => makePathsProxy(await importOr
}));
afterAll(cleanupTempDataRoots);
-const injected = vi.hoisted(() => ({ statusPath: null, statusThrows: false, beforeRemove: null, owners: [], policies: [] }));
+const injected = vi.hoisted(() => ({ statusPath: null, statusThrows: false, beforeRemove: null, owners: [], policies: [], forge: {} }));
vi.mock('../lib/execGit.js', async (importOriginal) => {
const actual = await importOriginal();
return { ...actual, execGit: async (args, cwd, options) => {
@@ -56,6 +56,18 @@ vi.mock('./branchCompletionPolicy.js', async (importOriginal) => {
}) };
});
+// The hermetic repo has no forge. A branch's merged PR is injected at the
+// forge-read boundary: { head, mergedAt }, or 'unavailable' for a failed read.
+vi.mock('./heldCheckoutReview.js', async (importOriginal) => ({
+ ...await importOriginal(),
+ findMergedPullRequest: async (repoPath, branch) => {
+ const pr = injected.forge[branch];
+ if (!pr || pr === 'unavailable') throw new Error('retirement-forge-unavailable');
+ return { url: `https://github.com/example/repo/pull/${branch.split('-').at(-1)}`, mergedAt: pr.mergedAt };
+ },
+ readRetirementForgeEvidence: async (repoPath, branch, prUrl) => ({ prUrl, prHead: injected.forge[branch].head }),
+}));
+
// Keep the run hermetic: the verdict ledger otherwise reads this install's
// real CoS data directory.
vi.mock('./supersededLedger.js', async (importOriginal) => ({
@@ -75,7 +87,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (re
let external;
beforeEach(async () => {
- Object.assign(injected, { statusPath: null, statusThrows: false, beforeRemove: null, owners: [], policies: [] });
+ Object.assign(injected, { statusPath: null, statusThrows: false, beforeRemove: null, owners: [], policies: [], forge: {} });
scratch = realpathSync(await mkdtemp(join(tmpdir(), 'portos-reconcile-own-')));
const safeRepo = join(scratch, 'repo');
await mkdir(safeRepo);
@@ -223,6 +235,63 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch-reconcile worktree ownership (re
expect(await branches()).toEqual(expect.arrayContaining(['claim/issue-12', 'claim/issue-13', 'claim/issue-14']));
});
+ it('retires a forge-merged manual claim without a run receipt and holds every unproven sibling (#12849)', async () => {
+ const root = join(repo, '.claude', 'worktrees');
+ await mkdir(root, { recursive: true });
+ const HOUR = 60 * 60 * 1000;
+ const longAgo = new Date(Date.now() - 3 * HOUR).toISOString();
+ // A manual /claim: commit in the checkout, merge it into main, leave the tree.
+ const claim = async (n, { merge = true, ageMs = 2 * HOUR } = {}) => {
+ const branch = `claim/issue-${n}`;
+ const path = await addTree(join(root, `claim-issue-${n}`), branch);
+ await writeFile(join(path, `work-${n}.txt`), `issue ${n}\n`);
+ await execGit(['add', `work-${n}.txt`], path);
+ await execGit(['commit', '-m', `feat: issue ${n}`], path);
+ const head = (await execGit(['rev-parse', 'HEAD'], path)).stdout.trim();
+ if (merge) await execGit(['merge', '--no-ff', '-m', `Merge ${branch}`, branch], repo);
+ if (ageMs) await utimes(path, new Date(Date.now() - ageMs), new Date(Date.now() - ageMs));
+ injected.forge[branch] = { head, mergedAt: longAgo };
+ return { branch, path, head };
+ };
+ const shipped = await claim(21);
+ const dirty = await claim(22);
+ await writeFile(join(dirty.path, 'unsaved.txt'), 'preserve\n');
+ await utimes(dirty.path, new Date(Date.now() - 2 * HOUR), new Date(Date.now() - 2 * HOUR));
+ const locked = await claim(23);
+ await execGit(['worktree', 'lock', locked.path], repo);
+ const owned = await claim(24);
+ injected.owners = [{ id: 'agent-live-claim', status: 'running', sourceWorkspace: repo, workspacePath: repo,
+ metadata: { sourceWorkspace: repo, claimBranches: [owned.branch] } }];
+ const unmerged = await claim(25, { merge: false });
+ const forgeDown = await claim(26);
+ injected.forge[forgeDown.branch] = 'unavailable';
+ const otherHead = await claim(27);
+ injected.forge[otherHead.branch] = { head: 'f'.repeat(40), mergedAt: longAgo };
+ const justMerged = await claim(28);
+ injected.forge[justMerged.branch].mergedAt = new Date().toISOString();
+ const young = await claim(29, { ageMs: 0 });
+
+ const result = await reconcile(repo, {
+ activeAgentIds: new Set(), claimOwners: { agents: injected.owners, readAgents: async () => injected.owners },
+ });
+ const context = JSON.stringify({ cleaned: result.cleaned, skipped: result.skipped });
+ expect(result.cleaned, context).toEqual([shipped.branch]);
+ expect(existsSync(shipped.path)).toBe(false);
+ expect(await branches()).not.toContain(shipped.branch);
+ expect((await execGit(['rev-parse', `refs/portos/completed/${shipped.head}`], repo)).stdout.trim()).toBe(shipped.head);
+
+ const reasonFor = branch => result.skipped.find(row => row.branch === branch)?.reason;
+ expect(reasonFor(locked.branch), context).toBe('worktree-locked');
+ expect(reasonFor(owned.branch), context).toBe('claim-owner-active');
+ for (const held of [forgeDown, otherHead, justMerged, young]) expect(reasonFor(held.branch), context).toBe('claim-completion-unverified');
+ expect(result.inFlight).toContainEqual(expect.objectContaining({ branch: dirty.branch, state: 'ABANDONED_WIP' }));
+ expect(result.wip).toContainEqual(expect.objectContaining({ branch: unmerged.branch }));
+ const kept = [dirty, locked, owned, unmerged, forgeDown, otherHead, justMerged, young];
+ for (const { path } of kept) expect(existsSync(path)).toBe(true);
+ expect(existsSync(join(dirty.path, 'unsaved.txt'))).toBe(true);
+ expect(await branches()).toEqual(expect.arrayContaining(kept.map(held => held.branch)));
+ });
+
it('holds a clean agent tree at the default HEAD while its dispatch is still registering (#11775)', async () => {
const root = join(repo, '.claude', 'worktrees');
await mkdir(root, { recursive: true });
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index eb067f4cd8..282b390b3f 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -1,4 +1,7 @@
-vi.mock('./completedCheckoutEvidence.js', () => ({ hasCompletedCheckoutEvidence: vi.fn(async records => records.some(agent => agent.result?.success === true)) }));
+vi.mock('./completedCheckoutEvidence.js', () => ({
+ hasCompletedCheckoutEvidence: vi.fn(async records => records.some(agent => agent.result?.success === true)),
+ readMergedClaimEvidence: vi.fn(async () => null),
+}));
vi.mock('./branchCompletionPolicy.js', async () => ({
...await vi.importActual('./branchCompletionPolicy.js'),
readBranchCompletionPolicies: vi.fn(async () => (await wt.listWorktrees()).map(tree => ({ id: 'completed-owner', status: 'completed', result: { success: true }, metadata: { sourceWorkspace: '/repo', worktreeBranch: tree.branch?.replace('refs/heads/', '') } }))),
diff --git a/server/services/branchReconcileRetirement.js b/server/services/branchReconcileRetirement.js
index ec5f8ff454..02a3e8d652 100644
--- a/server/services/branchReconcileRetirement.js
+++ b/server/services/branchReconcileRetirement.js
@@ -2,41 +2,10 @@
import { processAuditFingerprint } from '../lib/persistentMindProcessAudit.js';
import { agentApiCurl } from '../lib/agentApiToken.js';
import { localApiBaseUrl } from '../lib/networkExposure.js';
-import { parsePullRequestUrl } from '../lib/gitForge.js';
async function mergedPrUrl(app, branch, tip) {
- const [{ execGh }, { resolveForgeExecOptions }, { getOriginInfo }, { githubRepoSpec }] = await Promise.all([
- import('./github.js'), import('./forgeExecOptions.js'), import('../lib/gitRemote.js'), import('../lib/workTracker.js'),
- ]);
- const origin = await getOriginInfo(app.repoPath);
- const spec = githubRepoSpec(origin);
- if (!spec) throw new Error('retirement-forge-unsupported');
- const options = await resolveForgeExecOptions(app.repoPath, { forgeAccount: app.forgeAccount ?? null });
- if (!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(tip || '')) throw new Error('retirement-pr-ambiguous');
- // Query the exact commit, not an unbounded reused-branch history. A capped
- // association result cannot establish uniqueness and stays held.
- const rows = JSON.parse(await execGh(['api', '--hostname', origin.host,
- `repos/${origin.fullName}/commits/${tip}/pulls?per_page=100`], undefined, options));
- if (!Array.isArray(rows) || rows.length >= 100
- || new Set(rows.map(row => row?.html_url)).size !== rows.length
- || rows.some(row => {
- const parsed = parsePullRequestUrl(row?.html_url);
- return !parsed || parsed.host !== origin.host || `${parsed.owner}/${parsed.repo}` !== origin.fullName
- || typeof row.head?.ref !== 'string' || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(row.head?.sha || '');
- })) throw new Error('retirement-pr-ambiguous');
- const matches = rows.filter(row => row.head.sha === tip && row.head.ref === branch
- && row.head.repo?.full_name === origin.fullName && row.base?.repo?.full_name === origin.fullName
- && row.state === 'closed' && typeof row.merged_at === 'string' && Number.isFinite(Date.parse(row.merged_at)));
- if (matches.length > 1) throw new Error('retirement-pr-ambiguous');
- // Selection is not proof: the preview re-reads this exact PR and verifies its
- // repository, merge, current refs and complete original scope before review.
- if (matches.length === 1) return matches[0].html_url;
- // Preserve historical review of an older local tip only when branch history
- // itself has exactly one candidate. Never choose among mismatching heads.
- const historical = JSON.parse(await execGh(['pr', 'list', '--repo', spec, '--head', branch, '--state', 'merged',
- '--limit', '2', '--json', 'url'], undefined, options));
- if (!Array.isArray(historical) || historical.length !== 1 || typeof historical[0]?.url !== 'string') throw new Error('retirement-pr-ambiguous');
- return historical[0].url;
+ const { findMergedPullRequest } = await import('./heldCheckoutReview.js');
+ return (await findMergedPullRequest(app.repoPath, branch, tip, { forgeAccount: app.forgeAccount ?? null })).url;
}
/** Inventory is persisted first: the same preview used by the live endpoint
diff --git a/server/services/completedCheckoutEvidence.js b/server/services/completedCheckoutEvidence.js
index cc5ecfb35c..3eb603ce9e 100644
--- a/server/services/completedCheckoutEvidence.js
+++ b/server/services/completedCheckoutEvidence.js
@@ -100,3 +100,15 @@ export async function hasCompletedCheckoutEvidence(records, target) {
&& Date.parse(receipt.capturedAt) <= Date.parse(agent.completedAt)
&& same(current, { repoPath: receipt.repoPath, branch: receipt.branch, path: receipt.path, head: receipt.head, incarnation: receipt.incarnation })));
}
+
+/** A manual /claim session records no receipt (#12849). Its proof is the forge:
+ * a PR merged into the default branch whose head is exactly this checkout's head.
+ * Returns that PR and its merge time, or null — any read failure grants nothing.
+ */
+export async function readMergedClaimEvidence({ repoPath, branch, head, forgeAccount = null }) {
+ const { findMergedPullRequest, readRetirementForgeEvidence } = await import('./heldCheckoutReview.js');
+ const pr = await findMergedPullRequest(repoPath, branch, head, { forgeAccount }).catch(() => null);
+ if (!pr || !Number.isFinite(Date.parse(pr.mergedAt))) return null;
+ const forge = await readRetirementForgeEvidence(repoPath, branch, pr.url, { forgeAccount }).catch(() => null);
+ return forge?.prHead === head ? { prUrl: pr.url, mergedAt: pr.mergedAt } : null;
+}
diff --git a/server/services/heldCheckoutReview.js b/server/services/heldCheckoutReview.js
index f883e9a2c3..3e74d4857f 100644
--- a/server/services/heldCheckoutReview.js
+++ b/server/services/heldCheckoutReview.js
@@ -10,6 +10,43 @@ const oid = value => typeof value === 'string' && /^[a-f0-9]{40}(?:[a-f0-9]{24})
const safePath = value => typeof value === 'string' && value.length > 0 && !value.includes('\0') && !value.startsWith('/') && !value.split('/').some(part => part === '..' || part === '.');
const git = (args, cwd) => execGit(args, cwd, { maxBuffer: 4 * 1024 * 1024 }).then(r => r.stdout);
+/** Selects the merged PR for an exact local tip. Selection is not proof: callers
+ * re-read the PR with `readRetirementForgeEvidence` before acting on it.
+ * `mergedAt` is the forge's merge time, or null for a historical-branch match.
+ */
+export async function findMergedPullRequest(repoPath, branch, tip, { forgeAccount = null } = {}) {
+ const [{ execGh }, { resolveForgeExecOptions }, { githubRepoSpec }] = await Promise.all([
+ import('./github.js'), import('./forgeExecOptions.js'), import('../lib/workTracker.js'),
+ ]);
+ const origin = await getOriginInfo(repoPath);
+ const spec = githubRepoSpec(origin);
+ if (!spec) throw new Error('retirement-forge-unsupported');
+ const options = await resolveForgeExecOptions(repoPath, { forgeAccount });
+ if (!oid(tip)) throw new Error('retirement-pr-ambiguous');
+ // Query the exact commit, not an unbounded reused-branch history. A capped
+ // association result cannot establish uniqueness and stays held.
+ const rows = JSON.parse(await execGh(['api', '--hostname', origin.host,
+ `repos/${origin.fullName}/commits/${tip}/pulls?per_page=100`], undefined, options));
+ if (!Array.isArray(rows) || rows.length >= 100
+ || new Set(rows.map(row => row?.html_url)).size !== rows.length
+ || rows.some(row => {
+ const parsed = parsePullRequestUrl(row?.html_url);
+ return !parsed || parsed.host !== origin.host || `${parsed.owner}/${parsed.repo}` !== origin.fullName
+ || typeof row.head?.ref !== 'string' || !oid(row.head?.sha);
+ })) throw new Error('retirement-pr-ambiguous');
+ const matches = rows.filter(row => row.head.sha === tip && row.head.ref === branch
+ && row.head.repo?.full_name === origin.fullName && row.base?.repo?.full_name === origin.fullName
+ && row.state === 'closed' && typeof row.merged_at === 'string' && Number.isFinite(Date.parse(row.merged_at)));
+ if (matches.length > 1) throw new Error('retirement-pr-ambiguous');
+ if (matches.length === 1) return { url: matches[0].html_url, mergedAt: matches[0].merged_at };
+ // Preserve historical review of an older local tip only when branch history
+ // itself has exactly one candidate. Never choose among mismatching heads.
+ const historical = JSON.parse(await execGh(['pr', 'list', '--repo', spec, '--head', branch, '--state', 'merged',
+ '--limit', '2', '--json', 'url'], undefined, options));
+ if (!Array.isArray(historical) || historical.length !== 1 || typeof historical[0]?.url !== 'string') throw new Error('retirement-pr-ambiguous');
+ return { url: historical[0].url, mergedAt: null };
+}
+
export async function readRetirementForgeEvidence(repoPath, branch, prUrl, { forgeAccount = null, exactAliasHead = null } = {}) {
const origin = await getOriginInfo(repoPath);
const parsed = parsePullRequestUrl(prUrl);