In this post, we discuss how we achieved a ~290x cost improvement, eliminating a potential US $12M manual refactoring of stored procedures, by building our version of a constrained software factory.
The simulation above (Figure 1) illustrates our constrained software factory: highly automated lines can generate code in minutes, but human experts remain at every gate.
To break down exactly how this works, we will cover (1) why financial services was first to computerize and is therefore last to modernize, (2) what a stored procedure is and why thousands of them are a problem, (3) the five-step evolution of our factory, (4) the economics, and (5) why most corporate AI programs still fail.
First to computerize, last to modernize
Financial services and commercial aviation were the first industries to put computers directly into the path of live transactions. Because these critical systems can never be switched off, these industries carry the deepest legacy debt.
American Airlines and IBM launched SABRE in 1964 to handle real-time reservations, while SRI and Bank of America deployed ERMA in 1959 to automate check bookkeeping across California branches, introducing the magnetic ink character recognition (MICR) numbers still printed on checks today.
To be precise, these were not the very first business computers. That honor goes to the business computer job that ran in the United Kingdom on LEO I for J. Lyons & Co. (costing bakery ingredients in September 1951). The key distinction between these efforts is that the LEO and the Louisville UNIVAC ran batch jobs: payroll, inventory valuations, cost accounting, while ERMA and SABRE sat directly in the transaction path. A flight reservation or a ledger posting happens in (near) realtime.
Because these transaction systems worked, they endured—perhaps longer than they should’ve. Even as best engineering practices evolved, these systems have not. Today, 45 of the top 50 banks, 8 of the top 10 insurers, and 4 of the top 5 airlines still run core operations on mainframes. With agentic coding, the promise of autonomously rewriting legacy software is compelling. On February 23, 2026, Anthropic published a playbook on modernizing COBOL using Claude Code, triggering a ~13% single-day drop in IBM shares. IBM responded that decades of deep hardware-software integration cannot be replicated simply by moving code. They are not wrong, which this post will further enumerate.
So why did the legacy logic migrate into the database?
When code sits in the transaction path, it must execute where data lives at transaction speed, apply logic uniformly across every system, and accept changes without downtime. In the client-server era of the 1990s, the stored procedure satisfied all three: it eliminated network round trips, applied rules centrally across every client application, and allowed a database administrator to modify production logic on a Tuesday afternoon without an application release. That operational convenience is why they multiplied. Every operational edge case, such as a new column, an adjusted threshold, or an ad-hoc regulatory export, became a procedure. Thirty years later, that convenience has hardened into an immense technical debt.
For reasons stated above, as it turns out, stored procedures are ubiquitous across the financial services industry.
What a stored procedure is, and why thousands of them are a liability
Technically, a stored procedure (code that lives inside the database and runs there) is a named block of SQL combined with procedural control flow, including loops, conditional branches, and local variables. An application calls the procedure by name over a database connection; the database retrieves the procedure, queries or mutates the underlying tables, and returns a processed result set.
In a firm like ours, there are typically tens of thousands of stored procedures powering business transformation logic and operational screens. Within our own operations domain, hundreds of these procedures directly drive the screens used daily by back-office staff. Alongside them sits a legacy file layer consisting of exported spreadsheets and fixed-width text files consumed by downstream systems.
These portal-facing procedures handle foundational back-office functions. Over the decades, as software architecture moved business logic out of databases and into decoupled, version-controlled application layers, leaving critical rules trapped inside stored procedures has become a profound operational liability across five specific areas:
- Not versioned. The code lives inside the database rather than in source control. Version control is managed informally through procedure naming conventions (
_v3_FINAL_newis the version control).- Hard-coded values. Account identifiers, execution cutoffs, thresholds, and unexplained "magic numbers" are baked directly into the query logic.
- Brittle. An upstream schema change causes the procedure to fail—or worse, execute silently while returning corrupted numbers that look right.
- Not testable, not reusable. The code lacks automated unit tests. Logic was repeatedly copied across dozens of near-identical procedures, and nobody dares delete one because nobody knows which batch job or reporting interface calls it.
- Opaque. The business rule exists only inside the SQL, and the person who wrote it left years ago.
The ops reporting domain is the right domain to start a constrained version of a software factory
AI code generation functions most reliably when degrees of freedom are low. Consider greenfield product development. In greenfield projects, requirements are ambiguous, user workflows are unproven, and verifying output correctness is difficult because no baseline standard exists.
Operational reports present the inverse environment. An operational report is simply a deterministic function. The inputs are strictly defined by existing database schemas. The outputs are known because the legacy report is actively running in production and is the executable specification. Correctness is checkable: an engineer or agent can execute the legacy procedure, run the modernized replacement against identical source records, and evaluate the diff down to the individual cell.
This is why we picked this domain for our first software factory. We did not design our modernization engine as an all-encompassing platform up front. It evolved across five distinct experiments, each structured around a recurring cycle: experiment → validate → encode as a skill → more automation with fewer human steps.
In our environment, a skill is a written, versioned playbook that an AI agent loads and follows. It defines the required inputs, operational boundaries, verification scripts, and the stopping rules, so that an execution path proven by one engineer can be repeated consistently by the entire team.
The evolution: five experiments that became skills
Experiment ───> Validate ───> Encode as Skill ───> More Automation
Context store: one place for everything
Operational reports do not exist in isolation; they bridge user interfaces, backend APIs, database stored procedures, and scheduled batch jobs. And AI agents cannot reverse-engineer systems they cannot inspect. As such, our first experiment addressed context fragmentation. We built a mirror monorepo containing 20+ application repositories, the database schemas, every stored procedure, and the metadata from our job scheduler. Placing these assets into a single unified context store allowed an agent to trace a visual grid in our internal operations portal back through its API, down to the stored procedure execution, and out to the nightly scheduled batch job that populates the base tables.
Reverse-engineering the business logic (analyze-app)
With context centralized, we built analyze-app. Operating initially in "single-player mode," an engineer directed the agent to trace dependencies from the user interface down to scheduled jobs, extracting undocumented business logic into structured functional requirements and business rules.
We tested this against an active operational workflow: a daily exception report fed by an external data source.
The analysis extracted more than a dozen functional requirements and distinct business rules, validating each directly against the SQL. More importantly, tracing the code exposed exactly why stored procedures are such a liability: they fail silently, and because they lack automated tests, those failures become accepted behavior.
The agent also uncovered two undocumented blind spots:
- First, the procedure had no mechanism to verify if the day’s upstream data had actually arrived. A stalled feed simply rendered an empty grid, making a pipeline outage look identical to a clean day with zero exceptions.
- Second, several UI filters were completely disconnected from the backend query, returning blank views instead of throwing an error.
The agent turned these blind spots into explicit new requirements: automated feed monitoring and "filters that filter." Finally, dependency mapping proved we could decouple this specific workflow from adjacent systems and migrate it independently.
Build (implement-requirement)
Once requirements were surfaced, we needed a structured way to implement them without introducing regressions. We encoded this into implement-requirement.
Requirements are formalized using EARS (a plain-English requirements template in which every rule is a WHEN / IF…THEN / WHILE / ALWAYS sentence). Structuring specifications through strict conditional grammar forces edge cases into view before any code is generated. A sibling skill, prd-intake, analyzes draft documentation to flag ambiguities up front, directing clarifying questions to business stakeholders before execution begins.
Within the requirement specification, rules are explicitly tagged by origin:
- [SQL]: Discovered directly within legacy database code.
- [PRD]: Sourced from current product requirement documents.
- [PROPOSED]: New architectural or operational rules introduced during analysis.
Revisions are tracked visually with struck-through text on the requirement page to make manual reviews auditable.
During implementation, specialized sub-agents execute tasks by architectural layer: UI components, server endpoints, and database migrations. Once code is generated, the pipeline executes quality checks: code linters, project compilation, unit tests, and automated browser tests. The process concludes when an engineer reviews and signs off on the rendered interface in a local browser session.
The system incorporates a self-learning loop. When a skill encounters execution friction—such as an unhandled framework exception or an ambiguous prompt step—it logs an entry into an active journal. These entries aggregate into proposed playbook updates. A developer reviews and approves the batch, and evolve-skill applies the modifications to the playbook. Over the course of this exception report project, the journal captured 36 operational notes; items 31 through 36 were applied in a single systematic update near the end of the implementation.
Review and ship: the bottleneck moves (prepush-audit → ship-feature → audit-pr)
Accelerating code generation exposed the next operational constraint: pull request review.
Engineers found themselves parsing large diffs, leading to extensive comment threads, slow turnarounds, and CI pipelines that ran 45 to 60 minutes per cycle only to fail on minor issues. The automated reviewer embedded in our remote pipeline regularly stalled.
To resolve this, we built prepush-audit. It reviews the branch before anyone else sees it. The tool runs the same checks CI would run, just earlier and locally, and it will not start if the branch is dirty, protected, or contains nothing new. It gets someone else's eyes on the code: the reviewers are separate agents that never hear your reasoning, so they judge the diff on its own. It keeps going until the code is clean: you get a ranked list of problems, you fix them, and it looks again—up to three rounds—then tells you plainly: good to go, good with caveats, or stop.
If the audit clears, ship-feature opens the remote pull request and tracks the remote test suite. Finally, audit-pr performs an independent review, categorizing remaining findings by severity to confirm whether the branch is safe to merge.
This review structure is now our default deployment mechanism. The stopping criteria are strictly enforced: during week three of the project, an audit remained red after three evaluation rounds. Rather than bypassing the check, the developer halted work, documented the failure on the pull request, and resolved the underlying defect. Across the project, 11 of 13 pull requests carried a verified independent check report.
The factory proper: Dataset Studio + Report Builder
The preceding experiments laid the groundwork for our factory model, which is manifested in two applications:
- Dataset Studio ingests a legacy stored procedure, an ad-hoc flat file, or raw database tables and converts it into a named dataset, which is then served to Report Builder.
- Report Builder. This platform allows analysts and engineers to compose certified datasets into functional interfaces. The platform automatically manages column projections, type mappings, aggregations, and layout configurations, governed by a maker-checker publish control (one person builds, a different person approves—a structural safeguard borrowed from financial accounting controls).
At this stage, a stored procedure ceases to be custom application code that must be manually rewritten. It becomes a certified data asset that an operator can select, configure, and publish.
Human in the loop: three phases and the arithmetic
The table below summarizes our operational transition across three distinct stages.
| Phase | Execution Model | Operational Throughput |
|---|---|---|
| 1. Human + AI | AI assists with requirement drafting and initial code; engineers drive every step. | 3.5 months → 4 days per report |
| 2. Human + AI Agents | Multi-agent execution harness; engineers validate steps. | < 1 day per report |
| 3. The Factory | Automated pipeline; product and operations teams validate; engineering involvement minimized. | ~2–4 hours per report |
The software factory saves us an estimated $12M in manual refactoring effort, replacing that with roughly $40K of token spend, a 290x cost reduction.
Nonetheless, three essential caveats must accompany that figure: (1) it excludes the capital and engineering hours invested in building the factory harness itself; (2) every generated report still requires rigorous human verification before reaching production; and (3) the 2-4 hour window applies to standard tabular reports, not every complex data workflow across the firm.
There are tasks the factory cannot execute. It cannot invent business rules that were never documented, reconstruct missing data sources, or exercise strategic judgment about how an operational workflow ought to function.
Why most AI programs fail (and why consultants can't do this for you)
It's no secret that enterprise adoption of artificial intelligence remains split between significant investment and marginal measurable returns. Last year, MIT NANDA published a report that stated that 95% of enterprise generative AI pilots deliver no measurable P&L impact. The reasons can be boiled down to two points:
- The "learning gap": enterprise deployments fail to retain user feedback, adapt to specific context, or systematically improve over time.
- Selecting the wrong problem: Most of these projects were for implementing AI for sales and marketing initiatives, even though the clearest operational returns appear in back-office workflow automation.
Despite these low pilot success rates, IT services firms have scaled their billings rapidly (see below):
- Accenture reported advanced-AI new bookings of approximately US $5.9B with US $2.7B in revenue for FY2025. By Q1 FY2026, cumulative AI bookings reached roughly US $11.5B across 11,000 client engagements, alongside US $2.2B in new quarterly bookings. Following that quarter, Accenture ceased breaking out advanced-AI metrics separately, folding the figures into its broader services lines. (Accenture reported FY2026 total revenue of US $74.2B on US $84.5B in total bookings).
- Infosys reported that AI-related revenue reached 8.2% of total revenue in Q1 FY27 (April–June 2026), citing consistent double-digit quarter-over-quarter growth across its AI services portfolio.
- Cognizant reported running over 5,000 active AI engagements in early 2026, noting that over 50% of its internal code was AI-assisted, though it does not isolate AI revenue in public filings.
Having built a working software factory, our perspective is clear: external systems integrators cannot execute this transformation for you.
The time-consuming elements of our implementation had little to do with raw prompt engineering. The labor went entirely into foundational engineering:
- Assembling fragmented system context into a unified store that an agent can parse.
- Uncovering what legacy database routines were actually computing.
- Constructing mechanical test harnesses, circuit breakers, and self-learning feedback loops.
- Resolving organizational friction by coordinating with data, compliance, and operations teams to establish new verification patterns.
Technological diffusion across an enterprise is inherently gradual. Organizational inertia must be tackled from within; an outside consultant cannot resolve it on your behalf. An external vendor receives a six-month statement of work and an hour-long weekly status check. Their consultants will not get the time of day from the operations lead who understands why SQL script _v3_FINAL was deployed to production a decade ago, and they will never care about the integrity of your reporting as much as you do.
What risk would falsify our thesis? If frontier research labs ship turnkey legacy-modernization agents that seamlessly parse legacy data structures off the shelf, the competitive advantage of building an internal code generation harness diminishes. Even in that scenario, however, the primary operational hurdles, unified context extraction, domain expertise, and organizational alignment, remain internal responsibilities.
Closing thoughts
A viable software factory does not require complex autonomy. It requires a tightly bounded domain, centralized system context, versioned skills that encode proven engineering patterns, and a qualified person presiding at every gate. The economic advantage is very substantial. We can shift build times from months to hours and drop marginal generation costs by roughly two orders of magnitude.
Fair warning though, the work is not for the faint of heart. The true challenge does not reside in the 85% of code that the agent generates cleanly; it lives in the final 15% of business rules where human verification and institutional context are indispensable. A software factory is only as reliable as the humans-in-the-loop who inspect the work before it ships.