Review+fix protocol with optional pre-core git diff review and safety guardrails (unsoundness, invariants, footguns, incidental complexity). Use when prompts say "/tw-fix this PR", "fix current branch", "fix this diff", "repair CI red", or "apply a minimal patch", and when crash/corruption/invariant-break issues need correction with a validation signal. Stop only after self-review exhausts actionable changes, each full cycle reaches post-self-review rerun plus terminal diff-review closure, an...
Scanned 9/9/2026
Install to Claude Code
npx -y skills add SDiamante13/dotfiles --skill tw-fix --agent claude-codeInstalls into .claude/skills of the current project.
Are you the author of Tw Fix?
Add the live security badge to your README — it updates automatically with every re-scan.
[](https://www.skillsdirectory.com/skills/sdiamante13-tw-fix)More formats (shields.io, HTML) on the badges page.
---
name: tw-fix
description: Review+fix protocol with optional pre-core git diff review and safety guardrails (unsoundness, invariants, footguns, incidental complexity). Use when prompts say "/tw-fix this PR", "fix current branch", "fix this diff", "repair CI red", or "apply a minimal patch", and when crash/corruption/invariant-break issues need correction with a validation signal. Stop only after self-review exhausts actionable changes, each full cycle reaches post-self-review rerun plus terminal diff-review closure, and two consecutive zero-edit full cycles are clean.
---
# Fix
## Intent
Make risky or unclear code safe with the smallest sound, validated change, then keep rerunning the whole `/tw-fix` skill as an outer fixed-point loop until no actionable self-review change remains, 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`; `/tw-fix` stops only when that streak reaches `2`. Broader architecture, product, or roadmap analysis belongs to another skill.
Skill-artifact refinement belongs to `/tw-refine`; `/tw-fix` stays focused on code/diff repair turns.
## Execution spine
- `Preflight + frozen review context`
- `Core passes`
- `Residual risk sweep`
- `Agent-directed self-review loop`
- `Post-self-review rerun + final diff review closure`
- `Outer fixed-point cycle convergence`
- `Output / 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 `/tw-creative-problem-solver` when multiple viable strategies exist).
## Auxiliary skills (mandatory)
- `/tw-invariant-ace`: run it on every `/tw-fix` cycle to lock owner/scope, counterexamples, and enforcement boundaries before deciding how to repair the slice.
- `/tw-complexity-mitigator`: run it on every `/tw-fix` cycle after `/tw-invariant-ace` to separate essential complexity from auditability noise before reshaping code.
- Required order: run `/tw-invariant-ace` first, then `/tw-complexity-mitigator`, and import both outputs into `/tw-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)**`, not `Findings`).
- 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.md` when editing this contract.
### Embedded mode (when /tw-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 /tw-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 trace` section 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 produce a complete finding record for every acted-on issue:
- proof_target
- counterexample
- invariant_before
- invariant_after
- fix
- proof
- proof_strength
- compatibility_impact
- MUST follow the delegation contract in `Auxiliary skills (mandatory)` (including order: `/tw-invariant-ace` -> `/tw-complexity-mitigator`) on every `/tw-fix` cycle.
- 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 trace` section in the deliverable/Fix Record.
- MUST use native `git diff review` invocations for git-backed review rounds instead of copying the review prompt into this skill: default to `git diff review --base <base_branch>` for branch-diff review context, and reserve `git diff review --commit <sha>` only for explicitly commit-scoped runs.
- MUST run `P0 Core Review` as the first core pass, using native `git diff review` output against the frozen review context as a fixer-owned pass that is reported in `Pass trace`, not `Review loop trace`.
- MUST classify `P0 Core Review` output into `local_findings` and `blocked_findings` only; `stale_findings` are terminal-review-only.
- MUST stop `P0 Core Review` only when no `local_findings` remain; blocked `P0 Core Review` findings may carry forward as pre-terminal only and do not close `/tw-fix`.
- MUST run every terminal `R#` review round in a fresh `git diff review` CLI invocation with no authoring carry-over from the fixer. For `git diff review --base <base_branch>` rounds, first confirm the live merge base still matches the frozen `comparison_sha`; if it drifts, stop blocked and refresh review context in a new `/tw-fix` run. The fixer may address findings but must not both author and adjudicate the same review round.
- MUST derive `base_branch` and `comparison_sha` from 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 successful `skip_missing_base_context` path.
- MUST verify `comparison_sha` resolves to a commit before activating `P0 Core Review` or 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 in `Review loop trace`.
- MUST rerun the native `git diff review` loop against the current final diff after the self-review loop and after any post-self-review rerun edits; do not close `/tw-fix` until two consecutive terminal review rounds on the unchanged final diff yield `local_findings=0`, `blocked_findings=0`, `stale_findings=0`, `overall_correctness="patch is correct"`, and every enumerated proof surface is `proved|blocked`.
- MUST treat blocked `P0 Core Review` carry-forward as pre-terminal only. A terminal final-diff closure round with any `blocked_findings` or `stale_findings` is not review-clean and does not close `/tw-fix`.
- MUST NOT treat a terminal final-diff review round with `blocked_findings>0` as closed or `local_clean`; if a fresh reviewer still emits any finding, `/tw-fix` is not done.
- MUST NOT treat a terminal final-diff review round with `stale_findings>0` as closed or `local_clean`; if a fresh reviewer still emits a repeated finding, `/tw-fix` is not done.
- MUST use `result=local_clean` only when `local_findings=0`, `blocked_findings=0`, `stale_findings=0`, and `overall_correctness="patch is correct"`; otherwise keep `result=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 `/tw-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 native `git diff review` output for diff-review findings and normalize it into the local bookkeeping with `[P0]`..`[P3]` titles, numeric `priority`, tight diff-overlapping `code_location`, and an `overall_correctness` verdict.
- MUST NOT try to append a custom prompt to `git diff review --base` or `git diff review --commit`; the CLI target owns the review prompt, and the optional `[PROMPT]` argument is only for the standalone custom-review mode.
- 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 trace` section 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 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=none` is 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 `/tw-fix` passes once after the self-review loop reaches `no_new_actionable_changes` or `blocked`.
- MUST NOT use `scope_guardrail` as 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 as `local_findings` or 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=none` only 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 `/tw-fix` as 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`, and `review_context_receipt` for each full cycle; use `git 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=0` and the cycle's review-context receipt is unchanged (`fingerprint=same` for 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`, and `Review loop trace`.
- MUST NOT add an explicit outer-cycle cap; keep looping until `zero_edit_cycle_streak=2` or another existing blocker stops the run.
- MUST stop `/tw-fix` once no new actionable self-review change remains, the current cycle reaches clean terminal final-diff review closure, and `zero_edit_cycle_streak=2`; do not continue under `/tw-fix` into broader architecture, product, roadmap, or conceptual analysis.
- MUST, if the user asks for broader or bolder analysis after a clean or closed `/tw-fix` pass, close the `/tw-fix` deliverable first and recommend the next skill explicitly (`/tw-grill-me`, `/tw-parse`, `/tw-plan`, or `/tw-creative-problem-solver`) instead of continuing under `/tw-fix`.
- When paired with `/tw-tk` in wave execution, MUST treat `/tw-fix` as the final mutating pass before artifactization:
- `commit_first`: hand off immediately to `/tw-commit` after passing validation.
- `patch_first`: hand off immediately to `/tw-patch` after passing validation.
## Default policy (non-interactive)
Use these defaults to maximize autonomy (avoid asking).
Priority order (highest first):
1. correctness + data safety + security
2. compatibility for PROVEN_USED behavior
3. 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:
1. 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.
2. 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).
3. 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/workflows`
- `rg -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/JS `export`, 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:
1. Enumerate `proof surfaces` from 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
2. 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).
3. For each proof surface, record:
- surface token/form
- evidence that it is PROVEN_USED
- exact proof hook OR explicit blocker
- status=`proved|blocked`
4. 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 `free` is safe only if explicitly documented as permitted/no-op.
### Validation signal selection
Algorithm:
1. IF the user provided a command, use it.
2. ELSE choose the cheapest local signal (no network) in this order:
- README/QUICKSTART
- `scripts/check` / `scripts/test`
- `Makefile` / `justfile` / `Taskfile.yml`
3. 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_proof` and 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`, or `corruption`
- 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
- 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_guardrail` is 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>`, and `next=<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 native `git diff review` against the frozen review context as a fixer-owned analysis lens before `P1`.
- Loop: classify returned findings into `local_findings` and `blocked_findings`, fix `local_findings`, re-run the local signal, and repeat until no `local_findings` remain.
- Reporting: record `P0 Core Review` in `Pass trace` and runtime pass updates; reserve `Review loop trace` for terminal isolated closure only.
- Carry-forward: blocked `P0 Core Review` findings 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) Surface (compat + misuse)
- Scope: externally-used surfaces touched by the diff (exports/CLI/config/format/docs).
- Focus: additive compatibility, defuse top footguns, clearer errors.
- Change budget: additive/wrapper/adapter preferred; breaking change => stop and ask.
Pass 3) Audit (invariants + ownership + proof quality)
- Scope: final diff slice.
- Focus: invariants enforced at strongest cheap boundary; ownership release-on-all-paths; proof strength.
- Delegation: always run `/tw-invariant-ace` first for invariant framing, then `/tw-complexity-mitigator` for 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) Surface + proof delta rescan
- Re-enumerate behavior tokens from the FINAL diff (including newly introduced errors/flags/exports/config keys).
- 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 `/tw-fix` even 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 trace` section.
## 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: <one sentence>
- 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: <smallest sound fix that removes the bug-class>
- 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.
```md
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
- 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
1. Determine mode: review-only vs fix.
2. 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.
3. If the request is PR-scoped (for example "`/tw-fix this PR`", "`/tw-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.
4. Apply `PR/diff scope guardrail` for review mode.
5. Apply `Generated / third-party code guardrail` before editing.
6. Determine review-loop activation:
- If `git rev-parse --is-inside-work-tree` fails, set `Review loop trace` to `- None (skip_not_git_repo)` and continue.
- If the repo is git-backed and there is a live diff while `base_branch` or `comparison_sha` is 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_branch` or `comparison_sha` is still missing after derivation, stop and ask with the derivation attempts; do not emit `skip_missing_base_context`.
- If there is no live diff and no review target can be derived, set `Review loop trace` to `- None (skip_missing_base_context)` and continue.
- Otherwise verify `comparison_sha` with `git rev-parse --verify <comparison_sha>^{commit}` and freeze the canonical commit for the rest of the run and every outer cycle. For base-branch review runs, also freeze `review_cmd=git diff review --base <base_branch>` and require later CLI rounds to re-derive the same merge base before invoking the reviewer.
- If that verification fails, stop before editing and report the failed command as a blocker.
7. Select validation signal (or create proof hook).
8. If signal/proof creation fails, stop before editing and return `blocked_by=no_repro_or_proof` with attempted commands.
9. Initialize outer fixed-point state:
- set `cycle_index=1`
- set `zero_edit_cycle_streak=0`
- reuse the same frozen `base_branch`/canonical `comparison_sha` and validation signal across all later cycles
- when review context exists, use `git diff --no-ext-diff <comparison_sha>` as the fingerprint source for every cycle receipt
### 1) Diff review loop
This phase runs only as the final closure gate on the current final diff after self-review/post-self-review edits settle. `P0 Core Review` reuses native `git diff review` inside `Core passes`, but it is fixer-owned and reported in `Pass trace`, not `Review loop trace`.
### Diff review finding bar (required)
- Flag only discrete, actionable bugs introduced by the diff that materially impact correctness, performance, security, or maintainability.
- Apply the author-fix-worthiness bar: the issue should be something the original author would likely fix if it were pointed out.
- Do not flag pre-existing issues, intentional behavior changes, speculative risks, or style-only nits unless they obscure meaning or violate documented standards.
- Do not rely on unstated assumptions about intent or environment; when claiming broader impact, identify the concrete callers/files/functions that are provably affected.
- Prefer no findings over weak findings.
### Diff review comment bar (required)
- Use one finding per distinct issue and keep the line range as short as possible while still pinpointing the problem.
- Keep the body to one paragraph in a matter-of-fact tone. Explain why it is a bug, how severe it is in context, and the scenario or inputs required for it to arise.
- Avoid long code excerpts; do not include code blocks longer than 3 lines.
### Diff review priority bar (required)
- Prefix each finding title with `[P0]`, `[P1]`, `[P2]`, or `[P3]`.
- `P0`: universal/blocking release or major usage issue with no special assumptions.
- `P1`: urgent; should be fixed in the next cycle.
- `P2`: normal; should be fixed eventually.
- `P3`: low; nice to have.
- Mirror the title priority in numeric `priority` using `0` for `P0`, `1` for `P1`, `2` for `P2`, and `3` for `P3`.
### Diff review output schema (required)
```json
{
"findings": [
{
"title": "<= 80 chars, starts with [P0]-[P3]>",
"body": "<one-paragraph Markdown explaining why this is a bug and when it occurs>",
"confidence_score": "<float 0.0-1.0>",
"priority": "<int 0-3>",
"code_location": {
"absolute_file_path": "<absolute file path>",
"line_range": {
"start": "<int>",
"end": "<int>"
}
}
}
],
"overall_correctness": "\"patch is correct\" | \"patch is incorrect\"",
"overall_explanation": "<1-3 sentence explanation>",
"overall_confidence_score": "<float 0.0-1.0>"
}
```
Rules:
- The diff review output is JSON-only: no fences, no prose, no fix patch.
- `code_location` is required, must overlap the diff, and should stay as tight as possible.
- Return all qualifying findings, not just the first. If there is no finding the author would definitely want to fix, return an empty `findings` list and set the overall verdict accordingly.
### Native git diff review command (required)
- Default git-backed review command: `git diff review --base <base_branch>`.
- Explicit commit-scoped review command: `git diff review --commit <sha>`.
- `git diff review --base <base_branch>` resolves the merge base internally; before each round, confirm that the currently derived merge base still matches the frozen `comparison_sha`.
- Do not paste the built-in review prompt into this skill. `git diff review` owns the reviewer rubric and target prompt internally.
- The optional `[PROMPT]` argument belongs only to standalone custom-review mode; with `--base` or `--commit`, the target flag wins and the prompt argument is ignored.
- Consume the CLI's native prioritized findings plus `overall_correctness`, then normalize them into the local `local_findings` / `blocked_findings` / `stale_findings` bookkeeping.
Algorithm:
1. If `Review loop trace` already contains a skip line from preflight, continue to phase 2.
2. Run `git diff review --base <base_branch>` in a fresh CLI invocation after confirming the live merge base still matches the frozen `comparison_sha`.
3. Partition the returned findings into:
- `local_findings`: locally fixable under the active guardrails for the current phase
- `blocked_findings`: findings that are blocked under the existing blocker model
- `stale_findings`: repeated locally-fixable findings whose normalized fingerprint and implicated path set did not change across consecutive rounds after an address round
- Once self-review has started, the terminal final-diff closure loop is current-worktree scoped and `scope_guardrail` is not a valid blocker.
4. Emit one `Review loop trace` row per terminal review round.
5. If `local_findings > 0`, address all review findings, re-run the chosen validation signal, then repeat from step 2.
6. If a repeated locally-fixable finding is stale, suppress it from loop continuation and count it under `stale_findings` only when its normalized fingerprint and implicated path set did not change across consecutive rounds and the current proof bundle directly disproves the finding or the implicated diff hunk/form no longer exists.
- Do not mark a finding stale if it targets a PROVEN_USED external surface that still lacks a dedicated proof hook or explicit blocker.
7. Re-check `Surface proof coverage (deterministic)` against the current diff before closing the round.
8. Close the terminal diff review loop only when a review round yields `local_findings=0`, `blocked_findings=0`, `stale_findings=0`, `overall_correctness="patch is correct"`, and every enumerated proof surface is `proved|blocked`.
### 2) Core passes
1. Determine PROVEN_USED behavior:
- Apply `PROVEN_USED evidence checklist` to the behavior tokens affected by the slice.
2. Enumerate proof surfaces:
- Apply `Surface proof coverage (deterministic)` to the touched code/docs/examples before deriving closure.
3. Derive contract without asking (in this order):
- tests that exercise the slice
- callsites in the repo
- docs/README/examples
- if none: add a characterization test for current behavior
4. Write contract (1 sentence): "Working means …".
5. Run baseline signal once; record result.
6. If baseline signal is ok, apply `Proof discipline for passing baselines`.
7. Enumerate candidate failure modes for the slice.
8. Rank security > crash > corruption > logic.
9. For each issue you will act on, create a finding record.
10. Run the `Multi-pass loop (default)` for the touched slice, starting with `P0 Core Review`.
#### 2a) Unsoundness scan
For each hazard class that applies:
- Identify the first failure point.
- Provide a concrete counterexample (input/timeline).
- Specify the smallest sound fix that removes the bug-class.
Hazard classes:
- Security boundaries: authz/authn, injection, path traversal, SSRF, unsafe deserialization, secrets/PII handling.
- Nullability/uninitialized state; sentinel values.
- Ownership/lifetime: leaks, double-free, use-after-close, lock not released.
- Concurrency/order/time: races, lock ordering, reentrancy, timeouts/retries, TOCTOU.
- Bounds/arithmetic: indexing/slicing, overflow/underflow, signedness.
- Persistence/atomicity: partial writes, torn updates, non-transactional multi-step updates.
- Encoding/units: bytes vs chars, timezone/locale, unit mismatches, lossy normalization.
- Error handling: swallowed errors, missing context, silent fallback.
Language cues (examples only):
- Rust: `unsafe`, `unwrap/expect`, `as` casts.
- JS/TS: `any`, implicit coercions, `undefined` flows.
- Python: bare `except`, truthiness-based branching.
- C/C++: raw pointers, unchecked casts, manual `malloc/free`.
#### 2b) Invariant strengthening scan
Run `/tw-invariant-ace` on every `/tw-fix` cycle and import its artifacts into `fix`.
Default execution:
1. Run `/tw-invariant-ace` Compact Mode first.
2. Capture at minimum:
- `Counterexample`
- `Invariants`
- `Owner and Scope`
- `Enforcement Boundary`
- `Seam (Before -> After)`
- `Verification`
3. Map these to `fix` finding fields:
- `invariant_before` from broken trace + prior scope,
- `invariant_after` from chosen predicate(s) + holds scope,
- `fix` from seam,
- `proof` from verification signal.
4. Escalate to full `/tw-invariant-ace` protocol if Compact Mode does not yield an inductive predicate.
#### 2c) Footgun scan + defusal
Trigger: you touched an API surface OR a caller can plausibly misuse the code.
For top-ranked misuse paths:
1. Provide minimal misuse snippet + surprising behavior.
2. Defuse by changing the surface:
- options structs / named params
- split booleans into enums or separate functions
- explicit units/encodings
- richer returns (no sentinels)
- separate pure computation from effects
3. Lock with a regression test or boundary assertion.
#### 2d) Complexity scan (risk-driven)
Run `/tw-complexity-mitigator` on every `/tw-fix` cycle after `/tw-invariant-ace`; implement only via `fix`.
Rule: reshape only when it reduces risk and improves auditability of invariants/ownership.
Algorithm:
1. Run `/tw-complexity-mitigator` on the touched slice (heat read + essential/incidental verdict + ranked options + TRACE).
2. Select the smallest viable cut that directly supports a finding (safety/surface/invariant ownership/proof quality).
3. If simplification depends on an unstated invariant, run/refresh `/tw-invariant-ace` first.
4. Keep complexity-only cleanup out of scope unless it closes a concrete risk.
11. Implement fixes (per finding).
For findings in severity order:
1. Implement the smallest sound fix that removes the bug-class.
2. Apply correctness tightening when allowed.
3. Ensure invariants + ownership hold on all paths.
4. Keep diff reviewable; avoid drive-by refactors.
12. Close the core-pass phase.
- Run the chosen validation signal.
- If it fails, update findings with the new counterexample, apply the smallest additional fix, and re-run the SAME signal.
- Repeat until the signal passes.
- Re-check `Surface proof coverage (deterministic)` and do not close while any proof surface remains unproved.
- If you cannot make progress after 3 repair cycles, stop and ask with the last failing output, what you tried, and the smallest remaining decision that blocks you.
### 3) Residual risk sweep (required)
1. Re-check `Residual risks / open questions policy`.
2. Any item without a valid blocker becomes a finding and is fixed (with proof) or dropped.
### 4) Agent-directed self-review loop (required final step when a changeset exists)
1. Precondition gate: run this step only when `Changes applied` is not `None` and the latest validation signal result is `ok`.
2. Freeze the self-review baseline as the latest validated changeset.
3. Ask internally exactly: `If you could change one thing about this changeset what would you change?`
4. Before considering ergonomic/structural/API-shaping improvements, 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.
5. If public/documented surfaces are touched, answer that question by first inventorying which advertised proof surface remains unproven.
6. Summarize the self-round in `Self-review loop trace` with one delta row.
7. If the answer yields one new actionable self-review change:
- convert it into one concrete finding,
- treat compatible ergonomic/structural/API-shaping improvements as actionable when they materially improve the current validated changeset and can be proven locally,
- widen anywhere in the current repo/worktree as needed,
- apply the smallest sound change that materially addresses the critique,
- re-run the chosen validation signal and update findings/proof,
- record the `(validated_changeset_fingerprint, normalized_answer_summary)` pair so repeated suggestions cannot loop forever,
- repeat from step 2.
8. If the answer yields only blocked changes, record `stop_reason=blocked`, carry blockers to `Residual risks / open questions`, and continue to phase 5.
9. If the answer yields no new actionable self-review change, record `stop_reason=no_new_actionable_changes` and continue to phase 5.
- `finding=none` is allowed only when every enumerated proof surface is `proved|blocked` and the current final diff yields zero qualifying findings under the diff review bars.
- This check is against the current final validated changeset, not an earlier pre-delta review state.
- `already green`, `architectural`, `not fix-shaped`, or `no failing proof hook` are not sufficient reasons by themselves when a concrete compatible/provable improvement or review-qualifying finding still exists.
10. Skip gate: if `Changes applied` is `None` or the run is blocked before edits, output `- None (skip_gate)` in `Self-review loop trace` and proceed to phase 7.
### 5) Post-self-review rerun + final diff review closure (required per cycle)
1. Run the non-self-review core passes once against the full resulting changeset.
2. If that rerun edits code, discard the stale self-review state, revalidate, and restart from phase 4 against the new final validated changeset.
3. If that rerun applies no edits and `Review loop trace` already contains a skip line from preflight, continue to phase 6.
4. Otherwise rerun phase 1 `Diff review loop` against the current final diff using the frozen `base_branch` label, canonical `comparison_sha`, and native `git diff review` command.
5. If that terminal diff review loop applies edits, discard the stale self-review state, revalidate, and restart from phase 4 against the new final validated changeset.
6. If that terminal diff review loop yields `local_findings=0`, `blocked_findings=0`, `stale_findings=0`, `overall_correctness="patch is correct"`, and every enumerated proof surface is `proved|blocked`, rerun the same terminal diff review once more on the unchanged final diff (same frozen `base_branch`/`comparison_sha`, same `git diff review --base <base_branch>` command, no intervening edits).
7. If that confirmation round is also clean under the same criteria, continue to phase 6.
8. Otherwise treat the confirmation round as the new terminal output: if it introduces new local findings, address/revalidate and restart from phase 4; if it still yields `blocked_findings > 0`, `stale_findings > 0`, or `overall_correctness="patch is incorrect"`, stop and report those findings/verdict as blockers.
### 6) Outer fixed-point cycle convergence (required)
1. At cycle start, record `cycle_start_edit_tally=0`; increment it for every code edit applied anywhere in phases 2 through 5.
2. At cycle start and cycle end, record the cycle review-context receipt:
- review-backed runs: `fingerprint=<sha256(git diff --no-ext-diff <comparison_sha>)>`
- skipped-review runs: `review_context=<skip_not_git_repo|skip_missing_base_context>`
3. Emit one cycle summary row in `Pass trace` for the current cycle with `zero_edit_cycle_streak`, `edits`, `review_context`, `fingerprint`, and `result=<restart|continue|close>`.
4. If `cycle_edit_tally>0`, reset `zero_edit_cycle_streak=0`, increment `cycle_index`, and restart from phase 0 Preflight using the already-frozen review context and validation signal.
5. If `cycle_edit_tally=0`, count the cycle as zero-edit only when the review-context receipt is unchanged (`fingerprint=same` for review-backed runs or the same skip reason for skipped-review runs); otherwise reset `zero_edit_cycle_streak=0`, increment `cycle_index`, and restart from phase 0.
6. If the cycle counts as zero-edit, increment `zero_edit_cycle_streak`.
7. If `zero_edit_cycle_streak < 2`, increment `cycle_index` and restart from phase 0, even when the current cycle is already the first no-op cycle.
8. If `zero_edit_cycle_streak = 2`, continue to phase 7.
### 7) Output / handoff (required)
1. If a clean or closed `/tw-fix` pass surfaces broader non-fix opportunities, do not continue exploring them under `/tw-fix`.
2. If the user explicitly asks for broader or deeper follow-up after closure, recommend the next skill explicitly:
- `/tw-parse` for architecture or purpose analysis
- `/tw-grill-me` for interrogation, pressure-testing, or narrowing the next move
- `/tw-plan` for a decision-complete roadmap
- `/tw-creative-problem-solver` for wider option generation
3. Do not place those broader opportunities in `Residual risks / open questions` unless a valid blocker from the allowed set applies.
4. Output lock (required):
1. Heading set is exact and complete (`Contract`, `Findings (severity order)`, `Changes applied`, `Review loop trace`, `Pass trace`, `Validation`, `Self-review loop trace`, `Residual risks / open questions`).
2. `Review loop trace` includes either a skip line or cycle-annotated `R#` rows, and any closing cycle still shows at least two consecutive terminal final-diff review rows on the unchanged final diff with `local_findings=0`, `blocked_findings=0`, `stale_findings=0`, and `overall_correctness="patch is correct"`.
3. `Pass trace` includes cycle summary rows plus planned/executed counts and P0/P1/P2/P3 lines (plus P4/P5 when executed) and `Post-self-review rerun` for every executed cycle.
4. Runtime pass updates (`Cycle <c>: Pass <n>/<total_planned>: ...`) were emitted during execution.
5. If embedded mode was used, include **Fix Record** in the same assistant message (after any required artifact).
6. `Validation` includes machine-checkable keys: `baseline_cmd`, `baseline_result`, `proof_hook`, `final_cmd`, `final_result`.
7. Every acted-on finding includes `Proof strength` and `Compatibility impact` using the allowed enums.
8. Every residual `blocked_by` uses only: `product_ambiguity|breaking_change|no_repro_or_proof|scope_guardrail|generated_output|external_dependency|perf_unmeasurable`.
9. If `Changes applied` is not `None` AND the latest validation result is `ok`, `Self-review loop trace` includes a terminal row with `stop_reason=<no_new_actionable_changes|blocked>` and the user-facing final line is not the question.
## Deliverable format (chat)
Output exactly these sections in this order.
If no findings:
- **Findings (severity order)**: `None`.
- **Changes applied**: `None`.
- **Review loop trace**: either a skip line or one or more `R#` rows.
- **Self-review loop trace**: `- None (skip_gate)`.
- **Residual risks / open questions**: `- None`.
- Still include **Pass trace** and **Validation**.
**Contract**
- <one sentence>
**Findings (severity order)**
For each finding:
- `F#` `<file:line>` — `<security|crash|corruption|logic>` — <issue>
- Surface: Tokens=<...>; PROVEN_USED=<yes/no + evidence>; External=<yes/no>; Diff_touch=<yes/no>
- Proof target: <exact advertised/documented form covered by the proof>
- Counterexample: <input/timeline>
- Invariant (before): <what was assumed/allowed>
- Invariant (after): <what is now guaranteed/rejected>
- Fix: <smallest sound fix summary>
- Proof: <test/assert/log + validation command> -> <ok/fail>
- Proof strength: `<characterization|targeted_regression|property_or_fuzz>`
- Compatibility impact: `<none|tightening|additive|breaking>`
**Changes applied**
- <file> — <rationale>
**Review loop trace**
- If skipped: `- None (skip_not_git_repo|skip_missing_base_context)`
- Otherwise: `R#` cycle=`<C#>`; base_branch=`<name>`; comparison_sha=`<sha>`; review_cmd=`git diff review --base <name>`; local_findings=`<N>`; blocked_findings=`<N>`; stale_findings=`<N>`; overall_correctness=`<patch is correct|patch is incorrect>`; change_applied=`<yes|no>`; result=`<continue|local_clean>`
- Use `result=local_clean` only when `local_findings=0`, `blocked_findings=0`, `stale_findings=0`, and `overall_correctness="patch is correct"`; otherwise keep `result=continue`.
- Each `R#` row comes from the terminal diff review closure loop in a fresh `git diff review` CLI invocation after confirming the live merge base still matches the frozen `comparison_sha`; the fixer does not self-grade that round.
- Terminal closure requires two consecutive clean rows on the unchanged final diff within the same cycle.
- Each terminal closure row must have `local_findings=0`, `blocked_findings=0`, `stale_findings=0`, and `overall_correctness="patch is correct"`.
**Pass trace**
- `Cycle C#` -> zero_edit_cycle_streak=`<0|1|2>`; edits=`<yes|no>`; review_context=`<comparison_sha|skip_not_git_repo|skip_missing_base_context>`; fingerprint=`<same|changed|n/a>`; result=`<restart|continue|close>`
- For each executed cycle, include:
- Core passes planned: `4`; core passes executed: `<4>`
- Delta passes planned: `<0|2>`; delta passes executed: `<0|2>`
- Total core/delta passes executed: `<4|6>`
- `P0 Core Review` -> `<done>`; edits=`<yes|no>`; signal=`<cmd|n/a>`; result=`<ok|fail|n/a>`
- `P1 Safety` -> `<done>`; edits=`<yes|no>`; signal=`<cmd|n/a>`; result=`<ok|fail|n/a>`
- `P2 Surface` -> `<done>`; edits=`<yes|no>`; signal=`<cmd|n/a>`; result=`<ok|fail|n/a>`
- `P3 Audit` -> `<done>`; edits=`<yes|no>`; signal=`<cmd|n/a>`; result=`<ok|fail|n/a>`
- If delta passes executed, also include `P4` and `P5` lines in the same format.
- `Post-self-review rerun` -> executed=`<yes|no>`; edits=`<yes|no>`; signal=`<cmd|n/a>`; result=`<ok|fail|n/a>`
**Validation**
- <cmd> -> <ok/fail>
- `{"baseline_cmd":"<cmd|n/a>","baseline_result":"<ok|fail|n/a>","proof_hook":"<test/assert/log|n/a>","final_cmd":"<cmd>","final_result":"<ok|fail>"}` (single-line JSON)
**Self-review loop trace**
- If none: `- None (skip_gate)`
- Otherwise: `S#` prompt=`If you could change one thing about this changeset what would you change?`; answer_summary=<...>; finding=`<F#|none>`; change_applied=`<yes|no>`; proof=`<cmd|n/a>`; result=`<ok|fail|n/a>`; stop_reason=`<continue|no_new_actionable_changes|blocked>`
**Residual risks / open questions**
- If none: `- None`
- Otherwise: `- <file:line or token> — blocked_by=<product_ambiguity|breaking_change|no_repro_or_proof|scope_guardrail|generated_output|external_dependency|perf_unmeasurable> — next=<one action>`
### Fix Record (embedded mode only)
Use only when /tw-fix is invoked inside another skill.
**Findings (severity order)**
For each finding:
- `F#` `<file:line>` — `<security|crash|corruption|logic>` — <issue>
- Surface: Tokens=<...>; PROVEN_USED=<yes/no + evidence>; External=<yes/no>; Diff_touch=<yes/no>
- Proof target: <exact advertised/documented form covered by the proof>
- Counterexample: <input/timeline>
- Invariant (before): <what was assumed/allowed>
- Invariant (after): <what is now guaranteed/rejected>
- Fix: <smallest sound fix summary>
- Proof: <test/assert/log + validation command> -> <ok/fail>
- Proof strength: `<characterization|targeted_regression|property_or_fuzz>`
- Compatibility impact: `<none|tightening|additive|breaking>`
**Changes applied**
- <file> — <rationale>
**Review loop trace**
- If skipped: `- None (skip_not_git_repo|skip_missing_base_context)`
- Otherwise: `R#` cycle=`<C#>`; base_branch=`<name>`; comparison_sha=`<sha>`; review_cmd=`git diff review --base <name>`; local_findings=`<N>`; blocked_findings=`<N>`; stale_findings=`<N>`; overall_correctness=`<patch is correct|patch is incorrect>`; change_applied=`<yes|no>`; result=`<continue|local_clean>`
- Use `result=local_clean` only when `local_findings=0`, `blocked_findings=0`, `stale_findings=0`, and `overall_correctness="patch is correct"`; otherwise keep `result=continue`.
- Each `R#` row comes from the terminal diff review closure loop in a fresh `git diff review` CLI invocation after confirming the live merge base still matches the frozen `comparison_sha`; the fixer does not self-grade that round.
- Terminal closure requires two consecutive clean rows on the unchanged final diff within the same cycle.
- Each terminal closure row must have `local_findings=0`, `blocked_findings=0`, `stale_findings=0`, and `overall_correctness="patch is correct"`.
**Pass trace**
- `Cycle C#` -> zero_edit_cycle_streak=`<0|1|2>`; edits=`<yes|no>`; review_context=`<comparison_sha|skip_not_git_repo|skip_missing_base_context>`; fingerprint=`<same|changed|n/a>`; result=`<restart|continue|close>`
- For each executed cycle, include:
- Core passes planned: `4`; core passes executed: `<4>`
- Delta passes planned: `<0|2>`; delta passes executed: `<0|2>`
- Total core/delta passes executed: `<4|6>`
- `P0 Core Review` -> `<done>`; edits=`<yes|no>`; signal=`<cmd|n/a>`; result=`<ok|fail|n/a>`
- `P1 Safety` -> `<done>`; edits=`<yes|no>`; signal=`<cmd|n/a>`; result=`<ok|fail|n/a>`
- `P2 Surface` -> `<done>`; edits=`<yes|no>`; signal=`<cmd|n/a>`; result=`<ok|fail|n/a>`
- `P3 Audit` -> `<done>`; edits=`<yes|no>`; signal=`<cmd|n/a>`; result=`<ok|fail|n/a>`
- If delta passes executed, also include `P4` and `P5` lines in the same format.
- `Post-self-review rerun` -> executed=`<yes|no>`; edits=`<yes|no>`; signal=`<cmd|n/a>`; result=`<ok|fail|n/a>`
**Validation**
- <cmd> -> <ok/fail>
- `{"baseline_cmd":"<cmd|n/a>","baseline_result":"<ok|fail|n/a>","proof_hook":"<test/assert/log|n/a>","final_cmd":"<cmd>","final_result":"<ok|fail>"}` (single-line JSON)
**Self-review loop trace**
- If none: `- None (skip_gate)`
- Otherwise: `S#` prompt=`If you could change one thing about this changeset what would you change?`; answer_summary=<...>; finding=`<F#|none>`; change_applied=`<yes|no>`; proof=`<cmd|n/a>`; result=`<ok|fail|n/a>`; stop_reason=`<continue|no_new_actionable_changes|blocked>`
**Residual risks / open questions**
- If none: `- None`
- Otherwise: `- <file:line or token> — blocked_by=<product_ambiguity|breaking_change|no_repro_or_proof|scope_guardrail|generated_output|external_dependency|perf_unmeasurable> — next=<one action>`
## Pitfalls
- Vague advice without locations.
- "Nice-to-have" refactors that don’t reduce risk.
- Feature creep.
- Continuing broad repo critique or planning under a completed `/tw-fix` label.
- Asking for risk tolerance instead of applying the default policy.
- Treating skill-artifact refinement as in-band `/tw-fix` work instead of using `/tw-refine`.
- Tightening presented as optional.
- Ownership fixes without proven allocator/owner.
- Editing generated/third-party outputs instead of source-of-truth.
- Code edits without a failing proof hook when baseline was ok.
- Recomputing the diff-review comparison, letting the live merge base drift, or trying to append a custom prompt onto `git diff review --base`.
- Closing after one zero-edit full cycle or re-deriving review context between cycles.
- Folding the terminal diff review loop into `Pass trace` instead of keeping `Review loop trace` terminal-only.
- Adding a new top-level cycle-reporting section instead of embedding cycle state in runtime pass updates, `Pass trace`, and `Review loop trace`.
- Using `Residual risks / open questions` as a substitute for fixable findings.
## Activation cues
- "resolve" / "fix" / "crash" / "data corruption"
- "/tw-fix this PR" / "/tw-fix current branch" / "fix this branch"
- "Review the code changes against the base branch" / "merge base commit" / "git diff review --base"
- "CI failed" / "fix the red checks" / "repair failing PR"
- "footgun" / "misuse" / "should never happen"
- "invariant" / "lifetime" / "nullable surprise"
- "too complex" / "branch soup" / "cross-file hops"
Is this your skill, or is something wrong with this listing? Request removal or report an issue. Author removals are honored within 72 hours.
No comments yet. Be the first to comment!