I Gave the Orchestrator Three Sentences. It Refactored a 1,375-LOC Monolith in 49 Minutes. Here’s What Actually Made It Work

Most developers approach AI coding agents through iterative prompting: describe a task, inspect the diff, manually correct mistakes in chat, and repeat.

Coming from an Industrial Automation / PLC (Programmable Logic Controller) background, I approached this experiment differently. I gave the orchestrator agent three plain-text directives:

  1. “Decouple this 1,375-LOC monolithic poker engine (game.py).”
  2. “Keep core operations intact. Do not break legacy logic, and do not touch existing tests.”
  3. “Issue the commands yourself and direct the execution worker to refactor.”

The initial instructions were short. The engineering work was not.

The result was a decoupled poker engine whose game.py facade shrank from 1,375 to 394 lines, a 71.3% reduction, while remaining below the enforced 400-LOC limit.

The automated verification suite reported that 1,210 native unit test cases across 16 test files passed. A 500-hand simulation using a fixed random seed (seed(42)) reported zero observed behavioral divergence across 53,905 compared internal state data points.

Based on local filesystem creation and modification timestamps, the core decoupling phase took 49 minutes, from 15:19 to 16:08. No application logic was manually written by a human. Total release packaging and adversarial verification-gate hardening took approximately three hours.

The important question is not whether three sentences can magically refactor a legacy system. It is how a short task description, an execution agent, and an independently enforced verification process can work together—and what evidence is needed to trust the result.


1. Translating Human Intent into Rigid Boundaries

Brief instructions alone do not guarantee safe refactoring. Without independently enforced acceptance criteria, an agent may introduce unintended changes or weaken tests in an attempt to satisfy the task.

The verification pipeline was designed to detect these failure modes rather than rely solely on the agent’s own assurances.

  • Structural Boundary: A static AST rule required game.py to remain below 400 LOC while disallowing mutable default arguments and bare except: blocks.

  • Anti-Tampering Interlock: All 16 test files, covering 1,210 test cases, were fingerprinted using SHA-256 before code generation. Unauthorized byte-level changes under tests/ were intended to trigger a non-zero exit code and reject the delivery.

  • Differential State Oracle: Unit tests alone cannot guarantee continuity across every multi-way betting sequence. A 500-hand baseline was therefore used to compare sequential state transitions, including chip counts, pots, and action indices.

  • Public API Stability: The verification process checked that the 37 identified public methods and properties on TexasHoldEm remained available through an in-situ facade delegating to internal domain modules.

The principle is straightforward: define acceptance criteria before execution, then verify the resulting artifacts independently of the agent’s claims.

2. How the Refactoring Was Executed

The orchestrator did not draft the implementation through interactive code suggestions in a conversation window. It analyzed the syntax tree of game.py, reported as containing 5,466 AST nodes, and directed the execution worker to extract four domain modules:

  1. side_pot_math.py — 360 LOC
    Pot splitting, all-in calculations, and chip allocation.

  2. round_scheduler.py — 215 LOC
    Blind handling, betting rounds, and street transitions.

  3. action_validator.py — 185 LOC
    Raise validation and legal-action checks, including the project’s WSOP Rule 96 logic.

  4. game_serializer.py — 140 LOC
    PGN history replay parsing and game-state cloning.

The original game.py was then restructured into a 394-LOC facade delegating to these specialized modules.

The objective was not simply to reduce the line count. It was to separate responsibilities while preserving the existing behavior within the scope of the verification performed.

3. Adversarial Verification: Testing the Safety Relay

In physical automation, an emergency-stop relay is meaningful only if it responds correctly when a fault occurs.

The same principle applies to AI coding agents. A verification gate should not merely report success on a clean build; it should also reject deliberately corrupted or incomplete inputs.

The verification harness was tested against eight intentional failure scenarios:

Failure scenario Expected result
Test assertion modification causing a SHA-256 mismatch REJECTED — Exit Code 1
Missing fingerprint catalog REJECTED — Exit Code 1
Facade exceeding the 400-LOC boundary REJECTED — Exit Code 1
Introduction of a bare except: block REJECTED — Exit Code 1
One-chip discrepancy introduced into pot calculation REJECTED — Exit Code 1
Missing golden baseline dataset REJECTED — Exit Code 1
Breaking public API method signatures REJECTED — Exit Code 1
Unchecked subprocess failures REJECTED — Exit Code 1

All eight scenarios were reported as rejected with non-zero exit codes.

On a clean release build running locally on Windows 11 and Python 3.10, the automated verification runner completed its validation gates in approximately 0.7 seconds.

That runtime refers to the verification runner, not the total time required to develop, refactor, or initially execute the full test and simulation workload.

These results demonstrate how explicit failure conditions can be built into the delivery process. They do not establish that every possible failure mode has been covered.

4. Can This Approach Be Replicated on Other Systems?

Potentially, yes—but not through basic prompt chat alone.

