Refactoring across multiple files is where automated coding assistants usually fall apart. Renaming a single exported interface or splitting a utility module looks trivial on paper, but in practice, an AI model that inspects only isolated files will hallucinate stale arguments, break downstream imports, and produce a pull request full of syntax errors.
Sweep tackles this challenge with a distinct two-stage architecture: an explicit, structured planning phase backed by hybrid repository indexing, followed by deterministic sandbox validation. At 365Finds, we look at how Sweep maps dependency graphs, avoids context window bloat, and coordinates cross-file edits—and where its architectural boundaries still lie.
The Core Dilemma: Why Naive RAG Fails at Cross-File Refactoring
Standard Retrieval-Augmented Generation (RAG) treats source code like plain prose. When asked to refactor an authentication middleware, a naive agent splits files into fixed 500-token chunks, vectorizes them, and retrieves whatever cosine similarity flags as relevant.
This fails during real-world refactoring for three specific reasons:
- Broken Call Hierarchies: Vector search identifies semantically related text (e.g., descriptions of authentication), but it often misses the exact caller sites scattered across twenty different controllers.
- The "Lost-in-the-Middle" Phenomenon: Stuffing full source files into 100k+ token context windows degrades the model's ability to reason about subtle signature changes.
- Desynchronized Diffs: When an agent writes code without a centralized dependency plan, it modifies file A using a new signature, but writes file B assuming the legacy signature still exists.
Sweep avoids this trap by decoupling repository indexing and dependency planning from the actual code generation.
1. Dual-Engine Indexing: AST-Guided Embeddings and Lexical Search
Sweep does not rely solely on vector search. Instead, it deploys a hybrid retrieval engine designed around programming language structures.
+-------------------------------------------------------------------+
| Sweep Indexing Engine |
+-------------------------------------------------------------------+
| |
v v
[ AST Chunking ] [ In-Memory TF-IDF ]
| |
Parsed via Tree-sitter CamelCase / snake_case
Scoped by Classes & Functions N-gram Call Patterns
| |
v v
[ Redis Vector DB ] [ Lexical Tokens ]
Lightweight Pointers Exact Symbol Matching
(filename:start:end) (imports, decorators)
| |
+---------------------+---------------------+
|
v
[ Hybrid Search Results ]
AST-Based Semantic Chunking
Instead of slicing code arbitrarily by line counts, Sweep parses source code into Abstract Syntax Trees (ASTs). Chunks correspond to logical constructs—classes, methods, functions, and interface declarations.
- Lightweight Storage Pointers: In its Redis vector database, Sweep avoids bloating storage by keeping pointers (
path/file.py:start_line:end_line) rather than storing redundant full-text blobs. - Content Hashing (SHA-256): Each chunk is tagged with a cryptographic hash. When a pull request merges or a branch updates, Sweep re-indexes only the modified chunks, updating repository context in seconds.
In-Memory Lexical TF-IDF Engine
Vector embeddings capture conceptual intent ("where do we handle token expiry?"), but they struggle with exact symbol resolutions. Sweep couples vector retrieval with an in-memory TF-IDF engine specifically tuned for code:
- Identifier Subtokenization: Splits
PascalCase,camelCase, andsnake_caseso that identifiers likegetUserSessionanduser_sessionmap to common token stems. - N-gram Matching: Indexes compound patterns like
db.session.queryorlogger.warning, ensuring that exact call chains surface immediately during dependency queries.
2. Bipartite Dependency Graphs and In-Degree Pruning
When refactoring, the critical question is not just "what code looks similar?" but "what code will break if this entity changes?"
Sweep constructs an entity-to-file graph:
- The Bipartite Model: The graph places source files on one side and parsed code entities (functions, classes, interfaces) on the other. Directed edges represent imports, function calls, and type references.
- In-Degree Zero Pruning: A raw bipartite code graph is flooded with noise—such as ubiquitous standard library calls (
import math,import logging). Sweep prunes uninstantiated external and standard dependencies with an in-degree of zero. In engineering benchmarks, this eliminates over 80% of spurious edges (for example, reducing an entity graph from 680 noisy edges down to 102 actionable links). - Planning in AST Space: Instead of feeding three 1,500-line files into the model context, Sweep isolates the target function entities (typically 100 to 200 lines each) and their immediate downstream dependents. This keeps the LLM focused on exact interface boundaries.
3. The Two-Phase Execution Workflow
Sweep treats multi-file refactoring as an architectural planning problem first, and a text editing problem second.
[ GitHub Issue / Prompt ]
|
v
+---------------------------------------+
| Phase 1: Dependency Mapping & Plan |
| - Traverse AST Call Graph |
| - Identify Upstream & Downstream |
| - Output (File, Action) Plan Tuple |
+---------------------------------------+
|
v
+---------------------------------------+
| Phase 2: Context-Injected Generation |
| - Sequential File Diff Generation |
| - New Contract Passed to Callers |
+---------------------------------------+
|
v
+---------------------------------------+
| Phase 3: Sandbox Verification Loop |
| - Linter (ruff, eslint) |
| - Type Checker (mypy, tsc) |
| - Unit Tests Run |
+---------------------------------------+
|
[ Clean PR ]
Phase 1: Generating the Execution Tuple
Sweep transforms the user prompt into an explicit plan before generating any file diffs. The output is a structured sequence of (file_path, instructions) tuples:
- Identifies the primary source of truth (the definition being modified).
- Traces all dependent call sites through the pruned graph.
- Specifies exact contractual expectations for each file (e.g., "Update
auth_service.pysignature to accepttenant_id; modify callers inapi/routes.pyandtests/test_auth.py").
Phase 2: Staged Code Generation with Contract Injection
Sweep executes changes file-by-file according to the plan. Crucially, when generating changes for downstream consumers, the agent injects the newly refactored upstream definition into the prompt context, guaranteeing that argument orders, parameter types, and return values remain consistent across file boundaries.
Phase 3: Closed-Loop Sandbox Validation
No AI refactor is trusted without deterministic verification. Sweep runs the modified repository inside an isolated execution sandbox:
- Formatters and Linters: Checks for broken imports and style violations (e.g.,
ruff,flake8,eslint). - Type Checking: Runs compilers (
tsc) or static type checkers (mypy,pyright) to catch argument mismatches across modules. - Automated Unit Tests: Executes existing test suites. If a downstream consumer breaks, the error stack trace is routed directly back into the agent loop to repair the diff before opening the pull request.
365Finds Assessment: Practical Strengths and Operational Limits
At 365Finds, we appreciate Sweep's disciplined separation of graph planning and code synthesis. However, cross-file refactoring agents are not universal magic. Knowing where they excel and where they stumble determines whether your team saves hours or inherits messy merge conflicts.
| Scenario | Sweep Performance | 365Finds Practical Recommendation |
|---|---|---|
| Static Symbol Refactoring (renaming, signature updates, file splits) | High accuracy; hybrid search and AST pruning capture callers cleanly | Highly recommended; safe to delegate via GitHub issue automation |
| Cross-Module Type Migrations (e.g., moving to Pydantic v2 or strict TypeScript) | Strong; deterministic type checkers catch missed callers in sandbox | Recommended; requires robust test suites or type coverage to validate |
Dynamic Runtime Invocations (getattr, dynamic dispatch, reflection) | Fragile; static AST graphs cannot resolve runtime string targets | Use with caution; requires explicit issue prompts naming target files |
| Large Monorepos (>500k LOC) | Moderate; graph retrieval scales, but cross-package boundaries can dilute context | Scope tasks to specific sub-directories using .sweep.yaml configuration |
Where Sweep Excels
For repetitive architectural chores—such as deprecating legacy helper functions, updating database model schemas across routes, or migrating internal APIs—Sweep functions like a diligent junior engineer. Its ability to generate an audit-ready plan before writing code prevents the context thrashing typical of generic chat assistants.
The Blind Spots
Sweep's dependency engine relies on static code properties. If your codebase relies heavily on dynamic dependency injection containers, string-based reflection, or loosely typed dictionary payloads, the bipartite graph cannot map the caller chain reliably. In those environments, human guidance in the initial prompt remains mandatory.
Best Practices for Multi-File Refactoring with Sweep
To maximize accuracy when triggering multi-file refactoring runs in Sweep:
- Provide Clear Behavioral Contracts: When writing the issue description, specify not just what needs to move, but what must remain backward-compatible or explicitly break.
- Configure
.sweep.yamlRules: Instruct Sweep to run project-specific linters and test commands (pytest,npm test) so its sandbox verification loop has immediate feedback. - Keep Commits Modular: Split massive repository-wide overhauls into logical subsystem migrations rather than dispatching a single prompt across forty modules.
- Leverage Type Hints: The stricter your repository's static types, the more effective Sweep's AST chunking and type-checker validation loop will be.