Chapter 11 – Automated Refactoring Under Guards
Now give the payments service a separate refactor Mission. It targets
one lint violation in a private payment-normalization helper. The run
ends complete with a supported proposal and sealed Run
Record, but Admission has not yet occurred:
| Moment | Observation | Governance status |
|---|---|---|
| Baseline | One declared lint violation, no contract failures, and 88.2% coverage under the measurement protocol and current non-regression baseline, revision 42 | Current admitted Terrain |
| Candidate | The lint violation is removed, declared behavior and measured coverage are unchanged, and the effect stays inside one file | complete; supported proposal; Run Record sealed |
| Admission boundary | Current-base revalidation and floor advancement have not run | Admission pending; non-regression baseline revision 42 remains authoritative |
The candidate improved one structural property without regressing the required behavior or metric floor. Nothing has merged, and the floor has not moved.
Automated refactoring is governable when the workflow may propose a behavior-preserving structural change but cannot redefine behavior, weaken measurement, lower the protected floor, or admit itself.
Fix the Measurement Before Mutation
The activated refactor Mission pins the base revision and the material controls needed to compare baseline and candidate. Its bindings identify:
- the measurement implementation and protocol used for both baseline and candidate;
- the current protected minimum, or Ratchet floor;
- the dependency closure whose behavior could be affected.
The same implementation and protocol, both outside candidate authority, must observe the baseline and candidate. Candidate-controlled package scripts, test configuration, benchmark settings, or thresholds cannot redefine what “unchanged” means.
The record must identify what was measured and how, and preserve the source revision, protocol, tools, environment, raw observations, comparison rule, and floor revision.
Preflight verifies only that the already-authorized Mission identity
and its bound protocol, base, affected closure, baseline, and floor
revision remain present, intact, and executable. It may not repeat
policy review, remeasure the baseline, or select, replace, change, or
rebind a dependency. A missing, altered, or unusable dependency ends the
run as blocked only when the result names the external
repair or decision needed for a new linked run; otherwise it ends
failed. In either case, the Run Record is sealed. The
workflow never treats uncertainty as a pass.
The normal starting point is a green base. A policy may permit a precisely enumerated known-failure set, but the candidate must introduce no new or changed failure. “The branch was already red” is not a waiver.
Declare the Equivalence Boundary
“No behavior change” means no change to the observations that adopted intent declares stable. Depending on the system, those observations may include return values, errors, persisted state, external calls, event order, idempotency, timing, performance, logging, or telemetry.
Internal representation remains unconstrained unless another Map makes it observable. A changed public schema, exception contract, event sequence, or data effect is a behavior migration and belongs in a different Mission.
Guard Sufficiency
No test suite is universally comprehensive. Evidence must match the behavior boundary, mutation scope, and consequence:
| Refactor class | Typical scope | Minimum required evidence | Default Admission |
|---|---|---|---|
| Private lint cleanup | One symbol or file | Intended finding removed, relevant tests, lint, and complete diff | Allowlist only after comparable runs demonstrate stable results |
| Private rename | One module or package | Symbol-aware rename evidence, types, tests, and affected closure | Review until comparable evidence supports deeper delegation |
| Extract or inline function | One module | Behavioral contracts, types, tests, and structural predicate | Review by default |
| Move private implementation | Several files in one package | Dependency closure, integration contracts, and diff budget | Human review |
| Public behavior or interface change | Not a refactor Mission | Migration Map, compatibility plan, and consumer evidence | Separate Mission and approval |
When guards are weak, strengthen them in a separate Mission first. Adopt and protect the new contract or check before activating the refactor. The same candidate cannot author the only oracle that approves its change.
Mutation testing may help determine whether a check detects small semantic changes. When used, a fixed mutation protocol should serve as eligibility evidence for a refactor class, not as a universal per-candidate ritual. A surviving mutant supports a guard-strengthening proposal; it does not widen the current Mission.
Produce a Refactor Within the Boundary
A refactor changes structure while preserving behavior declared by the Map. Suitable transformations include:
- remove one unused private symbol;
- rename one private symbol with a language-aware tool;
- extract or inline one function without changing its contract;
- simplify one expression under an explicit equivalence check;
- apply one approved formatter or codemod to an allowlisted region.
The Mission must also state why the change should exist: remove a named finding, reduce a declared complexity measure, or complete a specific structural transformation. Non-regression alone does not justify churn.
Dependency upgrades, security patches, migrations, public-interface changes, and architectural changes are not refactors for governance purposes. They may use the same workflow architecture, but they need different authority, checks, approvals, and recovery.
The candidate runs inside Chapter 10’s complete effect boundary. An ordinary refactor has no authority over protected checks, floor state, CI, credentials, deployment, databases, production configuration, or admission.
Validate Under Protected Acceptance Rules
The protected boundary applies to acceptance authority, not to where every check is authored or invoked. The workflow may create, run, and record checks under a declared protocol, but the candidate cannot rewrite their decisive meaning. The Mission’s bound validation plan answers five questions:
| Question | Required evidence |
|---|---|
| Did the intended refactor occur? | The named finding disappeared, the declared codemod completed, or the exact structural predicate holds |
| Is declared behavior preserved? | Contracts, tests, properties, and runtime observations named by the bound validation plan |
| Did effects remain in scope? | Runtime effect records and the complete diff computed outside candidate authority |
| Did measured quality regress? | Candidate observations compared with the current floor under the same protocol |
| Are required artifacts complete? | Declared identities, provenance, schemas, and output checks |
When recorded with provenance, candidate-supplied tests and results are evidence. By themselves, they neither independently corroborate the candidate nor replace the protected acceptance basis. A declared protocol may validate new tests as Chapter 3 describes. A candidate that edits its floor, required test harness, required configuration, or any required check outside authorized effects fails validation even when its own commands report success.
Affected checks follow dependency closure, not only changed paths. Shared contracts and transitive consumers may need validation even when the diff is local.
Noisy Measurements
A noisy required metric has three check results: pass, fail, or inconclusive. Its bound validation plan fixes the sampling protocol, aggregation rule, tolerance, retry budget, and inconclusive result. For performance-like observations, that protocol also fixes the warmup and environment class.
An inconclusive result may permit another declared sample batch for
the same candidate. Exhausting that budget without a decision ends as
failed. It ends as blocked only when progress
requires a named external repair or decision.
Protected Non-Regression
A Ratchet is a protected non-regression rule measured by one fixed protocol. It may require zero contract violations, non-increasing lint or type failures, a bounded performance distribution, or no undeclared API expansion.
Protected non-regression
Validate, Then Commit Admission and Floor Together
Validation may support proposal closure against one protected floor revision. Current-state Admission commits the candidate and next floor as one transaction.
Protocol: code-health@7
Floor: revision 42
Worker access to floor: read-only
For this candidate, failure, uncertainty, stale state, or a transaction write failure commits neither Admission nor floor advancement. Lowering the floor requires a separate Governance Mission and separate Adoption.
One lint finding is removed while required behavior remains unchanged and the current floor is preserved.
not run
not run
not eligible
revision 42
The candidate has not been evaluated.
Coverage and test count are weak universal floors because their denominators and semantics change. They are suitable only where the protocol and governed property make the comparison meaningful.
The floor, protocol, comparator, and advancement mechanism belong to the Protected Control Plane. The active refactor may read them but cannot modify them. Lowering a floor or changing its protocol requires a separate Governance Mission and separate Adoption before the change becomes authoritative.
A Ratchet lets an organization automate repeated improvement without letting automated work erase prior gains by lowering the baseline. Delegation can deepen only while a floor measured outside candidate authority continues to hold.
Admit and Advance the Floor Together
Following the lifecycle established in Chapters 5 and 10, the Mission Gate revalidates the candidate and its sealed Run Record against the current base, dependency closure, protocol, and floor.
For a ratcheted candidate, current-base Admission and floor advancement form one transactional transition. An Admission service whose authority is separate from the candidate producer revalidates the expected base, floor revision, candidate identity, and measured result, then commits the admitted state and new floor together. If either write fails, neither commits: the candidate remains unadmitted, the prior floor remains authoritative, and a retry requires current-state revalidation. If another Admission has already changed the base or floor, the transaction aborts and the candidate must be measured again. A conforming Ratchet therefore cannot expose a state in which Admission succeeded but its required floor advancement failed.
Before Admission, revert discards a candidate workspace
after required evidence is preserved. After Admission, rollback is a new
transition with authority and evidence appropriate to the affected
surface. The two are not interchangeable.
For a multi-step extract-rename-move sequence, keep intermediate work inside one isolated candidate and compare the final result with the original base. If an intermediate state must become Terrain, produce it through a separately activated child Mission and submit its supported proposal to separate Admission.
This is the bounded form of structural self-modification. The workflow may propose an improvement, but its structural gain, behavior boundary, effects, non-regression floor, and eventual Admission remain checkable outside candidate authority.