Applying this workflow to legacy systems requires at least three prerequisites.

  1. Objective Ground Truth

    The target system needs existing tests, a trusted executable baseline, or another measurable reference against which behavior can be compared. Without one, the agent may produce a plausible implementation without sufficient evidence that it preserves the original behavior.

  2. Closed-Loop Execution

    The agent must operate in an environment where it can execute commands, inspect concrete results and exit codes, and encounter enforced failure conditions. Generating code and describing what should happen is not equivalent to executing and verifying it.

  3. A Control-System Mindset

    The human defines the safety boundaries and acceptance criteria. The agent performs the implementation work within those boundaries. Verification determines whether the result is acceptable.

This is the distinction I wanted to explore from an industrial automation perspective: the agent performs the work, but its own assertion of success is not the acceptance criterion.

5. Scope and Limitations

This experiment does not establish that the resulting architecture is universally bug-free, nor does it claim that this approach is a silver bullet for every legacy codebase.

The evidence supports a narrower conclusion: bounded behavioral equivalence within the tested scope.

The reported results include 1,210 native unit test cases and 53,905 compared internal state data points from a 500-hand simulation, with no observed divergence in those comparisons.

That is useful evidence, but it is not a mathematical proof of equivalence across every possible input, execution path, or future change.

The 49-minute figure also describes the core decoupling phase based on local filesystem timestamps. It should not be interpreted as the total time required to design the constraints, harden the verification gates, package the release, and prepare the experiment for publication.

The broader lesson is that autonomous code generation becomes more credible when its output is evaluated against predefined, independently checked conditions—not simply when the code compiles or the agent reports success.


Code and Side-by-Side Comparison

The original implementation, refactored code, extracted modules, and release artifacts are available for inspection.

Reproducing the Verification Gate

Clone the repository and run the release verification script:

git clone https://github.com/zxmn999/texasholdem-decoupled.git
cd texasholdem-decoupled
python verify_release.py

Review the repository and release instructions for any additional environment or dependency requirements.

I welcome fellow engineers to inspect the diffs, reproduce the verification process, and share how they approach deterministic boundaries when deploying autonomous coding agents on legacy codebases.

Hey, thanks for sharing, and especially for the “Scope and Limitations” section. The wording “bounded behavioral equivalence within the tested scope” is a lot more honest than the usual headlines like “AI rewrote everything in an hour.”

If you want to take the idea further, check out Hooks | Cursor Docs. With hooks, you can build the gates directly into the agent loop instead of running them as a separate step afterward:

  • A preToolUse hook with the Write matcher can block writes to tests/ before any file is changed. That gives you protection before the fact, while the SHA-256 check only catches the change after it already happened.
  • A stop hook with loop_limit can run verify_release.py, so the agent won’t finish until the gates pass.
  • subagentStop lets you verify the execution worker’s result before the orchestrator accepts its work.

The project-level config lives in .cursor/hooks.json, so you can commit it with the repo, and anyone who wants to repeat your experiment will get the same constraints.

I’m curious how this approach would work on a codebase without such dense test coverage. If you try it, I’d love to hear how it goes.

Appreciate the feedback on the “Scope and Limitations” section.

Regarding your question about legacy codebases without dense test coverage:

I would distinguish between having no tests and having no reliable behavioral ground truth. The absence of a dense test suite does not mean an AI agent should be allowed to treat the code it is modifying as the sole authority for expected behavior.

My approach comes from PLC-based industrial control and semiconductor equipment engineering, where an unverified state transition can have serious operational and financial consequences. I apply the same fail-safe discipline to software governance.

The underlying engineering methodology was developed over approximately 17 months of building and hardening an automated quantitative trading system from scratch, at 14+ hours a day, including weekends. That represents roughly 7,000 hours of engineering work under conditions where silent state regressions and numerical drift have real financial consequences. This was an entirely self-directed effort, without relying on a pre-existing end-to-end playbook or ready-made governance framework.

The fail-closed gates, SHA-256 integrity controls, and independent behavioral verification mechanisms demonstrated in these experiments are the result of that accumulated engineering experience. Their underlying governance logic, integration, and verification strategies were independently developed and stress-tested from first principles.

I’m happy to share reproducible benchmarks, architectural principles, and verifiable results publicly. However, developing and validating a reliable approach for legacy codebases without adequate test coverage is a substantially larger research and engineering task.

The underlying implementation methodology is the culmination of those 17 months of independent R&D, and deeper technical transfer or additional validation would require a paid, formally scoped consulting engagement, rather than an informal forum discussion.

I appreciate your interest and hope the published experiments are useful to the Cursor community.

Got it, thanks for the detailed reply. The published experiment and the verify_release.py script already give the community a lot to reproduce and dig into.

Just a quick reminder: this forum is for open knowledge sharing, so offers of paid services or consulting aren’t appropriate here. No hard feelings, just keeping the discussion open for everyone.

We’ll leave the thread open. If anyone tries a similar approach on code with sparse tests, for example with characterization tests or a golden baseline taken from prod, it’d be great to hear how it went.