Fix
Intent
Make risky or unclear code safe with the smallest sound, validated change, then keep rerunning the whole $fix skill as an outer fixed-point loop until no actionable self-review change remains, no actionable footgun on the touched surfaces or adjacent seam remains unresolved, the unchanged final diff is review-clean across two consecutive terminal diff-review rounds within the current cycle, and two consecutive full cycles end with zero edits on the same frozen review context.
When a full cycle reaches post-self-review rerun plus two consecutive clean terminal diff-review closure rounds on the unchanged final diff, and that cycle also ends with cycle_edit_tally=0 plus an unchanged review-context receipt (fingerprint=same for review-backed runs or the same skip reason for skipped-review runs), increment zero_edit_cycle_streak; $fix stops only when that streak reaches 2. Broader architecture, product, or roadmap analysis belongs to another skill.
Skill-artifact refinement belongs to $refine; $fix stays focused on code/diff repair turns.
Execution spine
Preflight + frozen review contextCore passesResidual risk sweepAgent-directed self-review loopPost-self-review rerun + final diff review closureOuter fixed-point cycle convergenceOutput / handoff
Double Diamond fit
fix spans the full Double Diamond, but keeps divergence mostly internal to stay autonomous:
- Discover: reproduce/characterize + collect counterexamples.
- Define: state the contract and invariants (before/after).
- Develop: (internal) consider 2-3 plausible fix strategies; pick the smallest sound one per default policy.
- Deliver: implement + prove with a real validation signal.
If a fix requires a product-sensitive choice (cannot be derived or characterized safely), stop and ask (or invoke $creative-problem-solver when multiple viable strategies exist).
Auxiliary skills (mandatory)
$invariant-ace: run it on every$fixcycle to lock owner/scope, counterexamples, and enforcement boundaries before deciding how to repair the slice.$complexity-mitigator: run it on every$fixcycle after$invariant-aceto separate essential complexity from auditability noise before reshaping code.- Required order: run
$invariant-acefirst, then$complexity-mitigator, and import both outputs into$fix.
Inputs
- User request text.
- Repo state (code + tests + scripts).
- Optional git review context:
base_branch+comparison_sha. - Validation signal (failing test/repro/log) OR a proof hook you create.
Outputs (chat)
- Emit the exact sections in
Deliverable format (chat). - Use section headings verbatim (for example,
**Findings (severity order)**, notFindings). - Every complete finding report must make provenance visible enough to answer whether the issue came from the frozen input review seed or from
$fixitself. - During execution, emit one-line pass progress updates at pass start and pass end using:
Cycle <c>: Pass <n>/<total_planned>: <name> — <start|done>; edits=<yes|no|n/a>; signal=<cmd|n/a>; result=<ok|fail|n/a>. - In
Validation, include a machine-checkable JSON object with keys:baseline_cmd,baseline_result,proof_hook,final_cmd,final_result. - Keep review/self-review transcript shapes aligned with
references/self_review_loop_examples.mdwhen editing this contract.
Embedded mode (when $fix is invoked inside another skill)
- You may emit a compact Fix Record instead of the full deliverable.
- If another skill requires a primary artifact (for example patch-only diff), append Fix Record immediately after that artifact in the same assistant message.
- Do not mention “Using $fix” without emitting either the full deliverable or a Fix Record.
Hard rules (MUST / MUST NOT)
- MUST default to review + implement (unless review-only is requested).
- MUST triage and present findings in severity order: security > crash > corruption > logic.
- MUST NOT claim done without a passing validation signal.
- MUST NOT edit when no local signal/proof hook can be found or created under
Validation signal selection; fail fast and report blocker. - MUST NOT do product/feature work.
- MUST NOT do intentional semantic changes without clarifying, except correctness tightening.
- MUST resolve trade-offs using
Default policy (non-interactive). - MUST emit pass progress updates while running the multi-pass loop.
- MUST include a final
Pass tracesection in the deliverable/Fix Record with executed pass count and per-pass outcomes. - MUST include machine-checkable validation evidence keys in
Validation:baseline_cmd,baseline_result,proof_hook,final_cmd,final_result. - MUST use the exact heading names from
Deliverable format (chat)/Fix Record; do not alias or shorten heading labels. - MUST include a final
Review reconciliationsection in the deliverable/Fix Record. - MUST produce a complete finding record for every acted-on issue:
- origin
- seeded_review
- proof_target
- counterexample
- invariant_before
- invariant_after
- fix
- proof
- proof_strength
- compatibility_impact
- MUST, when a frozen input review seed exists, report
review_seed_count,seeded_findings_closed,seeded_findings_still_open,fix_discovered_count, andorigin_tallyinReview reconciliation. - MUST follow the delegation contract in
Auxiliary skills (mandatory)(including order:$invariant-ace->$complexity-mitigator) on every$fixcycle. - MUST NOT put fixable items in
Residual risks / open questions; if it is fixable under the autonomy gate + guardrails, treat it as a finding and fix it. - MUST include a final
Review loop tracesection in the deliverable/Fix Record. - MUST run
P2 Footgunsas a first-class core pass beforeP3 Surface + Audit. - MUST inspect every touched public/documented surface plus at most one adjacent caller, constructor, parser, wrapper, or config boundary seam when needed to prove or defuse misuse.
- MUST, in
P2 Footguns, produce at least one top-ranked misuse path or an explicitnone_with_reasonfor every touched public/documented surface. - MUST treat any concrete compatible/provable footgun mitigation on the touched surface or adjacent seam as a normal finding that blocks closure until it is fixed, proved, or blocked.
- MUST default git-backed branch-diff and commit review rounds to native
codex review --base <base_branch>orcodex review --commit <sha>when the run only needs a one-shot verdict on the frozen review context. Reserve split detached-review lifecycle commands (cas review_session start ...pluswait ...) for runs that explicitly need detached lifecycle control: persistedreviewThreadId, fresh-process polling after launch, explicit interrupt, compatibility diagnostics, or approval/runtime overrides. If an explicitly detached CAS round exits withfailureCodeinmissing_cas_dependency|missing_codex_binary|incompatible_codex_review_runtime|review_output_missing|parent_thread_not_materialized|unsafe_parent_thread_state, one temporary caller-owned fallback to nativecodex review --base <base_branch>orcodex review --commit <sha>is allowed; recordreview_transport=native_fallbackandfallback_reason=<failureCode>. - MUST keep standard git-backed branch-diff review scope on the entire frozen
base_branch/comparison_shadiff. Once preflight freezes a branch-diff review context, neither native review, detached CAS, nor native fallback may be narrowed to touched files, the current uncommitted patch, or another ad hoc sub-scope unless the run was explicitly commit-scoped or explicitly worktree-scoped from preflight. - MUST treat a slow native whole-diff review (
review_transport=native|native_fallback) as the intended closure lane for standard branch-backed$fixruns; do not relabel it as non-convergent or abandon it solely because the branch diff is larger than the immediate fix seam. - MUST run
P0 Core Reviewas the first core pass, using the frozen review context's active review transport (review_transport=nativeby default,review_transport=casonly for explicit detached-control runs) as a fixer-owned pass that is reported inPass trace, notReview loop trace. - MUST classify
P0 Core Reviewoutput intolocal_findingsandblocked_findingsonly;stale_findingsare terminal-review-only. - MUST stop
P0 Core Reviewonly when nolocal_findingsremain; blockedP0 Core Reviewfindings may carry forward as pre-terminal only and do not close$fix. - MUST run every terminal
R#review round in a fresh isolated review invocation with no authoring carry-over from the fixer. For branch-diff rounds, first confirm the live merge base still matches the frozencomparison_sha; if it drifts, stop blocked and refresh review context in a new$fixrun. Native rows use freshcodex review --base <base_branch>on the frozen whole diff; detached rows use fresh split CASstartpluswait; native fallback rows are allowed only when the immediately preceding detached CAS attempt for the same run-localcas_attempt_keyfailed with an allowed fallbackfailureCode. The fixer may address findings but must not both author and adjudicate the same review round. - MUST derive
base_branchandcomparison_shafrom repo state for any git-backed run with a live diff when they are omitted, preferring the branch's actual review base plus merge-base commit whenever derivable (tracked/upstream/default base branch). Reserve a current worktree/HEAD fallback only for explicitly worktree-scoped requests with no broader base. For git-backed live diffs, missing review context after derivation is a blocker, not a successfulskip_missing_base_contextpath. - MUST verify
comparison_sharesolves to a commit before activatingP0 Core Reviewor the terminal diff review loop. - MUST freeze that canonical review context for every outer cycle in the run once preflight verification succeeds.
- MUST keep the terminal diff review loop separate from
Pass trace; report it inReview loop trace. - MUST rerun the isolated review loop against the current final diff after the self-review loop and after any post-self-review rerun edits; do not close
$fixuntil two consecutive terminal review rounds on the unchanged final diff yieldlocal_findings=0,blocked_findings=0,stale_findings=0,overall_correctness="patch is correct", and every enumerated proof surface isproved|blocked. - MUST treat blocked
P0 Core Reviewcarry-forward as pre-terminal only. A terminal final-diff closure round with anyblocked_findingsorstale_findingsis not review-clean and does not close$fix. - MUST NOT treat a terminal final-diff review round with
blocked_findings>0as closed orlocal_clean; if a fresh reviewer still emits any finding,$fixis not done. - MUST NOT treat a terminal final-diff review round with
stale_findings>0as closed orlocal_clean; if a fresh reviewer still emits a repeated finding,$fixis not done. - MUST use
result=local_cleanonly whenlocal_findings=0,blocked_findings=0,stale_findings=0, andoverall_correctness="patch is correct"; otherwise keepresult=continue. - MUST require two consecutive clean terminal review rows on the unchanged final diff (same frozen
base_branch/comparison_sha, no intervening edits) before closing$fix. - MUST suppress a repeated diff-review finding only when its normalized fingerprint and implicated path set did not change across consecutive review rounds and the current proof bundle directly disproves the finding or the implicated diff hunk/form no longer exists; unchanged repetition alone is not enough.
- MUST judge diff-review findings by author-fix-worthiness: flag only discrete, actionable bugs introduced by the diff that materially affect correctness, performance, security, or maintainability and that the original author would likely fix if they knew about them.
- MUST prefer zero diff-review findings over speculative or assumption-heavy output; do not flag pre-existing issues, intentional behavior changes, or style-only nits.
- MUST require every diff-review finding that claims broader impact to name the concrete callers/files/functions that are provably affected, and keep each finding comment to one matter-of-fact paragraph that states the triggering scenario or inputs.
- MUST consume CAS
reviewResultoutput for diff-review findings and normalize its camelCase fields back into the local bookkeeping with[P0]..[P3]titles, numericpriority, tight diff-overlappingcode_location, and anoverall_correctnessverdict. - MUST NOT pass steady-state
--custom-instructionstocas review_session startwhen detached CAS is in use; thereview/starttarget owns the reviewer rubric for normal git-backed$fixrounds. - MUST NOT fall back to native
codex reviewwhen CAS returnsfailureCode=wait_timed_out|review_failed|review_interrupted|approval_denied; those are transport/runtime failures that must be retried on the samereviewThreadIdor reported, not masked. - MUST use a cumulative long-poll wait budget before declaring review transport blocked: for detached CAS waits, keep waiting on the same
reviewThreadIdacross a run-local timeout ladder of60000,120000,300000, and600000ms (total1080000ms) before stopping blocked; for native fallback on the same frozen review context, continue polling/waiting up to that same cumulative budget before declaring the review lane blocked. - MUST enumerate every PROVEN_USED external surface touched by code/docs/examples before closing the core-pass phase.
- MUST assign each enumerated public/documented surface exactly one dedicated proof hook or one explicit blocker; a sibling or nearby proof hook does not discharge another advertised form.
- MUST NOT accept a heuristic fallback or compatibility-sensitive public-seam change as done while the advertised/documented form it changes is still unproven.
- MUST NOT mark a diff-review finding stale when it targets a PROVEN_USED external surface that still lacks a dedicated proof hook or explicit blocker.
- MUST include a final
Self-review loop tracesection in the deliverable/Fix Record. - MUST run the final agent-directed self-review loop only after at least one change is applied and validation is passing.
- MUST run the self-review loop against the final validated changeset only.
- MUST invalidate and rerun the self-review loop if any non-self-review edit occurs after a self-review round, including edits from the post-self-review rerun or final diff review closure loop.
- MUST ask internally exactly:
If you could change one thing about this changeset what would you change? - MUST treat the final agent-directed self-review phase as current-worktree scoped once the first validated changeset exists; do not reject a self-review suggestion solely because it broadens the diff.
- MUST, when answering the self-review question, first inventory unresolved review-qualifying findings on the current final diff using
Diff review finding bar (required); if any exist, choose the highest-severity unresolved one before considering ergonomic/structural/API-shaping improvements. - MUST, when answering the self-review question, also inventory unresolved actionable footgun findings on the touched surfaces or adjacent seam before considering broader ergonomic/structural/API-shaping improvements.
- MUST treat a self-review answer as actionable whenever it identifies a concrete compatible/provable improvement on the current validated changeset, even if the improvement is ergonomic, structural, or API-shaping rather than a baseline bug fix.
- MUST answer that question internally, apply at most one new actionable self-review change per self-round, re-run validation, and repeat until a self-round yields no new actionable self-review change or only blocked changes.
- MUST, when public/documented surfaces are touched, answer that question by first inventorying which advertised surface remains unproven;
finding=noneis allowed only when every such surface is proved or explicitly blocked and the current final diff yields zero qualifying findings under the diff review bars. - MUST NOT reject a self-review suggestion solely because the baseline is already green, the concern sounds architectural, or the change would reshape a public/API seam; if it can stay backward-compatible and be revalidated locally, implement it.
- MUST, when a self-review critique is broader than the smallest bug repair, apply the narrowest compatible/provable slice that materially addresses the critique before considering broader follow-up skills.
- MUST rerun the non-self-review
$fixpasses once after the self-review loop reachesno_new_actionable_changesorblocked. - MUST NOT use
scope_guardrailas the reason to reject a self-review suggestion once the self-review phase has started. - MUST NOT carry a terminal final-diff review finding as
blocked_by=scope_guardrail; after self-review starts, treat it aslocal_findingsor block it for another allowed reason. - MUST NOT report a self-review answer that was already applied before the final self-review round; record
finding=noneonly when the current final validated changeset yields no concrete compatible/provable self-review change and no qualifying diff-review finding remains. - MUST NOT emit
If you could change one thing about this changeset what would you change?as a user-facing terminal line during normal successful completion. - MUST treat
$fixas a whole-skill outer fixed-point loop: complete the current cycle through post-self-review rerun plus terminal final-diff review closure, then decide whether to restart from preflight using the same frozen review context. - MUST record
cycle_index,cycle_edit_tally,zero_edit_cycle_streak, andreview_context_receiptfor each full cycle; usegit diff --no-ext-diff <comparison_sha>as the fingerprint source for review-backed cycles. - MUST count a cycle as zero-edit only when
cycle_edit_tally=0and the cycle's review-context receipt is unchanged (fingerprint=samefor review-backed runs or the same skip reason for skipped-review runs). - MUST require two consecutive zero-edit full cycles, even when the first full cycle applies no edits.
- MUST NOT add a new top-level transcript section for cycle reporting; keep cycle visibility inside runtime pass updates,
Pass trace, andReview loop trace. - MUST NOT add an explicit outer-cycle cap; keep looping until
zero_edit_cycle_streak=2or another existing blocker stops the run. - MUST stop
$fixonce no new actionable self-review change remains, no actionable footgun on the touched surfaces or adjacent seam remains unresolved, the current cycle reaches clean terminal final-diff review closure, andzero_edit_cycle_streak=2; do not continue under$fixinto broader architecture, product, roadmap, or conceptual analysis. - MUST, if the user asks for broader or bolder analysis after a clean or closed
$fixpass, close the$fixdeliverable first and recommend the next skill explicitly ($grill-me,$parse,$plan, or$creative-problem-solver) instead of continuing under$fix. - When paired with
$tkin wave execution, MUST treat$fixas the final mutating pass before artifactization:commit_first: hand off immediately to$commitafter passing validation.patch_first: hand off immediately to$patchafter passing validation.
Default policy (non-interactive)
Use these defaults to maximize autonomy (avoid asking).
Priority order (highest first):
- correctness + data safety + security
- compatibility for PROVEN_USED behavior
- performance
Definitions:
- PROVEN_USED = behavior with evidence (see checklist below).
- NON_PROVEN_USED = everything else.
PROVEN_USED evidence checklist (deterministic)
Goal: classify behavior as PROVEN_USED vs NON_PROVEN_USED without asking.
Algorithm:
- Enumerate affected behavior tokens:
- API symbols (functions/types/methods).
- CLI flags/commands.
- config keys / env vars.
- file/wire formats (field names, JSON keys).
- error codes/messages consumed by callers.
- Collect evidence in this order (stop at first match):
- User repro/signal references the token.
- Tests assert on the token/behavior.
- Docs/README/examples/CHANGELOG/config examples describe or demonstrate the token/behavior.
- Repo callsites use the token (non-test, non-doc).
- IF any evidence exists, THEN mark PROVEN_USED; ELSE mark NON_PROVEN_USED.
Evidence scan procedure (repo-local):
- Tests: search
tests/,test/,__tests__/,spec/, and files matching*test*/*.spec.*. - Docs/examples: search
README*,docs/,examples/,CHANGELOG*,config.example*, and*.md. - Callsites: search remaining source files.
- CI/config surfaces: also scan
.github/workflows/for env vars, flags, and script entrypoints.
Tooling hint: prefer rg -n "<token>" with --glob filters.
Deterministic scan command template (run in this order):
rg -n "<token>" tests test __tests__ spec --glob '*test*' --glob '*.spec.*'rg -n "<token>" README* docs examples CHANGELOG* config.example* --glob '*.md'rg -n "<token>" .github/workflowsrg -n "<token>" .
Externally-used surface checklist (deterministic)
Treat a surface as external if ANY is true:
- Token appears in docs/README/examples.
- Token is a CLI flag/command, config key, env var, or file format field.
- Token is exported/public API (examples: Rust
pub, TS/JSexport, Python in__all__, Go exported identifier).
If external use is plausible but uncertain:
- Prefer an additive compatibility path (wrapper/alias/adapter) if small.
- Ask only if a breaking change is unavoidable.
Compatibility rules:
- MUST preserve PROVEN_USED behavior unless it is unsafe (crash/corruption/security). If unsafe, tighten and return a clear error.
- For NON_PROVEN_USED behavior, treat it as undefined; tightening is allowed.
API/migration rules:
- IF a fix touches an externally-used surface (use
Externally-used surface checklist), THEN prefer additive/backward-compatible changes (new option/new function/adapter) over breaking changes. - IF a breaking change is unavoidable, THEN stop and ask.
Surface proof coverage (deterministic)
Goal: prevent public/documented surfaces from closing on partial or sibling proof.
Algorithm:
- Enumerate
proof surfacesfrom the touched slice:- every PROVEN_USED external surface touched by code changes
- every docs/example form changed by the diff that advertises caller-visible behavior on that surface
- Split one API seam into multiple proof surfaces when callers observe distinct forms separately (for example inferred vs explicit errors, omitted vs provided config, or separate constructor/helper forms).
- For each proof surface, record:
- surface token/form
- evidence that it is PROVEN_USED
- exact proof hook OR explicit blocker
- status=
proved|blocked
- Do not close the diff review loop or the core-pass phase while any proof surface is still unproved.
Rules:
- A failing/proving hook for one lexical lane does not discharge a different advertised/documented form on the same public surface.
- Docs/examples edits create proof obligations for the advertised forms they change; they are not commentary-only when they describe caller-visible behavior.
- If a public seam fix introduces a heuristic fallback, unresolved-default, or compatibility-sensitive narrowing, treat that seam as unproved until the exact advertised/documented form is covered by a dedicated proof hook or blocker.
Performance rules:
- MUST avoid obvious asymptotic regressions in hot paths.
- IF performance impact is plausible but unmeasurable locally,
THEN choose the smallest correctness-first fix and record the risk in
Residual risks / open questions(do not ask).
Autonomy gate (conviction)
Proceed without asking only if ALL are true:
- SIGNAL: you have (or can create) a local repro/signal without product ambiguity.
- CONTRACT: you can derive contract from repo evidence OR characterize current behavior without product ambiguity.
- INVARIANT: you can state invariant_before and invariant_after.
- DIFF: the change is localized and reviewable for the chosen strategy.
- PROOF: at least one validation signal passes after changes.
If ANY gate fails:
- Apply Defaults + contract derivation.
- Ask only if still blocked.
Correctness tightening (default)
Definition: tightening = rejecting invalid/ambiguous states earlier, removing silent failure paths, or making undefined behavior explicit.
Rule:
- IF tightening prevents crash/corruption/security issue, THEN apply it (even if PROVEN_USED), return a clear error, and record the compatibility impact.
- ELSE IF tightening affects only NON_PROVEN_USED inputs/states, THEN apply it without asking.
- ELSE (tightening might change PROVEN_USED behavior):
- prefer a backward-compatible shape (adapter/additive API), OR
- lock current behavior with a characterization test,
- ask only if compatibility cannot be preserved.
Allowed tightening moves (examples only):
- Parse/coerce: implicit coercion/partial parse -> explicit parse + error (JS implicit string->number; Rust
parse().ok()fallback). - Fallbacks: warn+fallback/default-without-signal -> explicit error OR explicit "unknown"/"invalid".
- Lossy conversion: truncation/clamp/wrap -> checked conversion + error (Rust
as; C casts; Go int conversions). - Partial updates: multi-step mutation -> atomic/transactional boundary OR explicit partial result.
- Ignored errors: ignore -> propagate with context; if intentionally ignored -> compensating signal (assert/test/metric/log).
- Sentinels:
-1/0/""/None-> richer returns.
Defaults (use only when semantics-preserving for valid inputs)
Ownership / lifetimes
- MUST inventory in-slice resources: allocations, handles, sockets, locks, txns, temp files.
- For each resource, record: acquire_site, owner, release_action.
- MUST ensure every exit releases exactly once.
- MUST free/release ONLY via the proven owner/allocator/handle.
- Never assume a "free" is safe without proving allocator/ownership.
- Arena/bump allocators: per-object
freeis safe only if explicitly documented as permitted/no-op.
Validation signal selection
Algorithm:
- IF the user provided a command, use it.
- ELSE choose the cheapest local signal (no network) in this order:
- README/QUICKSTART
scripts/check/scripts/testMakefile/justfile/Taskfile.yml
- ELSE create a proof hook in this order:
- focused regression/characterization test
- boundary assertion that fails loudly
- scoped + rate-limited diagnostic log tied to ONE invariant (never log secrets/PII)
No-signal fail-fast (deterministic):
- If no signal/proof hook is available after executing the selection algorithm once, stop before editing.
- Return one blocker with
blocked_by=no_repro_or_proofand include the exact commands you attempted.
PR/diff scope guardrail (default in review mode)
- Default slice = changed lines/paths (git diff/PR diff) + at most one boundary seam (parse/construct/API edge) required to make the fix sound.
- Do not fix pre-existing issues outside the slice unless:
- severity is security/crash/corruption AND
- the fix is localized and provable without widening the slice.
- Otherwise: record as
Residual risks / open questions.
Scope widening trigger (deterministic):
- Widen beyond the diff only when ALL are true:
- severity is
security,crash, orcorruption - you can show a concrete causal chain from a diff token to the out-of-slice location
- the widening is limited to one adjacent seam (at most one additional file/module boundary)
- one local validation signal can prove the widened fix
- severity is
- If any check fails, keep scope fixed and record
blocked_by=scope_guardrail. - This guardrail applies to the core review passes.
- Once the final agent-directed self-review loop starts, scope expands to the current repo/worktree and
scope_guardrailis not a valid reason to reject the self-review suggestion.
Generated / third-party code guardrail
- If a file appears generated or is under third-party/build output, do not edit it directly.
- Prefer to locate the source-of-truth + regeneration step; apply fixes there and regenerate as needed.
- Common no-edit zones (examples):
dist/,build/,vendor/,node_modules/.
Proof discipline for passing baselines
When the baseline signal is ok:
- For every acted-on finding, prefer a proof hook that fails before the fix (focused regression/characterization test).
- For every enumerated proof surface under
Surface proof coverage (deterministic), prefer a failing proof hook before the fix; only an explicit blocker may replace that hook. - If you cannot produce a failing proof hook, do not edit; attempt to create one first by:
- turning the counterexample into a focused regression/characterization test
- enforcing the invariant at a single boundary seam (parse/refine once) and testing the new error
- reducing effects to a pure helper and unit-testing it
- using an existing fuzzer/property test harness if present
- Only if you still cannot create a proof hook without product ambiguity, record the blocker as residual risk.
- A proof hook for one sibling, lexical, or nearby form does not satisfy another advertised proof surface.
- If the fix changes a public seam by adding a heuristic fallback or narrowing unresolved behavior, treat that seam as unproved until the exact advertised/documented form has a dedicated proof hook or blocker.
- Self-review exception: when the self-review finding is a concrete compatible simplification or auditability improvement on an already-green changeset, a fresh failing hook is preferred but not mandatory; the primary validation bundle may serve as the proof hook if it still proves the improved invariant after the change.
Residual risks / open questions policy (last resort)
Residual risks are a record of what you could not safely fix (not a to-do list).
Rules:
- Before emitting a residual item, attempt to convert it into an actionable finding:
- produce a concrete counterexample
- attach a proof hook (test/assert) that fails before the fix
- apply the smallest localized fix within guardrails
- re-run the validation signal
- Only emit residual items that are truly blocked by one of these blockers:
product_ambiguity(semantics cannot be derived/characterized safely)breaking_change(no additive path; fix would be breaking)no_repro_or_proof(cannot create a repro/proof hook locally)scope_guardrail(outside diff slice and not severe enough to widen)generated_output(generated/third-party output; need source-of-truth + regen)external_dependency(needs network/creds/services/hardware)perf_unmeasurable(impact plausible; no local measurement)
- For self-review-originated changes, do not emit
blocked_by=scope_guardrail; if scope is the only blocker, widen and continue. - Every residual bullet MUST include: a location or token,
blocked_by=<product_ambiguity|breaking_change|no_repro_or_proof|scope_guardrail|generated_output|external_dependency|perf_unmeasurable>, andnext=<one action>. - If there are no residual items, output
- None.
Multi-pass loop (default)
Goal: reduce missed issues in PR/diff reviews without widening scope.
Run 4 core passes (mandatory). Run 2 additional delta passes only if pass 3 edits code.
Pass 0) Core Review
- Scope: diff-driven slice against the frozen
comparison_sha. - Focus: run one isolated git-backed review against the frozen review context as a fixer-owned analysis lens before
P1. Prefer nativecodex review --base <base_branch>orcodex review --commit <sha>for ordinary one-shot verdicts; use split detached CAS (startpluswait) only when the run explicitly needs detached lifecycle control. Normalize the chosen review transport's output into the same local bookkeeping. - Loop: classify returned findings into
local_findingsandblocked_findings, fixlocal_findings, re-run the local signal, and repeat until nolocal_findingsremain. - Reporting: record
P0 Core ReviewinPass traceand runtime pass updates; reserveReview loop tracefor terminal isolated closure only. - Carry-forward: blocked
P0 Core Reviewfindings may continue as pre-terminal only and can later become residual items if they stay valid.
Pass 1) Safety (highest severity)
- Scope: diff-driven slice + required boundary seams.
- Focus: security/crash/corruption hazards, unsafe tightening, missing error propagation.
- Change budget: smallest sound fix only.
Pass 2) Footguns
- Scope: every touched public/documented surface plus at most one adjacent caller, constructor, parser, wrapper, or config boundary seam when needed to prove misuse.
- Focus: concrete plausible misuse, surprising defaults, ambiguous booleans, implicit units, sentinel returns, partially validated option combinations, order dependence, overloaded helpers, and silent fallbacks.
- Output: for each touched public/documented surface, produce at least one top-ranked misuse path or an explicit
none_with_reason. - Change budget: additive/clarifying defusals preferred; if the compatible/provable mitigation is concrete, it becomes a normal finding and blocks closure until fixed, proved, or blocked.
Pass 3) Surface + Audit
- Scope: externally-used surfaces touched by the diff plus the final diff slice.
- Focus: additive compatibility, public/documented proof surfaces, invariants enforced at strongest cheap boundary, ownership release-on-all-paths, and proof strength.
- Delegation: always run
$invariant-acefirst for invariant framing, then$complexity-mitigatorfor complexity verdicts that affect auditability. - Change budget: no refactors unless they directly reduce risk/auditability of invariants.
Early exit (stop after pass 3):
- If pass 3 applies no edits, stop the core-pass phase (after running/confirming the primary validation signal).
Delta passes (only if pass 3 applied edits)
Pass 4) Safety delta rescan
- Scope: ONLY lines/paths changed by passes 1-3 and their immediate boundaries.
- Focus: new security/crash/corruption hazards introduced by the fixes.
Pass 5) Footgun + surface/proof delta rescan
- Re-enumerate behavior tokens from the FINAL diff (including newly introduced errors/flags/exports/config keys).
- Re-run the footgun discovery bar on newly introduced or narrowed surfaces and adjacent seam obligations.
- Re-run PROVEN_USED/external-surface checks for newly introduced tokens.
- Ensure proof is still strong for the final diff.
Rules:
- After any pass that edits code, run a local signal before continuing.
- Do not edit on suspicion: every edit must have a concrete counterexample, invariant_before/after, and a proof hook.
- During the self-review phase, the counterexample may be an auditability or responsibility-split failure in the current validated changeset; if the change is compatible and locally validated, that is actionable under
$fixeven when the baseline was already green. - Merge/de-duplicate findings across passes; final output format stays unchanged.
- Emit pass progress updates in real time at pass start/end; these updates are required and do not replace the final
Pass tracesection.
Clarify before changes
Stop and ask ONLY if any is true:
- Behavior is contradictory/product-sensitive AND cannot be derived from tests/docs/callsites AND cannot be characterized safely.
- A breaking API change or irreversible migration is unavoidable (no backward-compatible path).
- No local signal/proof hook can be found or created without product ambiguity.
Finding record schema (internal)
For every issue you act on, construct this record before editing:
- id:
F<number> - location:
file:line - severity:
security|crash|corruption|logic - issue:
- origin:
review_seed|p0_core_review|proof_hook|footgun_scan|self_review|terminal_review - seeded_review:
yes|no - tokens: <affected behavior tokens; empty if none>
- proven_used: <yes/no + evidence if yes>
- external_surface: <yes/no + why>
- diff_touch: <yes/no>
- proof_target: <exact advertised/documented form covered by the proof>
- counterexample: <input/timeline>
- invariant_before: <what is allowed/assumed today>
- invariant_after: <what becomes guaranteed/rejected>
- fix:
- proof: <test/assert/log + validation command + result>
- proof_strength:
characterization|targeted_regression|property_or_fuzz - compatibility_impact:
none|tightening|additive|breaking
Canonical finding example (fully-filled)
Use this as the reference shape when writing findings.
F1 `src/config_loader.py:88` — crash — untrusted config type causes uncaught attribute access
- Surface: Tokens=config.path; PROVEN_USED=yes (tests/config/test_loader.py::test_reads_path); External=yes; Diff_touch=yes
- Provenance: Origin=review_seed; Seeded review=yes
- Proof target: explicit rejection of null `config.path` before `cfg.path.strip()`
- Counterexample: `{"path":null}` reaches `cfg.path.strip()` and raises `AttributeError`
- Invariant (before): loader assumes `path` is a non-empty string
- Invariant (after): loader accepts only non-empty string `path`; invalid type returns explicit error
- Fix: add boundary validation in `parse_config()` and reject invalid `path` before use
- Proof: `uv run pytest tests/config/test_loader.py::test_rejects_null_path` -> ok
- Proof strength: `targeted_regression`
- Compatibility impact: `tightening`
Residual risks / open questions
- `vendor/generated/config_schema.py` — blocked_by=generated_output — next=edit source schema and regenerate artifact
Workflow (algorithm)
0) Preflight
- Determine mode: review-only vs fix.
- Define slice:
- If in a git repo and there is a diff, derive slice/tokens from the diff (paths, changed symbols/strings).
- Otherwise: entrypoint, inputs, outputs, state.
- If the request is PR-scoped (for example "
$fix this PR", "$fix current branch", CI failure on a PR), anchor the slice to PR diff/base and keep the work PR-local unless severity widening is required. - Apply
PR/diff scope guardrailfor review mode. - Apply
Generated / third-party code guardrailbefore editing. - Determine review-loop activation:
- If
git rev-parse --is-inside-work-treefails, setReview loop traceto- None (skip_not_git_repo)and continue. - If the repo is git-backed and there is a live diff while
base_branchorcomparison_shais missing, derive them from repo state, preferring the branch's actual review base plus merge-base commit whenever derivable (tracked/upstream/default base branch). Reserve a current worktree/HEAD fallback only for explicitly worktree-scoped requests with no broader base; omitted-but-derivable git context is not a skip case. - If the repo is git-backed and there is a live diff, but
base_branchorcomparison_shais still missing after derivation, stop and ask with the derivation attempts; do not emitskip_missing_base_context. - If there is no live diff and no review target can be derived, set
Review loop traceto- None (skip_missing_base_context)and continue. - Otherwise verify
comparison_shawithgit rev-parse --verify <comparison_sha>^{commit}and freeze the canonical commit for the rest of the run and every outer cycle. For review-backed runs, also freezereview_transport_default=<native|cas>(nativefor ordinary one-shot branch/commit verdicts;casonly for explicit detached-control runs), the frozen review comman
- If
…(truncated)