code-remediate
Apply selected review fixes; bare PR targets use current online items, while PR +review adds the latest matching artifact.
Install
npx skills add https://github.com/Borda/AI-Rig/tree/main/plugins/codex-rig/skills/code-remediate
claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install borda-ai-rig@llmmart
git clone https://github.com/Borda/AI-Rig.git
The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole borda/ai-rig collection as a plugin from our marketplace. Git is the plain clone.
Skill manifest
Before asking, read User Questions.
Code Remediate
When independently reviewing applied fixes in a cycle, read ../../shared/adversarial-loop.md for convergence and stop rules. A clean loop never replaces selection, implementation evidence, or this skill's normal completion gates; after authorized recovery, resume them.
See the fixed recurrence and root-cause policy and reasoning-progress escalation policy for repeated-obstacle handling; record and validate reasoning-progress.json before another cycle after escalation trigger.
Run linear code remediation to close findings.
Input Schema
{
"findings_source": "optional path, explicit list, review for the current-session assessed review, or +review/+report/report/latest to auto-select the newest matching PR review report; omit with a bare PR target to use current online review items",
"mode": "optional report|pr|auto; infer pr for bare number, #number, or PR URL",
"target": "optional shorthand target number, issue/PR URL, path, or current branch",
"pr_target": "optional PR number, PR URL, or current branch PR when mode=pr",
"approve_gh": "optional boolean; default false; --approve-gh means the user has already approved required GitHub operations; use managed host preapproval to run without another prompt",
"remediation_scope": "optional all|critical|high|medium|low|comma-separated severities|comma-separated selection indexes; ask before editing when omitted",
"target_scope": "required path/module",
"done_when": "selected findings are fixed/resolved and unselected critical/high findings are explicitly deferred"
}
Workflow (Exact Commands)
Apply GitHub Workflow Consent whether or not --approve-gh is present: reuse existing scoped authorization; never require a flag reply or reinvocation. Ask only for genuinely missing consent through the permitted question control.
For required GitHub operations covered by --approve-gh or recorded same-scope workflow consent, apply Managed Host Preapproval to the helper actually used. Reuse the loaded matching host allow rule and execute directly; do not introduce a workflow confirmation or a wrapper that breaks matching. Diagnose unexpected prompts with the exact command and applicable rules. Missing or stricter host permissions remain authoritative.
01: Create Run Directory
Run create_run.py --skill code-remediate per ../../shared/helper-cli-contract.md.
02: Normalize input and optional report findings
For an incomplete requested review, return to Code Review step 12 under existing authorization and complete its ordered artifact closure before intake. Preflight success and direct-check receipts are preliminary evidence; applicable gate failures cannot become not-applicable to complete the handoff. Preserve the candidate recovery's same-parent and bounded-retry conditions below; completing missing artifacts never authorizes inventing provenance or skipping source-freshness checks.
Shorthand rules:
- Normalize a standalone
--approve-ghbefore target or report parsing: setapprove_gh=true. Remove--approve-ghbefore invokingcollect_pr.py; it is a skill flag, not a collector option. Never infer it from PR evidence; only direct user invocation may supply it. Repeated exact--approve-ghis idempotent. Reject--approve-gh=<value>asapprove-gh-invalid-value. $code-remediate 123 --approve-gh=>mode=pr,PR_TARGET=123,REQUESTED_REPORT=false,approve_gh=true. Existing explicit report aliases remain report-backed. Outsidemode=pr, failapprove-gh-requires-prbefore collection. Without--approve-gh, preserve existing PR collection approval behavior.--approve-ghnever selectsremediation_scope=all; continue normal scope selection.- Canonical in-session report:
$code-remediate review=>mode=report,REQUESTED_REPORT=true,FINDINGS_SOURCE=latest-assessed-current-session-review. It resolves to the latest assessedcode-reviewresult created in the current session. Reuse the exact prior artifact path recorded in this session; do not scan reports or infer a PR target. Do not collect PR evidence or fetch online review comments. If no assessed current-session review result is available, fail withcurrent-session-review-report-requiredand instruct the user to run$code-review <target>first or supply a report path. - Canonical online-only PR:
$code-remediate #123=>mode=pr,PR_TARGET=123,REQUESTED_REPORT=false,FINDINGS_SOURCE=none. Accepted bare PR forms are: bare number,#number, PR URL, and natural-language bare PR targets; they collect current online items and verified local checkout without a prior review report. - Natural-language online-only aliases:
remediate 123,remediate #123,remediate PR 123, andremediate <github-pr-url>use same bare-PR route. - Canonical report-backed PR:
$code-remediate #123 +review=>mode=pr,PR_TARGET=123,REQUESTED_REPORT=true,FINDINGS_SOURCE=latest-matching-review-report. matching-review-incomplete:<run-directory>means identified review retained notes but never produced promoted result or candidate. First explain in plain English that preliminary evidence exists but review did not complete; then stateReview handoff blocked, link that retained run, and name exact failed checkpoint with evidence-backed next action. Return to producer completion checkpoint and perform permitted diagnosis yourself; do not claim no review was performed, consume notes as validated result, select older verdict, or switch to online-only intake. This applies across sessions as well as within one session. A newer malformed result similarly blocks stale assessed fallback.- Compatibility alias:
$code-remediate #123 +report=>mode=pr,PR_TARGET=123,REQUESTED_REPORT=true,FINDINGS_SOURCE=latest-matching-review-report;$code-remediate #123 +report compatibility aliashas same report lookup. - Natural-language aliases:
remediate 123 report,remediate #123 report, andremediate PR 123 report=>mode=pr,PR_TARGET=123,REQUESTED_REPORT=true,FINDINGS_SOURCE=latest-matching-review-report. remediate <github-pr-url> report=>mode=pr,PR_TARGET=<github-pr-url>,REQUESTED_REPORT=true,FINDINGS_SOURCE=latest-matching-review-report.- An explicit review result path combined with PR target sets
REQUESTED_REPORT=true; bare PR target has no implicit report path. - Bare PR and report-backed PR routing are distinct: explicit
+review,+report, report aliases, and report paths retain report-plus-online behavior; absence of report source selects online-only intake and never falls back to report lookup. - If
+review,+report,report,latest,latest-report, orreview-reportreplaces path, find newest matching result across canonical.reports/codex/code-review/pr-<number>/run-<NNN>/result.jsonand legacy flat.reports/codex/code-review/<timestamp>/result.jsonartifacts whose siblingpr.jsonhas same PR number/URL asPR_TARGET. - When
REQUESTED_REPORT=true, no matching code-review report means the requested assessed findings are missing. Explain that first, then ask for an existing report path or permission to run$code-review <target>if not already authorized. Amatching-review-unavailable-rerun-code-reviewresult means PR collection failed before any assessed review; do not use it as findings input. Inspect that run's classified error and retained checkout diagnostics, perform permitted recovery, and rerun collection only when the diagnosed cause or external state supports it; ask only for the specific missing access or decision. Amatching-review-closed-not-remediableresult is a terminal close disposition with no source findings; do not remediate it or fall back to an older assessed report. Amatching-review-candidate-unpromoted:<path>result requires the bounded same-session recovery below; do not fall back to an older assessed report. - When canonical matching PR runs exist, select greatest parsed numeric
run-<NNN>index. Otherwise select greatest parsed legacy flat timestamp. Never rely on lexical glob order, modification time, or directory traversal order; record selected path in<run-directory>/findings-input.txt.
When FINDINGS_SOURCE=latest-matching-review-report, inspect python PLUGIN_ROOT/shared/find-review-report.py --help, resolve PR_TARGET against .reports/codex/code-review, and assign printed path to FINDINGS_SOURCE. The helper searches explicit canonical nested PR runs plus legacy flat timestamped runs; no migration is required. It filters explicit review_status=unavailable diagnostics, so older assessed review remains eligible when newer collection failure exists. A newer review_status=closed result instead blocks older findings because close disposition is current and non-remediable. Before accepting explicit review result path as findings input, invoke same helper with --result <path>; it rejects unavailable results with rerun instruction, closed results with matching-review-closed-not-remediable, and candidate paths with matching-review-candidate-unpromoted:<path>. A bare PR target must not run this helper, scan prior review reports, or require a code-review artifact.
Explicit local working-tree, path and commit intake requires canonical result.json and reruns both producer artifact validators, including source/provenance and final-handoff bindings, before returning its path. A plausible recommendation or filename alone is not validation. For a report produced in another session, pass its recorded producer thread through the existing --parent-thread-id option; use --codex-home only for the actual retained rollout root when needed. These identify evidence for validation, never waive it. Without overrides the helper uses current runtime defaults. Missing or invalid evidence stops intake; retain the validation diagnostic and return to the producer checkpoint without falling back to an older report. PR-only automatic discovery remains unchanged.
For matching-review-candidate-unpromoted:<path>, recover only when the candidate's specialist-manifest.json names the same parent thread as the current remediation session. Run the review-specific validator, then the shared validator, against that exact candidate and its review run directory; promote it to result.json only after both validators pass, then rerun the finder and use the promoted result. Never consume result.candidate.json directly. If either validator fails, persist its exact stderr code in <run-directory>/review-candidate-validation.txt, including manifest-invalid-attempt-count:<role> when applicable, and return to the code-review manifest preflight checkpoint for one evidence-preserving repair from retained specialist and rollout records. Never invent missing attempt provenance or retry a specialist for artifact bookkeeping. After a repaired manifest passes --manifest-only, rerender/rewrite the candidate as required and retry both validators once. If exact evidence cannot repair the run or either validator still fails, do not promote the candidate, rerun the full review, or fall back to an older assessed report; stop this candidate-repair operation with the exact error and candidate path. Explain the failed proof in plain English and use Code Review's Reviewer validation recovery guidance to propose a return to the producer for fresh sequential inspection or a supported independent route; do not launch that new review without existing authorization or the user's choice. Remediation resumes only after the producer completes and validates the requested review. This recovery has no waiting loop and makes no remote mutation.
When FINDINGS_SOURCE exists, copy its exact bytes to <run-directory>/findings-input.txt with filesystem tool. Do not depend on shell variable retaining that source path. For bare PR online-only intake, do not create <run-directory>/findings-input.txt; set CODE_REMEDIATE_METADATA.review_report_intake.requested_report=false and every report-item counter to 0.
For mode=pr, inspect python PLUGIN_ROOT/shared/collect_pr.py --help. Keep PR_TARGET for report lookup; for a numeric PR target, first run local python PLUGIN_ROOT/shared/select-git-remote.py --canonical-pr-url <positive-number> --cwd <source-repository> and set COLLECTION_TARGET to its single canonical URL. Stop on missing or ambiguous local GitHub repository identity; do not launch a numeric-target collector. For a user-supplied canonical PR URL, use that URL as COLLECTION_TARGET. Collect COLLECTION_TARGET into <run-directory>/pr with --checkout --checkout-mode remediate; use the same URL in the proposed runtime prefix. Remediation first invokes gh pr checkout <canonical PR URL>, including when the current HEAD already equals the PR head. If that command fails, only a verified same-repository PR may use direct Git checkout of its actual PR branch; fork PRs use the bounded recovery loop below.
On resume, inspect an existing <run-directory>/remediation-branch.json before collection. If <run-directory>/remediation-branch-recovered.json exists, use it for all continuation checks; never replace it or fall back after a failed check. Otherwise, a schema-1 receipt uses the legacy recovery procedure below. Check the selected receipt against the last recorded authorized revision with remediation_branch.py check; never recollect with checkout merely to replace local remediation commits or edits with the original PR head. Reuse still-valid source receipts and closure evidence. If fresh PR metadata changes the source contract, preserve the current branch and work and resolve that integration decision before further edits.
When approve_gh=true, treat required GitHub operations as already approved by the user. Do not ask for another workflow confirmation. Apply PR Collection Preapproval before collector execution, including the direct command and exact PR URL prefix. Do not create or modify runtime approval rules files.
In runtimes with network sandboxing, execute the complete collector command with approved external network access from its first attempt under ../../shared/native-skill-contract.md. Before requesting it, state:
Action and purpose: collect current PR evidence before remediation.External capability: read-only GitHub access plus documented local checkout.Credential behavior:ghis opaque local credential broker.Filesystem and worktree effects: write collection artifacts and may update local checkout.Retry policy and safe denial outcome: one classified recovery only, otherwise remediation uses its core collection-failure path.- For Codex exec, set
sandbox_permissions="require_escalated"on the collector with a narrow read-only GitHub justification; never request a broadpythonapproval prefix. Apply the other shared runtime and denial boundaries. A direct approval forgh pr viewdoes not coverghspawned by the collector: the outer collector command owns its nested GitHub CLI, HTTPS fallback, checkout, and Git fetch traffic. Completed user authorization through--approve-ghremoves workflow reconfirmation, never runtime permission checks. - If an agent-caused unapproved attempt returns
github-networkbefore any user approval request or denial, rerun that same complete collector command once through the runtime's external-network approval mechanism before treating collection as terminal. This recovery exists only for that pre-denial sandbox mistake; after the user denies approval, the current turn stops and the retry is forbidden. Only after that approved collector attempt fails, external-network approval is unavailable, or the user denies it may remediation apply its core collection-failure path; never repeat more than one approved recovery attempt.
github_read.py is plugin-wide GitHub data boundary: do not invoke gh outside it.
- It uses
ghas opaque local credential broker, never invokesgh auth, reads token/keychain state, or persists GitHub CLI failure output. - It permits only audited built-in view groups (
gist,issue,pr,project,release,repo,ruleset,run,workflow), REST GET, and GraphQL queries; no remote mutation is permitted. - Its public HTTPS fallback cannot establish private PR evidence.
Core and supplemental evidence:
collect_pr.pytreats PR identity/body plus exact local source as core evidence. In remediation mode it must first record the canonicalgh pr checkout <canonical PR URL>attempt,checkout_mode=remediate, an attached local branch, and the exact verified PR head; a matching HEAD does not skip that command. After a failed command, only a same-repository PR may record direct checkout of the actualheadRefNamebranch, with local branch name, exact SHA, merge tracking, and effective destination identity all verified. Fork recovery must end in a successful attachedghcheckout. It derivesdiff.patchlocally. Itsworktree-preflight.jsonpreserves unrelated tracked edits but blocks unresolved index entries, edits to PR-changed files, and paths checkout would overwrite; matching HEAD does not bypass these checks.- Retain checkout
force_policyand classified failure evidence: no forced checkout, manual tracking repair, reset, rebase, stash, or discarded user changes. A failed remediation checkout stops before edits or commits unless the verified same-repository branch route or the bounded fork recovery loop completes. - GraphQL review-thread resolution status is supplemental; if unavailable, collector writes empty normalized thread arrays plus
review-threads-error.txtand continues. - Record that online-triage coverage gap in
action-items.md, result confidence gaps, and unresolved/deferred closure rationale; never treat it as code finding or silently claim complete thread triage. - On core collection failure, use
<run-directory>/pr/pr-error.txt,<run-directory>/pr/worktree-preflight.json, and<run-directory>/pr/command-failure.jsonwhen present to distinguish classified process failure from source-review findings; for dirty-worktree overlap, name exactoverlapping_pathsfirst; do not treat it as merge recommendation.
When gh pr view metadata fails, public unauthenticated HTTPS fallback is eligible only when all of these hold:
- The failure is
github-network,github-auth,github-rate-limit, orcommand-timeout. - The checkout target is trusted: canonical PR URL must match configured GitHub remote; numeric target requires exactly one distinct configured GitHub repository identity.
Ambiguous or unsafe targets, permission failures, not-found failures, and unclassified failures remain fail-closed.
Fallback behavior:
- Public metadata fallback alone never satisfies remediation's attached-branch checkout contract or authorizes edits. It may supply limited metadata for the same-repository original-branch route only when every identity, checkout, destination, and degraded-evidence gate passes. After
gh pr checkoutfails, remediation has no exact-commit, detached, unverified cached-ref, generated-branch, or manual set-upstream fallback; only the verified same-repository original-branch route or the fork recovery loop is permitted. online-review-summary.jsonmust list unavailable fallback evidence as sorted IDs.- Raw GitHub CLI stderr is never persisted; terminal diagnostics may include safe
failure_reasonenum alongside non-secret classification metadata.
Findings intake:
- For
mode=report, normalize only the review report after confirming it is assessed. Rejectreview_status=unavailableandreview_status=closed; the latter is a close disposition without source findings. Do not read, collect, or infer any<run-directory>/pr/evidence. - For
mode=pr, always normalize<run-directory>/pr/comments.json,<run-directory>/pr/reviews.json,<run-directory>/pr/review-threads.json, and<run-directory>/pr/unresolved-review-threads.json.- When
REQUESTED_REPORT=false, those current online records are complete findings source. Do not read or infer review report, and do not require prior assessed artifact. If no online item is actionable after triage, continue through documentednone-selectablepath instead of requestingcode-review. - When
REQUESTED_REPORT=true, additionally normalize<run-directory>/findings-input.txt. Treat review report as closure contract, not only code findings: before editing normalize report findings, failedchecks_failed,follow_up,review_decision.required_next_work, confidence gaps, confidence-recovery remaining limits, and no-finding residual risks into report-origin action items. - Use local checkout in
<run-directory>/pr/local-checkout.jsonas the authoritative collected PR source and require itsverified-local-checkoutdiff provenance. After authorized target integration, apply the recorded merge result as described below; do not switch back to the unmerged PR head for finding edits. - Refresh both target and PR head yourself before conflict/review-item resolution;
<run-directory>/pr/target-branch.jsonand<run-directory>/pr/pr-head-fetch.jsonmust record fetched tips, including fork PRs. Normal fetches use no persistent ref destinations and avoid forced cache updates; the verified same-repository original-branch fallback may instead perform a guarded local update of an explicitly selected remote-tracking ref from the already fetched, verified PR head, using the observed prior value and preserving divergent or concurrently changed refs, for native tracking creation. Do not perform a second network fetch for that update. Capture verified IDs before another fetch changesFETCH_HEAD. Routine freshness is agent-owned work, not request for user to pull branches. Use the immutable fetched target ID intarget-branch.json.remote_ref; separate local target checkout is unnecessary. - Remediation checkout artifacts must prove
checkout_mode=remediate, the initialgh pr checkout <canonical PR URL>command and result, attached branch, and exact PR head. If that command fails, retain its safe classified cause and fresh local identity/state. A same-repository fallback must provehead_repository == base_repository, local branch name equalsheadRefName, exact head SHA,branch.<name>.merge=refs/heads/<headRefName>, and effective push destination identity; native tracking setup performed by the authorized direct checkout is allowed, but manual tracking repair is not. A fork fallback must complete the bounded recovery loop and then rerunghto obtain an attached branch. Any detached, wrong-branch, wrong-head, unverified destination, or incomplete loop stops before prepare, edits, merges, or commits. Never replace it with exact-SHA detach, an unverified cached-ref checkout, a generated branch, or a generic "repair checkout" instruction. If fresh fetched evidence proves the PR moved, a new authorized collection must still use this remediation checkout route. - If core metadata, target refresh, checkout, or local diff fails, record failure; continue with supplied report only when user accepts stale online-review coverage and no code edits are required, else fail.
- If only supplemental review-thread resolution status is unavailable, continue with explicit partial-coverage evidence and do not infer that any thread is resolved.
- Never inspect/edit PR code from
curl,raw.githubusercontent.com, or copiedhead-files/snapshots; raw-file snapshot rejection: snapshots are rejected.
- When
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.
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 effective push 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. - Fork PR: do not directly check out a local branch or use an exact-SHA fallback. 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. At most three rounds, includingW_0, are allowed; plateau, non-convergence, or round-cap 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.
Explain the 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 fork, use only the shared adversarial recovery loop. If new authorization 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 report discussion 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.
03: Understand PR Intent, Then Resolve Merge Conflicts
For a new PR remediation run, after successful remediation-mode collection and before target integration or finding edits, inspect python PLUGIN_ROOT/shared/remediation_branch.py --help and run its prepare action with <run-directory>/pr and receipt <run-directory>/remediation-branch.json. prepare is read-only Git verification plus a schema-2 status=prepared receipt: it never creates, switches, deletes, or manually re-tracks a branch. Require the initial gh pr checkout <canonical PR URL> evidence, or a positively verified same-repository direct checkout of the actual headRefName branch, plus an attached branch at the verified PR SHA, local branch name equal to headRefName, branch.<name>.merge=refs/heads/<headRefName>, and an effective push destination identifying the original PR head repository through a named remote or fork URL. Missing or wrong same-repository identity, tracking, custom push refspecs, or an unverified destination stop before edits; fork recovery must have completed the shared adversarial loop and returned to successful attached gh checkout. Native tracking set up by the authorized original-branch checkout is allowed. This proves configured destination identity, not live write access or universal plain-push success. Show the observed branch and original PR destination; local fixes and optional commits remain there, while remote updates remain human-owned. A review-only invocation does not prepare a remediation receipt.
Run the helper's read-only check action with the receipt and previously recorded expected HEAD before any authorized merge and before each commit. Initially use the collected PR head; after authorized integration or a commit use its recorded resulting revision. Do not derive a replacement expected value from current HEAD merely to silence a mismatch. On every resume, check must reverify the recorded worktree, attached branch, local branch name equal to headRefName, expected HEAD, ancestry, merge tracking, effective push destination, and original PR repository; leave the receipt unchanged. Detached HEAD, branch/worktree mismatch, unexpected revision, invalid ancestry, wrong destination, or a pre-existing receipt without verified continuation stops mutation for evidence-backed recovery; never automatically switch, reset, delete, overwrite the receipt, repair tracking, or recollect to hide drift. Keep source receipts immutable and record branch verification separately.
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 the live branch or destination is still wrong, stop with the failed check and required branch decision; recovery never switches branches, repairs tracking, replays checkout, or rewrites history.
For mode=pr, required before action-items.md, resolution-scope.md, or report/PR-review code changes. Establish clean PR and latest target implementation before conflict markers make worktree noisy.
Read remote_ref from <run-directory>/pr/target-branch.json with JSON parser and retain exact printed value as <base-remote-ref>. Run git merge-base HEAD <base-remote-ref> as argv, retain its single printed value as <merge-base>, and write that value to <run-directory>/pr/merge-base.txt. Run these argv commands separately and write stdout to named artifacts:
git diff --stat <merge-base>..HEAD→<run-directory>/pr/pr-intent.diffstatgit diff --name-only <merge-base>..HEAD→<run-directory>/pr/pr-intent-files.txtgit diff --stat <merge-base>..<base-remote-ref>→<run-directory>/pr/target-since-merge-base.diffstatgit merge-tree <merge-base> HEAD <base-remote-ref>→<run-directory>/pr/merge-tree.txt
Record each command's exit status; unavailable evidence is gap, never implied clean result.
Write <run-directory>/merge-prestage.md sections before attempting merge:
## PR And Target Refresh: PR number/head, target branch, fetched target hash, local checkout hash, evidence paths.## Clean PR Implementation Context: intended change, changed files, key invariants, clean-PR-implied tests/docs.## Target Branch Context: relevant fetched-target details, especially likely collision files.## Conflict Risk: mergeability,merge-treesignal, both-side changed files, conflicts present/likely/absent.## Resolution Strategy: reconcile PR intent and target implementation for each conflict/likely collision before review/report findings.## Merge Execution: conflict decision, authorization state, merge command/status, resolved paths, verification, and evidence path.
Write <run-directory>/pr/merge-resolution.json with schema_version, conflicts_detected, status, authorization, base_remote_ref, target_oid, pre_merge_head, post_merge_head, merge_commit, resolved_paths, unmerged_paths, and evidence. Use status=not-needed and authorization=not-required when fresh evidence proves no conflict. Do not merge target merely to refresh conflict-free PR.
If conflicts are present or likely, resolve them as PR integration before normalizing or addressing any report/online-review item:
- Use already-recorded clean PR purpose, invariants, target changes, and per-file resolution strategy as primary context. Inspect
git show <base-remote-ref>:<path>and nearby tests where needed; conflict markers are secondary evidence only. - A generic remediation request does not authorize local merge commit. Show target ref/OID, intended merge, collision files, resolution strategy, and overwrite/commit effect. Through User Questions, ask
Authorize this local merge and commit?with separate canonical optionsApproveandDeny; use the permitted async control when sync is unavailable or prohibited for authorization. Ask only when that exact action is not already authorized. ADenyleaves the merge unapproved. Recordauthorization=explicit-input|user-confirmed; if authorization is absent or runtime cannot ask, stop withtarget-merge-authorization-requiredbefore review-item work. - After authorization, run
git merge --no-commit --no-ff <base-remote-ref>with retained literal ref. Never rebase, force checkout, or rewrite history as substitute. - Resolve only merge collisions, preserving recorded PR intent atop fetched target implementation. Do not combine review-comment fixes unless same lines cannot otherwise form coherent merge; record unavoidable coupling in
<run-directory>/closure-log.md. - Verify
git diff --name-only --diff-filter=Uis empty, run smallest collision-relevant tests, then create authorized merge commit using../../shared/commit-response-template.mdand requiredCo-authored-by: Codex <codex@openai.com>trailer. Record pre/post HEAD, merge commit, resolved paths, tests, and empty unmerged-path list inmerge-resolution.jsonand## Merge Execution.
Do not create action-items.md, resolution-scope.md, or edit for report/online-review finding until merge-resolution.json is not-needed or completed, worktree has no unmerged paths, and no merge is in progress. If merge resolution or its verification fails, stop; do not hide conflict behind finding remediation.
If checkout starts conflicted or partially merged, apply Existing merge or conflict recovery below before editing. Unrelated tracked changes alone do not require cleanup; apply the existing checkout-overlap and ownership checks. Never use existing conflicted worktree as primary truth.
Existing merge or conflict recovery
Explain an unmerged entry such as UU as "This local file still contains an unresolved merge conflict, so I cannot safely switch this working copy to the PR version yet." Keep it separate from a failed remote fetch: resolving the conflict does not prove the fetch will succeed. Do not claim a pull caused the conflict or that the merge belongs to this task without evidence.
Inspect unmerged paths and read-only operation state, including MERGE_HEAD when present, current HEAD, and available pre-merge evidence. UU alone does not establish that a merge is still in progress; determine whether this is a merge, another Git operation, or unresolved index state before proposing a command. Identify intended changes and pre-existing changes to preserve. Do not treat unrelated dirty files as a checkout blocker or tell the user only to "resolve or abort in your own workflow".
Give an evidence-backed recommendation and one concrete choice among the applicable options; omit unsupported options and explain missing evidence:
- Finish the existing merge: describe the identified merge, affected files, intended resolution, verification, and any local commit. Offer agent-owned resolution when the merge's purpose and ownership are known; obtain explicit authorization for the resolution and any required commit unless already granted.
- Abort the existing merge: offer only when an active merge is verified and the user wants to cancel it. Explain that abort attempts to return to the pre-merge state, can discard conflict-resolution work, and may not restore pre-existing changes exactly. Establish a preservation plan and obtain explicit authorization before aborting; never promise lossless recovery or abort automatically.
- Defer: preserve current work and continue permitted diagnosis or user-accepted report discussion; PR code edits remain paused. State the exact missing evidence or decision if neither finish nor abort can yet be proposed safely.
For the recommended applicable action, after showing its concrete scope and effects, ask only the matching question through User Questions: Authorize finishing this existing merge and the described local commit? when a commit is needed, Authorize resolving these existing conflicts without committing? when no commit is proposed, or Authorize aborting this existing merge with the stated preservation plan?. Pass Approve and Deny as separate canonical options to the selected permitted native control. An Approve authorizes only the described action; a Deny selects Defer, preserves current state, and permits only the stated unaffected work. Do not ask all questions in succession or reprompt an action already authorized.
When verification identifies a repair outside the authorized scope, finish the permitted diagnosis and show the concrete proposed repair, affected paths, evidence, checks, and effect of declining. Ask only for the missing scope expansion through User Questions with separate canonical options Approve and Deny. Generated repair questions follow the same native routing as the merge question; do not append a keyed slash-separated authorization menu to the status message. Keep dependent repair or commit work pending until an explicit bound answer arrives, and reuse any previously granted commit authorization.
Resolving files while a merge remains in progress is partial recovery, not a completed merge. Continue to its first unmet checkpoint: if the required commit was not authorized, ask for that specific commit decision and explain that finding edits remain paused; if already authorized, complete and verify it. No-commit authorization never implies commit permission or satisfies merge-resolution.json.status=completed.
Once an authorized recovery succeeds, resume the active code-remediate workflow from its first unmet checkpoint under existing authorization. Preserve the resolved work and revalidate affected source and operation-state evidence; recollect missing or stale PR evidence and verify the current PR head when required by that checkpoint. For an already-authorized target integration, preserve and verify its recorded merge result rather than replacing it with the unmerged PR head. Continue the normal merge-prestage, findings-selection, implementation, and completion gates as applicable; do not stop at conflict resolution or ask the user to rerun the skill. A merge repaired by the user is a resume checkpoint, not proof that earlier fetch or source-validation failures are resolved. If an independent blocker remains, diagnose and explain only that unmet condition and its next action.
Retain local-checkout.json and after-checkout worktree-preflight.json as pre-merge source receipts. merge-resolution.json.pre_merge_head must match the collected PR head and its target_oid the captured target; a completed authorized integration's post_merge_head/merge_commit records the starting revision for finding edits. Verify current HEAD against that recorded revision before resuming, preserving subsequent authorized finding changes and their closure-log evidence. Never rewrite the pre-merge receipt to pretend the merged commit was the PR head, or recollect by replacing an authorized merge merely to satisfy a source-receipt check.
04: Normalize Findings Before Editing
Embedded review findings
Read every complete review/comment body, including nested <details> blocks, suppressed comments, nitpicks, and outside-diff suggestions. A fetched review is a container, not necessarily one finding. Enumerate every nested finding before deduplication; do not infer the count from Comments generated, inline-thread totals, or the review's summary verdict.
- Assign each embedded finding
<parent-id>#finding-<ordinal>in body order, starting at 1 within the immutable collected parent. This is a local source identity, not a GitHub comment ID. Preserve its exact finding text (including suggestions/code), file/line orgeneral, and evidence path to the complete parent body inpr/reviews.jsonorpr/comments.json. Do not create an additional parent-only item unless it contains a distinct obligation outside the enumerated findings; give that obligation its own ordinal too. Freeze identities for selection and final reconciliation; a changed parent body requires fresh intake, never silently rebind an earlier selection. - In
action-items.md, record each parent ID, advertised per-section finding counts when present, enumerated source IDs, and their owning item IDs. Reconcile advertised counts against entries before deduplication. Missing or ambiguous entries remainneeds-clarificationwith the exact gap; do not claim complete intake while a count is unexplained. With no advertised count, inspect the entire body and retain the enumeration as evidence; structural validators cannot prove semantic completeness. - Give distinct obligations separate selectable items and individual dispositions. Group repeated obligations across bodies, bots, and inline comments only when the required change is demonstrably the same; same file or line alone is insufficient. Preserve every fragment/inline source and location in the owning item's
sources; do not discard a suppressed finding merely because it is labelled duplicate by the bot. Validate each claim against current code before acceptance or rejection. - Before selection and at final handoff, reconcile every nested finding in the parent enumeration with the source records and dispositions. The existing executable inventory and final-table checks enforce unique fragment ownership and preserve selected identities; their success alone is not proof that enumeration captured the entire body.
For embedded findings, the source rules below apply to each composite identity and its complete finding body; the original unsplit parent remains in collected evidence. Whole-comment/thread/review identities remain valid for sources containing only one obligation.
Structural context (optional): when target_scope names Python module, also probe codemap-py once for changed-symbol/caller impact: python PLUGIN_ROOT/shared/codemap_adapter.py context --category review [--target <qname>] --out <run-directory>/codemap-context.json. Per ../../shared/codemap-contract.md, absence/incompatibility is non-fatal — continue normalizing available report and/or online findings evidence. Persist result once here; specialist owners assigned in step 06 receive <run-directory>/codemap-context.json in their context pack, never fresh query.
Write <run-directory>/action-items.md starting with ## Review Item Resolution Table, before prose. Normalize by canonical obligation, not by each report mention. For structured reviews, consume each review_findings record once using report [<report-json>#<finding-id>]; copy its title, summary, required change, evidence and closure evidence. Historical ID/severity-only or Markdown reviews remain readable: identify one primary finding/action record and attach other views of that same finding as related_mentions, never independent source records. Consolidate only matching canonical finding IDs within one report or independently evidenced same obligation; shared closure text, test command or source location alone never justifies merging distinct findings. A genuinely independent gate or confidence obligation remains separate item. Do not weaken report validation or certify historical failed results.
Every source has one owning item. Preserve genuinely independent report and fresh-online evidence with exact references, bodies and evidence paths. An online comment already attached to finding must not also be ingested as second duplicate row; record its duplicate/corroborating relationship in owning item's expanded record. Multiple different sources for same obligation may share item; never drop provenance. Each report source carries finding_id when known; optional related_mentions retains repeated summary/action/confidence locations without increasing source counts. Render primary sources as report [<report-file>:<line>], report [<report-json>#<finding-id>], or online [<comment|thread|review-id>]. Keep full source records in metadata and expanded item records: category, stable source ID, location or general, complete body, evidence path or report-only. No counts, representative sources, ellipses or artifact links may replace required evidence. Before asking for selection, run executable inventory gate in step 05; handwritten counts are not acceptance evidence.
When online-review-summary.json reports pr_metadata_transport=public-https-fallback, list sorted unavailable_evidence IDs github_provided_file_list, mergeability, review_decision, reviews, and top_level_comments in action-items.md and online action evidence, and add exact confidence gap Public HTTPS PR metadata fallback omitted evidence: <sorted IDs>. Substitute that sorted list into <sorted IDs>. The final remediation confidence is capped at 0.89; carry gap and its closure state through action-items.md, result metadata, and unresolved/deferred evidence.
For mode=pr, check every report/PR-review item against PR intent and changed diff before triage:
direct-diff: references PR-changed file/hunk/behavior.pr-intent: connects to PR purpose, acceptance criteria, review decision, requested change, even outside touched hunk.adjacent: touches nearby code/tests/docs/config/verification needed for safe merge.unknown: current evidence cannot determine relation.unrelated: no connection to PR intent, changed files, adjacent verification, or merge readiness after local PR-context inspection.
Write relation in action table and every expanded item. direct-diff, pr-intent, adjacent, unknown are never out-of-scope; keep valid/needs-clarification and selectable unless resolved, already-fixed, or already-applied evidence closes them. If current PR cannot close one, record unresolved, deferred, or required follow-up; never downgrade to out-of-scope. User can select, defer, or explicitly rule it into PR.
When REQUESTED_REPORT=true, include non-code report-origin review obligations:
- failed
checks_failed, including missing independence, full gates, lint, type, test, confidence gates follow_up, especiallyneeds-independent-reviewreview_decision.required_next_workand merge/readiness blockers- confidence gaps, confidence-recovery remaining limits, no-finding residual risks blocking acceptance
Report-origin obligations default in scope for +review, +report, report, or review-report path. Never mark out-of-scope merely because closure needs independent reviewer, installed tool, CI/full-gate run, or unavailable local environment. Mark valid/needs-clarification, keep selectable, leave unresolved/user-deferred until closure evidence. out-of-scope only for item proven unrelated to requested report/PR/target after citing evidence; never use it to silence failed gates/follow-up.
After resolution table, add ## Review Report Intake: whether report was requested, total report-origin items, report-origin review-gate/follow-up items, selectable review-gate/follow-up items, and report-origin out-of-scope count. When REQUESTED_REPORT=false, record requested report: false and 0 for every report count. The out-of-scope count must be 0 unless item is proven unrelated to requested report/PR/target.
Required table columns:
- selection index: numeric selectable;
-non-selectable - input item: stable input row id, report id, PR comment id, review id, thread id, source location
- item name: short human-readable finding/review obligation/gate/comment/thread name
- item type:
code|test|docs|review-gate|confidence-gap|pr-comment|pr-review|pr-thread|unresolved-pr-thread|ci|typing|lint|security|performance|process|other - sources: ordered compact unique pointers rendered as
report [<report-file>:<line>],report [<report-json>#<finding-id>], oronline [<comment|thread|review-id>]; join multiple records with one plain ASCII space and never append locations, bodies, evidence paths, resolutions, summaries, or online URLs - item id or source location
- source category:
report|online;onlinecovers PR comments, reviews, threads, and unresolved threads while item type preserves detailed online subtype - fetched evidence path, or
report-only - PR/diff relation:
direct-diff|pr-intent|adjacent|unknown|unrelated - severity
- summary
- triage status:
valid|resolved|duplicate|out-of-scope|already-fixed|already-applied|needs-clarification - resolution:
implemented|resolved|rejected|not-applicable|duplicate|already-fixed|already-applied|needs-clarification|unresolved - owner/status:
todo|fixed|resolved|deferred|unresolved|not-selected|not-actionable - resolved how:
[O<row-position>]; immediately below table define[O<row-position>] <how/why resolved/unresolved/deferred/not applicable> - evidence: closure evidence or unresolved rationale as
[E<row-position>]; immediately below table define[E<row-position>] <complete evidence, unresolved rationale, owner action, or next action>
After table add ## Final Resolution Summary:
- what was requested
- ingested entries total
- resolved or already-closed entries total
- implemented entries total
- unresolved entries total
- deferred/not-selected entries total
- not-applicable/duplicate/rejected entries total
- one sentence: all selected local actionable items closed or not
Then add ## Final Resolution Table Completeness:
- ingested entries total
- final table rows total
- omitted entries total: must be
0 - selectable/non-selectable row totals
- triage status counts
- resolution status counts
- source records total
- represented source records total
- omitted source records total: must be
0 - grouped items total
CODE_REMEDIATE_METADATA.final_resolution_table has same item and source counts plus items, ordered machine-readable source for durable and final-chat tables. Each item contains non-empty input_item_id, item_name, item_type, severity, triage_status, resolution_status, owner_status, resolved_how, and evidence, plus boolean selectable and non-empty ordered sources list. Each source contains kind=report|online, source_id, location, body, and evidence; (kind, source_id) is unique across items. A report source_id is <report-file>:<line> or <report-json>#<finding-id>; online source_id is its stable comment, thread, or review ID, or <parent-id>#finding-<ordinal> for an embedded finding, never URL. Preserve source order, full bodies, and unique IDs. Render the Review Item Resolution Table and Final Outcome Table from this list. Their Sources cells contain only ordered compact pointers; full source records remain in metadata and expanded item records. The durable table uses [O<n>] and [E<n>] cells and defines their complete resolved_how and evidence text immediately below table. The final handoff maps cells mechanically as input_item_id, severity, item_name, every compact source reference joined in source order, resolution_status — [O<n>], and [E<n>] — owner/status: owner_status; its table details list contains ordered O<n>/E<n> definitions. No later prose rewrite may change those values. Fail before output if durable table and items disagree, compact pointer or detail symbol is missing or changed, expanded source detail is missing, omitted_source_records_total is nonzero, source counts disagree, final table omits or changes item, counts fail to account for every row, or any row lacks disposition. CODE_REMEDIATE_METADATA.final_resolution_table.required_columns lists input item, item name, item type, sources, triage status, resolution, owner/status, resolved how, evidence.
Closure evidence for report-origin obligation must match type:
- independent review: independent specialist/maintainer output path plus updated metadata proving independence, or unavailable rationale
- full gates: clean full-gate/CI result path, or workspace/environment-prevented rationale
- type/lint/test environment: installed-environment command log, or missing executable/dependency rationale
- confidence gap: closing evidence, or explicit unresolved/deferred record
After table, keep expanded item record for every remediation item:
- finding id or source location
- severity
- source and fetched evidence path
- every contributing
report|onlinesource ID, location, complete body, and evidence path - PR/diff relation and evidence
- summary
- exact affected files
- expected closure evidence
- triage status:
valid|resolved|duplicate|out-of-scope|already-fixed|already-applied|needs-clarification - resolution:
implemented|resolved|rejected|not-applicable|duplicate|already-fixed|already-applied|needs-clarification|unresolved - owner/status:
todo|fixed|resolved|deferred|unresolved - unresolved rationale, when applicable
For ambiguous finding/thread/comment, inspect referenced local/checked-out code; sharpen to action item or needs-clarification before edits. If fetched PR evidence marks comment/thread resolved, table it as triage/resolution resolved, cite fetched evidence, state current PR marks it resolved; do not create implementation follow-up. If requested change already exists locally, mark triage/resolution already-applied, cite code evidence, no follow-up. Never fix duplicate, out-of-scope, already-fixed, already-applied, or resolved comments; record triage evidence.
Never classify or skip a review concern as stale. An outdated anchor, isOutdated flag, or line change caused by conflict resolution does not prove the concern is gone. Follow the original obligation into current code and reassess it; do not automatically relabel it rejected. All other dispositions retain their existing evidence requirements. Keep legacy stale count keys at zero in current results; historical artifacts remain readable.
05: Ask For Resolution Scope Before Editing
Before code changes, build <run-directory>/resolution-scope.md with ## Resolution Scope Selection. Selectable list includes every non-closed work-requiring finding; omits fetched online PR comments/threads currently resolved. Omit resolved online PR items from selection; keep them in action-items.md only as non-selectable audit rows, selection index -; omit-resolved-online rule.
Write <run-directory>/selection.json before prompting or accepting explicit scope: schema_version=1, selected_indexes=null while awaiting input, and items in stable ledger order. Each item copies input_item_id, item_name, item_type, severity, selectable, and complete ordered sources from normalized ledger, plus nonempty summary and closure_evidence. Classify report-origin non-code gate/follow-up obligations as review-gate or confidence-gap; intake counts derive from these types, not words in titles. Include nonselectable items for identity/count reconciliation; only selectable items appear as choices. A confirmed selection is list of numeric selection indexes, not finding IDs. No-selectable uses [] without pretending user selected anything.
Report identity defaults to its source file path, so different reports may reuse finding IDs. When different files are verified views of same report, give their sources same explicit report_id; do not use shared directory as identity. Selection input/output must be distinct files; output symlinks and aliases are rejected before writing.
Set selection.json.presentation_version=3 and add a short, concrete resolution_proposal to each selectable item. Inspect python PLUGIN_ROOT/shared/final_handoff.py selection --help, then run its selection action with --input <run-directory>/selection.json --out-scope <run-directory>/resolution-scope.md. Failure blocks the prompt and edits. The helper validates unique item/source/canonical-finding ownership and any declared totals before writing. It renders # | Severity | Finding | Resolution proposal | Sources. Sources are derived tags such as report ×1; online ×2, counting genuine source records only; never fill the overview with paths
Files (ai-rig)
-
references
-
parallel-lifecycle.md 6.2 KB
# Production Parallel Lifecycle `parallel-specialists` is planning-only until schema-v2 production lifecycle reaches `complete` and shared artifact validator reconciles it. Approval proves only authorization for exact plan; it never proves dispatch, execution, integration, or source application. The route is local to code-remediate, and generic `write_parallel_promoted` remains `false`. Inspect `python PLUGIN_ROOT/shared/parallel_worktrees.py --help`, then use its parent-owned commands in this order: `prepare`, one `create-handover` per terminal child, one `join` containing every handover file, one `collect` per joined node, `integrate`, `apply-source`, then `cleanup`. Handover files must remain inside source-local run directory. If parent cannot invoke this boundary or any precondition is unavailable, do not dispatch parallel writers; revise plan to parent-owned or sequential execution. Preparation requires completely clean authoritative repository with no merge, cherry-pick, revert, or rebase in progress; exact plan and approval digests; matching baseline HEAD/tree; exact new lifecycle-state basename in plan/approval run directory; two to four independent buckets; concrete non-overlapping owned paths; compatible resource locks; actual source-local context-pack paths and SHA-256 values; fixed `code-remediate-shared-quality-gates` reference; and generated detached worktrees outside authoritative checkout. Re-hash every context pack at preparation and each authority transition. Reject arbitrary bucket fields such as plan-driven shell commands, caller-selected or pre-existing state/output paths, source drift, aliases, symlinks, ignored or untracked output, commits, staged content, deletes, renames, file-mode/type changes, undeclared paths, or operation-state changes. Every declared owned path is required to change. Each parallel child context pack must preserve zero ignored or untracked output at handover by naming exact no-cache or no-output verification commands for every required child check. Prefer tool-native flags or environment controls that suppress disposable caches, coverage files, bytecode, reports, and equivalent generated output; parent integration still runs the authoritative shared quality gates after source application. Before hashing the plan, preflight every exact child verification command against the unchanged baseline in a disposable clean worktree; require unchanged tracked files and zero ignored or untracked output. Record expected baseline regression failures separately from command-launch, configuration, or output-boundary failures; a failing assertion that the selected fix must repair does not block plan approval. Do not create planned postimages before approval. Freeze only byte-identical command text that passed preflight's command and output-boundary checks. Changing a command or its environment after preflight requires a new plan digest and approval. A child must not delete verification output after the command because deletion would hide an observed boundary violation. When a required check cannot run without writing outside the declared tracked paths, re-plan that bucket as parent-owned or sequential before dispatch. Freeze one dependency-ready wave before child dispatch. Each child receives one worktree; its terminal handover contains canonical status, summary, changed paths, and patch SHA-256 without committing. After implementation and before handover, require exit zero on every exact approved child check, unchanged intended tracked postimages, and zero ignored or untracked output. Expected baseline regression failures are no longer acceptable at this stage. A failing postimage check blocks handover and integration; preserve its evidence and return control to parent. This postimage gate precedes structural collection and integration steps below. The parent re-derives every patch from child worktree, validates its report and exact ownership, joins all required terminal handovers, then applies parent-derived patches to separate integration worktree in lexical bucket ID order. Lifecycle integration verifies only Git structure, exact paths, and postimage hashes and records `structurally-verified`; it does not execute or claim plan-provided commands. After parent source application, run existing shared quality-gate phase and require its validated `gates.json` before passing remediation result. Only the parent may apply the integrated bundle to the authoritative repository. Immediately before application, recheck the exact HEAD/tree, clean operation state, and every approved path preimage. Persist one durable reverse patch plus its SHA-256 before writing; preflight one parent-generated forward bundle; apply it once; then verify every expected postimage. This is parent-authoritative operational postcondition containment with `capability_sandbox_verified=false`, not per-child capability isolation and not a hostile-child security boundary. Without a repository-wide external lock, source application is conditionally reversible rather than globally atomic. If any affected path after apply failure matches neither its recorded preimage nor expected postimage, record `rollback-ambiguous`, retain all worktrees and patches, and stop without automatic restoration. Otherwise restore only known approved paths to frozen baseline, recompute every path hash, and record `failed-rolled-back` only when all restored hashes equal frozen preimages; restore error or mismatch becomes `rollback-ambiguous`. Retain durable reverse patch as independent recovery evidence. Perform non-force cleanup only after durable source application and exact postcondition verification; cleanup failure retains evidence and blocks `completed`. Bind the final lifecycle projection into `CODE_REMEDIATE_METADATA.resolution_workplan.production_lifecycle` with its run-relative path, SHA-256, and status. The projection must reconcile the plan digest, baseline, joined node/path/patch hashes, every retained parent-derived child patch, deterministic structural integration order, source preimages/postimages, the retained parent forward bundle, source-application status, rollback artifact, cleanup outcome with `force=false`, and containment limitation. Never emit a completed remediation result from plan metadata alone or without passing shared-gate evidence.
-
-
result-template.json 5.6 KB
{ "artifact_path": ".reports/codex/code-remediate/<timestamp>/result.json", "checks_failed": [], "checks_run": [ "lint", "format", "types", "tests", "review" ], "confidence": 0.0, "findings": { "critical": 0, "high": 0, "low": 0, "medium": 0 }, "metadata": { "confidence_gap_closures": [ { "evidence": "evidence that closes the gap when status=closed", "gap": "why confidence is below 1.0 or residual limits still matter", "rationale": "why the gap remains open when status=unresolved|deferred", "status": "closed|unresolved|deferred" } ], "confidence_gaps": [ "why confidence is below 1.0 or residual limits still matter" ], "confidence_recovery": { "evidence": [ "objective evidence supporting final confidence" ], "final_confidence": 0.0, "initial_confidence": 0.0, "recovery_actions": [ "internal confidence-improvement loop performed before output" ], "remaining_limits": [ "residual uncertainty" ], "status": "shared-confidence-band-status" }, "final_handoff": { "branch": "standard", "handoff_path": ".reports/codex/code-remediate/<timestamp>/final-handoff.json", "handoff_sha256": "sha256", "rendered_path": ".reports/codex/code-remediate/<timestamp>/final.md", "rendered_sha256": "sha256", "schema_version": 1, "validation_path": ".reports/codex/code-remediate/<timestamp>/final-handoff.validation.json" }, "final_resolution_table": { "grouped_items_total": 0, "ingested_entries_total": 0, "items": [], "nonselectable_rows_total": 0, "omitted_entries_total": 0, "omitted_source_records_total": 0, "represented_source_records_total": 0, "required_columns": [ "input item", "item name", "item type", "sources", "triage status", "resolution", "owner/status", "resolved how", "evidence" ], "resolution_status_counts": { "already-applied": 0, "already-fixed": 0, "duplicate": 0, "implemented": 0, "needs-clarification": 0, "not-applicable": 0, "rejected": 0, "resolved": 0, "stale": 0, "unresolved": 0 }, "selectable_rows_total": 0, "source_records_total": 0, "table_rows_total": 0, "triage_status_counts": { "already-applied": 0, "already-fixed": 0, "duplicate": 0, "needs-clarification": 0, "out-of-scope": 0, "resolved": 0, "stale": 0, "valid": 0 } }, "merge_resolution": { "artifact_path": ".reports/codex/code-remediate/<timestamp>/pr/merge-resolution.json", "authorization": "not-required|explicit-input|user-confirmed", "conflicts_detected": false, "status": "not-needed|completed" }, "mode": "report|pr", "out_of_scope_confirmation": { "all_confirmed_by_user": true, "count": 0, "items": [] }, "pr_relevance": { "connected_items_marked_out_of_scope": 0, "connected_open_items_total": 0, "connected_required_followup_total": 0, "connected_selectable_items_total": 0, "evaluated": false }, "resolution_scope": { "deferred_indexes": [], "omitted_resolved_online_count": 0, "presentation_version": 2, "prompt_presented": false, "requested": "all|critical|high|medium|low|indexes", "selected_indexes": [], "selected_severity_groups": [], "selection_confirmed_by_user": false, "selection_source": "explicit-input|user-prompt|none-selectable" }, "resolution_workplan": { "approved_plan_sha256": null, "bucket_plan_path": ".reports/codex/code-remediate/<timestamp>/work-bucket-plan.json", "bucket_plan_sha256": "sha256 of exact work-bucket-plan.json bytes", "execution_mode": "parent-owned|sequential-specialists|parallel-specialists", "groups_total": 0, "max_items_per_bucket": 5, "parallel_approval_path": ".reports/codex/code-remediate/<timestamp>/parallel-approval.json", "parallel_approval_required": false, "parallel_approval_response": "not-required|approve|parent-only", "parallel_approval_source": "not-required|explicit-input|user-prompt", "parallel_approval_status": "not-required|approved|parent-only", "parallel_eligible": false, "parallel_prompt_presented": false, "parent_owned_groups": 0, "production_lifecycle": { "path": "production-lifecycle.json", "sha256": "sha256 of exact schema-v2 lifecycle bytes", "status": "completed" }, "specialist_owned_groups": 0, "unassigned_selected_items": 0, "verifier_groups": 0, "work_buckets": [], "workplan_path": ".reports/codex/code-remediate/<timestamp>/resolution-workplan.md" }, "review_report_intake": { "report_items_marked_out_of_scope": 0, "report_items_total": 0, "requested_report": false, "review_gate_items_selectable": 0, "review_gate_items_total": 0 }, "unresolved_summary": { "all_local_actionable_items_closed": true, "environment_blocked_items": 0, "external_owner_items": 0, "local_actionable_items_unresolved": 0, "process_gate_items_unresolved": 0, "selected_items_resolved": 0, "selected_items_total": 0, "selected_items_unresolved": 0, "unresolved_reason_groups": [], "user_deferred_items": 0 } }, "schema_version": 2, "status": "pass|fail" } -
SKILL.md 109 KB
--- name: code-remediate description: Apply selected review fixes; bare PR targets use current online items, while PR +review adds the latest matching artifact. --- > Before asking, read [User Questions](../../shared/codex-user-questions.md). # Code Remediate When independently reviewing applied fixes in a cycle, read `../../shared/adversarial-loop.md` for convergence and stop rules. A clean loop never replaces selection, implementation evidence, or this skill's normal completion gates; after authorized recovery, resume them. See the [fixed recurrence and root-cause policy](../../shared/native-skill-contract.md#recurrence-and-root-cause-policy) and [reasoning-progress escalation policy](../../shared/native-skill-contract.md#reasoning-progress-escalation) for repeated-obstacle handling; record and validate `reasoning-progress.json` before another cycle after escalation trigger. Run linear code remediation to close findings. ## Input Schema ```json { "findings_source": "optional path, explicit list, review for the current-session assessed review, or +review/+report/report/latest to auto-select the newest matching PR review report; omit with a bare PR target to use current online review items", "mode": "optional report|pr|auto; infer pr for bare number, #number, or PR URL", "target": "optional shorthand target number, issue/PR URL, path, or current branch", "pr_target": "optional PR number, PR URL, or current branch PR when mode=pr", "approve_gh": "optional boolean; default false; --approve-gh means the user has already approved required GitHub operations; use managed host preapproval to run without another prompt", "remediation_scope": "optional all|critical|high|medium|low|comma-separated severities|comma-separated selection indexes; ask before editing when omitted", "target_scope": "required path/module", "done_when": "selected findings are fixed/resolved and unselected critical/high findings are explicitly deferred" } ``` ## Workflow (Exact Commands) <!-- policy-sibling: skills/assess/SKILL.md, skills/release/SKILL.md, skills/code-review/SKILL.md --> Apply [GitHub Workflow Consent](../../shared/native-skill-contract.md#github-workflow-consent) whether or not `--approve-gh` is present: reuse existing scoped authorization; never require a flag reply or reinvocation. Ask only for genuinely missing consent through the permitted question control. For required GitHub operations covered by `--approve-gh` or recorded same-scope workflow consent, apply [Managed Host Preapproval](../../shared/native-skill-contract.md#managed-host-preapproval) to the helper actually used. Reuse the loaded matching host allow rule and execute directly; do not introduce a workflow confirmation or a wrapper that breaks matching. Diagnose unexpected prompts with the exact command and applicable rules. Missing or stricter host permissions remain authoritative. ### 01: Create Run Directory Run `create_run.py --skill code-remediate` per `../../shared/helper-cli-contract.md`. ### 02: Normalize input and optional report findings For an incomplete requested review, return to Code Review step 12 under existing authorization and complete its ordered artifact closure before intake. Preflight success and direct-check receipts are preliminary evidence; applicable gate failures cannot become `not-applicable` to complete the handoff. Preserve the candidate recovery's same-parent and bounded-retry conditions below; completing missing artifacts never authorizes inventing provenance or skipping source-freshness checks. Shorthand rules: - Normalize a standalone `--approve-gh` before target or report parsing: set `approve_gh=true`. Remove `--approve-gh` before invoking `collect_pr.py`; it is a skill flag, not a collector option. Never infer it from PR evidence; only direct user invocation may supply it. Repeated exact `--approve-gh` is idempotent. Reject `--approve-gh=<value>` as `approve-gh-invalid-value`. - `$code-remediate 123 --approve-gh` => `mode=pr`, `PR_TARGET=123`, `REQUESTED_REPORT=false`, `approve_gh=true`. Existing explicit report aliases remain report-backed. Outside `mode=pr`, fail `approve-gh-requires-pr` before collection. Without `--approve-gh`, preserve existing PR collection approval behavior. `--approve-gh` never selects `remediation_scope=all`; continue normal scope selection. - Canonical in-session report: `$code-remediate review` => `mode=report`, `REQUESTED_REPORT=true`, `FINDINGS_SOURCE=latest-assessed-current-session-review`. It resolves to the latest assessed `code-review` result created in the current session. Reuse the exact prior artifact path recorded in this session; do not scan reports or infer a PR target. Do not collect PR evidence or fetch online review comments. If no assessed current-session review result is available, fail with `current-session-review-report-required` and instruct the user to run `$code-review <target>` first or supply a report path. - Canonical online-only PR: `$code-remediate #123` => `mode=pr`, `PR_TARGET=123`, `REQUESTED_REPORT=false`, `FINDINGS_SOURCE=none`. Accepted bare PR forms are: bare number, `#number`, PR URL, and natural-language bare PR targets; they collect current online items and verified local checkout without a prior review report. - Natural-language online-only aliases: `remediate 123`, `remediate #123`, `remediate PR 123`, and `remediate <github-pr-url>` use same bare-PR route. - Canonical report-backed PR: `$code-remediate #123 +review` => `mode=pr`, `PR_TARGET=123`, `REQUESTED_REPORT=true`, `FINDINGS_SOURCE=latest-matching-review-report`. - `matching-review-incomplete:<run-directory>` means identified review retained notes but never produced promoted result or candidate. First explain in plain English that preliminary evidence exists but review did not complete; then state `Review handoff blocked`, link that retained run, and name exact failed checkpoint with evidence-backed next action. Return to producer completion checkpoint and perform permitted diagnosis yourself; do not claim no review was performed, consume notes as validated result, select older verdict, or switch to online-only intake. This applies across sessions as well as within one session. A newer malformed result similarly blocks stale assessed fallback. - Compatibility alias: `$code-remediate #123 +report` => `mode=pr`, `PR_TARGET=123`, `REQUESTED_REPORT=true`, `FINDINGS_SOURCE=latest-matching-review-report`; `$code-remediate #123 +report compatibility alias` has same report lookup. - Natural-language aliases: `remediate 123 report`, `remediate #123 report`, and `remediate PR 123 report` => `mode=pr`, `PR_TARGET=123`, `REQUESTED_REPORT=true`, `FINDINGS_SOURCE=latest-matching-review-report`. - `remediate <github-pr-url> report` => `mode=pr`, `PR_TARGET=<github-pr-url>`, `REQUESTED_REPORT=true`, `FINDINGS_SOURCE=latest-matching-review-report`. - An explicit review result path combined with PR target sets `REQUESTED_REPORT=true`; bare PR target has no implicit report path. - Bare PR and report-backed PR routing are distinct: explicit `+review`, `+report`, report aliases, and report paths retain report-plus-online behavior; absence of report source selects online-only intake and never falls back to report lookup. - If `+review`, `+report`, `report`, `latest`, `latest-report`, or `review-report` replaces path, find newest matching result across canonical `.reports/codex/code-review/pr-<number>/run-<NNN>/result.json` and legacy flat `.reports/codex/code-review/<timestamp>/result.json` artifacts whose sibling `pr.json` has same PR number/URL as `PR_TARGET`. - When `REQUESTED_REPORT=true`, no matching code-review report means the requested assessed findings are missing. Explain that first, then ask for an existing report path or permission to run `$code-review <target>` if not already authorized. A `matching-review-unavailable-rerun-code-review` result means PR collection failed before any assessed review; do not use it as findings input. Inspect that run's classified error and retained checkout diagnostics, perform permitted recovery, and rerun collection only when the diagnosed cause or external state supports it; ask only for the specific missing access or decision. A `matching-review-closed-not-remediable` result is a terminal close disposition with no source findings; do not remediate it or fall back to an older assessed report. A `matching-review-candidate-unpromoted:<path>` result requires the bounded same-session recovery below; do not fall back to an older assessed report. - When canonical matching PR runs exist, select greatest parsed numeric `run-<NNN>` index. Otherwise select greatest parsed legacy flat timestamp. Never rely on lexical glob order, modification time, or directory traversal order; record selected path in `<run-directory>/findings-input.txt`. When `FINDINGS_SOURCE=latest-matching-review-report`, inspect `python PLUGIN_ROOT/shared/find-review-report.py --help`, resolve `PR_TARGET` against `.reports/codex/code-review`, and assign printed path to `FINDINGS_SOURCE`. The helper searches explicit canonical nested PR runs plus legacy flat timestamped runs; no migration is required. It filters explicit `review_status=unavailable` diagnostics, so older assessed review remains eligible when newer collection failure exists. A newer `review_status=closed` result instead blocks older findings because close disposition is current and non-remediable. Before accepting explicit review result path as findings input, invoke same helper with `--result <path>`; it rejects unavailable results with rerun instruction, closed results with `matching-review-closed-not-remediable`, and candidate paths with `matching-review-candidate-unpromoted:<path>`. A bare PR target must not run this helper, scan prior review reports, or require a `code-review` artifact. Explicit local working-tree, path and commit intake requires canonical `result.json` and reruns both producer artifact validators, including source/provenance and final-handoff bindings, before returning its path. A plausible recommendation or filename alone is not validation. For a report produced in another session, pass its recorded producer thread through the existing `--parent-thread-id` option; use `--codex-home` only for the actual retained rollout root when needed. These identify evidence for validation, never waive it. Without overrides the helper uses current runtime defaults. Missing or invalid evidence stops intake; retain the validation diagnostic and return to the producer checkpoint without falling back to an older report. PR-only automatic discovery remains unchanged. For `matching-review-candidate-unpromoted:<path>`, recover only when the candidate's `specialist-manifest.json` names the same parent thread as the current remediation session. Run the review-specific validator, then the shared validator, against that exact candidate and its review run directory; promote it to `result.json` only after both validators pass, then rerun the finder and use the promoted result. Never consume `result.candidate.json` directly. If either validator fails, persist its exact stderr code in `<run-directory>/review-candidate-validation.txt`, including `manifest-invalid-attempt-count:<role>` when applicable, and return to the code-review manifest preflight checkpoint for one evidence-preserving repair from retained specialist and rollout records. Never invent missing attempt provenance or retry a specialist for artifact bookkeeping. After a repaired manifest passes `--manifest-only`, rerender/rewrite the candidate as required and retry both validators once. If exact evidence cannot repair the run or either validator still fails, do not promote the candidate, rerun the full review, or fall back to an older assessed report; stop this candidate-repair operation with the exact error and candidate path. Explain the failed proof in plain English and use Code Review's Reviewer validation recovery guidance to propose a return to the producer for fresh sequential inspection or a supported independent route; do not launch that new review without existing authorization or the user's choice. Remediation resumes only after the producer completes and validates the requested review. This recovery has no waiting loop and makes no remote mutation. When `FINDINGS_SOURCE` exists, copy its exact bytes to `<run-directory>/findings-input.txt` with filesystem tool. Do not depend on shell variable retaining that source path. For bare PR online-only intake, do not create `<run-directory>/findings-input.txt`; set `CODE_REMEDIATE_METADATA.review_report_intake.requested_report=false` and every report-item counter to `0`. For `mode=pr`, inspect `python PLUGIN_ROOT/shared/collect_pr.py --help`. Keep `PR_TARGET` for report lookup; for a numeric PR target, first run local `python PLUGIN_ROOT/shared/select-git-remote.py --canonical-pr-url <positive-number> --cwd <source-repository>` and set `COLLECTION_TARGET` to its single canonical URL. Stop on missing or ambiguous local GitHub repository identity; do not launch a numeric-target collector. For a user-supplied canonical PR URL, use that URL as `COLLECTION_TARGET`. Collect `COLLECTION_TARGET` into `<run-directory>/pr` with `--checkout --checkout-mode remediate`; use the same URL in the proposed runtime prefix. Remediation first invokes `gh pr checkout <canonical PR URL>`, including when the current HEAD already equals the PR head. If that command fails, only a verified same-repository PR may use direct Git checkout of its actual PR branch; fork PRs use the bounded recovery loop below. On resume, inspect an existing `<run-directory>/remediation-branch.json` before collection. If `<run-directory>/remediation-branch-recovered.json` exists, use it for all continuation checks; never replace it or fall back after a failed check. Otherwise, a schema-1 receipt uses the legacy recovery procedure below. Check the selected receipt against the last recorded authorized revision with `remediation_branch.py check`; never recollect with checkout merely to replace local remediation commits or edits with the original PR head. Reuse still-valid source receipts and closure evidence. If fresh PR metadata changes the source contract, preserve the current branch and work and resolve that integration decision before further edits. When `approve_gh=true`, treat required GitHub operations as already approved by the user. Do not ask for another workflow confirmation. Apply [PR Collection Preapproval](../../shared/native-skill-contract.md#pr-collection-preapproval) before collector execution, including the direct command and exact PR URL prefix. Do not create or modify runtime approval rules files. In runtimes with network sandboxing, execute the complete collector command with approved external network access from its first attempt under `../../shared/native-skill-contract.md`. Before requesting it, state: - `Action and purpose`: collect current PR evidence before remediation. - `External capability`: read-only GitHub access plus documented local checkout. - `Credential behavior`: `gh` is opaque local credential broker. - `Filesystem and worktree effects`: write collection artifacts and may update local checkout. - `Retry policy and safe denial outcome`: one classified recovery only, otherwise remediation uses its core collection-failure path. - For Codex exec, set `sandbox_permissions="require_escalated"` on the collector with a narrow read-only GitHub justification; never request a broad `python` approval prefix. Apply the other shared runtime and denial boundaries. A direct approval for `gh pr view` does not cover `gh` spawned by the collector: the outer collector command owns its nested GitHub CLI, HTTPS fallback, checkout, and Git fetch traffic. Completed user authorization through `--approve-gh` removes workflow reconfirmation, never runtime permission checks. - If an agent-caused unapproved attempt returns `github-network` before any user approval request or denial, rerun that same complete collector command once through the runtime's external-network approval mechanism before treating collection as terminal. This recovery exists only for that pre-denial sandbox mistake; after the user denies approval, the current turn stops and the retry is forbidden. Only after that approved collector attempt fails, external-network approval is unavailable, or the user denies it may remediation apply its core collection-failure path; never repeat more than one approved recovery attempt. `github_read.py` is plugin-wide GitHub data boundary: do not invoke `gh` outside it. - It uses `gh` as opaque local credential broker, never invokes `gh auth`, reads token/keychain state, or persists GitHub CLI failure output. - It permits only audited built-in view groups (`gist`, `issue`, `pr`, `project`, `release`, `repo`, `ruleset`, `run`, `workflow`), REST GET, and GraphQL queries; no remote mutation is permitted. - Its public HTTPS fallback cannot establish private PR evidence. Core and supplemental evidence: - `collect_pr.py` treats PR identity/body plus exact local source as core evidence. In remediation mode it must first record the canonical `gh pr checkout <canonical PR URL>` attempt, `checkout_mode=remediate`, an attached local branch, and the exact verified PR head; a matching HEAD does not skip that command. After a failed command, only a same-repository PR may record direct checkout of the actual `headRefName` branch, with local branch name, exact SHA, merge tracking, and effective destination identity all verified. Fork recovery must end in a successful attached `gh` checkout. It derives `diff.patch` locally. Its `worktree-preflight.json` preserves unrelated tracked edits but blocks unresolved index entries, edits to PR-changed files, and paths checkout would overwrite; matching HEAD does not bypass these checks. - Retain checkout `force_policy` and classified failure evidence: no forced checkout, manual tracking repair, reset, rebase, stash, or discarded user changes. A failed remediation checkout stops before edits or commits unless the verified same-repository branch route or the bounded fork recovery loop completes. - GraphQL review-thread resolution status is supplemental; if unavailable, collector writes empty normalized thread arrays plus `review-threads-error.txt` and continues. - Record that online-triage coverage gap in `action-items.md`, result confidence gaps, and unresolved/deferred closure rationale; never treat it as code finding or silently claim complete thread triage. - On core collection failure, use `<run-directory>/pr/pr-error.txt`, `<run-directory>/pr/worktree-preflight.json`, and `<run-directory>/pr/command-failure.json` when present to distinguish classified process failure from source-review findings; for dirty-worktree overlap, name exact `overlapping_paths` first; do not treat it as merge recommendation. When `gh pr view` metadata fails, public unauthenticated HTTPS fallback is eligible only when all of these hold: - The failure is `github-network`, `github-auth`, `github-rate-limit`, or `command-timeout`. - The checkout target is trusted: canonical PR URL must match configured GitHub remote; numeric target requires exactly one distinct configured GitHub repository identity. Ambiguous or unsafe targets, permission failures, not-found failures, and unclassified failures remain fail-closed. Fallback behavior: - Public metadata fallback alone never satisfies remediation's attached-branch checkout contract or authorizes edits. It may supply limited metadata for the same-repository original-branch route only when every identity, checkout, destination, and degraded-evidence gate passes. After `gh pr checkout` fails, remediation has no exact-commit, detached, unverified cached-ref, generated-branch, or manual set-upstream fallback; only the verified same-repository original-branch route or the fork recovery loop is permitted. - `online-review-summary.json` must list unavailable fallback evidence as sorted IDs. - Raw GitHub CLI stderr is never persisted; terminal diagnostics may include safe `failure_reason` enum alongside non-secret classification metadata. Findings intake: - For `mode=report`, normalize only the review report after confirming it is assessed. Reject `review_status=unavailable` and `review_status=closed`; the latter is a close disposition without source findings. Do not read, collect, or infer any `<run-directory>/pr/` evidence. - For `mode=pr`, always normalize `<run-directory>/pr/comments.json`, `<run-directory>/pr/reviews.json`, `<run-directory>/pr/review-threads.json`, and `<run-directory>/pr/unresolved-review-threads.json`. - When `REQUESTED_REPORT=false`, those current online records are complete findings source. Do not read or infer review report, and do not require prior assessed artifact. If no online item is actionable after triage, continue through documented `none-selectable` path instead of requesting `code-review`. - When `REQUESTED_REPORT=true`, additionally normalize `<run-directory>/findings-input.txt`. Treat review report as closure contract, not only code findings: before editing normalize report findings, failed `checks_failed`, `follow_up`, `review_decision.required_next_work`, confidence gaps, confidence-recovery remaining limits, and no-finding residual risks into report-origin action items. - Use local checkout in `<run-directory>/pr/local-checkout.json` as the authoritative collected PR source and require its `verified-local-checkout` diff provenance. After authorized target integration, apply the recorded merge result as described below; do not switch back to the unmerged PR head for finding edits. - Refresh both target and PR head yourself before conflict/review-item resolution; `<run-directory>/pr/target-branch.json` and `<run-directory>/pr/pr-head-fetch.json` must record fetched tips, including fork PRs. Normal fetches use no persistent ref destinations and avoid forced cache updates; the verified same-repository original-branch fallback may instead perform a guarded local update of an explicitly selected remote-tracking ref from the already fetched, verified PR head, using the observed prior value and preserving divergent or concurrently changed refs, for native tracking creation. Do not perform a second network fetch for that update. Capture verified IDs before another fetch changes `FETCH_HEAD`. Routine freshness is agent-owned work, not request for user to pull branches. Use the immutable fetched target ID in `target-branch.json.remote_ref`; separate local target checkout is unnecessary. - Remediation checkout artifacts must prove `checkout_mode=remediate`, the initial `gh pr checkout <canonical PR URL>` command and result, attached branch, and exact PR head. If that command fails, retain its safe classified cause and fresh local identity/state. A same-repository fallback must prove `head_repository == base_repository`, local branch name equals `headRefName`, exact head SHA, `branch.<name>.merge=refs/heads/<headRefName>`, and effective push destination identity; native tracking setup performed by the authorized direct checkout is allowed, but manual tracking repair is not. A fork fallback must complete the bounded recovery loop and then rerun `gh` to obtain an attached branch. Any detached, wrong-branch, wrong-head, unverified destination, or incomplete loop stops before prepare, edits, merges, or commits. Never replace it with exact-SHA detach, an unverified cached-ref checkout, a generated branch, or a generic "repair checkout" instruction. If fresh fetched evidence proves the PR moved, a new authorized collection must still use this remediation checkout route. - If core metadata, target refresh, checkout, or local diff fails, record failure; continue with supplied report only when user accepts stale online-review coverage and no code edits are required, else fail. - If only supplemental review-thread resolution status is unavailable, continue with explicit partial-coverage evidence and do not infer that any thread is resolved. - Never inspect/edit PR code from `curl`, `raw.githubusercontent.com`, or copied `head-files/` snapshots; raw-file snapshot rejection: snapshots are rejected. ### 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. 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 actual `headRefName` branch; an authorized checkout may create that original branch and establish native tracking. Verify local branch name equals `headRefName`, `HEAD` equals the verified PR head SHA, `branch.<name>.merge` equals `refs/heads/<headRefName>`, and the effective push 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. - **Fork PR:** do not directly check out a local branch or use an exact-SHA fallback. Reuse [the shared adversarial-loop procedure](../../shared/adversarial-loop.md), 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 `gh` without 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. At most three rounds, including `W_0`, are allowed; plateau, non-convergence, or round-cap 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 until `gh pr checkout <canonical PR URL>` succeeds and the attached branch, exact SHA, and destination checks pass. Explain the 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 fork, use only the shared adversarial recovery loop. If new authorization 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 report discussion 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. ### 03: Understand PR Intent, Then Resolve Merge Conflicts For a new PR remediation run, after successful remediation-mode collection and before target integration or finding edits, inspect `python PLUGIN_ROOT/shared/remediation_branch.py --help` and run its `prepare` action with `<run-directory>/pr` and receipt `<run-directory>/remediation-branch.json`. `prepare` is read-only Git verification plus a schema-2 `status=prepared` receipt: it never creates, switches, deletes, or manually re-tracks a branch. Require the initial `gh pr checkout <canonical PR URL>` evidence, or a positively verified same-repository direct checkout of the actual `headRefName` branch, plus an attached branch at the verified PR SHA, local branch name equal to `headRefName`, `branch.<name>.merge=refs/heads/<headRefName>`, and an effective push destination identifying the original PR head repository through a named remote or fork URL. Missing or wrong same-repository identity, tracking, custom push refspecs, or an unverified destination stop before edits; fork recovery must have completed the shared adversarial loop and returned to successful attached `gh` checkout. Native tracking set up by the authorized original-branch checkout is allowed. This proves configured destination identity, not live write access or universal plain-push success. Show the observed branch and original PR destination; local fixes and optional commits remain there, while remote updates remain human-owned. A review-only invocation does not prepare a remediation receipt. Run the helper's read-only `check` action with the receipt and previously recorded expected HEAD before any authorized merge and before each commit. Initially use the collected PR head; after authorized integration or a commit use its recorded resulting revision. Do not derive a replacement expected value from current HEAD merely to silence a mismatch. On every resume, `check` must reverify the recorded worktree, attached branch, local branch name equal to `headRefName`, expected HEAD, ancestry, merge tracking, effective push destination, and original PR repository; leave the receipt unchanged. Detached HEAD, branch/worktree mismatch, unexpected revision, invalid ancestry, wrong destination, or a pre-existing receipt without verified continuation stops mutation for evidence-backed recovery; never automatically switch, reset, delete, overwrite the receipt, repair tracking, or recollect to hide drift. Keep source receipts immutable and record branch verification separately. 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 the live branch or destination is still wrong, stop with the failed check and required branch decision; recovery never switches branches, repairs tracking, replays checkout, or rewrites history. For `mode=pr`, required before `action-items.md`, `resolution-scope.md`, or report/PR-review code changes. Establish clean PR and latest target implementation before conflict markers make worktree noisy. Read `remote_ref` from `<run-directory>/pr/target-branch.json` with JSON parser and retain exact printed value as `<base-remote-ref>`. Run `git merge-base HEAD <base-remote-ref>` as argv, retain its single printed value as `<merge-base>`, and write that value to `<run-directory>/pr/merge-base.txt`. Run these argv commands separately and write stdout to named artifacts: - `git diff --stat <merge-base>..HEAD` → `<run-directory>/pr/pr-intent.diffstat` - `git diff --name-only <merge-base>..HEAD` → `<run-directory>/pr/pr-intent-files.txt` - `git diff --stat <merge-base>..<base-remote-ref>` → `<run-directory>/pr/target-since-merge-base.diffstat` - `git merge-tree <merge-base> HEAD <base-remote-ref>` → `<run-directory>/pr/merge-tree.txt` Record each command's exit status; unavailable evidence is gap, never implied clean result. Write `<run-directory>/merge-prestage.md` sections before attempting merge: - `## PR And Target Refresh`: PR number/head, target branch, fetched target hash, local checkout hash, evidence paths. - `## Clean PR Implementation Context`: intended change, changed files, key invariants, clean-PR-implied tests/docs. - `## Target Branch Context`: relevant fetched-target details, especially likely collision files. - `## Conflict Risk`: mergeability, `merge-tree` signal, both-side changed files, conflicts present/likely/absent. - `## Resolution Strategy`: reconcile PR intent and target implementation for each conflict/likely collision before review/report findings. - `## Merge Execution`: conflict decision, authorization state, merge command/status, resolved paths, verification, and evidence path. Write `<run-directory>/pr/merge-resolution.json` with `schema_version`, `conflicts_detected`, `status`, `authorization`, `base_remote_ref`, `target_oid`, `pre_merge_head`, `post_merge_head`, `merge_commit`, `resolved_paths`, `unmerged_paths`, and `evidence`. Use `status=not-needed` and `authorization=not-required` when fresh evidence proves no conflict. Do not merge target merely to refresh conflict-free PR. If conflicts are present or likely, resolve them as PR integration before normalizing or addressing any report/online-review item: 1. Use already-recorded clean PR purpose, invariants, target changes, and per-file resolution strategy as primary context. Inspect `git show <base-remote-ref>:<path>` and nearby tests where needed; conflict markers are secondary evidence only. 2. A generic remediation request does not authorize local merge commit. Show target ref/OID, intended merge, collision files, resolution strategy, and overwrite/commit effect. Through User Questions, ask `Authorize this local merge and commit?` with separate canonical options `Approve` and `Deny`; use the permitted async control when sync is unavailable or prohibited for authorization. Ask only when that exact action is not already authorized. A `Deny` leaves the merge unapproved. Record `authorization=explicit-input|user-confirmed`; if authorization is absent or runtime cannot ask, stop with `target-merge-authorization-required` before review-item work. 3. After authorization, run `git merge --no-commit --no-ff <base-remote-ref>` with retained literal ref. Never rebase, force checkout, or rewrite history as substitute. 4. Resolve only merge collisions, preserving recorded PR intent atop fetched target implementation. Do not combine review-comment fixes unless same lines cannot otherwise form coherent merge; record unavoidable coupling in `<run-directory>/closure-log.md`. 5. Verify `git diff --name-only --diff-filter=U` is empty, run smallest collision-relevant tests, then create authorized merge commit using `../../shared/commit-response-template.md` and required `Co-authored-by: Codex <codex@openai.com>` trailer. Record pre/post HEAD, merge commit, resolved paths, tests, and empty unmerged-path list in `merge-resolution.json` and `## Merge Execution`. Do not create `action-items.md`, `resolution-scope.md`, or edit for report/online-review finding until `merge-resolution.json` is `not-needed` or `completed`, worktree has no unmerged paths, and no merge is in progress. If merge resolution or its verification fails, stop; do not hide conflict behind finding remediation. If checkout starts conflicted or partially merged, apply Existing merge or conflict recovery below before editing. Unrelated tracked changes alone do not require cleanup; apply the existing checkout-overlap and ownership checks. Never use existing conflicted worktree as primary truth. ### Existing merge or conflict recovery Explain an unmerged entry such as `UU` as "This local file still contains an unresolved merge conflict, so I cannot safely switch this working copy to the PR version yet." Keep it separate from a failed remote fetch: resolving the conflict does not prove the fetch will succeed. Do not claim a pull caused the conflict or that the merge belongs to this task without evidence. Inspect unmerged paths and read-only operation state, including `MERGE_HEAD` when present, current HEAD, and available pre-merge evidence. `UU` alone does not establish that a merge is still in progress; determine whether this is a merge, another Git operation, or unresolved index state before proposing a command. Identify intended changes and pre-existing changes to preserve. Do not treat unrelated dirty files as a checkout blocker or tell the user only to "resolve or abort in your own workflow". Give an evidence-backed recommendation and one concrete choice among the applicable options; omit unsupported options and explain missing evidence: - **Finish the existing merge:** describe the identified merge, affected files, intended resolution, verification, and any local commit. Offer agent-owned resolution when the merge's purpose and ownership are known; obtain explicit authorization for the resolution and any required commit unless already granted. - **Abort the existing merge:** offer only when an active merge is verified and the user wants to cancel it. Explain that abort attempts to return to the pre-merge state, can discard conflict-resolution work, and may not restore pre-existing changes exactly. Establish a preservation plan and obtain explicit authorization before aborting; never promise lossless recovery or abort automatically. - **Defer:** preserve current work and continue permitted diagnosis or user-accepted report discussion; PR code edits remain paused. State the exact missing evidence or decision if neither finish nor abort can yet be proposed safely. For the recommended applicable action, after showing its concrete scope and effects, ask only the matching question through User Questions: `Authorize finishing this existing merge and the described local commit?` when a commit is needed, `Authorize resolving these existing conflicts without committing?` when no commit is proposed, or `Authorize aborting this existing merge with the stated preservation plan?`. Pass `Approve` and `Deny` as separate canonical options to the selected permitted native control. An **Approve** authorizes only the described action; a **Deny** selects **Defer**, preserves current state, and permits only the stated unaffected work. Do not ask all questions in succession or reprompt an action already authorized. When verification identifies a repair outside the authorized scope, finish the permitted diagnosis and show the concrete proposed repair, affected paths, evidence, checks, and effect of declining. Ask only for the missing scope expansion through User Questions with separate canonical options `Approve` and `Deny`. Generated repair questions follow the same native routing as the merge question; do not append a keyed slash-separated authorization menu to the status message. Keep dependent repair or commit work pending until an explicit bound answer arrives, and reuse any previously granted commit authorization. Resolving files while a merge remains in progress is partial recovery, not a completed merge. Continue to its first unmet checkpoint: if the required commit was not authorized, ask for that specific commit decision and explain that finding edits remain paused; if already authorized, complete and verify it. No-commit authorization never implies commit permission or satisfies `merge-resolution.json.status=completed`. Once an authorized recovery succeeds, resume the active code-remediate workflow from its first unmet checkpoint under existing authorization. Preserve the resolved work and revalidate affected source and operation-state evidence; recollect missing or stale PR evidence and verify the current PR head when required by that checkpoint. For an already-authorized target integration, preserve and verify its recorded merge result rather than replacing it with the unmerged PR head. Continue the normal merge-prestage, findings-selection, implementation, and completion gates as applicable; do not stop at conflict resolution or ask the user to rerun the skill. A merge repaired by the user is a resume checkpoint, not proof that earlier fetch or source-validation failures are resolved. If an independent blocker remains, diagnose and explain only that unmet condition and its next action. Retain `local-checkout.json` and after-checkout `worktree-preflight.json` as pre-merge source receipts. `merge-resolution.json.pre_merge_head` must match the collected PR head and its `target_oid` the captured target; a completed authorized integration's `post_merge_head`/`merge_commit` records the starting revision for finding edits. Verify current HEAD against that recorded revision before resuming, preserving subsequent authorized finding changes and their closure-log evidence. Never rewrite the pre-merge receipt to pretend the merged commit was the PR head, or recollect by replacing an authorized merge merely to satisfy a source-receipt check. ### 04: Normalize Findings Before Editing #### Embedded review findings Read every complete review/comment body, including nested `<details>` blocks, suppressed comments, nitpicks, and outside-diff suggestions. A fetched review is a container, not necessarily one finding. Enumerate every nested finding before deduplication; do not infer the count from `Comments generated`, inline-thread totals, or the review's summary verdict. 1. Assign each embedded finding `<parent-id>#finding-<ordinal>` in body order, starting at 1 within the immutable collected parent. This is a local source identity, not a GitHub comment ID. Preserve its exact finding text (including suggestions/code), file/line or `general`, and evidence path to the complete parent body in `pr/reviews.json` or `pr/comments.json`. Do not create an additional parent-only item unless it contains a distinct obligation outside the enumerated findings; give that obligation its own ordinal too. Freeze identities for selection and final reconciliation; a changed parent body requires fresh intake, never silently rebind an earlier selection. 2. In `action-items.md`, record each parent ID, advertised per-section finding counts when present, enumerated source IDs, and their owning item IDs. Reconcile advertised counts against entries before deduplication. Missing or ambiguous entries remain `needs-clarification` with the exact gap; do not claim complete intake while a count is unexplained. With no advertised count, inspect the entire body and retain the enumeration as evidence; structural validators cannot prove semantic completeness. 3. Give distinct obligations separate selectable items and individual dispositions. Group repeated obligations across bodies, bots, and inline comments only when the required change is demonstrably the same; same file or line alone is insufficient. Preserve every fragment/inline source and location in the owning item's `sources`; do not discard a suppressed finding merely because it is labelled duplicate by the bot. Validate each claim against current code before acceptance or rejection. 4. Before selection and at final handoff, reconcile every nested finding in the parent enumeration with the source records and dispositions. The existing executable inventory and final-table checks enforce unique fragment ownership and preserve selected identities; their success alone is not proof that enumeration captured the entire body. For embedded findings, the source rules below apply to each composite identity and its complete finding body; the original unsplit parent remains in collected evidence. Whole-comment/thread/review identities remain valid for sources containing only one obligation. **Structural context (optional)**: when `target_scope` names Python module, also probe codemap-py once for changed-symbol/caller impact: `python PLUGIN_ROOT/shared/codemap_adapter.py context --category review [--target <qname>] --out <run-directory>/codemap-context.json`. Per `../../shared/codemap-contract.md`, absence/incompatibility is non-fatal — continue normalizing available report and/or online findings evidence. Persist result once here; specialist owners assigned in step 06 receive `<run-directory>/codemap-context.json` in their context pack, never fresh query. Write `<run-directory>/action-items.md` starting with `## Review Item Resolution Table`, before prose. Normalize by canonical obligation, not by each report mention. For structured reviews, consume each `review_findings` record once using `report [<report-json>#<finding-id>]`; copy its title, summary, required change, evidence and closure evidence. Historical ID/severity-only or Markdown reviews remain readable: identify one primary finding/action record and attach other views of that same finding as `related_mentions`, never independent source records. Consolidate only matching canonical finding IDs within one report or independently evidenced same obligation; shared closure text, test command or source location alone never justifies merging distinct findings. A genuinely independent gate or confidence obligation remains separate item. Do not weaken report validation or certify historical failed results. Every source has one owning item. Preserve genuinely independent report and fresh-online evidence with exact references, bodies and evidence paths. An online comment already attached to finding must not also be ingested as second duplicate row; record its duplicate/corroborating relationship in owning item's expanded record. Multiple different sources for same obligation may share item; never drop provenance. Each report source carries `finding_id` when known; optional `related_mentions` retains repeated summary/action/confidence locations without increasing source counts. Render primary sources as `report [<report-file>:<line>]`, `report [<report-json>#<finding-id>]`, or `online [<comment|thread|review-id>]`. Keep full source records in metadata and expanded item records: category, stable source ID, location or `general`, complete body, evidence path or `report-only`. No counts, representative sources, ellipses or artifact links may replace required evidence. Before asking for selection, run executable inventory gate in step 05; handwritten counts are not acceptance evidence. When `online-review-summary.json` reports `pr_metadata_transport=public-https-fallback`, list sorted `unavailable_evidence` IDs `github_provided_file_list`, `mergeability`, `review_decision`, `reviews`, and `top_level_comments` in `action-items.md` and online action evidence, and add exact confidence gap `Public HTTPS PR metadata fallback omitted evidence: <sorted IDs>.` Substitute that sorted list into `<sorted IDs>`. The final remediation confidence is capped at `0.89`; carry gap and its closure state through `action-items.md`, result metadata, and unresolved/deferred evidence. For `mode=pr`, check every report/PR-review item against PR intent and changed diff before triage: - `direct-diff`: references PR-changed file/hunk/behavior. - `pr-intent`: connects to PR purpose, acceptance criteria, review decision, requested change, even outside touched hunk. - `adjacent`: touches nearby code/tests/docs/config/verification needed for safe merge. - `unknown`: current evidence cannot determine relation. - `unrelated`: no connection to PR intent, changed files, adjacent verification, or merge readiness after local PR-context inspection. Write relation in action table and every expanded item. `direct-diff`, `pr-intent`, `adjacent`, `unknown` are never `out-of-scope`; keep `valid`/`needs-clarification` and selectable unless `resolved`, `already-fixed`, or `already-applied` evidence closes them. If current PR cannot close one, record `unresolved`, `deferred`, or required follow-up; never downgrade to `out-of-scope`. User can select, defer, or explicitly rule it into PR. When `REQUESTED_REPORT=true`, include non-code report-origin review obligations: - failed `checks_failed`, including missing independence, full gates, lint, type, test, confidence gates - `follow_up`, especially `needs-independent-review` - `review_decision.required_next_work` and merge/readiness blockers - confidence gaps, confidence-recovery remaining limits, no-finding residual risks blocking acceptance Report-origin obligations default in scope for `+review`, `+report`, `report`, or review-report path. Never mark `out-of-scope` merely because closure needs independent reviewer, installed tool, CI/full-gate run, or unavailable local environment. Mark `valid`/`needs-clarification`, keep selectable, leave `unresolved`/user-deferred until closure evidence. `out-of-scope` only for item proven unrelated to requested report/PR/target after citing evidence; never use it to silence failed gates/follow-up. After resolution table, add `## Review Report Intake`: whether report was requested, total report-origin items, report-origin review-gate/follow-up items, selectable review-gate/follow-up items, and report-origin `out-of-scope` count. When `REQUESTED_REPORT=false`, record `requested report: false` and `0` for every report count. The `out-of-scope` count must be `0` unless item is proven unrelated to requested report/PR/target. Required table columns: - selection index: numeric selectable; `-` non-selectable - input item: stable input row id, report id, PR comment id, review id, thread id, source location - item name: short human-readable finding/review obligation/gate/comment/thread name - item type: `code|test|docs|review-gate|confidence-gap|pr-comment|pr-review|pr-thread|unresolved-pr-thread|ci|typing|lint|security|performance|process|other` - sources: ordered compact unique pointers rendered as `report [<report-file>:<line>]`, `report [<report-json>#<finding-id>]`, or `online [<comment|thread|review-id>]`; join multiple records with one plain ASCII space and never append locations, bodies, evidence paths, resolutions, summaries, or online URLs - item id or source location - source category: `report|online`; `online` covers PR comments, reviews, threads, and unresolved threads while item type preserves detailed online subtype - fetched evidence path, or `report-only` - PR/diff relation: `direct-diff|pr-intent|adjacent|unknown|unrelated` - severity - summary - triage status: `valid|resolved|duplicate|out-of-scope|already-fixed|already-applied|needs-clarification` - resolution: `implemented|resolved|rejected|not-applicable|duplicate|already-fixed|already-applied|needs-clarification|unresolved` - owner/status: `todo|fixed|resolved|deferred|unresolved|not-selected|not-actionable` - resolved how: `[O<row-position>]`; immediately below table define `[O<row-position>] <how/why resolved/unresolved/deferred/not applicable>` - evidence: closure evidence or unresolved rationale as `[E<row-position>]`; immediately below table define `[E<row-position>] <complete evidence, unresolved rationale, owner action, or next action>` After table add `## Final Resolution Summary`: - what was requested - ingested entries total - resolved or already-closed entries total - implemented entries total - unresolved entries total - deferred/not-selected entries total - not-applicable/duplicate/rejected entries total - one sentence: all selected local actionable items closed or not Then add `## Final Resolution Table Completeness`: - ingested entries total - final table rows total - omitted entries total: must be `0` - selectable/non-selectable row totals - triage status counts - resolution status counts - source records total - represented source records total - omitted source records total: must be `0` - grouped items total `CODE_REMEDIATE_METADATA.final_resolution_table` has same item and source counts plus `items`, ordered machine-readable source for durable and final-chat tables. Each item contains non-empty `input_item_id`, `item_name`, `item_type`, `severity`, `triage_status`, `resolution_status`, `owner_status`, `resolved_how`, and `evidence`, plus boolean `selectable` and non-empty ordered `sources` list. Each source contains `kind=report|online`, `source_id`, `location`, `body`, and `evidence`; `(kind, source_id)` is unique across items. A report `source_id` is `<report-file>:<line>` or `<report-json>#<finding-id>`; online `source_id` is its stable comment, thread, or review ID, or `<parent-id>#finding-<ordinal>` for an embedded finding, never URL. Preserve source order, full bodies, and unique IDs. Render the `Review Item Resolution Table` and `Final Outcome Table` from this list. Their `Sources` cells contain only ordered compact pointers; full source records remain in metadata and expanded item records. The durable table uses `[O<n>]` and `[E<n>]` cells and defines their complete `resolved_how` and `evidence` text immediately below table. The final handoff maps cells mechanically as `input_item_id`, `severity`, `item_name`, every compact source reference joined in source order, `resolution_status — [O<n>]`, and `[E<n>] — owner/status: owner_status`; its table `details` list contains ordered `O<n>`/`E<n>` definitions. No later prose rewrite may change those values. Fail before output if durable table and items disagree, compact pointer or detail symbol is missing or changed, expanded source detail is missing, `omitted_source_records_total` is nonzero, source counts disagree, final table omits or changes item, counts fail to account for every row, or any row lacks disposition. `CODE_REMEDIATE_METADATA.final_resolution_table.required_columns` lists `input item`, `item name`, `item type`, `sources`, `triage status`, `resolution`, `owner/status`, `resolved how`, `evidence`. Closure evidence for report-origin obligation must match type: - independent review: independent specialist/maintainer output path plus updated metadata proving independence, or unavailable rationale - full gates: clean full-gate/CI result path, or workspace/environment-prevented rationale - type/lint/test environment: installed-environment command log, or missing executable/dependency rationale - confidence gap: closing evidence, or explicit unresolved/deferred record After table, keep expanded item record for every remediation item: - finding id or source location - severity - source and fetched evidence path - every contributing `report|online` source ID, location, complete body, and evidence path - PR/diff relation and evidence - summary - exact affected files - expected closure evidence - triage status: `valid|resolved|duplicate|out-of-scope|already-fixed|already-applied|needs-clarification` - resolution: `implemented|resolved|rejected|not-applicable|duplicate|already-fixed|already-applied|needs-clarification|unresolved` - owner/status: `todo|fixed|resolved|deferred|unresolved` - unresolved rationale, when applicable For ambiguous finding/thread/comment, inspect referenced local/checked-out code; sharpen to action item or `needs-clarification` before edits. If fetched PR evidence marks comment/thread resolved, table it as triage/resolution `resolved`, cite fetched evidence, state current PR marks it resolved; do not create implementation follow-up. If requested change already exists locally, mark triage/resolution `already-applied`, cite code evidence, no follow-up. Never fix duplicate, out-of-scope, already-fixed, already-applied, or resolved comments; record triage evidence. Never classify or skip a review concern as `stale`. An outdated anchor, `isOutdated` flag, or line change caused by conflict resolution does not prove the concern is gone. Follow the original obligation into current code and reassess it; do not automatically relabel it `rejected`. All other dispositions retain their existing evidence requirements. Keep legacy `stale` count keys at zero in current results; historical artifacts remain readable. ### 05: Ask For Resolution Scope Before Editing Before code changes, build `<run-directory>/resolution-scope.md` with `## Resolution Scope Selection`. Selectable list includes every non-closed work-requiring finding; omits fetched online PR comments/threads currently resolved. Omit resolved online PR items from selection; keep them in `action-items.md` only as non-selectable audit rows, selection index `-`; omit-resolved-online rule. Write `<run-directory>/selection.json` before prompting or accepting explicit scope: `schema_version=1`, `selected_indexes=null` while awaiting input, and `items` in stable ledger order. Each item copies `input_item_id`, `item_name`, `item_type`, `severity`, `selectable`, and complete ordered `sources` from normalized ledger, plus nonempty `summary` and `closure_evidence`. Classify report-origin non-code gate/follow-up obligations as `review-gate` or `confidence-gap`; intake counts derive from these types, not words in titles. Include nonselectable items for identity/count reconciliation; only selectable items appear as choices. A confirmed selection is list of numeric selection indexes, not finding IDs. No-selectable uses `[]` without pretending user selected anything. Report identity defaults to its source file path, so different reports may reuse finding IDs. When different files are verified views of same report, give their sources same explicit `report_id`; do not use shared directory as identity. Selection input/output must be distinct files; output symlinks and aliases are rejected before writing. Set `selection.json.presentation_version=3` and add a short, concrete `resolution_proposal` to each selectable item. Inspect `python PLUGIN_ROOT/shared/final_handoff.py selection --help`, then run its `selection` action with `--input <run-directory>/selection.json --out-scope <run-directory>/resolution-scope.md`. Failure blocks the prompt and edits. The helper validates unique item/source/canonical-finding ownership and any declared totals before writing. It renders `# | Severity | Finding | Resolution proposal | Sources`. Sources are derived tags such as `report ×1; online ×2`, counting genuine source records only; never fill the overview with paths
Comments (0)
Sign in to join the conversation.
Reviews (0)
No reviews yet.
No comments yet.