# Refactor

> Plans and executes a behavior-preserving refactor end-to-end from an approved plan or a new codebase-first hybrid decision workflow, using serialized disjoint-path Task writers, fresh per-phase code audits, and one final report-only deep review with gates. Use for refactors, restructuring, decomposition, code movement, and staged migrations that do not change observable behavior.

- Skill: `abchoudh-amd/refactor` (Agent Skill, multi-file: 3 files)
- Install (CLI): `npx skillmds@latest add abchoudh-amd/refactor`
- Raw SKILL.md: https://api.skillmd.com/api/skills/abchoudh-amd/refactor/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Docs & Writing
- Author: abchoudh-amd (https://skillmd.com/u/abchoudh-amd)
- Updated: 2026-09-21
- Page: https://skillmd.com/skills/abchoudh-amd/refactor

---


# Refactor

Change structure while preserving every observable contract. This skill owns
planning and execution. Characterization tests establish a GREEN baseline;
they are never a TDD RED phase. The terminal deep review automatically saves
and returns its exact report once, and never reopens implementation or creates
a PR.

## Entry and supplied-plan gate

Inspect first for a user-identified, explicitly approved refactor plan. A
supplied plan is executable only when its complete final contents satisfy the
semantic contract in this skill and [REFERENCE.md](REFERENCE.md), and current
repository inspection confirms its paths, baseline, commands, dependencies,
and assumptions remain fresh.

The plan must include:

- `Plan kind: refactor`, `Status: approved`, approver, approval evidence,
  approval timestamp, owner, target base, and baseline revision;
- `Behavior delta: none` for every source phase;
- baseline commands/results and an explicit Phase B applicability decision;
- per-task owner, behavioral scope, and disjoint `Files written:` paths inside
  each phase; every Phase B task records `Writer agent:
  rocprof-compute-unit-test-writer` and `Writer mode: characterization`, and
  every source task records `Writer agent:
  rocprof-compute-blind-source-writer` and `Writer mode: refactor`;
- every phase review records `Auditor agent:
  rocprof-compute-code-auditor` and `Auditor mode: phase-review`;
- exact verification/pass conditions and concrete rollback procedures;
- a plan-level risk register; and
- temporary scaffolding paired with an in-plan cleanup phase, or `none`.

When a supplied plan is valid, record `planning: supplied approved plan`, keep
the artifact immutable, and skip `grill-me` and replacement
planning. When it is incomplete, stale, or unapproved, halt and request a
distinct revised artifact with fresh explicit approval. Never repair,
overwrite, silently replan, or translate supplied input. Reject predecessor
`Writer skill`, combined skill/mode, generic `Writer`, and `Executor skill`
fields even when the rest of an older artifact is complete.

When no plan is supplied, inspect the target source, tests, documentation,
history, and prior plans. Resolve the desired structural end state, non-goals,
compatibility, owner, baseline evidence, rollback constraints, and target base
(default `rocprofiler-compute-develop`). After inspection, repeatedly inventory
the current material decisions across structural target, behavior and
compatibility invariants, safety-net gaps, characterization needs, phase
boundaries, ownership, verification and pass conditions, temporary
scaffolding and cleanup, rollback, and risk.

Route each current inventory through
[`QUESTION-ROUTING.md`](../_shared/QUESTION-ROUTING.md). At zero, continue toward
the local draft. At one to three, run one codebase-first
[`grill-me`](../grill-me/SKILL.md) pass over that complete inventory, then
recalculate. At four or more, dispatch the controlled
`rocprof-compute-decision-questionnaire-writer` in the applicable
`refactor-initial` or `refactor-follow-up` mode under
[`DECISION-QUESTIONNAIRE-ORCHESTRATION.md`](../_shared/DECISION-QUESTIONNAIRE-ORCHESTRATION.md),
report the exact saved path, and pause for human completion of that path.

On exact-path
resume, validate the completed questionnaire and its lineage under the shared
orchestration contract, then recalculate. An incomplete questionnaire receives
a precise correction request for that same path; it does not authorize a plan
draft or a new questionnaire version. A later newly exposed four-or-more
inventory may create the next contiguous create-only follow-up. There is no
fixed pass limit.

The main coordinator renders the existing template below only after the
inventory reaches zero, then runs the agent-native self-check in
[REFERENCE.md](REFERENCE.md). That check is advisory: it produces findings for
the human and never a verdict, and the coordinator never approves its own plan.
Present the unsaved draft for explicit human approval together with a
`## Self-check findings` section listing every finding verbatim (or `none`) and
the coordinator's current `Critical open questions:` statement. Both are
reported context, not new plan fields: do not change the saved-plan schema or
use either to invalidate an accepted supplied plan. Only a human response —
approval, or feedback requesting changes — advances or revises the draft; a
self-check finding never does so on its own. A requested revision rebuilds the
inventory and repeats routing, the advisory check, and presentation. After
approval, change only the deferred metadata to `Status: approved`, the
approver, approval evidence, and timestamp. Save only those approved contents
as `plans/<target>-refactor-plan.md`, adding `-v2`, `-v3`, and so on instead of
overwriting; nothing is written under `plans/` before approval.

Plan provenance is current-run coordinator state, never artifact metadata. Set
it once at entry to `supplied` when the user identifies an existing approved
artifact, or `local` when this run creates and approves the plan. Carry that
runtime value through all pre-terminal routing without writing it into the plan.
A supplied artifact remains immutable even if it was originally created by a
prior local run. Any required plan change during execution halts for a distinct
approved artifact regardless of provenance; phase audit never reopens local
planning.

If any intended behavior, contract, or output change appears, stop and report
the boundary. Route planning-only intent to `plan-feature`, full delivery to
`build-feature`, or an exact approved feature implementation plan to
`implement-feature`. Never adapt feature work into a refactor.

## Pipeline

```mermaid
flowchart TD
    S{Valid supplied approved plan?}
    S -- yes --> P[Immutable approved plan]
    S -- no plan --> I{Current material question count}
    I -- 0 --> SC[Draft plus advisory coordinator self-check]
    I -- 1 to 3 --> G[One grill-me pass]
    G --> I
    I -- 4 or more --> Q[Controlled refactor questionnaire]
    Q --> X[Pause on exact saved path]
    X -- completed and validated --> I
    SC --> A{Explicit human approval?}
    A -- revision --> I
    A -- approved and collision-safe save --> P
    P --> B{Phase B applicable?}
    B -- yes --> C[GREEN characterization writers]
    B -- no --> R[Phase 1..N writers]
    C --> CB[Fresh baseline code auditor and rollback check]
    CB -- test correction --> C
    CB -- plan defect --> H
    CB -- approved --> R
    R --> E[Fresh equivalence code auditor and rollback check]
    E -- behavior-preserving correction --> R
    E -- plan defect --> H[Halt for distinct revised approved artifact]
    E -- approved, more phases --> R
    E -- approved, final phase --> D[One deep-review --gates --base target]
    D --> O[Exact saved report inline, absolute path, and residual risks; no fixes and no PR]
```

Pre-terminal correction loops remain active. Only the terminal deep review is
report-only.

## Phase B: optional GREEN characterization

Run Phase B only when the plan marks it applicable. Dispatch the named
[`rocprof-compute-unit-test-writer`](../../agent-resources/rocprof-compute-unit-test-writer/WORKFLOW.md)
in mode `characterization`,
never TDD mode. Before test edits, record the planned baseline revision and
confirm all in-scope production files still match it, with no untracked
production paths in scope. New tests pin observed public behavior and must pass
against that unmodified baseline.

Dispatch disjoint test tasks as serialized named Tasks, each beginning with a
fresh exact boundary manifest. The coordinator confirms source immutability,
runs and normalizes the exact characterization commands, applies every pass
condition, and dry-reads the rollback contract. Then a fresh named
`rocprof-compute-code-auditor` in `phase-review` reviews the union diff and
normalized results and reports rollback evidence using [REFERENCE.md](REFERENCE.md).
A RED result is invalid
characterization evidence and does not authorize source changes. A
`request-changes` verdict redispatches only the intersecting Phase B test
owners with new manifests and then reruns the complete Phase B gate. A required
plan change is `blocked` and halts for a distinct approved artifact. If Phase B
is N/A, retain the plan's
rationale and frozen baseline command list.

## Refactor phases

Execute phases sequentially. Within one phase, validate that every task has
disjoint `Files written:` ownership, then dispatch the tasks serially using
named `rocprof-compute-blind-source-writer` Tasks in mode `refactor`, each with
a fresh exact boundary manifest. The source-writer allowlist contains exactly
[`rocprof-compute-blind-source-writer`](../../agent-resources/rocprof-compute-blind-source-writer/WORKFLOW.md).
Reject the plan before dispatch if any source phase or source task names another agent;
never invoke a side-effecting, delivery, or orchestration skill as a refactor
writer. Phase B separately permits only `rocprof-compute-unit-test-writer` in characterization
mode.

Each blind source payload contains only the behavior-preservation contract,
structural intent, public interfaces, in-scope and out-of-scope production
paths, the task's exact file ownership, and non-test verification. Never send
test paths, names, commands, fixtures, assertions, runner output, or failures.

After all writers in a phase finish, the coordinator validates results/diffs
and runs all declared gates. It then spawns the named read-only
`rocprof-compute-code-auditor` in `phase-review`, supplying the union diff and
normalized gate results. The auditor:

1. reviews the union diff and checks verbatim moves preserve comments,
   docstrings, annotations, and public interfaces;
2. checks the normalized planned lint/build/type and non-test results;
3. checks the normalized frozen baseline/equivalence results;
4. applies the phase's declared pass conditions to supplied evidence; and
5. reviews the rollback trigger, steps, config/data undo, and verification.

The auditor never runs a command and never reviews or revises a plan.

Auditor routing before the terminal review:

- `approve` advances to the next phase.
- `request-changes` redispatches only owners of
  evidence-intersecting files. Sanitize feedback into observable behavior
  before any blind-writer retry, then rerun the complete phase gate.
- `blocked` halts with the concrete blocker. Any required plan change requires
  a distinct revised and explicitly approved artifact.

## Terminal deep review: exactly once, report-only

After every planned phase and required gate has completed, obtain exactly one
completed pass from the Cursor [`deep-review`](../deep-review/SKILL.md):

```text
Skill(skill="deep-review", args="--gates --base <approved Target base>")
```

The deep-review invocation captures its physical invocation directory before
inspection and automatically publishes a collision-safe report under its
`reviews/` directory. Completion requires successful publication: read the
saved file and return its exact full Markdown inline plus the absolute path
printed by the helper. Do not offer a save choice or require confirmation. Do
not remediate findings, redispatch writers, revise a plan, rerun phase gates,
repeat deep review, or invoke `create-pr`.

Classify the terminal result as:

- `clean`: review completed, required gates did not fail, and no findings
  survived;
- `findings`: review completed with one or more surviving findings and no
  required final gate failed; or
- `gate failures`: review completed with one or more failed final gates,
  whether or not findings also survived.

Every surviving finding and failed gate is a residual risk regardless of
severity. Interpretation does not change control flow:

- a behavior-preserving issue is a refactor residual;
- weak characterization, plan, or rollback evidence is reported with its plan
  impact; and
- a remedy that would change behavior is reported as separate work for a later
  `plan-feature` planning request or `build-feature` full-delivery request.

A required gate that runs and reports a project failure produces the completed
`gate failures` outcome. If deep review itself cannot complete—for example,
the target base is missing or infrastructure prevents a required tool or gate
from running or reporting—or if result normalization/rendering or
collision-safe publication fails, then that invocation is not a pass. Halt
without marking the terminal phase complete so the same one-pass terminal
action can be retried later. A real failed gate does not block report
publication.

## Structural policies

- Every source phase states `Behavior delta: none`.
- Move or copy code verbatim unless a separate behavior-preserving cleanup
  phase says otherwise. Preserve comments, docstrings, type annotations, and
  inline documentation; update only stale location tokens.
- Three touched modules per phase is a soft cap. Exceeding it requires an
  atomicity and safe-intermediate-state justification.
- Six total planned phases is a soft cap. Exceeding it requires a plan-level
  justification; unrelated objectives become separate plans.
- Pair every temporary adapter, shim, flag, dual path, or compatibility branch
  with an explicit cleanup phase in the same plan.
- Every phase has a runnable command or deterministic procedure, an explicit
  pass condition, and concrete rollback trigger, steps, config/data undo (or
  `none`), and rollback verification.
- Plan-level owner and risk register are mandatory. Per-task ownership is
  mandatory for execution; per-phase ownership remains optional.
- All same-phase `Files written` sets are disjoint.
- The baseline revision and the exact GREEN commands are recorded, and Phase B
  applicability carries an explicit rationale.
- Phase B uses agent `rocprof-compute-unit-test-writer` in mode
  `characterization`, every source task uses agent
  `rocprof-compute-blind-source-writer` in mode `refactor`, and every phase
  audit uses agent `rocprof-compute-code-auditor` in mode `phase-review`.
- The complete final contents carry explicit human approval.

Check these before dispatching any writer and refuse a plan that fails one. They
are admission checks, not a checklist the plan restates.

## Response contract

Report:

1. outcome and terminal classification, or the exact incomplete-review reason;
2. plan path, current-run coordinator provenance (`local` or `supplied`), any
   decision-questionnaire lineage and normalized local decision closure,
   approver/evidence/timestamp, target base, baseline revision, and
   semantic/freshness result;
3. Phase B status and GREEN evidence;
4. task fanout, per-phase auditor results, equivalence gates, retries, and
   rollback readiness;
5. for a completed pass, the one saved deep-review report's exact full Markdown inline,
   its absolute path, and gate results; for an incomplete invocation, the exact reason,
   pending terminal status, and confirmation that no review result was recorded;
6. residual risks, including any behavior-changing remedy as separate
   `plan-feature` or `build-feature` work; and
7. the explicit statements: `No terminal finding was remediated or re-reviewed.`
   and `No PR was created.`

Also state that no test artifact reached a `rocprof-compute-blind-source-writer` Task agent.

## Saved plan template

The unsaved local draft uses `Status: pending` with deferred approval values;
the final saved artifact uses the approved form below.

```md
# Refactor Plan: [Target Area]

## Plan Metadata
- Plan kind: refactor
- Status: approved
- Approved by:
- Approval evidence:
- Approved at:
- Owner:
- Target base:
- Baseline revision:

## Objective
- Current pain:
- Desired end state:
- Non-goals:

## Constraints and assumptions
- Constraints:
- Assumptions:
- Compatibility strategy (optional):
- Phase-count exception justification (if > 6 phases):
- Open questions: none

## Baseline and safety net
- Existing tests/contracts:
- Current baseline commands and results:
- Safety-net gaps:
- Phase B applicability: applicable | N/A
- Phase B rationale:
- Runtime signals:

## Phase sequence

Every task is one table row. The `Rollback` cell states the trigger, the exact
undo steps including any config/data undo, and how the undo is verified. Every
phase audit uses agent `rocprof-compute-code-auditor` in mode `phase-review`;
the plan never restates it per task.

### Phase B: GREEN characterization tests
- Status: applicable | N/A
- Writer: rocprof-compute-unit-test-writer / characterization
- Behavior delta: none
- Dependencies:

| Task | Owner | Files written | Behavior pinned | Verification / pass condition | Rollback | Commit |
| --- | --- | --- | --- | --- | --- | --- |
| B.1 | | `path` | | | | |

### Phase 1: [outcome-focused title]
- Goal:
- Writer: rocprof-compute-blind-source-writer / refactor
- Behavioral acceptance criteria:
- Temporary scaffolding:
- Behavior delta: none
- Touched modules:
- Exception justification (if > 3 modules):
- Dependencies:

| Task | Owner | Files written | In / out of scope | Structural intent | Verbatim moves (source -> destination) | Verification / pass condition | Rollback | Commit |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 1.1 | | `path` | | | none \| [...] | | | |

## Risk register
| Risk | Trigger | Owner | Mitigation |
| --- | --- | --- | --- |
```

## Resources

- [REFERENCE.md](REFERENCE.md): semantic validation, Task contracts, auditor
  verdicts, sanitation, and terminal interpretation.
- [EXAMPLES.md](EXAMPLES.md): supplied-plan, planned execution, loopback, and
  one-pass terminal outcomes.
- [DECISION-QUESTIONNAIRE-ORCHESTRATION.md](../_shared/DECISION-QUESTIONNAIRE-ORCHESTRATION.md):
  hybrid routing, controlled questionnaire lineage, and exact-path resume.
- [writing style](../_shared/WRITING-STYLE.md): normative prose rules and the pre-save self-check for
  every human-read artifact this skill produces.
- [design principles](../_shared/DESIGN-PRINCIPLES.md): the structure a refactor plan
  targets. Read as an author: the plan is bounded by these, and the writers executing it
  cannot correct a boundary the plan gets wrong. Behavior preservation still wins, so a
  principle that would change observable behavior is a finding for the plan, not an edit.

