Writing contracts before agents write the code, part 1
I let agents write implementation code only after I write down what the function or service promises, what inputs it rejects, and how tests will verify it.
Part 1 of a series. Design by contract is decades old. What changed is that an LLM can now generate a thousand lines of plausible code in thirty seconds. Part 1 covers why I write contracts before prompting an agent. Part 2 covers the tooling.
Cheap code and fast fashion
Agents dropped the cost of typing out code to near zero. That feels great on day one. The bill shows up two weeks later when nobody on the team can explain what a generated module actually guarantees when an upstream service times out. Software starts looking like fast fashion, cheap to spin up, disposable when it breaks, and painful to depend on.
Typing was never the bottleneck in systems work. Deciding what the code must guarantee under bad inputs, concurrent edits, and partial failure is the hard part. We need those guarantees written down in a form both engineers and test runners can check.
I call this workflow contract-driven coding.
Where reliability actually matters
When manufacturing gets cheaper, disposable goods flood the market first. Most scripts and internal dashboards can be disposable. If a throwaway prototype breaks, you regenerate it and move on.
Core systems do not get that luxury. Storage engines, spreadsheet calculation engines, payment ledgers, and medical devices are bought because they behave predictably at 3 a.m. Toyota, Casio, and Sony built their reputations on hardware that keeps working ten years later.
I want the speed of coding agents on serious systems without gambling with production state. Writing the contract first is how I keep both.
The abstraction ladder
A system has layers. Product behavior sits at the top, followed by services, modules, and individual functions. Each layer has its own failure modes.
Most teams scatter their specifications across product docs, type definitions, comments, and ad-hoc unit tests. Those artifacts drift apart within a month, and none of them check the others.
My workflow is direct. Write an explicit contract at the boundary you are touching, generate tests straight from that contract, and only then let the agent write the implementation until the checks pass.
What goes into a contract
A contract answers two questions. What does this caller have to provide, and what does this component guarantee when it returns?
At the function level, a contract states valid input ranges, return values, state mutations, error returns, and complexity bounds. Any caller reading the contract knows exactly what they can rely on without reading the function body.
The same structure applies as you move up the stack.
- A module contract lists its exported API, owned state, invariants, error types, and thread-safety rules. "The in-memory index always matches the write-ahead log" and "a failed call never leaks a file descriptor" are module contracts.
- A service contract defines wire formats, message ordering, durability guarantees, retry rules, and backpressure limits. "Writes are fsynced before returning HTTP 200" is a service contract.
- A product contract states what user actions are valid, what data must never be lost, and what latency or security bounds apply. "A confirmed order never charges a card twice" is a product contract.
The syntax changes across layers, while the core questions stay the same. What is promised, how can it fail, and what does it cost?
Looking closely at sum
Take sum, a function that takes an array of numbers and returns their total.
function sum(values: number[]): number
That type signature leaves almost every production bug wide open. Does sum accept NaN, Infinity, or floats that overflow Number.MAX_SAFE_INTEGER? What should sum([]) return? Is the function allowed to sort or mutate values in place?
Now scale the input up. What if values has fifty million entries, streams off disk in chunks, or comes from a buffer another thread is still writing? Those are four completely different implementations hiding behind one function signature.
If you ask an agent to write sum and write unit tests for sum, the agent will invent whatever assumptions match the code it just wrote. When you write the contract first, the tests check decisions a human actually made.
Deriving tests from contracts
Once a contract is written down, an agent can generate property checks and edge-case tests directly from the preconditions and postconditions. I review those test cases against the contract before a single line of implementation exists.
Each layer's tests come from its own contract. Function tests check function postconditions. Module tests check state invariants across sequences of calls. Integration tests check the wire contract between two services.
When a refactor three layers down breaks an invariant, the contract test at that boundary fails immediately during the build instead of surfacing as a corrupted record in production two weeks later.
Why agents make this mandatory
When humans wrote every line by hand, the sheer friction of typing forced us to think through edge cases along the way. Agents remove that friction. An agent will happily generate five hundred lines of clean-looking error handling around a completely wrong assumption.
If you give an agent a vague prompt, it fills in the blanks with statistical guesses. If you give it a strict contract and a failing test suite derived from that contract, the agent becomes a fast compiler from specification to working code.
Contracts are the real design work
Writing down where state lives, what happens when a network call stalls, and which invariant must hold on rollback forces you to design the system before you build it. Once those decisions are made, writing the code is mostly mechanical.
Contracts also save the next engineer who touches the code. New teammates can read the preconditions, invariants, and failure cases directly instead of doing git-blame archaeology to guess why a lock was acquired in a specific order.
Where to spend the effort
Writing formal preconditions for every five-line helper function is a waste of time. Spend the effort where a bug is expensive to fix or hard to spot. Put explicit contracts on public module boundaries, state machines, storage formats, and user-facing data mutations.
What comes next in this series
In the next posts, I will walk through concrete code examples.
- Writing function and module contracts that can be checked automatically.
- Generating property-based test suites from those contracts.
- Feeding contracts into coding agents and catching spec drift in CI.
- Deciding which boundaries in a codebase need strict contracts and which ones do not.
Models can write code faster than any of us. Our job is deciding what that code must guarantee.