Intake
For allowed GitHub reads, run the direct collector under current effective network and filesystem grants or request runtime approval for the complete owning command when required capability is unavailable. No separate workflow consent is needed. Apply GitHub Read Execution; runtime permission and denial remain authoritative.
When runtime permissions show network access enabled and the helper's required paths writable, omit sandbox_permissions and justification on the direct helper call; give no approval brief. Apply GitHub Read Execution even when the active profile name is omitted. A missing label or failed lookup does not mean disabled access; do not run codex execpolicy list to detect a profile. Preserve explicit destination restrictions and check report, .git, and checkout paths separately where applicable.
Carry a request to publish alongside the remediation instructions until delivery. If the user asks after delivery, enter the PR worktree publication gate using the promoted remediation run and its verified delivery checkout, including a historically recorded delivery checkout. This route applies regardless of the original --worktree option. A worktree delivery holding a commit the run created enters it automatically after the final handover, so no request is needed. It preserves the completed result and requires user consent for that push and one-time runtime approval.
For a promoted PR result with a verified combined push-and-cleanup offer, resume pending approved worktree cleanup before requiring a live delivery checkout or remote preflight. Use the original run or its verified publication-request checkpoint, including when promotion finished before the cleanup journal was created or Git already removed the worktree. Reacquire the applicable checkout claim from the invoking repository. Let the helper verify the original consent, execution, readback and allocation, then validate the retained result, release the claim and report the disposition. This continuation performs local cleanup only.
For a continuation limited to the same PR run's unfinished local report, inspect its retained delivery evidence before remote preflight. A record of delivered in the original invoking checkout permits local report completion while offline or after the PR has closed or merged, subject to the checks below. For a historical run with recovery-worktree.json and verified delivered status, finish the existing report at the recorded destination. An explicit --worktree run requires its linked delivery and publication evidence. Bind the run, canonical PR and destination to the original invocation. An incomplete delivery requires its lifecycle diagnosis. Fresh intake, source changes and further commits require normal PR State Preflight. When the continuation is limited to completing the local report, use finalize --promote --no-publication-offer at final promotion.
- For the same retained PR
--worktreerun at local report completion, inspectPLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/remediation_finalize.py publication-resume --run <run-directory>before remote preflight. A passing read returns the linked delivery coordinates and the publication disposition. Use itspr_handoff_summarywhen present for the linked PR and actual push status in the publication update. If the continuation records a matching Deny as declined below, use the summary for that final recorded disposition. For in-place delivery, including historical recovery without--worktree, use the retainedworktree-delivery.mdand active PR branch receipt directly. Resume the successful collection’s canonical run. The failed attempt supplies collision evidence only. - Recover checkout ownership before any durable write of this continuation. Inspect
status --slot <retained locator>for each recorded claim. Match the checkout, claim kind and PR target where applicable. For in-place delivery, acquire the writer before the target. For a historical independent recovery use the retained control checkout bound to the original caller and canonical PR, and require the linked destination to share its common directory. If the locator was lost and normal Git inspection is permitted, use checkout-bound status for the recorded claim kind and compare its locator with retained acquisition evidence. For a live claim matching this run's retained acquisition evidence, use checkout-bound acquisition with the original owner ID. Never take an owner ID from slot status alone. If the slot is free or the prior release is confirmed, acquire with a new continuation ID and queue behind any known peer. An inspection hold or an occupied claim whose owner cannot be established from retained evidence follows Review checkout scheduling. Never infer release from the existence of a publication question or the age of a claim. - Under the slot, reverify the destination path and common directory, attached branch, exact HEAD, ancestry from the original PR receipt, observed upstream configuration (including absence) and separately verified PR head destination, operation and writer state, the entire owned path inventory and bytes/type/mode, and unrelated index and worktree state against the frozen delivery evidence. For committed delivery also verify the expected commit tree and absence of owned residue. Missing proof or drift must stop report completion for diagnosis. For historical independent recovery also verify the original caller’s preserved branch, tip and user state against its recorded baseline. After verified in-place delivery finish only the existing report and release the slot after all writers stop. Never recollect, replay a transfer, edit source, commit, offer publication or contact GitHub on this route.
- Only for an explicit
--worktreeinvocation, reread the publication checkpoint under the slot before using it. Ifneeds_terminal_recordis true, writepublication.jsonthrough a temporary file in the run directory renamed into place, so a crash never leaves a partial record, with exactlyschema_version,status,reasonandobserved_oidfrom the returned disposition, never copying itsevidenceorevidence_sha256fields or its readback digest. Averifieddisposition binds the recorded successful transport and exact audited readback to the consumed offer. Use its returnedobserved_oid. A returnedskippeddisposition covers interruption before or during the optional question without a consumed attempt, and an approved attempt that ended while no execution marker (publication-executed) existed, so nothing was sent. When no approval was consumed andpublication-answer.jsonholds aDenybound to this run's offer (itsoffer_digestis the SHA-256 ofpublication-offer.jsonand itsdecision_idispr-worktree-publication-<that digest>), writestatusdeclinedwith a reason citing that recorded answer instead, so a recorded Deny is reported asdeclined;publication-resumestill returnsskipped, and this continuation applies that change itself. A missing or unbound answer record, or a recorded Approve with no consumed attempt, keeps the returnedskippeddisposition and never authorizes a push. Only an answer interrupted before its record was written still resumes asskipped; no push can have happened without a consumed attempt and its execution marker. Then finish only the existing local handoff using that disposition. This limited continuation does not require a remote state read and cannot offer, authorize, or execute another publication attempt, recollect, edit source or create a commit. It never runs the publication helper, not even the gate's single retry after anot-sentrefusal, which belongs only to the invocation that saw the refusal. Apublication.jsonthat is not a valid record while nothing was sent (no consumed attempt, or no execution marker) is rewritten by this continuation as the sameskippedterminal record, or as thedeclinedrecord for a recorded Deny. If the delivery or publication evidence is otherwise invalid or local verification detects drift, diagnose that retained checkpoint without replaying delivery or publication. Release the slot after all handoff writers stop.
For ordinary entry, before creating a run, normalize only the target and apply PR State Preflight for PR scope, including ordinary resumed PR work, bare PRs, +review and explicit PR report-backed requests. Use the retained canonical PR URL on resume. Stop immediately for a currently closed or merged PR before prior-report lookup or validation, a missing-review question, collector access, run creation or other dependent work. Preserve existing artifacts and local work. The metadata reader owns entry permissions and classified failures. Local report-only intake remains network-free.
For resumed source drift before worktree delivery, apply the preflight's guarded-pull exception and Source drift recovery before requiring the remote state read. Locate and verify the original PR branch's current checkout, acquire or retain its writer and PR target claims before the permitted fast-forward-only pull, then finish PR State Preflight before resuming intake or fixes. A moved HEAD or metadata approval timeout alone does not justify asking for another message instead of attempting that recovery.
Resolve the metadata reader's profile-or-approval route before the first read, and finish permitted reader permission recovery before reporting entry blocked. Use GitHub Read Execution to distinguish missing capability from an actual denial, then continue this same remediation after a successful state check.
01: Create Run Directory¶
For a new in-place PR remediation following a review, including a requested nested +review, keep the run’s own reports outside the source before the first write to preserve the reviewed execution inputs. An explicit --sandbox selects confinement immediately and can use the normal report location. Run PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/review_code_safety.py report-root --checkout <original invoking checkout> --pr-url <canonical PR URL>. The helper selects the existing checkout’s Git administration directory when it can verify reverse worktree registration. For a separate Git directory or submodule without that registration, it returns the checkout’s .reports/codex; inspect executable inputs when these in-tree reports change the reviewed source fingerprint. Pass its printed absolute path as create_run.py --root for allocation and promotion, and retain it for nested evidence and resumption. If this invocation allocated an in-place run from a remembered Git report directory without verifying its root, run the same report-root check for the original checkout and canonical PR. On a match, restore the applicable claims and continue the allocated run at its first unmet checkpoint. Resolve a mismatch before dependent work. Use the installed run-creation helper named below. Source collection, edits and delivery still use the ordinary in-place checkout. If that report root is unavailable, preserve the normal in-tree allocation and inspect the current command inputs. Resume a pre-existing run at its retained location.
Before allocation, follow Review checkout scheduling. For in-place PR remediation, run PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/review_checkout_slot.py acquire --checkout <invoking checkout> --writer --owner <invocation ID> --queue first. Run PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/review_checkout_slot.py acquire --checkout <invoking checkout> --target <canonical PR URL> --owner <invocation ID> --queue for both delivery modes. Retain each locator separately. Keep the in-place writer claim through delivery and release it by its own locator after quiescence. A nested review shares the enclosing claims.
Treat --worktree as a PR remediation option, independent of the target and findings selection. Resolve the canonical PR in the invoking checkout before changing directories. Keep discovery, run creation and promotion rooted in the invoking checkout, including when the collector runs elsewhere. A local report without a PR identity cannot select a contributor branch with this option.
After entry admits an OPEN PR, or for local mode=report scope (report-backed or supplied findings), run create_run.py --skill code-remediate --pr-number <resolved-pr-number> for PR scope, using the already resolved entry identity. Local report-only scope uses --branch <branch-name> from local Git identity, or detached-<commit-id> for detached HEAD. Follow ../../../shared/helper-cli-contract.md; naming makes no additional network read, and resume reuses its existing run. Immediately after allocation, and again on resume, run PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/remediation_finalize.py start --run <run-directory> so a run that stops before promotion still leaves its incomplete run-state.json stub; it never replaces a promoted result.json. After PR or local source collection succeeds, run the same action with --checkpoint source-collected. Passing the respective preflight stages advances the stub to selection and plan. Appending a closure-log.md record for a selected bucket advances the stub to implementation.
02: Normalize input and optional report findings¶
+review joins review with remediation and authorizes the needed review step for the same target: reuse current eligible evidence, update a recoverable stale review, or create a fresh review when needed, then resume remediation. Carry this authorization into the owning Code Review entry decision without another review-choice question; preserve actual runtime, paid-execution, independence and retry boundaries. +report, report aliases and explicit report paths request existing evidence only; they do not independently authorize new review work. Remediation remains the primary goal. Before a nested review retries missing dependencies, the remediation parent prepares its complete declared test environment under Project Dependency Preparation, including before finding selection; the read-only child retains its own boundaries. When requested PR review evidence is missing or incomplete, apply Missing requested PR review decision below: use the original invocation to determine whether it permits a nested review. With existing evidence only, continue available findings only after explicit user confirmation. Disclose the requested review evidence as unavailable without manufacturing a finding. Retain the report request and exact diagnostic. Preflight success and direct-check receipts remain preliminary evidence; never convert applicable gate failures to not-applicable, invent provenance, or skip source-freshness checks. Before selection, completing requested review evidence is a primary prerequisite under the authorization above. After selection, auxiliary producer bookkeeping cannot displace an established authorized fix and its regression; follow the bounded recovery conditions below.
Shorthand rules:
$code-remediate 123=>mode=pr,PR_TARGET=123,REQUESTED_REPORT=false. Existing explicit report aliases remain report-backed. Reject unsupported flags before collection. Continue normal remediation 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 this completed-report lookup withcurrent-session-review-report-required; retain the exact known run when present and apply preliminary finding intake below. Do not infer a PR or start a review. If no independently usable finding evidence exists, ask only for the missing finding evidence or selection, such as an existing report path or a concrete finding and source target. - 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>selects recovery work, not a terminal outcome. The identified review has no result or candidate yet; it may retain only a PR target, collectedpr.json, or notes. Record the diagnostic and retained run in the remediation run, then take the applicable action now:- For an explicit
+reviewin this remediation invocation, including its retained invocation on resume, read Report compatibility and recovery and execute Code Review at the first unmet checkpoint. Inspect source bindings, original reviewer evidence and checks; reuse authenticated evidence and perform missing, stale or unverifiable work through the current producer. An old failed validation is evidence to recheck, not a new denial. When reviewer validation is the missing checkpoint, read Reviewer validation recovery and attempt its permitted recovery. Complete the producer's validators, promotion and--complete-run; admit that exact result and continue this remediation through selection, fixes and verification. Reading notes, acknowledging authorization and naming these steps do not execute them. Do not send a final response while one of these authorized actions is available, even when the advisory Stop hook is unavailable or untrusted. - For existing-only
+report, report aliases or explicit report paths, apply Missing requested PR review decision and ask its native question when needed. For an actual denied capability, unverified source, exhausted recovery or missing decision, identify the concrete boundary and ask only the required question; retain all protections and still-permitted independent work. Never substitute a hidden request to resume for that question. - Continuing without a completed report still requires the user's explicit choice; only then use current-online/user findings and eligible preliminary hypotheses through normal selection and source validation, with the missing report limitation explicit. Do not claim no review was performed, consume notes as a validated result, or select an older verdict. These rules apply across sessions. A newer candidate or malformed result with damaged PR identity also 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. Collect current online comments, reviews and threads even when the assessed report matches the PR head. Reconcile newly raised or edited concerns against the verified source before presenting the selection inventory. 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 eligible report roots for canonicalcode-review/pr-<number>/run-<NNN>/result.jsonand legacy flatcode-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; for PR intake, apply Missing requested PR review decision below before continuing, even when usable findings exist. 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; fresh PR collection still follows this skill's current-source gates. Only this remediation invocation’s explicit+reviewpermits a fresh review. 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 read-only diagnosis below followed by the same decision; do not fall back to an older assessed report. Current-session report and local explicit-report intake retain their separate preliminary boundaries. - Within each root, 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 PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/find-review-report.py --help, run it with --target <canonical PR URL> from the original invoking checkout, and assign its printed path to FINDINGS_SOURCE. The helper searches explicit canonical nested PR runs plus legacy flat timestamped runs; no migration is required. Lookup compares reviews in the checkout’s Git administration directory, its local report tree and its verified historical private workspaces by allocation time. Preserve historical precedence. A historical numbered review with no retained allocation time cannot settle a comparison with another producer. Report the ambiguous dates and preserve both runs. It filters explicit review_status=unavailable diagnostics, so an older current schema-3 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, candidate paths with matching-review-candidate-unpromoted:<path>, schema-2 archives with historical-review-unverified-archive, and any assessed PR result superseded by a newer run. Use --archive-result <path> only to locate schema-2 or schema-3 historical data for reading; its explicitly unverified JSON status is never findings input. 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. The helper defaults to the report's recorded producer thread, including across sessions; an explicit --parent-thread-id override remains authoritative. Use --codex-home only for the actual retained rollout root when needed. These identify evidence for validation, never waive it. Missing or invalid evidence stops completed-report admission; retain the validation diagnostic without falling back to an older report. Continue independently usable findings under preliminary finding intake; incomplete report proof remains open. PR-only automatic discovery remains unchanged.
Before treating any lookup, validation or selection-preflight failure as a missing review, apply Report compatibility and recovery. Assess actual retained evidence, not the version number alone; a helper diagnostic code containing rerun-code-review describes the diagnostic and supplies no dispatch authority. Automatically repair deterministic consumer-owned inventory or presentation from verified evidence; leave producer-owned records intact. Only a joined +review resumes Code Review for producer-owned derived repairs. Preserve original evidence and rerun the failed consumer check. A package reader that rejects its own documented supported presentation is a consumer defect, not proof the review needs rerunning; repair the authorized package source and verify its next consumer, or report the exact installation capability needed. Never modify installed package files outside task authority.
For matching-review-candidate-unpromoted:<path>, the review run belongs to code-review: remediation never directly repairs, rewrites, rerenders, or promotes its specialist-manifest.json, result.candidate.json, or result.json. Run the review-specific validator, then the shared validator, read-only against that exact candidate and its review run directory, and persist each exact stdout/stderr code in <run-directory>/review-candidate-validation.txt, including manifest-invalid-attempt-count:<role> when applicable. A passing read-only validation does not admit the candidate either; only code-review's own finalize step promotes it. Resume that owning producer automatically only for an explicit +review when the compatibility assessment proves a deterministic repair or unfinished finalization is sufficient; do not ask the user to re-run code-review for an agent-owned bookkeeping failure. Never consume result.candidate.json as a completed review; only its eligible finding records may be considered under preliminary finding intake below. Never invent missing attempt provenance, retry a specialist for artifact bookkeeping, rerun the full review without the explicit authorization below, or fall back to an older assessed report. If substantive evidence is still missing after feasible automatic recovery, apply Missing requested PR review decision before continuation. For requested PR evidence, continue source-verified remediation with the report limitation disclosed only after the user explicitly chooses to continue without a completed report. Disclose any missing independent coverage as a limitation. This check has no waiting loop and makes no remote mutation.
Missing requested PR review decision¶
Only when
mode=prandREQUESTED_REPORT=truehas no eligible completed report (including+review,+report, report aliases and explicit PR report paths), read missing-review-decision.md and apply it before continuation, even when usable findings exist; every Missing requested PR review decision pointer in this skill means this reference. Bare PR online-only intake, current-sessionreviewand local report intake do not load it. Joined+reviewreuses its already authorized review step through that reference rather than asking for the same permission again. Use its existing-evidence choices for report-only requests and its producer recovery choices only for joined review.
Review evidence freshness¶
When remediation follows a completed review, retain its canonical result path and the producer’s trusted result digest when available. This applies to a natural-language follow-up or a bare PR following that review in the same session. If the user refers to a prior review without a path, resolve that review from the original checkout using the existing matching-report finder. This evidence selects the execution policy only. Keep the requested findings source and scope. Forward an explicit --sandbox immediately without requiring a safe result. Otherwise check the admitted review against the current PR, head, base and execution checkout using Contributed Code Execution. A missing or stale safety assessment calls for inspection of the command and the code it can load. The remediation parent can do that inspection directly.
After collecting verified source and before selecting findings, apply the same freshness assessment to saved reports and online review comments. Compare the report's reviewed head, online review/comment commit identifiers and thread isOutdated evidence with the current verified head where available; fetch time does not establish review freshness. Record older source as stale and missing revision evidence as unknown, never silently current. An older finding may still be valid: freshness alone neither proves nor disproves the claim, and every selected claim must be checked against current source.
For bare PR online-only remediation, stale or unknown comment provenance remains a disclosed evidence limit, not a new permission question. Inspect each claim against the verified current source, retain its original provenance and actual disposition, then continue normal finding selection and fixes. Do not start or offer an additional review solely because comments predate the head; the requested current-source triage is already authorized. A concrete ambiguity that prevents establishing the requested change may still require the user's decision.
For existing-only reports, preserve the reviewed SHA and disclose stale or unknown freshness. Check each claim against current source. Use the existing-evidence decision in missing-review-decision.md if the requested report cannot be admitted. A bare PR stays online-only throughout.
Only an explicit +review in this remediation invocation authorizes updating or creating a review. Reuse current evidence or run the needed review for the same target, and do not ask again for that authorization. Preserve prior evidence, retain online evidence and admit the exact returned canonical result through missing-review-decision.md. A local reassessment references the original comment; never edit or post GitHub comments. A fresh review still requires the producer’s full artifact and provenance gates.
Preliminary finding intake¶
An unfinished report is not a validated review, but a concrete finding can still be checked against source. Requested PR evidence first follows Missing requested PR review decision, which requires an explicit continue choice before preliminary findings stand in for the requested completed PR report. Use retained canonical finding records only with matching exact PR identity, head, scope, and source evidence; triage each claim against the freshly verified current source before accepting it. Reuse the existing action-item inventory, scope selection, and workplan; preserve the original record ID/body/evidence path and its preliminary status in action-items.md and resolution-scope.md. Treat a current user-supplied finding similarly. Markdown notes without canonical records remain hypotheses requiring concrete finding and source evidence, not a completed report or authority to fix an unverified claim.
- Keep completed-report lookup and its validators unchanged; never present preliminary records as a validated review result, infer specialist authors/ratings, promote a candidate without proof, or substitute an older verdict.
- Selection, source checkout, target integration, and merge authorization gates still apply. Only selected source-confirmed findings may be implemented; missing report evidence does not authorize unselected edits.
- Preserve requested-report intent and missing coverage in the existing notes and unresolved evidence. Do not manufacture an assessed JSON report, silently clear
REQUESTED_REPORT, or claim complete report-origin inventory when the producer has not established it. Use the admission contract below to retain actual fixed work and the explicit review limitation; completed-report admission still requires its genuine original input. - Preserve any required post-fix independent review and applicable gates; do not certify unreviewed fixes as clean. Report actual fixes and actual verification separately from missing producer proof, failed gates, or unfulfilled review coverage. A post-fix implementation challenge that cannot run follows step 08: a limitation and confidence gap, never a blocker.
- If no finding can be identified and source-confirmed, ask only for the missing finding evidence or selection. Do not make the user choose reviewer routes, repartition contexts, or debug agent setup.
Report admission and supplied findings¶
New CODE_REMEDIATE_METADATA.review_report_intake writes use schema_version=2 and admission_status=completed|preliminary|unavailable; keep requested_report=true whenever review evidence was requested. Historical missing admission fields mean completed and retain the original strict report coverage.
| Admission | Retained input | Remediation result |
|---|---|---|
completed |
Exact validated report in findings-input.txt; full source-finding coverage and separate review context. |
Normal closure and verification rules. |
preliminary |
Byte-exact original structured canonical records in findings-input.txt, original pr.json, and current-source match. Plain notes do not qualify. |
Report actual selected fixes and checks; disclose unavailable completed-report proof as a limitation, never a synthetic finding. |
unavailable |
Actual lookup/validation diagnostic; available current-online or user-supplied findings. No report-origin sources. | Report actual selected fixes and checks separately from the missing report limitation. |
For either noncompleted state, set admission_evidence with run-relative diagnostic_path, its byte SHA-256 diagnostic_sha256, byte SHA-256 selection_sha256 of frozen selection.json, and limitation containing the exact corresponding metadata.confidence_gaps entry. Do not add open_item_id or invent a work item. Historical admission schema 1 retains its original open-item and failed-result requirements. In PR mode, also bind the exact canonical current pr_url, head_oid, base_oid from pr/pr-routing.json. Keep selected source-work status separate from missing requested proof; that proof remains unavailable even when the actual fix is complete. On authorized available-finding continuation, do not ask the user again to select reviewer bookkeeping or start a review merely to represent the partial result. Existing source, selection, workplan, inventory, gate, and commit validators still apply.
For local mode=report with unavailable requested evidence, use admission_status=unavailable. Before selection or edits, capture the actual source destination with PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/collect_diff.py --snapshot --repository <actual-source> --scope-path <selected-source-path> --out <run-directory>/local-source/source-snapshot.json, repeating --scope-path for each source scope. In that destination, collect the ordinary diff pack with PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/collect_diff.py --out <run-directory>/local-source; do not create a review worktree. Set admission_evidence.local_source and the identical frozen selection.json.local_source to run-relative snapshot_path, byte snapshot_sha256, run-relative diff_path, byte diff_sha256, and the snapshot's exact repository, revision, and scope_paths. Preserve this pre-edit snapshot after intended fixes; ordinary closure and gate receipts prove the resulting work separately. Do not invent PR identity for local remediation. Local preliminary report-origin admission is unsupported without matching original source proof; use unavailable intake with source-confirmed supplied findings instead.
For preliminary, additionally retain run-relative original_pr_path, its byte SHA-256 original_pr_sha256, and SHA-256 original_input_sha256 of findings-input.txt. Original PR URL/base/head and review_input_sha256 must match the canonical current PR diff. Preserve every enriched finding's ID, severity, title, summary, required change, evidence, closure evidence, and declared authors losslessly; these declarations are preliminary, not independently authenticated assessments. Do not manufacture JSON from plain notes to satisfy this path; use unavailable and directly source-confirmed online/user findings instead.
For supplied findings, retain the complete actual request in a run-local evidence file and use the existing per-source fields with kind=user, stable local source_id=user-<input-key>#finding-<positive-ordinal>, exact location or general, complete body, and run-relative evidence. This is a local finding identity, not a claimed runtime message ID. Preserve separate user/report/online sources and derived counts/tags; never disguise user text as GitHub evidence or a completed report. The final consumer requires each full supplied body in its retained evidence file. For new handoffs, user sources use remediation selection presentation_version=5 and final handoff presentation_version=15; historical selection versions 2/3/4 and handoff versions 2/3/5/6 retain their original source kinds and rendering. Other workflows retain their own presentation versions.
When a validated FINDINGS_SOURCE file 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 completed report intake, retain the admitted canonical result path as review_report_intake.admission_evidence.producer_result_path, especially when the copied result's artifact_path is relative to its original run. When ordinary admission used explicit evidence coordinates, also retain producer_codex_home and producer_parent_thread_id in that same evidence map. Without an explicit thread, producer validation derives the original manifest thread for every assessed scope; the consuming session cannot substitute for it. The selected evidence home remains necessary when native rollout proof is outside the default home; wrong coordinates, missing logs and invalid proof still reject. Current validation compares the copy byte-for-byte with that producer and revalidates its promotion, source/provenance and completion through the existing report finder. A resolvable original artifact_path remains compatible; never resolve a producer-relative basename inside the consumer or convert a copied candidate into completed evidence. Missing or rejected producer proof uses the existing preliminary/unavailable route and preserves the factual report limitation. These checks do not require the reviewed head to equal an advanced remediation head: current-source revalidation remains separate.
For mode=pr, inspect PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/collect_pr.py --help. Keep PR_TARGET for report lookup; for a numeric PR target, first run local PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/select-git-remote.py --canonical-pr-url <positive-number> --cwd <source-repository> and set COLLECTION_TARGET to its canonical URL for valid GitHub origin, or the sole GitHub remote when origin is absent. Stop only if no safe default identity exists; do not launch a numeric-target collector. A user-supplied canonical PR URL takes precedence as COLLECTION_TARGET and must match a configured remote. Collect COLLECTION_TARGET into <run-directory>/pr with --checkout --checkout-mode remediate. 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; for a fork, follow Source recovery to diagnose the checkout and preserve local commits.
Choose the working directory for this same collector command before executing it:
- By default, use the original invoking checkout. Preserve the collector's dirty-path and branch-ownership checks. If another linked checkout owns the PR branch, use attached-worktree recovery before requesting intervention, including after an unclassified checkout failure. For a verified fork branch collision with local-only commits, present the local/remote comparison and user-owned branch cleanup options in Source recovery. An explicit original-checkout-only requirement takes precedence.
- With
--worktree, after run creation and before collection, runPLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/remediation_branch.py worktree --receipt <absolute-run-directory>/remediation-worktree.jsonfrom the invoking checkout. Use its absoluteworktreepath as the collector's working directory and absolute<run-directory>/pras its output. Pass the canonical PR URL already bound by preflight in the invoking checkout, including for a current-branch target. The helper creates a detached linked Git worktree; the collector then runs nativegh pr checkoutthere. Keep both paths. Resume an existing collected run from the recorded source and verify the existing branch receipt. If worktree allocation was interrupted before native checkout, rerun the same helper from the invoking checkout with the original locator after diagnosing the interruption. It reuses the verified detached checkout or retries the exact reserved path once when still vacant. On an attached branch, use the retained collector and branch receipts to prepare or check the verified PR source at its recorded revision. Preserve ambiguous state and never restart checkout over local fixes. Never replace an occupied branch, detach another worktree, create a clone, or change tracking to get past a checkout failure.
At collection, before any PR code executes, retain the verified head/base repository identity, exact base branch name, collected base and PR head OIDs, and pristine checkout receipt digest in parent context. Apply Contributed Code Execution throughout selection, nested review, implementation, gates and resume, including forks. Use authenticated, still-current review evidence when available. Otherwise inspect the exact command and its current inputs before ordinary execution. Preserve the origin and source checks required by the collector. Retain an explicit --sandbox, active protected intervals and existing integrity stops across a fallback.
After successful PR collection for a newly created run, invoke PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/create_run.py --skill code-remediate --promote-pr-run <run-directory> per the helper contract. It reads the collected <run-directory>/pr/pr.json and moves the complete run into code-remediate/pr-<number>/run-<NNN>/ under the root selected at allocation. Capture its single printed final path and use it for every subsequent artifact and command, before creating branch receipts, selection, dispatch or result bindings. Never construct the PR number or run index yourself. Local report-only runs and collection failures keep their timestamp paths; resumed runs retain their existing paths and are never promoted again.
On resume, inspect <run-directory>/worktree-delivery.md first when present. A partial handoff requires diagnosis; a verified delivered run resumes report-only under Worktree lifecycle, and further source edits or commits require a new normal run. The following source-receipt route applies only before delivery begins. 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.
Apply PR Collection Runtime Boundary before collector execution. Do not create or modify runtime approval rules files.
Run the direct owning collector per GitHub Read Execution. Its nested GitHub CLI, HTTPS fallback, checkout, and Git fetch traffic remain bound by the collector contract. An explicit runtime denial or non-overridable restriction stops the collection attempt; diagnose the active permissions and exact command without broadening access or retrying the denied command. Apply the existing core collection-failure path.
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 source repository 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 until the verified same-repository branch route succeeds or native fork checkout succeeds in the verified branch owner, after the user frees a divergent branch name, or after an explicitly requested bounded recovery loop resolves the verified obstacle. - After binding PR identity, the remediation collector overlaps the supplemental GraphQL review-thread request with its verified Git fetch and checkout. A bounded request worker reads threads. The collector owns Git and all evidence writes, then joins the request before returning, including on checkout failure. If thread status is unavailable, the 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 a configured GitHub remote; a numeric target is bound to valid GitHub
origin, or the sole GitHub remote whenoriginis absent.
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; use the verified same-repository original-branch route or follow Source recovery for branch comparison, user-owned local cleanup or an explicitly requested fork recovery loop. 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; if admission is unavailable, only source-confirmed findings from the explicitly identified report or user-supplied evidence may proceed under preliminary finding intake. 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=trueand a completed report has been admitted, additionally normalize<run-directory>/findings-input.txt. When admission is unavailable, continue the preliminary/current-online/user intake above only after the required missing-review decision, and retain the factual report limitation; do not pretend its entire inventory is known. Normalize source findings into action items. Retain failedchecks_failed,follow_up,review_decision.required_next_work, confidence gaps, confidence-recovery remaining limits and no-finding residual risks as exact review context; only a verified source defect or genuine project-required check becomes work. - 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. Keep the immutable target ID intarget-branch.json.remote_refas the collection-time capture. At integration, refresh the live target and compare its OID from the verified PR checkout. - 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 fetch-source repository identity; native tracking setup performed by the authorized direct checkout is allowed, but manual tracking repair is not. When a verified fork branch has local commits, show the difference and guide the user through trying a safe local deletion after preserving the tip. Retain the matching review. Resume native checkout after the user resolves a branch collision. Other fork repairs require an explicitly requested bounded recovery loop followed by a successful native checkout. Any detached, wrong-branch, wrong-head, unverified source identity, 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 at Report discussion after deferred source recovery 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.
Versioned review candidate intake¶
- For review reports with
finding_records_version=2, require the producer completion validator supportingreview_validation.schema_version=1andsource_rating_version=2(historical reports may carrysource_rating_version=1); an incompatible reader stops only dependent admission while Report compatibility and recovery diagnoses the missing capability and uses an authorized compatible reader or package-source repair. Do not prescribe a review rerun for the version alone; substantive missing evidence determines that choice. - Only confirmed
review_findingsauthorize defect fixes. - Retain open candidate IDs, exact missing prerequisites, owners, next checks and closure conditions as evidence obligations; unverified or pending concerns are not automatic edit requests.
- Preserve applicable authoritative retained evidence if fresh retrieval fails.
- Unavailable or inconclusive evidence does not refute a defect; if binding is invalid, retain an unverified obligation.
- New ratings use 1 Approve, 2 Minor changes, 3 Major revision, 4 Insufficient but a good initiative, 5 Block or explicit null for a completed undecidable assessment.
- Historical absent-family reports keep 4 insufficient evidence and 5 block/reject; never reinterpret old 4.
Collection failure recovery¶
Only on a PR collection failure, a deferred source recovery, source drift, or a schema-1 legacy receipt, read source-recovery.md before diagnosing or retrying; successful collection does not load it. The reference holds Collection failure recovery, Report discussion after deferred source recovery, Source drift recovery, and Legacy receipt recovery.