Completion
11: Write And Validate Result Artifact¶
For terminal remediation finalization, before rendering the handoff, record final-handoff.json.commit_disposition with exactly status, reason, and evidence as defined in ../../../shared/final-handoff-contract.md. This checkpoint applies to successful, partial, blocked, resumed, and no-change runs reaching terminal remediation finalization; the interim report-discussion checkpoint remains paused before source preparation. A summary must never silently omit the commit decision.
Include the observed local branch and absolute checkout path in the disposition reason, following ../../../shared/final-handoff-code-remediate.md. The finalizer derives a clickable source-checkout artifact from the active branch receipt; it does not infer current Git status or remote publication. If the invoking checkout differs, name its path, branch and separately inspected staged/unstaged/untracked state so a clean remediation worktree cannot be mistaken for a clean invoking checkout.
- Failed required checks, a failed/timeout result, incomplete required closure, or unproven ownership/destination: use
blocked; state why changes remain unstaged, the next owner/action, the actual gate/closure/ownership evidence, and the controlling rule in this section. A solecommon:refsstop follows the verified target-branch fast-forward procedure. Eligible ignored-file drift follows Restart after inspected integrity drift before reconsidering a retained commit decision. Do not ask for commit authorization while blocked. An explicit local commit request uses the local snapshot exception below; reassess the recorded evidence instead of repeating a prior refusal. A bounded implementation challenge that could not run is none of these and never makes the dispositionblockedor needs that exception: ordinary readiness applies, and the plan and commit message disclose it underResidual limits:. - Explicit local snapshot exception: an actual user request such as
commit this, or an answeredall at once,group findings by topic, oreach finding as a separate commitchoice bound to this scope, authorizes a local snapshot even with failed canonical checks, timeouts, unavailable environment checks, missing independent review, incomplete fixes or a known regression. Inspect the actual request; a standing grant, default/preselected grouping, plan prose or silence alone does not invoke this exception. Do not downgrade a recorded commit-mode choice to a grouping preference or ask for the same authorization again. Record the exact request, owned paths, destination and grouping under## Explicit Commit Requestincommit-plan.md; retain every failed check and unresolved finding with evidence, owner and next action under## Remaining Verification, inunresolved.txtand in the commit message'sResidual limits:. Keep the resultfailortimeout, preserve raw gate evidence and classify the real cause; never relabel a source regression as environment failure or claim remediation complete merely because it was committed. This exception covers verification readiness only: disputed ownership, ambiguous destination, a later decline/deferred decision, runtime denial, hook failure and open security/critical findings still block the affected mutation. Do not bypass hooks or change history to satisfy it. A generic failed gate is not a valid refusal of an otherwise authorized snapshot. State any actual remaining blocker and its controlling rule. - When this run created a verified target merge and there are no finding edits to commit, record the existing merge as
committedwith its commit and two-parent integration proof. Record the existing integration commit, exact parent commits, reviewed paths, destination and checks incommit-plan.md; preserve the chosen finding-commit disposition separately when applicable. Keep implemented findings at zero. Continue to the publication gate for a qualifying worktree. - No remediation-owned tracked or untracked change or run-created commit: use
not-applicablewith closure evidence; do not manufacture a commit plan or question. Existing tracked or new changes with disputed ownership areblocked, not a no-change result. - Eligible changes: write
<run-directory>/commit-plan.mdnow, listing exact remediation-owned paths and mapping each to its selected finding and work-bucket topic. For ordinary readiness, include resolved work; an explicit local snapshot includes all authorized owned edits, additions and deletions in the bound scope, including incomplete fixes and new untracked files. Never omit new files or unresolved work merely to satisfy the ordinary resolved-path filter. Record exclusions, destination, current verification, and any existing bound answer. Explicit user-deferred work outside this plan may remain nonblocking under the shared commit-disposition contract; record the matching deferment and excluded paths, never relabel required unresolved work as deferred. If an explicit sequencing override already completed the commit, preserve its hashes andcommitteddisposition; otherwise usependinguntil the optional commit is completed or declined; identify an already-authorized commit still awaiting execution accurately rather than asking again. - An explicit matching leave-unstaged answer: use
declined, cite that answer in the existing decision record, and leave changes unstaged. Silence or unavailable input is not a decline.
Follow ../../../shared/helper-cli-contract.md and authoritative help. Write CODE_REMEDIATE_METADATA and validate the code-remediate candidate. Do not promote or emit terminal output yet: continue to step 12, including after blocked or partial remediation. This continuation takes precedence over the shared handoff's ordinary promote-and-output sequence.
Before writing confidence, run PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/run_gap_records.py prepare --run <run-directory>. For each GAP_KNOWN_LIMIT= whose absence the current evidence confirms, use the exact reason and record the gap once as (-0.00) <id>: <reason> (known limit) with an unresolved closure. Omit limits whose absence the current evidence no longer shows. If the file is ignored, deduct and name each hardware gap once.
First render the durable ledger from the status events with remediation_finalize.py ledger. When a work-bucket plan exists, also run remediation_finalize.py workplan with the metadata draft; that action reuses the recorded Ineligibility reason when --ineligibility-reason is omitted. For none-selectable, skip the workplan action and do not invent a bucket plan. Item outcomes are judgement recorded as events, not copied into the metadata draft by hand. Finalize with one command. Inspect PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/remediation_finalize.py finalize --help, write a metadata draft and a final-handoff.json draft containing only judgement fields, and run finalize without --promote. It derives every copied field listed in the helper's help, renders final.md, writes result.candidate.json through write-result.py, and runs validate-artifacts.py --all-errors, returning one JSON summary. Judgement fields are item outcomes, closure evidence, confidence gaps and closures, unresolved summary, out-of-scope confirmation, report intake, parallel eligibility, and the handoff outcome, remaining work, next steps, and commit_disposition. Never hand-copy a derived field. This includes triage_status_counts and resolution_status_counts: the finalizer derives their complete zero-inclusive dictionaries from folded final item rows and refreshes the durable resolution table, source records and numeric completeness section before validation. Keep authored explanations in the summary or intake sections. When the summary fails, repair every listed error in one round from its hint, then rerun finalize; do not rerun the validator after each single fix. When validating outside this helper, use validate-artifacts.py --all-errors. If the same error code remains after its repair, diagnose its cause through Automatic presentation recovery before another attempt. A formatting-only complaint is advisory to source readiness: repair owned derived output automatically and continue authorized remediation without a new user decision. A reader rejecting its own supported contract needs a reproduced consumer fix, not altered provenance or a rerun of completed source work. Follow Actionable Pauses only for a concrete unresolved structural, factual, verification or authority boundary affecting the next operation; preserve the candidate until validation passes and name the exact remaining repair or capability. Never repeat an unchanged failing command, bypass validation, or end silently. finalize never answers a user question or runtime approval: it copies only answers already recorded, and --promote renames only a validated candidate.
CODE_REMEDIATE_METADATA records:
- normalized
mode confidence_gaps,confidence_recovery: initial/final score, status, evidence, recovery actions, remaining limitsconfidence_gap_closures: oneclosed|unresolved|deferredclosure with evidence/rationale per non-empty confidence gapresolution_scope: requested scope,selection_source, prompt,selection_confirmed_by_user, selected indexes/severity groups, deferred indexes, omitted resolved-online countresolution_workplan:groups_total, ownership counts,unassigned_selected_items, five-item cap, execution mode, parallel eligibility,parallel_approval_status, exact bucket membership/owned paths, workplan path, and path/SHA-256/status of reconciled production lifecycle when completed parallel specialists are claimedreview_report_intake: schema version, admission state/evidence, requested-report and report/review-gate counts, includingreport_items_marked_out_of_scopefinal_resolution_table: ordered per-item machine ledger, ingested/final/omitted/selectability counts, source records and grouped-item counts, required columns, triage/resolution countsout_of_scope_confirmation: count,all_confirmed_by_user, and each item id/source/rationale/evidence path/confirmationpr_relevance: evaluation,connected_items_marked_out_of_scope, andconnected_required_followup_totalplus connected open/selectable countsunresolved_summary: selected/closure-class counts,all_local_actionable_items_closed, and reason/count/owner/next-action/evidence groupsmerge_resolution: merge artifact path, conflict decision, status, and authorization
For mode=pr, also include selected PR target plus pr-routing.json, target-branch.json, local-checkout.json, merge-resolution.json, and merge-prestage.md paths under run directory.
12: Offer An Opt-In Commit After Verified Remediation¶
An explicit user request to commit may invoke this step before final report validation. Do not wait solely for final report validation: finish applicable source/quality checks, prove the exact owned paths and destination, prepare commit-plan.md, and use the shared commit execution and post-commit proof below. Run and report required checks and retain their evidence. Ordinary readiness requires passing checks; an explicit local snapshot may proceed with failed verification under step 11. The ordinary readiness and explicit local snapshot rules in step 11 still apply; ownership, destination and runtime restrictions remain binding. Record the request under ## Explicit Commit Request and the unfinished report checkpoint under ## Remaining Report Checkpoint; do not mislabel pending report assembly as missing source verification. A local Git approval grant or an upfront grouping preference alone retains the normal sequence. After the requested commit, resume step 11 with the actual hashes and committed disposition, finish validation/promotion, and report the remaining limits. A new explicit request bound to the unchanged plan supersedes an earlier decision to wait without another consent question; an ambiguous request still needs its missing scope.
When the schema-3 lifecycle has delivered worker-owned topic commits, record the exact ordered integrated commit IDs, topic ownership, destination and gate evidence in commit-plan.md. The finalizer derives committed, the ordered integrated commit IDs and the evidence link directly from the digest-bound completed lifecycle. Verify those commits and the owned-path delivery postconditions below before returning. The integrated commits already satisfy the selected mode, so skip the additional staging, commit and consent steps. In the all-at-once route, the parent consolidates the parallel patches and makes one verified commit on the chosen branch.
After shared quality gates and result validation finish, inspect the recorded commit disposition before final output. A later explicit commit this request reopens a previously blocked disposition for the explicit local snapshot exception if its evidence still matches the current source and plan; do not treat the old blocked render as the current decision. For blocked, not-applicable, or declined, skip staging and the question, then complete the final handoff below with the explicit reason and controlling rule. For pending, show the complete compact commit-plan.md, ownership exclusions, destination, and verification limits. If an earlier explicit answer already supplies the mode and still unambiguously authorizes this plan's paths, destination, grouping, and current verification, record that binding, omit the question and reuse that authorization. An upfront packet commit mode is such an answer when every commit-plan path belongs to a selected finding's work bucket, the destination is the recorded receipt branch or the commit-baseline.json branch, the chosen grouping is feasible, and either ordinary verification passed or the explicit local snapshot exception applies; a packet leave unstaged answer makes the disposition declined, and an explicit decide after verification answer asks here. Under a local Git approval grant, a preference left unanswered or dismissed uses the recorded all at once default without another consent question; without a grant, it asks here. Record the grant as the consent source in commit-plan.md and bind its scope to the same paths, destination, grouping and verification checks. A new exclusion, destination change, or infeasible grouping is a materially changed decision. An explicit local snapshot within the recorded mode and owned scope retains that authorization; disclose remaining verification in the plan and commit message without another question. Ask exactly once through User Questions only for a missing or materially changed decision. For multiple selected actionable items, use sync only if permitted for authorization and able to represent all four feasible modes; otherwise use the packaged native ask_user form with all four choices, or verified suitable async. Use plain chat only when no permitted native control is suitable; never hide a mode behind Other. The following are canonical choices, not prose to repeat beside a native control:
For exactly one selected actionable item, never reopen the grouping question: use its recorded all at once default, or preserve an explicit equivalent grouping choice. Reuse existing bound authorization; honor explicit deferral or denial. If authorization is still needed, ask Commit verified remediation-owned changes? and offer only all at once and leave unstaged, through an authorization-capable native control. The single-item default supplies no authorization or explicit local snapshot exception. The four-mode menu below applies only to multiple selected actionable items.
Commit verified remediation-owned changes?
- all at once
- group findings by topic
- each finding as a separate commit
- leave unstaged
Without a grant, the commit mode answers Approve for this plan and leave unstaged answers Decline, per Local Git approval grant. Do not ask a separate remember-approval question. The mode authorizes only this plan and never creates a standing grant; never infer standing approval from the selected mode.
Do not stage without a local Git approval grant or an explicit valid answer bound to this plan. An existing matching authority satisfies this requirement without a new question. Bind the decision to exact commit-plan paths, destination, grouping, and current verification; silence, preselection, stale or duplicate replies cannot create authorization; a grant supplies it independently. If a mode is known unsafe, explain why and offer only feasible choices; never omit a feasible mode to fit a menu limit or invent disabled-option fields. A direct user selection authorizes only selected local commit mode. An explicit commit this or commit for the current remediation means all at once when the plan's exact owned paths, destination, and verification bind unambiguously to that request, including when the plan is prepared in response to it; do not ask again. A summary request does not authorize commit. If authorization is missing and runtime cannot ask, or user chooses leave unstaged, leave every remediation change unstaged. That choice does not cancel completed remediation. A later ownership/grouping failure still stops before staging under the existing preflight.
Build commit units from recorded plan, never from retrospective guess:
all at once: one unit containing every eligible remediation-owned path; an explicit local snapshot includes authorized incomplete edits, new files and deletions.group findings by topic: use coherent work-bucket topic already recorded inresolution-workplan.md; include its implementation, regression tests, and required documentation together. Do not invent new topics after implementation.each finding as a separate commit: use one unit per finding only when all unit paths are exact and disjoint. If findings share changed path, do not use partial-hunk staging to separate them; report collision and requiregroup findings by topicorall at once.
Before staging each chosen unit, require all following:
For PR mode, first run remediation_branch.py check against the selected original or recovered receipt and the last recorded authorized HEAD. If only a schema-1 receipt exists, complete the legacy recovery procedure before staging. Include the receipt path and destination branch in commit-plan.md and the commit question. Recheck immediately before commit and verify afterward that the recorded branch contains the new commit. The shared template's message/index checks do not replace this destination check.
- The index is empty (
git diff --cached --quiet) on initial entry; an existing staged change without ownership evidence is user state. A failed-hook resumption may retain only this unit's proven staged content under Hook Failure Recovery, comparing retained paths, blobs and modes and refreshing the reviewed repair before re-staging. Unrelated or uncertain entries stop execution without resetting or unstaging them. - Every candidate path is absent from
commit-baseline.json's dirty/untracked inventory and belongs to exactly one chosen unit. A pre-existing or concurrently disputed path is not safe to attribute to Codex; leave that unit unstaged and explain boundary. - Show the unit's exact path list and full commit message in chat, inspect
git diff HEAD -- <paths>andgit status --porcelain=v1 -- <paths>for exactly those paths, then stage and commit the unit with the shared template's one owning command, which runsgit add -- <paths>with only the unit's explicit repo-relative file paths before the commit. Never usegit add .,git add -A, a glob, a directory, or an inferred worktree-wide path list. - After the commit, require
git --no-pager show --no-renames --name-only -z --format= HEADto equal the unit's planned paths exactly as a set. A mismatch follows the shared template's failure rule: report it; do not repair the index or history automatically.
The resulting commit therefore contains only remediation-owned changes from chosen unit; unrelated worktree changes remain untouched. If preflight cannot prove that boundary, do not commit and retain validated remediation result plus exact blocker in commit-plan.md.
For each eligible, user-authorized unit, load ../../../shared/commit-response-template.md and use its exact message shape. Every proposed or created remediation commit must end with:
Do not commit for remediation summary alone or without an applicable local Git approval grant or explicit authorization. Creating new remediation commit never authorizes rewriting existing commit. Amend, rebase, reset, squash, fixup, and equivalent history edits require explicit request for that exact operation. After every commit, verify its stored message, HEAD, and post-commit index/worktree state through shared template before attempting another unit.
Complete return delivery and the optional PR worktree publication checkpoint below before final promotion and output; a still-pending required commit decision remains an interim handoff. Complete the final handoff with the actual disposition. A submitted question without an answer stays pending when it requests required authorization or an explicit deferred decision: record the question/plan binding and show any required pending handoff context before asking. Follow User Questions for delivery: prefer a permitted structured control; a plain-text fallback ends with the question and complete options or accepted input syntax as the very last terminal block. After an accepted idle async question, yield without a final/status handoff; never repeat its live menu or stage. Unavailable required input also stays pending with the actual limitation; optional grouping under standing approval uses its documented default. On resume, recover that decision and continue the first unmet checkpoint. A valid leave-unstaged answer becomes declined; a preflight or execution failure becomes blocked, retaining any already-created commit hashes and uncommitted units. Only after every authorized unit and post-commit check succeeds use committed, with hashes, mode and plan evidence. Re-render and revalidate the candidate when disposition changes; then promote and emit the exact validated handoff. Do both with one remediation_finalize.py finalize --promote call carrying the final disposition; run Review feedback below after that call succeeds and before emitting the handoff. Never present the earlier pending render as the completed commit outcome.
Selected commit completion gate¶
A selected commit mode is an execution obligation, not a summary preference. Before return delivery and again immediately before final output, inspect full Git status including staged, unstaged and all untracked entries in both the actual source and invoking checkout (once when identical). Compare with the pre-edit baseline and the complete owned inventory, including newly created files and deletions; classify unexpected entries instead of silently excluding them. Require every authorized task-owned change to be contained in the intended commits and zero task-owned uncommitted entries. Unrelated pre-existing changes remain untouched and separately reported; global worktree cleanliness is not required.
Before delivery succeeds, remaining owned content keeps commit work active: finish the already-authorized units after current ownership/destination and verification checks, applying the explicit local snapshot exception when applicable. A hook-created edit, unexpected concurrent change, execution denial or disputed ownership requires diagnosis under the shared commit failure rule; never blindly re-stage or create a repair commit. Do not report committed for the whole task or successful completion while authorized owned content remains pending. Preserve existing hashes and name exact residual paths, reason and next owner/action when blocked. After verified delivery, later drift fails the final recheck and uses the report-only resume/new-run boundary; never replay an old source commit or return transfer. An explicit no-commit/leave-unstaged decision takes precedence and does not require this zero-residue gate.
Return remediation to the invoking checkout¶
Before recording a new PR delivery, verify the current PR target against the actual delivery tip. If it moved beyond the tested revision, complete the local integration and verification first. A report-only continuation of an already recorded delivery retains its historical evidence.
The PR default delivers in place in the invoking checkout. The explicit --worktree option selects worktree-only output: retain the verified branch, edits and any authorized local commits in that linked checkout and verify in place there. Show its absolute path, local branch, actual upstream (branch.<name>.remote and branch.<name>.merge) or its absence, and the contributor repository and head branch that a human would target. When native GitHub CLI tracks the base repository's refs/pull/<n>/head, identify it as fetch-only and distinguish the contributor branch as the publication destination. Remote write access and push configuration remain unverified. Preserve the original checkout's branch and user changes.
After all source-dependent checks and authorized commits, but before final promotion and output, execute Worktree lifecycle. This applies to no-commit and leave-unstaged outcomes too. Retain <run-directory>/worktree-delivery.md with the exact destination branch/HEAD, owned payload, unrelated-state preservation proof and final delivery status; link it in the handoff artifacts and any existing commit plan. Record the current destination as a separate clickable artifact. In the detailed delivery note, retain a Status: delivered or Status: worktree-only line after successful verification, a Local destination: <absolute checkout>, branch <branch>, head <full OID> line, and a Git common directory: <absolute directory> line. A later publication request uses these destination fields independently of the historical source checkout. The finalizer's source-checkout artifact remains historical evidence; never rewrite its receipt to make it a delivery receipt.
Lead the outcome with the current absolute checkout and branch, stating whether delivery succeeded in the invoking checkout, was explicitly waived for worktree-only output, or remains incomplete with its blocker and next owner/action. Keep actual local commits in commit_disposition even when delivery fails; delivery failure prevents a successful remediation outcome, not the existence of those commits. Finish allowed report assembly with that accurate incomplete state. On resume after delivery, use the report-only destination verification route; never repeat source detachment, transfer, source-receipt checks or the opt-in commit step blindly.
Optional PR worktree publication¶
Use the PR worktree publication gate after successful local delivery. For a linked worktree with a run-created commit that passes the gate's checks, always show the local result, checkout, branch and commit range as the final handover in a progress message, then open the single native Approve / Deny push question in the same turn. Combine removal with the push when --check-owner confirms ownership of the offered checkout unless the user asks to keep it. An initial explicit --worktree run opens the question after validating its local candidate and before promotion. An existing PR worktree promotes locally with delivered recorded in worktree-delivery.md, then enters the post-delivery route automatically after showing the final handover. A primary checkout offers publication only on request. A manual command for an earlier tip applies only to that tip. Use --no-publication-offer on final promotion only for a report-only continuation or an explicit opt-out for this delivered commit. For an explicit --worktree run, record that opt-out as skipped before validating the initial candidate. A recorded native Deny retains its declined disposition.
In gate step 1, run PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/publication_preflight.py --routing <admitted run>/pr/pr-routing.json from the verified delivery checkout. On retry: true, diagnose the classified reason once using next_action and repeat the helper once with --retry. Only network and rate-limit failures qualify for retry. A failed verdict with retry: false leaves the verified delivery local. Report its stage and reason.
Apply the shared gate when local checks pass or are documented as not applicable and the validated, committed delivery passes its destination checks. An aggregate failure due solely to hosted CI findings that require publication of this commit still qualifies for the native question. Preserve the failed result and the open findings. After the user selects Approve and the one-time runtime approval passes, Codex runs the push from the verified checkout and checks the remote branch against the approved commit. When the native route alone is unavailable for a safe, verified delivery, name the prerequisite for Codex to run it and include the human-run publication command with all actual arguments in the handoff. Honor a hold or denial and resolve missing identity or unsafe conditions before giving a push command.
For eligible linked-worktree delivery outside the initial explicit-worktree route, or for an outstanding user request to publish, enter the shared gate's post-delivery route from the existing promoted result and verified checkout. For a historical recovery delivery, reuse its verified locator. Never manufacture remediation-worktree.json or worktree-delivery.json for a completed run. Keep the new offer, distinct native answer, attempt, terminal disposition and any readback in the exclusive publication-request/ checkpoint. Validate its disposition with the shared gate and report it separately. The following steps describe initial explicit-worktree delivery.
- After all local delivery checks pass, retain the detailed
worktree-delivery.mdand aworktree-delivery.jsoncontaining exactlyschema_version: 1,status: worktree-only, absolutecheckout, attachedbranch, full authorizedhead, and absolutecommon_dir. The checkout and common directory must matchremediation-worktree.json. - Validate the local candidate with
remediation_finalize.py finalizewithout--promote. Resolve the optional native publication decision and retain its evidence under the shared gate, including thepublication-answer.jsonrecord it writes before any push route. Writepublication.jsonthrough a temporary file in the run directory renamed into place, so a crash never leaves a partial record, with exactlyschema_version: 1,status(verified,declined,skipped,failedorunverified), a concretereason, andobserved_oid(a full readback OID ornull). Usedeclinedfor a Deny recorded inpublication-answer.json. Useskippedwhen nothing was sent: no approval was consumed and the offer was ineligible, dismissed, or unavailable, or an approved attempt ended while no execution marker (publication-executed) existed, such as the helper'snot-sentresult, a failed recheck or a runtime denial, with the concrete reason. Usefailedfor a started attempt (execution marker present) with a known refusal andunverifiedwhere a started publication cannot be established, including everyunverifiedresult of the helper (publication-push-outcome-unknownorpublication-update-unverified). Keep the raw audited ref response inpublication-readback.jsonwhen claimingverified; the proof also requires the successful transport record and its execution marker. Preserve the original offer, answer and execution records. Write this record only after the shared gate's single retry afterpublication-push-precheck-failedis used or not taken, because the helper refuses to run oncepublication.jsonexists. On resume, a consumed attempt without an execution marker isskipped. With a marker and no terminal record, the finalizer uses the existing proof checks. A matching transport and exact audited ref readback recoververifiedwith the observed OID. Incomplete or conflicting proof leaves the attemptunverifiedor reports invalid evidence. Never run the publication helper or contact the remote to complete an interrupted report. - Recheck the local destination and run
remediation_finalize.py finalize --promotewith the actual local result. A passing linked-worktree result requires the verified local delivery evidence plus a terminal or consumed publication disposition. The finalizer derives the publication status, matches verified readback to the offer's exact GitHub repository and branch, binds the disposition and verified readback bytes, and links the evidence in the handoff. Direct artifact validation rechecks that binding. Report the concrete reason and publication limits alongside the local outcome.
For a combined push-and-cleanup offer, after promotion run approved worktree cleanup before releasing the slot. Report the removal or retention alongside the verified publication. When the user opts to keep the delivery local, include the human-run publication command for that checkout as an optional Recommendations / next steps entry. Use the finalizer’s manual_push_command when present and verified for the current delivery. Print it in a fenced code block headed Recommendations / next steps so its arguments remain copyable. For an explicit local-only decision before an offer, fill the same command from the verified delivery and original PR head location. This terminal supplement also applies to later publication requests and preserves the previously validated local report.
Successful linked-worktree promotion derives metadata.worktree_publication_contract_version: 1 alongside the publication binding. The marker, a handoff publication link, or any retained publication sidecar identifies the current contract on direct validation of a promoted result. The prepublication candidate can pass before the binding exists. A historical result with the linked-worktree locator and Markdown delivery record remains readable when no current publication evidence survives. If all current markers, links, and sidecars are removed and the result is rewritten to the historical format, the remaining local records cannot identify the original contract.
Review feedback¶
Before final rendering, resolve the admitted review directory and its resolution.jsonl destination, including symlinks, and check current write authority and any explicit read-only evidence restriction. Admitted report identity does not grant write authority. If the destination is read-only or outside authorized writes, retain all outcomes in this remediation run, record skipped feedback as an ancillary limitation in the handoff, and omit the append below. Do not request expanded authority merely for optional feedback or block completed remediation on it.
After finalize --promote succeeds and before emitting the handoff, when this run admitted a completed review report (admission_status=completed) and its feedback destination is writable under the authority check above, feed each finding's outcome back to that review. Preliminary and unavailable intake also write findings-input.txt but never feed back. Inspect PLUGIN_ROOT/bin/python PLUGIN_ROOT/shared/remediation_finalize.py resolutions --help, then run it with --run <run-directory> --review-run <admitted review run directory>; add --sha <commit> when one commit holds every fix, or one --item-sha <input-item-id>=<commit> per unit for separate commits, and omit both while changes stay unstaged. It appends one {finding_id, verdict, sha, why} line per admitted finding to that review run's append-only resolution.jsonl, with verdict fixed, rejected, skipped, or deferred derived from the promoted result, and refuses any review run whose result bytes differ from findings-input.txt. Reclassified review_limitations also append a rejected record with the preserved rationale and null sha, so later intake does not reopen them as findings. This append is remediation's only write into a review run. A later commit or outcome is a new run of the same command; identical records are not appended twice, and the newest line per finding wins. Skip it for bare-PR online-only intake. A feedback failure does not change the validated result: emit the handoff, then name the failed step and its code.
Fail-Fast Rules¶
- Missing findings source in report mode, an explicit report path, or a report alias => fail completed-report admission. Requested PR review evidence follows Missing requested PR review decision; available findings require explicit user confirmation before continuation, with missing requested proof disclosed as a limitation. Local report intake retains independently usable finding intake. A bare PR has current online PR evidence as its findings source and must not fail or request
code-reviewmerely because no assessed review artifact exists. 01a. No usable finding or missing selection => ask for that concrete evidence or selection; never implicitly dispatch a new review. Missing completed-report proof still prevents certification of complete report-backed intake. - Shared gate script missing => fail.
- Selected critical unresolved => fail. Unselected critical/high allowed only when user selection explicitly records deferred.
- Finding marked fixed without closure evidence => fail.
- Gate fails because of resolution patch => fail unless explicitly unresolved.
- PR mode without fresh core PR evidence or explicit supplemental-thread/stale-coverage caveat => fail. 06a. PR code edits without
pr/local-checkout.jsonproving local checkout matches PR head anddiff_source=verified-local-checkout=> fail. - Online thread/comment fixed without valid triage status => fail.
- Duplicate/out-of-scope/already-fixed review thread/comment edited, not recorded => fail. Review concern classified or skipped as stale, including after conflict-resolution line drift => fail.
- Result artifact validator failure => fail.
- Result artifact missing => fail. A new remediation handoff omits
commit_disposition, silently skips step 12, or claims a failed/timed-out local snapshot without the explicit request and verification evidence, or finishes a selected commit with task-owned residue => fail. Keep real commits distinct from passing verification; useremediation-commit-disposition-missing,remediation-commit-result-blocked, or the exact residue path evidence. <run-directory>/action-items.mdlacks complete review item resolution table => fail.- PR mode uses
curl,raw.githubusercontent.com, or copiedhead-files/snapshots for code inspection/edits => fail. <run-directory>/resolution-scope.mdlacksResolution Scope Selectionbefore edits => fail.- Edit finding not selected in
resolution-scope.md=> fail. - Selectable list includes fetched online PR resolved comment/thread => fail.
- PR mode lacks
<run-directory>/pr/target-branch.json,<run-directory>/pr/merge-tree.txt, or<run-directory>/merge-prestage.mdbefore review/report finding edits => fail. - PR merge conflicts resolved from markers without recorded clean PR/target context => fail.
- Apply report/online-review findings before PR merge/conflict prestage complete => fail.
- PR mode runs
git/ghwith--force, a forced checkout, or a forced ref update before explicit user confirmation and overwrite-risk explanation => fail. - Review report
checks_failed,follow_up, required next work, confidence gaps, residual risks omitted fromaction-items.md=> fail. - Report-origin obligation marked
out-of-scopebefore user selection without cited unrelatedness evidence => fail. - Selected review gate/follow-up marked resolved without matching closure evidence => fail.
- Selectable findings and omitted
remediation_scope, but no recorded user prompt/confirmed selection before edit => fail. - Any
out-of-scopeitem lacks specific rationale and explicit user confirmation => fail. - PR item connected to PR intent, changed diff, adjacent verification, or unknown relation marked
out-of-scope=> fail. - Connected PR item omitted from selectable scope/required follow-up without closure evidence => fail.
- Selected items but missing
<run-directory>/resolution-workplan.mdbefore edits => fail. - Selected item absent from
Work Bucket Planor present in more than one bucket => fail. - Specialist-owned bucket lacks existing in-run context pack or supported owner/verifier assignment => fail.
- Selected unresolved items but
<run-directory>/unresolved.txtlacksUnresolved Work Summary,Why Selected Items Remain Unresolved, orNext Action=> fail. remediation_scope=allwith selected unresolved, but final output says/implies all selected work resolved => fail.- Unresolved selected item lacks closure class, attempted evidence, next owner, or next action => fail.
- Selected local code/doc unresolved without blocker evidence and status fail/timeout => fail.
- Final table row count differs from total ingested entries => fail.
- Final table omits ingested entry or
omitted_entries_totalis not0=> fail. - Final table status counts do not cover every row => fail.
- Final table lacks
input item,item name,item type,triage status,resolution,owner/status,resolved how, orevidence=> fail. - Final chat lacks the compact per-item resolution table (including a one-item run), concrete resolution reasons, unresolved/deferred items, confidence/material limits, or artifact path => fail.
- A pre-edit scope interaction omits or shortens the complete selection table, omits any required item-labelled path lines immediately below it, or omits available PR relevance counts => fail:
scope-context-not-rendered. - The terminal selection table, its path list, optional PR Relevance Summary, and
Full reportlink/path to<run-directory>/action-items.mdare not emitted in that order => fail:scope-report-link-missing. - The user-visible assistant message does not contain the complete terminal selection table, every path moved to
- <item>: <file-path>lines immediately below it, available PR Relevance Summary andFull reportpath before the native question, or plain-chat fallback omits the question/accepted syntax; collapsed tool output does not count => fail:scope-context-not-visible.- A selectable scope menu is collapsed into a free-text field, or scope, commit, and work-plan decisions share one answer field => fail:
remediation-scope-menu-collapsed. - Per-item
###detail groups or their context/closure/evidence blocks are printed in terminal selection => fail:scope-detail-groups-displayed. - A scope-selection question or its choices appear in both prose and a native control => fail:
scope-prompt-duplicated. - Parent-owned or sequential fallback requires an approval question, or proceeds without its concrete ineligibility reason and actual mode recorded under
## Parallel Approval=> fail:parallel-fallback-not-recorded.
- A selectable scope menu is collapsed into a free-text field, or scope, commit, and work-plan decisions share one answer field => fail:
- An explicitly requested remediation commit omits
Co-authored-by: Codex <codex@openai.com>or shared commit-response template => fail:codex-coauthor-trailer-missing. - Existing history would be rewritten without explicit request for that exact operation => fail:
history-rewrite-not-explicitly-authorized. 43a. Automatic finding-fix commit units governed by steps 11–12 must not stage or commit before gates/result validation. An explicit user request to commit overrides this automatic sequencing restriction. Run and report required checks and retain their evidence. Ordinary readiness requires passing checks; an explicit local snapshot may proceed with failed verification under step 11. The ownership, destination and runtime restrictions remain binding, including open security/critical findings, runtime denial and hook failure. After applying these rules and shared commit checks, commit without waiting solely for final report validation, then resume that report checkpoint. Standing approval or an upfront grouping preference alone does not supply this override. A missing commit plan or unbound scope still fails: a unit that does not have<run-directory>/commit-plan.mdor stages before recording its bound user choice or standing-policy grouping default => fail:code-remediate-commit-plan-missing. Step 03 target integration follows its own merge checks and is outside this finding-fix sequencing rule. 43b. A remediation commit includes path outside its recorded unit, path present in commit baseline, run artifact, or any pre-existing staged change => fail:code-remediate-commit-scope-unsafe. 43c. Per-finding commits split overlapping path with partial-hunk staging or topic commits invent post-hoc grouping => fail:code-remediate-commit-grouping-unsafe. - The fetched target is not already included but
merge-resolution.jsonis absent or notcompletedbefore report/online-review work => fail:target-merge-not-completed. - Target merge starts or commits without recording its authorization (
explicit-inputfor this run's task-owned merge,user-confirmedfor an explicit approval), or against a narrower no-commit instruction or recorded denial => fail:target-merge-authorization-required. - Report/online-review finding work starts while unmerged paths or in-progress merge remain => fail:
merge-conflicts-unresolved-before-review-remediation. - Work bucket contains more than five selected items => fail:
code-remediate-work-bucket-too-large. - Selected item is absent from all work buckets or appears in more than one => fail:
code-remediate-work-bucket-coverage-mismatch. - A coherent fix is split only to manufacture parallelism, or low-volume sequential work is fanned out without a meaningful role boundary => fail:
code-remediate-low-volume-fanout. - Parallel specialist execution begins without an exact-plan dispatch record from the workflow default or explicit user choice => fail:
code-remediate-parallel-approval-missing. - Parallel buckets use aliases or ancestor/descendant paths, or exact shared-file edits are applied without verified parent reconciliation after a collision => fail:
code-remediate-parallel-ownership-overlap. - Bucket plan JSON, metadata, rendered table, or SHA-256 digest disagree => fail:
code-remediate-work-bucket-plan-content-mismatch. - An eligible parallel dispatch record does not bind
approveto the current plan digest => fail:code-remediate-parallel-approved-plan-not-bound. - A workflow-default parent-owned or sequential fallback is missing
parallel_eligible=false,parallel_approval_required=false,parallel_approval_status=parent-only,prompt_presented=false, orapproved_plan_sha256=null, or its## Parallel ApprovalomitsIneligibility reason: <concrete reason tied to this plan and available runtime>=> fail:code-remediate-parallel-fallback-invalid. - Bucket owner/verifier is outside supported role enums or its execution mode contradicts parent/specialist ownership => fail.
- Specialist context pack is missing or resolves outside run directory => fail.
- Parallel owned path is absolute, globbed, contains
.., aliases another path, or overlaps another bucket by ancestor/descendant => fail. final_resolution_table.itemsis absent, duplicates input ID, disagrees with declared counts, or does not match durable Markdown rows => fail.- A remediation item has no source record, uses source category other than
report|online|user, duplicates a(kind, source_id), or omits source ID, location, complete body, or evidence path => fail:code-remediate-source-provenance-incomplete. - Presentation loses or changes required source pointer, detail, or expanded source record => fail:
code-remediate-source-presentation-mismatch. Apply format-specific contract: concise and historical grouped selection/final output retain ordered pointers and complete labeled supporting details without requiring visible symbols; durable ledgers and historical symbol layouts retain compact source cells and every referenced symbol definition immediately below their table. Expanded records always preserve source location, complete body, and evidence path. - Source-record totals disagree or
omitted_source_records_totalis not0=> fail:code-remediate-source-coverage-mismatch. - A completed
parallel-specialistsresult uses a schema-v1 planning artifact or omits the completed production lifecycle for its schema-2 patch plan or schema-3 grouped plan => fail:code-remediate-production-lifecycle-required. - A referenced production lifecycle is absent, escapes run directory, has wrong SHA-256, or is not durably readable => fail:
code-remediate-production-lifecycle-evidence-missing. - Production lifecycle evidence names different approved plan digest => fail:
code-remediate-production-lifecycle-plan-mismatch. - Production lifecycle status, joined nodes, ownership, patch hashes, integration order, any required parent reconciliation, source application, rollback material, cleanup, or containment fields do not reconcile with the frozen schema-v2 patch plan or schema-3 grouped plan and result metadata => fail closed; never downgrade result to planning evidence or infer completion.
- After the scope answer and before step 12, a conversational question asks for a commit preference or work-plan approval that the upfront packet collected or could have collected, or any other question outside the packet's data-dependent and recovery list => fail:
remediation-foldable-question-after-scope. - Remediation repairs, rewrites, rerenders, or promotes any file of a code-review run, or writes anything there other than the
remediation_finalize.py resolutionsappend toresolution.jsonl=> fail:code-remediate-review-run-mutated. - An outcome cell of
action-items.mdor a bucket status inresolution-workplan.mdis edited in place after selection, orclosure-log.md,resolution-events.jsonl, orresolution.jsonlis rewritten instead of appended => fail:code-remediate-ledger-rewritten. - An admitted report finding is triaged
needs-clarificationorrejected, or the user is asked about it, because it no longer matches source, without first reading its reviewer evidence => fail:code-remediate-reviewer-evidence-skipped.
Quality Gates¶
Required checks:
review: complete action-item resolution table/item and source-record counts; compact orderedreport|onlinereferences in visible tables plus full provenance in machine metadata and expanded records; review report failed-gate/follow-up intake; PR/diff relevance; indexed scope selection with prompt/confirmation; coherent work buckets with default parallel dispatch or parent-only/sequential fallback recorded with its concrete ineligibility reason; schema-v2 production lifecycle and collision reconciliation for completed parallel specialists; user-confirmed out-of-scope rationale; PR online-review triage; target refresh; intent-first merge/conflict resolution; merge authorization/completion evidence; relevant local checkout evidence; closure log; unresolved list with closure classes/next owner/attempted evidence/next action;git diff --check -- <remediation-changed paths>, excluding preserved unrelated dirty paths.tests: smallest checks proving fixed-finding closure.artifact: shared validator confirms closure artifacts, gate logs, result JSON shape.
Conditional checks:
lint/format/types: run configured checks for changed code/config.calibration: run owning calibration when findings affect skills, role/agent routing, or gate policy; Codex Rig source usesruntime/calibration/run.py --layout plugin.
Calibration Hooks¶
Update calibration when resolution policy/output shape changes:
- regression scenarios: locally completed remediation with unavailable supplemental hardware or hosted checks, incomplete remediation for unexecuted required live verification, declared backend preparation before environment-blocked closure, statistical confidence disclaimer without an invented calibration prerequisite, late ownership capture recovered only from contemporaneous evidence, and rejected event payload repair followed by current handoff regeneration
- benchmark patterns:
code-remediate - behavioral cases: bare PR online-only intake without prior review artifact, explicit report-alias boundary, ambiguous findings, false closure, unresolved critical/high handling, missing user-selected resolution scope, missing resolution workplan for selected items, selected item omitted or duplicated across buckets, bucket over five items, low-volume parallel domain split, artificial per-finding fan-out, default parallel dispatch without a matching plan digest, fallback reason and actual mode recorded without approval prompt, exact shared-file reconciliation, path-alias overlap rejection, specialist-owned bucket missing context pack, completed parallel remediation without hash-bound join/integration/reconciliation/source-application/rollback/cleanup evidence, capability-sandbox overclaim, unconfirmed out-of-scope triage, connected PR item marked out-of-scope, missing connected follow-up, code-review-to-remediation gate symmetry, unresolved selected-item closure summary, complete final resolution table, per-item machine ledger reconciled with durable Markdown, compact report/online references with full expanded source records, final chat outcome table for every ingested item and source, gate failure disclosure, artifact validator bypass, PR online review triage, supplemental-thread degradation, sandboxed collector network approval, PR target-branch refresh, PR intent-first merge/conflict completion, review-only isolated detached worktree, remediation
gh pr checkoutfirst, same-repository original-branch fallback identity gates, bounded fork recovery loop, read-only schema-2 branch receipt, legacy receipt preservation, original PR destination verification, verified local diff before edits, post-gate remediation commit mode choice, exact ownership-only staging, unsafe per-finding overlap rejection, read-only handling of an unpromoted review candidate, reviewer-evidence lookup before asking, append-only status events and closure log, and review feedback to the admitted run'sresolution.jsonl
Output Contract¶
Before writing result candidate, follow ../../../shared/final-handoff-contract.md: derive handoff rows and kind:source_id references directly from CODE_REMEDIATE_METADATA.final_resolution_table.items, render and bind final-handoff.json, final.md, and final-handoff.validation.json, then emit final.md verbatim only after both validators and promotion pass. Any item/source coverage mismatch blocks output.
Use ../../../shared/quality-gates.md.
Apply shared confidence band policy.
Keep complete, unabridged resolution ledger in <run-directory>/action-items.md, with its resolution table rendered from status events by remediation_finalize.py ledger: every ingested item, validated column/count/status vocabulary, resolved evidence, scope selection, workplan, PR relevance, unresolved class, and confidence recovery.
Record source coverage with exact counters source_records_total, represented_source_records_total, omitted_source_records_total, and grouped_items_total; reconcile them against item source records and require zero omissions.
The pre-edit scope context and one-channel interaction behavior remain exactly as required by Terminal Scope Context Contract; this output contract does not abridge or replace them.
Before every status or final answer, reconcile the requested remediation with its retained selection, closure ledger, gates and canonical result.
- A completed nested review, prepared branch receipt or passing tests alone does not prove any finding was fixed.
- A bounded implementation challenge that could not run is not a blocker, open obligation or reason to ask. With selected findings closed and gates passing, report remediation complete with
implementation challenge not run: <reason>under limitations and theimplementation-challenge-not-runconfidence gap; never claim independent coverage. - While an authorized checkpoint is available, continue executing it. Use the following incomplete handoff only when a concrete blocker or user instruction requires a stop.
- If implementation has not begun at such a stop, say
Remediation remains incomplete; zero implemented, name the first unmet checkpoint, confirmed open findings and next owner/action. A pending target merge or its conflicts is never that blocker: step 03 resolves and commits them first. - Distinguish evidence-only closure, rejection, user-authorized deferral and actual code changes.
- A no-change completion needs evidence-backed dispositions for every required finding and the normal remediation closing gates; open confirmed findings cannot become rejected or resolved because checkout failed.
- Before selection, report confirmed findings as awaiting selection rather than inventing selected counts.
- Keep any early blocked handoff explicitly incomplete without manufacturing a completed result or final resolution ledger.
Final chat follows shared ordered frame:
- Start with one short plain-English sentence naming the remediation outcome. Use labelled bullets in the existing outcome fields for workflow completion, finding totals and local completion; keep checks, commit disposition and next actions in their own sections. Do not repeat facts or replace the final table with paragraphs, including when only one finding was selected or resolved. Deliver the validated table verbatim; a prose-only or commit-only recap is incomplete. Artifact validation completed and remediation incomplete are distinct facts; a failed gate/result is not automatically a failed review workflow.
- For partial or blocked outcomes, lead with completed implementation or evidence-only closure and verification that passed, then name unfinished work and its reason. Distinguish failed, timed-out and not-run checks; explicitly state when no implementation or verification completed. Missing verification required for a selected obligation keeps remediation incomplete even after implementation; an implementation challenge that did not run is not such verification. Apply step 09 to distinguish a required check from a material limit on what was verified locally. Never use bare
Blocked, a generic incomplete status, or a blocker-only opening. Bothoutcome.titleandoutcome.summarymust name the specific current blocker while preserving completed work. In the summary, cite current-run gate or unresolved-item evidence and state the next owner/action needed to proceed; do not reuse a stale intake-review outcome or substitute a commit-only blocker for the remediation cause. - When implemented total is zero, state
No review findings were fixed by a new code change, then distinguish evidence-only closure, any target integration, and remaining selected work. - Follow the remediation outcome summary contract:
outcome.titleis one concise sentence naming the PR or local scope, initial problem or selected findings, and verified final state, never the genericRemediation Summarylabel. For a PR, the finalizer supplies the opening with the linked PR number, collected title when available, and the actual push status. Keep the authored remediation outcome and its evidence below it. Retain ingested/selected/implemented/unresolved/deferred totals, whether all selected local actionable items closed, and gate status in the existing outcome fields; avoid repeating the title sentence inoutcome.summary. - Passing gates do not close selected items: say remediation remains incomplete when any selected obligation remains open, even if every executed check passed.
Results: derive handoff machine cells fromCODE_REMEDIATE_METADATA.final_resolution_table.items, with one row for every ingested item, including non-selectable, rejected, resolved, and unselected rows. Preserve item and source order. Keep exact six machine columnsItem | Severity | Finding | Sources | Outcome | Evidence / next action, and set handoffpresentation_version=15, tablelayout=conciseandoverview_only=true.- Derive each row's
selectedasYes,No, orClosed:Closedfor nonselectable already-resolved or informational items,Yesfor confirmed selected indexes over selectable items, andNofor actionable unselected items.Allselects every actionable item; closed items remain visible asClosed. Never infer selection from outcome. - Keep every genuine source pointer in its bound machine cell, joined with newline in source order. The renderer shows
ID | Severity | Finding | Selected | Outcome | How resolved, including every ingested finding, with file paths removed from all table cells. After the table, render each path as- <item>: <file-path>; preserve all non-path prose in its existing display location and never discard or normalize machine source pointers. Selected isYes,No, orClosed; Outcome is the bound disposition label; How resolved is its complete concrete reason fromresolved_how, without repeating the label. Author that reason as one concise, finding-specific explanation; never truncate it during rendering. Full source and evidence/next-action details stay in the linkedaction-items.mdresolution ledger, without repeated ID detail blocks in chat. - Keep Outcome as
<resolution_status> — [O<n>], Evidence / next action as[E<n>] — owner/status: <owner_status>, and their exact bounddetailsvalues in JSON. Versions 8 and 9 keep detailed resolution reasons in the linked ledger and renders any paths extracted from table cells as item-labelled lines below the table; do not expose ungrouped O/E lists. Historical versions 5 and 6 and grouped/legacy handoffs retain their exact rendering. - Apply shared
Verification,Remaining,Next steps,Confidence, and supplementalArtifactrules. Include the explicit rendered commit disposition, reason and evidence even when commit cannot be offered. List every unresolved/deferred item with owner/action; link result and full ledger; formode=pr, add merge-prestage evidence and remaining collision risk. Item: exact stable input item ID; keep numeric selection indexes separate and explain them in selection overview.Outcome: use an explicit disposition and concrete reason in boundresolved_how:Implemented: <exact finding-specific change>orVerified without code changes: <existing behavior or fresh closure evidence>.Rejected: <why finding is invalid>,Blocked: <specific missing evidence or capability>,Deferred: <user decision and remaining work>, orNeeds clarification: <exact unanswered question>.- Never render bare
unresolvedor relabel a valid blocked finding as invalid, rejected, or resolved. Keep internal resolution counts truthful; record next owner/action in evidence and remaining work. - The current renderer shows the bound disposition prefix and concrete reason in separate compact table columns; the linked full report retains complete evidence. Historical versions 8 and 9 show only the disposition prefix.
- Do not collapse rows sharing outcome. Group exact duplicate sources only under source-preservation contract above. Say
resolved allonly whenselected_items_unresolved=0.
Minimum artifact payload template: result-template.json.