Tw fix

From SDiamante13/dotfiles · View interactive version

Tw fix is an AI agent skill from the GitHub repository SDiamante13/dotfiles. 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

How to use this skill

Skill file

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

Double Diamond fit

fix spans the full Double Diamond, but keeps divergence mostly internal to stay autonomous:

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)

Inputs

Outputs (chat)

Cycle <c>: Pass <n>/<total_planned>: <name> — <start|done>; edits=<yes|no|n/a>; signal=<cmd|n/a>; result=<ok|fail|n/a>.

baseline_cmd, baseline_result, proof_hook, final_cmd, final_result.

Embedded mode (when /tw-fix is invoked inside another skill)

Hard rules (MUST / MUST NOT)

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 evidence checklist (deterministic)

Goal: classify behavior as PROVEN_USED vs NON_PROVEN_USED without asking.

Algorithm:

  1. Enumerate affected behavior tokens:
  1. Collect evidence in this order (stop at first match):
  1. IF any evidence exists, THEN mark PROVEN_USED; ELSE mark NON_PROVEN_USED.

Evidence scan procedure (repo-local):

Tooling hint: prefer rg -n "<token>" with --glob filters.

Deterministic scan command template (run in this order):

Externally-used surface checklist (deterministic)

Treat a surface as external if ANY is true:

If external use is plausible but uncertain:

Compatibility rules:

API/migration rules:

THEN prefer additive/backward-compatible changes (new option/new function/adapter) over breaking changes.

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:
  1. 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).
  2. For each proof surface, record:
  1. Do not close the diff review loop or the core-pass phase while any proof surface is still unproved.

Rules:

Performance rules:

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:

If ANY gate fails:

Correctness tightening (default)

Definition: tightening = rejecting invalid/ambiguous states earlier, removing silent failure paths, or making undefined behavior explicit.

Rule:

THEN apply it (even if PROVEN_USED), return a clear error, and record the compatibility impact.

THEN apply it without asking.

Allowed tightening moves (examples only):

Defaults (use only when semantics-preserving for valid inputs)

Ownership / lifetimes

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:
  1. ELSE create a proof hook in this order:

No-signal fail-fast (deterministic):

PR/diff scope guardrail (default in review mode)

Scope widening trigger (deterministic):

Generated / third-party code guardrail

Proof discipline for passing baselines

When the baseline signal is ok:

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:

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

Pass 1) Safety (highest severity)

Pass 2) Surface (compat + misuse)

Pass 3) Audit (invariants + ownership + proof quality)

Early exit (stop after pass 3):

Delta passes (only if pass 3 applied edits)

Pass 4) Safety delta rescan

Pass 5) Surface + proof delta rescan

Rules:

Clarify before changes

Stop and ask ONLY if any is true:

Finding record schema (internal)

For every issue you act on, construct this record before editing:

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
  - 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:
  1. 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.
  2. Apply PR/diff scope guardrail for review mode.
  3. Apply Generated / third-party code guardrail before editing.
  4. Determine review-loop activation:
  1. Select validation signal (or create proof hook).
  2. If signal/proof creation fails, stop before editing and return blocked_by=no_repro_or_proof with attempted commands.
  3. Initialize outer fixed-point state:

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)

Diff review comment bar (required)

Diff review priority bar (required)

Diff review output schema (required)

{
  "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:

Native git diff review command (required)

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:
  1. Emit one Review loop trace row per terminal review round.
  2. If local_findings > 0, address all review findings, re-run the chosen validation signal, then repeat from step 2.
  3. 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.
  1. Re-check Surface proof coverage (deterministic) against the current diff before closing the round.
  2. 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:
  1. Enumerate proof surfaces:
  1. Derive contract without asking (in this order):
  1. Write contract (1 sentence): "Working means …".
  2. Run baseline signal once; record result.
  3. If baseline signal is ok, apply Proof discipline for passing baselines.
  4. Enumerate candidate failure modes for the slice.
  5. Rank security > crash > corruption > logic.
  6. For each issue you will act on, create a finding record.
  7. Run the Multi-pass loop (default) for the touched slice, starting with P0 Core Review.
2a) Unsoundness scan

For each hazard class that applies:

Hazard classes:

Language cues (examples only):

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:
  1. Map these to fix finding fields:
  1. 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:
  1. 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.
  1. 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.
  1. Close the core-pass phase.

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:
  1. If the answer yields only blocked changes, record stop_reason=blocked, carry blockers to Residual risks / open questions, and continue to phase 5.
  2. If the answer yields no new actionable self-review change, record stop_reason=no_new_actionable_changes and continue to phase 5.
  1. 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:
  1. 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>.
  2. 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.
  3. 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.
  4. If the cycle counts as zero-edit, increment zero_edit_cycle_streak.
  5. 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.
  6. 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:
  1. Do not place those broader opportunities in Residual risks / open questions unless a valid blocker from the allowed set applies.
  2. 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:

Contract

Findings (severity order)

For each finding:

Changes applied

Review loop trace

Pass trace

Validation

Self-review loop trace

Residual risks / open questions

Fix Record (embedded mode only)

Use only when /tw-fix is invoked inside another skill.

Findings (severity order)

For each finding:

Changes applied

Review loop trace

Pass trace

Validation

Self-review loop trace

Residual risks / open questions

Pitfalls

Activation cues

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.