Refactor — one structural experiment
Refactor changes structure while preserving observable behavior. It performs one
caller-selected transformation and reports the result. "Behavior-preserving" is
a claim to prove with before/after checks, never to assert. A user sees it
worked when the report shows the same checks run before and after with
identical results, and any suspected bug listed unfixed.
What counts as behavior
Unless the caller explicitly excluded a surface, all of these must survive:
- Messages and exit codes. Error and output text compares byte-for-byte;
exit codes, error types and which input raises which error stay the same.
Scripts and callers parse them. Preserve an inconsistent message and report
it; normalizing it is a behavior change.
- Differences between near-duplicates. When merging duplicated branches,
carry every difference (constants, comparisons, messages, extra steps) as a
parameter or a branch. Do not unify a difference the caller has not declared
accidental.
- Interfaces. Public signatures, defaults, return types, persisted field
names, protocol values and CLI flags. Renaming one is a compatibility change
unless the accepted scope provides for it.
- Order and coverage. Branch priority, default handling, evaluation count,
side-effect order, and the set of tests that run. A pre-existing red that
vanishes, or a test that stops running, is a behavior change.
- Protective checks. Trust-boundary validation, data-loss guards, security
controls and accessibility affordances stay, even when another layer,
upstream or downstream, duplicates one or no test reaches it. The neutrality
gates cannot see their removal, so looking redundant is no reason to delete
one.
Procedure
- Name the preserved behavior, the focused acceptance surface and the concrete
structural problem for its callers, in the caller's domain terms.
- Run the focused check and the smallest regression check the changed surface
justifies, error paths included, and record that honest baseline, including
reproducible ambient failures. Add any characterization test the
transformation needs now, before the edit, so it is part of the baseline.
For output-producing surfaces (generators, serializers, formatters,
reports), hash the output over fixed inputs. When the caller's evaluation
compares the built program before and after the change, pin the starting
source, build its baseline before edits and keep that binary and the
comparison inputs.
- Apply one bounded transformation: extract, move, rename, inline, simplify a
conditional, reduce parameters, encapsulate, substitute existing code, or
delete dead code; the
refactoring catalog
holds per-pattern safety checks. Judge it by what callers must
understand and where a domain rule must change, not by file size.
- A bug or suspicious inconsistency found on the way is reported separately
(location, why it looks wrong) and left unfixed. Fixing it inside the
refactor hides a behavior change the caller did not authorize.
- Rerun exactly the step-2 checks over the same inputs and compare any
output hashes byte-for-byte.
- Report, then stop. A red result is evidence for the caller; this skill does
not revert, narrow, retry, commit, validate, or route subsequent work.
When nothing can be executed (no runtime, no tests, code supplied in a
message), neutrality is unproven: give the exact before/after commands and
inputs the caller must run, error paths included, and list every surface under
not checked.
transformation: <the one change>
preserved: <behavior and surfaces from step 1>
checks: <command>: before -> <result>; after -> <result> (or "not run")
outputs: <before/after hashes when the surface produces output>
abstraction: <a new one and the second use or contract that justifies it, or "none">
diff: <files touched>; only those the transformation names, plus tests added before the change
suspected bugs: <file:line, why>; reported, not fixed
not checked: <surfaces no check covered>; present even when empty
Neutrality gates
The checks from step 2 give the same result after as before: no new red, no
vanished red, identical output hashes. A mismatch is a behavior diff to surface
and explain, never to shrug at; the caller decides whether to keep, narrow, or
reverse it. A gate skipped or narrowed after the fact is the post-hoc
neutrality failure mode — the diff decides what got tested. Name any surface
the gates did not cover under not checked.
Boundaries and tests
Refactoring after a check goes green is the step of test-driven development
that held for agents
(practice ledger).
- Use Implement to change behavior; it tidies its own
fresh change under its acceptance checks.
- Use Refactor when restructuring is the request, or reaches code the behavior
change did not touch; that green result is the baseline.
- Use Architecture to choose where to
restructure or a new module boundary; this skill executes one transformation
in the area the caller selected.
Reject a wrapper that only adds another name or pushes the same coordination into its callers. Keep
internal test seams private when callers need no substitution. Exercise the
preserved behavior through the caller-facing boundary; retain existing tests
until equivalent coverage of their distinct cases is demonstrated. Moving a
test is not permission to delete the behavior it protected.
Use the caller's vocabulary for extracted operations and types. A naming
ambiguity that changes behavior belongs with the existing domain definition;
consult Domain only when that distinction needs work.
When the caller-chosen transformation can be cut more than one way (which
lines an extraction takes, where a chosen interface sits), probe before you
cut. A choice between module boundaries the caller has not made goes to
Architecture first.
Run the probe in disposable isolation (a scratch branch, worktree, or copied
tree the caller's policy allows): rough in the seam, see what it forces —
signature churn, import cycles, test rewrites — then discard the probe and
keep only the knowledge. Stop condition: at most two probes; if the second
candidate seam also fights back, report both findings to the caller instead of
trying a third. Cutting the first imaginable seam directly into the working
tree is the premature seam failure mode: the wrong boundary calcifies
because reverting it now costs more than living with it.
References
- Behavior-preserving simplification — refactoring catalog and per-pattern safety checks
- Codebase design — Matt Pocock; the wrapper and test-seam rules under Boundaries and tests adapt it.
1---2name: refactor-53description: 'Restructure or clean up code with no behavior change, proved by before-and-after checks. Use when: asked to clean up, extract, dedupe or simplify, even one function.'4practices:5- refactoring6- legacy-code-seams7- design-patterns8hexagonal_role: supporting9consumes:10- repo-context11produces:12- code-changes13context_rel: []14skill_api_version: 115user-invocable: true16metadata:17 source: https://skillmd.com/skills/hashgraph-online/refactor-518 capabilities: [refactor]19 effects: [modify_source_files]20 canonical_status: canonical21 disposition: keep_specialist22 tier: execution23 dependencies: []24output_contract: code changes with regression evidence25---2627# Refactor — one structural experiment2829Refactor changes structure while preserving observable behavior. It performs one30caller-selected transformation and reports the result. "Behavior-preserving" is31a claim to prove with before/after checks, never to assert. A user sees it32worked when the report shows the same checks run before and after with33identical results, and any suspected bug listed unfixed.3435## What counts as behavior3637Unless the caller explicitly excluded a surface, all of these must survive:3839- **Messages and exit codes.** Error and output text compares byte-for-byte;40 exit codes, error types and which input raises which error stay the same.41 Scripts and callers parse them. Preserve an inconsistent message and report42 it; normalizing it is a behavior change.43- **Differences between near-duplicates.** When merging duplicated branches,44 carry every difference (constants, comparisons, messages, extra steps) as a45 parameter or a branch. Do not unify a difference the caller has not declared46 accidental.47- **Interfaces.** Public signatures, defaults, return types, persisted field48 names, protocol values and CLI flags. Renaming one is a compatibility change49 unless the accepted scope provides for it.50- **Order and coverage.** Branch priority, default handling, evaluation count,51 side-effect order, and the set of tests that run. A pre-existing red that52 vanishes, or a test that stops running, is a behavior change.53- **Protective checks.** Trust-boundary validation, data-loss guards, security54 controls and accessibility affordances stay, even when another layer,55 upstream or downstream, duplicates one or no test reaches it. The neutrality56 gates cannot see their removal, so looking redundant is no reason to delete57 one.5859## Procedure60611. Name the preserved behavior, the focused acceptance surface and the concrete62 structural problem for its callers, in the caller's domain terms.632. Run the focused check and the smallest regression check the changed surface64 justifies, error paths included, and record that honest baseline, including65 reproducible ambient failures. Add any characterization test the66 transformation needs now, before the edit, so it is part of the baseline.67 For output-producing surfaces (generators, serializers, formatters,68 reports), hash the output over fixed inputs. When the caller's evaluation69 compares the built program before and after the change, pin the starting70 source, build its baseline before edits and keep that binary and the71 comparison inputs.723. Apply one bounded transformation: extract, move, rename, inline, simplify a73 conditional, reduce parameters, encapsulate, substitute existing code, or74 delete dead code; the75 [refactoring catalog](references/behavior-preserving-simplification.md#refactoring-catalog)76 holds per-pattern safety checks. Judge it by what callers must77 understand and where a domain rule must change, not by file size.784. A bug or suspicious inconsistency found on the way is reported separately79 (location, why it looks wrong) and left unfixed. Fixing it inside the80 refactor hides a behavior change the caller did not authorize.815. Rerun exactly the step-2 checks over the same inputs and compare any82 output hashes byte-for-byte.836. Report, then stop. A red result is evidence for the caller; this skill does84 not revert, narrow, retry, commit, validate, or route subsequent work.8586When nothing can be executed (no runtime, no tests, code supplied in a87message), neutrality is unproven: give the exact before/after commands and88inputs the caller must run, error paths included, and list every surface under89`not checked`.9091```text92transformation: <the one change>93preserved: <behavior and surfaces from step 1>94checks: <command>: before -> <result>; after -> <result> (or "not run")95outputs: <before/after hashes when the surface produces output>96abstraction: <a new one and the second use or contract that justifies it, or "none">97diff: <files touched>; only those the transformation names, plus tests added before the change98suspected bugs: <file:line, why>; reported, not fixed99not checked: <surfaces no check covered>; present even when empty100```101102## Neutrality gates103104The checks from step 2 give the same result after as before: no new red, no105vanished red, identical output hashes. A mismatch is a behavior diff to surface106and explain, never to shrug at; the caller decides whether to keep, narrow, or107reverse it. A gate skipped or narrowed after the fact is the **post-hoc108neutrality** failure mode — the diff decides what got tested. Name any surface109the gates did not cover under `not checked`.110111## Boundaries and tests112113Refactoring after a check goes green is the step of test-driven development114that held for agents115([practice ledger](https://github.com/boshu2/agentops/blob/main/docs/practice-ledger.md#holds-in-a-different-shape)).116117- Use [Implement](../implement/SKILL.md) to change behavior; it tidies its own118 fresh change under its acceptance checks.119- Use Refactor when restructuring is the request, or reaches code the behavior120 change did not touch; that green result is the baseline.121- Use [Architecture](../architecture/SKILL.md#procedure) to choose where to122 restructure or a new module boundary; this skill executes one transformation123 in the area the caller selected.124125Reject a wrapper that only adds another name or pushes the same coordination into its callers. Keep126internal test seams private when callers need no substitution. Exercise the127preserved behavior through the caller-facing boundary; retain existing tests128until equivalent coverage of their distinct cases is demonstrated. Moving a129test is not permission to delete the behavior it protected.130131Use the caller's vocabulary for extracted operations and types. A naming132ambiguity that changes behavior belongs with the existing domain definition;133consult [Domain](../domain/SKILL.md) only when that distinction needs work.134135When the caller-chosen transformation can be cut more than one way (which136lines an extraction takes, where a chosen interface sits), probe before you137cut. A choice between module boundaries the caller has not made goes to138Architecture first.139Run the probe in disposable isolation (a scratch branch, worktree, or copied140tree the caller's policy allows): rough in the seam, see what it forces —141signature churn, import cycles, test rewrites — then discard the probe and142keep only the knowledge. Stop condition: at most two probes; if the second143candidate seam also fights back, report both findings to the caller instead of144trying a third. Cutting the first imaginable seam directly into the working145tree is the **premature seam** failure mode: the wrong boundary calcifies146because reverting it now costs more than living with it.147148## References149150- [Behavior-preserving simplification](references/behavior-preserving-simplification.md) — refactoring catalog and per-pattern safety checks151- [Codebase design](https://github.com/mattpocock/skills/blob/main/skills/engineering/codebase-design/SKILL.md) — Matt Pocock; the wrapper and test-seam rules under Boundaries and tests adapt it.