Source recovery¶
Collection failure recovery¶
Explain a failed pr-head-fetch as "The PR refresh failed before checkout verification, so I have not yet established which code is safe to fix." The commit may already exist locally; a failed cache/ref update is not proof that it could not be downloaded. When evidence proves the PR advanced, explain that the previous review covers an older version and include the actual old/current identifiers after that explanation. A failed fetch does not prove an authentication problem, unavailable contributor fork, or local merge failure; when the safe diagnostic lacks a cause, state that the reason is unknown.
Use the retained safe failure_reason to choose diagnosis: a rejected ref update needs local ref/state inspection; a missing ref or unavailable repository needs identity/access verification; transport failure may permit a bounded retry only after materially changed evidence; explicit permission failure needs private user-owned access repair. Unknown remains unknown. Do not print raw Git output, force-update a ref, or repeat an unchanged retry merely to obtain a more helpful error. Start each permitted collector retry in a fresh run/artifact directory that retains the failed attempt and links its recovery evidence; replace its own target identity as well as source evidence. After recollection succeeds, prepare, diff, target, and all downstream checks must consume the verified new attempt directory, never the failed <run-directory>/pr/ artifacts or a silently cleared/reused path; then resume the first unmet checkpoint.
The agent owns permitted diagnosis: inspect retained classified failure and fresh local identity/state before asking the user to repair access or rerun the skill. Identify the failed operation separately from any existing checkout/conflict obstacle. Recommend a concrete recovery supported by that evidence; ask only for the specific missing access, prerequisite, protected-state decision, or repair scope. Do not repeat an unchanged retry after a deterministic failure or reset recurrence counts.
If the native error identifies a different ref, or multiple local branch names could explain an unnamed failure, report the ambiguity and preserve the branches. When the collector records shallow-history, report that the local history cannot establish ahead/behind counts. Local branch cleanup requires verified local-only commits on the branch implicated by this checkout.
A successful native fork checkout with the verified PR head and base-repository refs/pull/<PR number>/head tracking is not a checkout failure. Prepare its source receipt and continue under the main skill’s source-tracking checks; do not ask for fork setup or rerun checkout solely to obtain contributor tracking. Publication configuration is not required for local remediation.
Reuse the attached PR worktree¶
When checkout fails after fetching the verified PR head, check for an existing branch owner before suggesting branch cleanup. This applies to same-repository and fork PRs, including an unclassified native checkout failure. Respect an explicit original-checkout-only request and recorded permission, access, or transport failures. From the original invoking checkout run PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/remediation_branch.py locate-owner --pr-dir <failed-run>/pr. This read checks the Git registration, attached branch, PR tracking, clean index and working tree, operation state and ancestry. A matching tip or a clean branch behind the fetched head can continue. Local-only commits still require the comparison below.
When the returned checkout differs from the failed collector's working directory, continue in the same invocation. Retain the failed evidence, release its claims after quiescence, and acquire the writer claim on the returned checkout before the canonical PR target claim. Repeat the owner check under those claims. Bind the fresh attempt to the same canonical PR and announce its delivery path. For default delivery, use the selected owner as the new in-place checkout through delivery and resume. For explicit --worktree, preserve the original invoking path and use the separate owner as the worktree-only destination. Pass --receipt <fresh-run>/remediation-worktree.json on the checked selection for that delivery. This borrowed locator grants no cleanup ownership.
If needs_update is true, apply the guarded git pull --ff-only procedure under Source drift recovery in the owner, preserving ignored files that overlap incoming changes. At an equal tip proceed directly. Run the normal remediation collector in the verified owner with the canonical PR URL and a fresh output directory. A successful native checkout, exact fresh head, source receipt and normal contribution checks are required before editing. Continue from the successful run. If the changed directory does not resolve checkout, diagnose the new failure without repeating the same attempt.
Other checkout failures¶
After remediation's initial gh pr checkout failure, apply these route-specific gates before any source edits:
- Same-repository original branch: continue only when retained PR identity proves
head_repository == base_repository. Directly check out the actualheadRefNamebranch; an authorized checkout may create that original branch and establish native tracking. Verify local branch name equalsheadRefName,HEADequals the verified PR head SHA,branch.<name>.mergeequalsrefs/heads/<headRefName>, and the fetch remote identifies the original PR repository through a named remote or fork URL. Do not manually set or repair tracking, use a generated branch, or accept equal SHA without branch/destination proof. - Show the difference before suggesting local branch cleanup. On
remediation-fork-checkout-branch-collision, readlocal_branch_comparisonincheckout-state.json. In the user-facing outcome show the verified local branch, local tip, current remote PR head, commits ahead/behind, and the retained file/line diffstat from remote to local. When Git abbreviates the path list, state that it shows only the first 12 path rows and that totals cover all changed files. Include the exact full comparison commands with the two verified commit IDs:git --no-pager diff --no-ext-diff --no-textconv --no-renames <remote-oid> <local-oid> --for files andgit --no-pager log --left-right --oneline --no-show-signature <remote-oid>...<local-oid>for commits. Treat filenames as data. If stats could not be obtained, say which part is unavailable and give the full comparison command. - Guide the user through freeing the local branch name. Retain the failed run and matching review, release only the attempt’s own claim, present the comparison and pause. A linked worktree shares this branch namespace, including when requested with
--worktree. Explain which local commits deletion could leave without a branch. Show commands for the user to run in the branch’s owning checkout, using shell-quoted actual names and commit IDs. Checkgit worktree listandgit status --short; preserve any pending work first. Create a fresh backup branch at the verified local tip withgit branch -- <unused-backup-name> <local-oid>and verify it withgit rev-parse --verify refs/heads/<backup-name>. If the old branch is checked out, usegit switch -- <backup-name>in its owning worktree. Recheck that the old branch still points to the displayed local OID, then suggest tryinggit branch -d -- <local-branch>. Git can refuse this safe deletion when the configured upstream lacks local commits, even with a verified backup. To free the name while retaining its history, the user can rungit branch -m -- <local-branch> <another-unused-name>. Never delete or rename the branch automatically, recommend a forced delete, or change the remote. On resume, refresh the PR and checkout. If the tips already match, report zero difference and proceed with normal verified checkout without suggesting deletion. - Fork PR: do not directly check out a local branch or use an exact-SHA fallback. Require separate explicit approval for the adversarial recovery loop through the user's own explicit request before entering it; the remediation invocation alone supplies none. Do not solicit that loop; without a request for that loop, present the branch comparison and cleanup guidance above, or report the specific remaining prerequisite. Once approved, reuse the shared adversarial-loop procedure, not a hand-coded loop or new helper: retain the safe classified cause plus fresh local identity/state, obtain an independent read-only challenge, and apply only one bounded evidence-backed non-destructive repair. Do not reset, rebase, stash, force, discard user changes, repair authentication or remote configuration, or retry
ghwithout materially changed evidence. Each retry starts in a fresh run/artifact directory that retains the failed attempt and links its recovery evidence; after successful recollection, every downstream check consumes that verified new attempt directory, never the failed artifacts or a silently reused path. This fork-checkout caller retains its stricter budget of at most three rounds, includingW_0; plateau, non-convergence, or exhaustion of that caller budget stops the loop, while a repeated signature requires root-cause evidence before another attempt. Missing access, scope, or a supported recovery route is a human decision. Edits remain stopped untilgh pr checkout <canonical PR URL>succeeds and the attached branch, exact SHA, and destination checks pass.
For a resumed attempt that predates the collector’s recovery disposition, retain the original reports. Check that it was the original checkout, the retained target and routing identify the same fork PR, and the final error identifies the native fork checkout failure or a native-success head mismatch. A checkout-started marker alone is insufficient. A historical unclassified GitHub command failure or a local branch collision can be reassessed; respect recorded access, transport, preflight and user stops. When the older collector could not distinguish a recoverable collision, run the current remediation collector once in a fresh run under the original checkout’s claim. This performs the missing verification of current PR state, tracking and the advertised head. Follow its actual result: continue on success, show the branch comparison and user-owned cleanup guidance on a verified collision receipt, or honor the reported stop. Preserve the branch and the matching review evidence until the user frees the name.
Explain any remaining continuation options and their limits:
- Recover current source (recommended): perform authorized diagnosis and supported recovery. For a same-repository PR, use only the verified original-branch route above; for a verified fork branch collision, show the local/remote differences and the user-owned cleanup procedure above. Other fork repairs use the shared adversarial recovery loop only on explicit user request. Do not offer an unsolicited loop as the recommended choice. If new authorization for a non-loop action is needed, describe the exact action and its effects and ask one question with accepted answers; explain what approval and decline mean. Resume remediation only after collection verifies the attached branch, current PR head, and required source bundle.
- Defer source recovery: only if a supplied assessed report exists and the user accepts stale online-review coverage, continue at Report discussion after deferred source recovery with no code edits and no claim that current findings are fixed. Otherwise preserve the run and pause dependent work until verified source is available.
- Sequential execution: does not recover missing source or authorize edits to outdated code. Do not offer it as a solution to this failure.
Report discussion after deferred source recovery¶
An admitted assessed report plus the user's accepted source deferral permits this interim checkpoint before step 03. Preserve mode=pr, requested-report intent, the admitted report, diagnosed collection-failure artifacts, the accepted coverage limitation, and the first unmet checkpoint. Do not silently convert the run to report mode or retry collection unchanged.
Read the report's canonical findings and review limitations. Retain finding IDs and evidence references; state available evidence, missing closure evidence, owner, and concrete next action for actual source defects or required project checks. Keep reviewer coverage and provenance limitations in the discussion context, without creating remediation work or repeating declined review requests. Do not require attached checkout, target integration, merge authorization, or a merge commit merely to discuss retained evidence. A checkout failure does not turn a review limitation into a source defect.
Only an original +review remediation invocation may resume the producer Code Review at its first unmet checkpoint when its source and recovery evidence permit it. Report discussion itself does not authorize a fresh review, paid wave, producer-artifact repair, or new dispatch. For existing-only report evidence, stay in discussion and retain missing producer proof as a limitation. Producer-owned validation and independence remain mandatory.
This checkpoint is discussion and planned work, not confirmed remediation scope or completed remediation. Do not create or promote a canonical remediation result, execute steps 03–12 with incomplete source receipts, edit source, merge, commit, claim findings fixed, or close missing independent coverage. Retain findings and separate coverage notes in <run-directory>/report-discussion.md; explain unresolved source work and factual review limits from those notes. Source-dependent work resumes at its first unmet checkpoint with the existing source, selection, merge, verification and finalization gates. A permitted review recovery that produces a new admitted report returns to report admission; discussion never bypasses those gates.
Source drift recovery¶
A stale SHA or a different current branch is a source-recovery checkpoint, not completed remediation. The agent owns permitted refresh and checkout under existing authorization; do not tell the user to pull, restore the branch or send another message when the safe route below is available. The read-only branch checker remains fail-closed; never substitute current HEAD for the last recorded authorized revision merely to pass it.
- Preserve the failed diagnostic and original receipts. Inspect current worktree, branch and SHA, the destination branch ref before checkout, the last recorded authorized revision, upstream and effective destination identity, index/worktree changes, untracked-path collisions, active Git operations and evidence of an active writer. Use
git worktree list --porcelainto locate the original PR branch when it has moved to another checkout; verify that checkout belongs to the same repository and is available for this task, with no active writer. A detached former worktree is not itself a blocker when the original branch is safely available in another checkout. A clean current branch alone does not prove the inactive PR branch is safe to replace. - If the original PR branch is attached in the verified checkout, its index/worktree is clean, its configured fetch remote and merge ref identify the PR head for this pull, there is no active Git operation or active writer, and there are no local remediation commits or unverified local-only commits to preserve, run
git -C <verified-pr-worktree> pull --ff-onlyunder the Git read boundary and existing task authorization. Do not require fresh GitHub metadata or a preliminary PR-head fetch before this pull; Git enforces fast-forward-only integration, including an already-up-to-date result. After the pull succeeds, obtain current PR metadata through the GitHub reader, verify the bound PR identity and OPEN state, verify the resulting SHA against current PR metadata, and recheck branch/destination. When ancestry needs a newer object, fetch the verified PR head read-only under the owning network boundary without a persistent ref destination and verify its SHA. If the pull fails or is denied, stop this recovery route and escalate to the user with the attempted action, safe classified cause, preserved state and specific missing decision/capability; do not force, reset, rebase, stash or retry unchanged. A moved remote head or divergent history is not success; a metadata-check approval timeout is not a pull failure. If post-pull verification cannot finish, retain the successful pull evidence and report that verification remains incomplete. A successful collector checkout already supplies fresh source; do not add a redundant pull. When the branch has no upstream or tracks the PR base, skip this pull. Use the existing receipt to check unchanged source. If source refresh is needed, verify current OPEN metadata and use fresh collection only after proving it preserves local work, as in steps 3–5. - If another branch or detached HEAD is current, never pull the unrelated current branch. First use the verified original-branch checkout from steps 1–2 when available; do not move that branch out of its checkout merely to match an old receipt. Otherwise obtain current PR metadata and verify the bound PR identity and OPEN state before checkout. Prove the inactive original PR branch is absent, equals the verified PR head, or is strictly behind it with no local commits or owned edits to preserve. After the normal overwrite/operation checks, use the canonical remediation collector route: native
gh pr checkoutthroughcollect_pr.py, with only the existing verified same-repository fallback or separately authorized fork recovery after a failed native checkout. An unrelated untracked note alone is not a blocker; an overwrite collision is. An active writer or unverified destination remains a concrete coordination blocker. - Do not recollect over local remediation commits. When the original branch contains the last recorded authorized revision and the remote has not advanced past the recorded source, verify that revision, ancestry and destination using the existing receipt and continue with those local fixes intact. If another branch is current but the original branch holds those recorded local fixes, require the destination tip to equal the last recorded authorized revision and verify its ancestry, original PR source under the branch receipt’s verification rules, absence of another worktree owner or active writer, and safe worktree/index/operation/overwrite state before
git switch <recorded-original-branch>. Switch only that existing branch; do not create a branch, repair tracking or invoke the exact-remote-head collector. Immediately rerun receiptcheckat the recorded revision; preserve both branch histories, untracked notes and receipts. If the remote advanced independently of those local fixes, a destination branch has commits outside verified PR or authorized local history, or ownership/ancestry cannot be proved, preserve all work and report the exact integration decision needed. Never replay an exact-remote-head checkout over an ahead branch or invent a new expected revision to hide drift. - A changed remote source or worktree location invalidates the old collection binding: retain old artifacts and use the existing Collection failure recovery fresh attempt path for successful remediation collection and a new branch receipt in the verified checkout, linking the prior run and carrying still-valid user decisions and review finding identities. Every downstream command must use the new verified attempt. Reassess each finding and rerun invalidated source-dependent checks; do not silently discard findings or rerun a completed review merely because source moved. Returning to the unchanged recorded branch in its recorded worktree may reuse its still-valid receipt after
checkpasses. Resume the first unmet checkpoint through selection, fixes and closure; only exhausted safe recovery or a genuinely missing decision/capability permits an incomplete handoff.
Legacy receipt recovery¶
For a schema-1 legacy receipt, inspect the helper's current --help and run recover with the original --legacy-receipt, retained --pr-dir, last recorded authorized --expected-head, and a separate --receipt <run-directory>/remediation-branch-recovered.json. Recovery requires retained PR/checkout identity matching the original receipt, current worktree, original PR branch/destination, expected HEAD, ancestry, and no unfinished Git operation. It preserves the legacy receipt and all Git state, writes new evidence with the legacy digest, and does not claim a new checkout. An already authorized commit choice permits this local verification without asking the user to select a mode again. Continue ordinary check calls using the recovered receipt and record its path in commit-plan.md. If another branch is current, apply Source drift recovery before recover: derive the original branch from the retained PR metadata, not a legacy generated branch name, and require the same recorded-revision, destination, ownership and overwrite proof before the guarded switch. Then run the read-only recover helper on that verified original branch. A wrong destination or unmet recovery proof remains an incomplete stop with its specific missing decision. The recover helper itself never switches branches, repairs tracking, replays checkout, or rewrites history.
An oversized local inventory is a collector execution failure, not evidence that user files need cleanup. Retain the diagnostic and use the current collector’s complete-inventory preservation check; never ask the user to delete or relocate ignored environments, reports or scratch work to fit a diagnostic output cap. Actual path collisions still block checkout. After a successful check, continue the same remediation at its first unmet checkpoint under existing authorization.