Code Remediate

SkillDev tools

Apply selected review fixes; bare PR targets use current online items, while PR +review adds the latest matching artifact.

Available today. Use it from your connected AI after setup.

Connect ahel once, and every AI you use reads what you have installed.

Then ask your AI: use the Code Remediate skill

What this skill tells your AI

The instructions your AI receives, as published by borda/ai-rig in plugins/codex-rig/skills/code-remediate/SKILL.md and read by ahel’s review.

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 an 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",
  "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)

01: Create Run Directory

Run create_run.py --skill code-remediate per ../../shared/helper-cli-contract.md.

02: Normalize input and optional report findings

Shorthand rules:

  • 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 the 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.
  • 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 a PR target sets REQUESTED_REPORT=true; a 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 a report source selects online-only intake and never falls back to report lookup.
  • If +review, +report, report, latest, latest-report, or review-report replaces a path, find the 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 the same PR number/URL as PR_TARGET.
  • When REQUESTED_REPORT=true, no matching code-review report => fail with direct instruction to run $code-review <target> first or supply report path. A matching-review-unavailable-rerun-code-review result means PR collection failed before any assessed review; do not use it as findings input, and rerun $code-review <target> after resolving the collection failure. 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 the greatest parsed numeric run-<NNN> index. Otherwise select the greatest parsed legacy flat timestamp. Never rely on lexical glob order, modification time, or directory traversal order; record the 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 the 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 an older assessed review remains eligible when a newer collection failure exists. A newer review_status=closed result instead blocks older findings because the close disposition is current and non-remediable. Before accepting an explicit review result path as findings input, invoke the same helper with --result <path>; it rejects unavailable results with the 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.

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 with the exact error and candidate path. 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 the filesystem tool. Do not depend on a 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; collect PR_TARGET into <run-directory>/pr with checkout enabled for current online evidence, target/head refresh, local checkout.

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 the documented local checkout.
  • Credential behavior: gh is an opaque local credential broker.
  • Filesystem and worktree effects: write collection artifacts and may update the 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. The PR request authorizes asking, never bypassing runtime approval.
  • 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 the plugin-wide GitHub data boundary: do not invoke gh outside it.

  • It uses gh as an 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: it uses numbered fork-aware gh pr checkout <number> when needed, verifies the PR head SHA, and derives diff.patch locally.
  • GraphQL review-thread resolution status is supplemental; if unavailable, the 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 a code finding or silently claim complete thread triage.
  • On core collection failure, use <run-directory>/pr/pr-error.txt and <run-directory>/pr/command-failure.json when present to distinguish the classified process failure from source-review findings; do not treat it as a 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: a canonical PR URL must match a configured GitHub remote; a 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:

  • The fallback normalizes limited PR metadata, then uses the verified refs/pull/<number>/head ref for a detached checkout and derives the local diff; it never establishes private PR evidence.
  • online-review-summary.json must list unavailable fallback evidence as sorted IDs.
  • Raw GitHub CLI stderr is never persisted; terminal diagnostics may include a 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 the complete findings source. Do not read or infer a review report, and do not require a prior assessed artifact. If no online item is actionable after triage, continue through the documented none-selectable path instead of requesting code-review.
    • When REQUESTED_REPORT=true, additionally normalize <run-directory>/findings-input.txt. Treat the review report as a 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 authoritative source for code triage/edits and require its verified-local-checkout diff provenance.
    • Require <run-directory>/pr/target-branch.json to prove base/target fetch before conflict/review-item resolution; <run-directory>/pr/pr-head-fetch.json records same-repo PR refresh or cross-repository skip rationale.
    • Checkout artifacts include force_policy; if checkout fails or does not match PR head, record forced-checkout-not-attempted and stop before forced retry.
    • 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.

03: Understand PR Intent, Then Resolve Merge Conflicts

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 a JSON parser and retain the 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 the 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 a gap, never an implied clean result.

Write <run-directory>/merge-prestage.md sections before attempting a 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 the target merely to refresh a 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 the 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 a local merge commit. Show the target ref/OID, intended merge, collision files, resolution strategy, and overwrite/commit effect. Ask for explicit authorization to create the local target-merge commit. Record authorization=explicit-input|user-confirmed; if authorization is absent or the 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 the retained literal ref. Never rebase, force checkout, or rewrite history as a substitute.
  4. Resolve only merge collisions, preserving the recorded PR intent atop the fetched target implementation. Do not combine review-comment fixes unless the same lines cannot otherwise form a coherent merge; record unavoidable coupling in <run-directory>/closure-log.md.
  5. Verify git diff --name-only --diff-filter=U is empty, run the smallest collision-relevant tests, then create the authorized merge commit using ../../shared/commit-response-template.md and the required Co-authored-by: Codex <codex@openai.com> trailer. Record the 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 a report/online-review finding until merge-resolution.json is not-needed or completed, the worktree has no unmerged paths, and no merge is in progress. If merge resolution or its verification fails, stop; do not hide the conflict behind finding remediation.

If checkout starts dirty, conflicted, or partially merged, fail or ask cleanup before editing. Never use an existing conflicted worktree as primary truth.

04: Normalize Findings Before Editing

Structural context (optional): when target_scope names a 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 the available report and/or online findings evidence. Persist the result once here; specialist owners assigned in step 06 receive <run-directory>/codemap-context.json in their context pack, never a fresh query.

Write <run-directory>/action-items.md starting with ## Review Item Resolution Table, before prose. Ingest every available report finding, normalized report-origin review obligation, fetched online PR comment, PR review, review thread, and unresolved review thread as a source record. For bare PR online-only intake, every source record is online; never synthesize a missing report item. Default to one item row per source record. Exact duplicates may share one item row only when they express the same obligation and receive one disposition; grouping never removes provenance. In the initial selection, durable resolution, and final outcome tables, render each contributing source only as report [<report-file>:<line>], report [<report-json>#<finding-id>], or online [<comment|thread|review-id>], preserving source order and joining grouped references with one plain ASCII space. A source cell is a unique pointer only: never add a location, body, evidence path, URL, resolution, or summary. Keep every table compact: cells contain identifiers, short names, statuses, and ordered symbols; put longer summaries, resolution explanations, evidence, and next actions in symbol definitions immediately below each table. If user supplied/requested report, preserve both the report and fresh-online records even when they repeat each other. Table is selectable-findings source; every resolved row needs resolution evidence. Full source details stay in machine metadata and expanded item records: category report|online, stable source ID, source location or general, complete body without truncation, and fetched evidence path or report-only. Never replace source references with counts, representative sources, ellipses, URLs, or artifact-only labels, and never reduce the ledger to changed/selected/unresolved/high-impact rows.

When online-review-summary.json reports pr_metadata_transport=public-https-fallback, list the sorted unavailable_evidence IDs github_provided_file_list, mergeability, review_decision, reviews, and top_level_comments in action-items.md and the online action evidence, and add the 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 the 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.

Shortened here. Read the whole file on GitHub.

Signals

GitHub stars
27
Forks
4
Last commit
Sep 2026
Advanced
Catalog kind
skill
Gateway key
code-remediate
Source
github.com/borda/ai-rig