Refactoring Orchestrator
Relevant source files
The following files were used as context for generating this wiki page:
The Refactoring Orchestrator is a central coordination layer designed to execute complex code transformations across files, projects, and entire workspaces. It integrates rule loading, safety management, and multi-layered execution strategies (text-based and Rope-backed) to ensure deterministic and safe refactoring operations within the FLEXT ecosystem. Sources: src/flext_infra/refactor/orchestrator.py:1-20, src/flext_infra/refactor/_orchestrator_scope.py:1-15
The system utilizes a mixin-based architecture to separate concerns such as CLI dispatching, scope management (workspace vs. project), and the core execution logic. It serves as the primary engine for automated code modernization, namespace enforcement, and MRO migrations. Sources: src/flext_infra/refactor/orchestrator.py:25-35, src/flext_infra/refactor/_orchestrator_dispatch.py:1-20
Core Architecture
The orchestrator is implemented via FlextInfraRefactorOrchestrator, which inherits from multiple specialized mixins and executors to provide a unified interface for refactoring tasks. Sources: src/flext_infra/refactor/orchestrator.py:28-33
Inheritance Structure
The following diagram illustrates the composition of the Orchestrator:
Key Components
| Component | Description | Source |
|---|---|---|
FlextInfraRefactorRuleLoader | Loads and manages the selection of refactoring rules to be applied. | src/flext_infra/refactor/orchestrator.py:38 |
FlextInfraRefactorSafetyManager | Manages checkpoints, semantic validation, and emergency rollbacks. | src/flext_infra/refactor/orchestrator.py:44, src/flext_infra/_models/refactor.py:133-149 |
FlextInfraRefactorOrchestrator | The primary class coordinating the execution of rules against files. | src/flext_infra/refactor/orchestrator.py:28 |
Refactoring Execution Flow
Refactoring occurs in a multi-stage pipeline, moving from high-level scope detection down to individual file transformations. Sources: src/flext_infra/refactor/orchestrator.py:53-95, src/flext_infra/refactor/_orchestrator_scope.py:100-150
Execution Pipeline Diagram
Multi-Layer Rule Application
The orchestrator applies two distinct types of rules:
- File Rules: Backed by the Rope library, these handle AST-based transformations like renames or MRO migrations. These require a workspace context to resolve resources. Sources: src/flext_infra/refactor/orchestrator.py:122-155
- Text Rules: Regex-based transformations applied directly to the source string. These are typically used for simpler pattern corrections. Sources: src/flext_infra/refactor/orchestrator.py:157-175
Safety and Rollback Strategy
Safety is enforced through a checkpoint system managed by the FlextInfraRefactorSafetyManager. This ensures that if a transformation leads to semantic failures, the workspace can be restored to its original state. Sources: src/flext_infra/refactor/_orchestrator_scope.py:35-95, src/flext_infra/_models/refactor.py:133-149
Safety Lifecycle
- Pre-transformation Checkpoint: Before processing a scope (project or workspace), a checkpoint of the target files is created. Sources: src/flext_infra/refactor/_orchestrator_scope.py:35-48
- Semantic Validation: After changes are applied, the system runs validation logic to ensure the code still passes fundamental quality gates. Sources: src/flext_infra/refactor/_orchestrator_scope.py:65-73
- Emergency Rollback: If validation fails or an error occurs during processing, the
_abort_with_rollbackmethod triggers an immediate restoration of the checkpoint. Sources: src/flext_infra/refactor/_orchestrator_scope.py:81-98
Checkpoint Data Model
The Checkpoint model tracks the state of an ongoing refactor operation.
Sources: src/flext_infra/_models/refactor.py:133-149
| Field | Type | Description |
|---|---|---|
workspace_root | str | Absolute path to the workspace root. |
status | str | Current status (e.g., "running", "post-transform"). |
processed_targets | t.StrSequence | List of file paths already processed. |
updated_at | str | ISO 8601 timestamp of the last checkpoint update. |
CLI and Dispatching
The FlextInfraRefactorOrchestratorDispatchMixin connects the orchestration logic to the Command Line Interface. It handles argument parsing, file collection, and reporting. Sources: src/flext_infra/refactor/_orchestrator_dispatch.py:20-50
Key Dispatch Functions
run_refactor: The main entry point for refactor commands. It resolves whether to target a single file, a project, or a workspace based on providedRefactorCliArgs. Sources: src/flext_infra/refactor/_orchestrator_dispatch.py:116-157run_analyze_violations: Scans the selected scope usingFlextInfraRefactorViolationAnalyzerto provide a summary of rule violations without applying changes. Sources: src/flext_infra/refactor/_orchestrator_dispatch.py:86-98_print_diff: Usesdifflib.unified_diffto display exactly what will change (or has changed) in a file during a dry-run or application. Sources: src/flext_infra/refactor/_orchestrator_dispatch.py:67-76
Result Model
Every file operation returns a Result object.
Sources: src/flext_infra/_models/refactor.py:65-85
| Field | Type | Description |
|---|---|---|
file_path | Path | The target file path. |
success | bool | True if the refactor completed without exceptions. |
modified | bool | True if the file content was changed. |
error | str | None | Error message if success is False. |
changes | t.StrSequence | Human-readable descriptions of applied rules. |
refactored_code | str | None | The final source code after all transformations. |
Implementation Example: refactor_file
The refactor_file method demonstrates the standard execution pattern, including dry-run support and protected writes.
# src/flext_infra/refactor/orchestrator.py:53-67
@override
def refactor_file(
self,
file_path: Path,
*,
dry_run: bool = False,
gates: t.StrSequence | None = None,
) -> m.Infra.Result:
"""Refactor one file using the loader's current rule selections."""
try:
if file_path.suffix != c.Infra.EXT_PYTHON:
return self._skip_result(file_path)
return self._refactor_python_file(
file_path,
dry_run=dry_run,
gates=gates,
)
except Exception as exc:
return self._error_result(file_path, str(exc))
Sources: src/flext_infra/refactor/orchestrator.py:53-67
Summary
The Refactoring Orchestrator provides a robust, fail-safe environment for large-scale code transformations. By combining high-level scope management with low-level AST and text manipulation, and wrapping the entire process in a safety-first checkpoint system, it enables automated maintenance and evolution of complex Python codebases with high confidence. Sources: src/flext_infra/refactor/orchestrator.py:28-50, src/flext_infra/refactor/_orchestrator_scope.py:15-30