A pattern

Code as a Contract — a pattern

Lean version for agents

Nine rules, one example and a check list, in about 800 tokens. An agent can read it and apply almost all of the pattern.

Read the lean version

Lead by example

# Before: inline ifs mixed with side effects. Nobody can cite them.
def refund(order, user):
    if order.days_since_delivery <= 30 and not order.final_sale:
        if user.is_vip or order.total < 500:
            gateway.refund(order.total)
            email.send(user, "Refunded")
# After: each rule is a named clause, filed under the party it binds.
# The decision is pure. Side effects happen at the edge.

# contract/customer.py
RETURN_WINDOW_DAYS = 30

def within_return_window(days_since_delivery: int, final_sale: bool) -> bool:
    return days_since_delivery <= RETURN_WINDOW_DAYS and not final_sale

# contract/business.py
AUTO_APPROVE_BELOW = Decimal(500)

def auto_approved(customer_is_vip: bool, total: Decimal) -> bool:
    return customer_is_vip or total < AUTO_APPROVE_BELOW

def decide_refund(days_since_delivery, final_sale, customer_is_vip, total) -> bool:
    return (within_return_window(days_since_delivery, final_sale)
            and auto_approved(customer_is_vip, total))
# Many facts, or facts from several objects? Bundle them in a frozen dataclass.

# Perform at the edge. One dispatch if on the decision; no rule is decided again here.
if decide_refund(order.days_since_delivery, order.final_sale, user.is_vip, order.total):
    gateway.refund(order.total)
    audit_log.record(order)
    email.send(user, "Refunded")

The tests are the expected behavior, written as code: precedents (in legal terms: case law). Each test name says, in plain words, one thing the code must always do. If a change breaks a promise, a test fails and names it. No docstring repeats the rule: text that no test checks can drift.

# precedents/test_customer.py
def test_customer_is_refunded_on_day_30():
    assert decide_refund(days_since_delivery=30, final_sale=False,
                         customer_is_vip=False, total=Decimal(80))

def test_business_may_refuse_a_final_sale_item():
    assert not decide_refund(days_since_delivery=3, final_sale=True,
                             customer_is_vip=True, total=Decimal(80))

Operational rules are policies

Retries, caching, rate limits and permissions are policies. Write each policy once, as plain data, instead of scattering decorators and flags across the code. One generic runner applies it. Each decision it needs is a small pure function with its own tests.

For lawyers: a policy is a schedule (an annex to the contract), and each rule in it is a clause.

@dataclass(frozen=True)
class RetryPolicy:
    max_attempts: int
    backoff_s: float
    retry_on: frozenset[type[Exception]]

GATEWAY_RETRY = RetryPolicy(3, 2.0, frozenset({TimeoutError}))

def should_retry(p: RetryPolicy, attempt: int, error: Exception) -> bool:
    return attempt < p.max_attempts and type(error) in p.retry_on

def refund_idempotency_key(order_id: str) -> str:
    return f"refund-{order_id}"

# The generic runner holds no rules of its own.
def run(action, p: RetryPolicy):
    attempt = 1
    while True:
        try:
            return action()
        except Exception as e:
            if not should_retry(p, attempt, e):
                raise
            time.sleep(p.backoff_s * attempt)
            attempt += 1

run(lambda: gateway.refund(total, key=refund_idempotency_key(order.id)), GATEWAY_RETRY)
def test_gateway_timeout_is_not_retried_a_fourth_time():
    assert not should_retry(GATEWAY_RETRY, 3, TimeoutError())

def test_card_declined_is_never_retried():
    assert not should_retry(GATEWAY_RETRY, 1, CardDeclined())

def test_retried_refund_reuses_the_same_key():
    assert refund_idempotency_key("A1") == refund_idempotency_key("A1")

Read the policies paper (titled “Schedules”) for caching, queues, forms and records.

Code is not instructions to a machine that humans happen to read. Code is a contract between many parties — the customer, the business, the payment processor, the next developer, the on-call engineer at 3am — that a machine happens to execute.

Read any well-drafted legal contract and you find the same structure good code wants: the parties first, then sections stating each party's obligations, responsibilities and abilities, the business rules and how they are applied, the succession of events — what must happen, in what order, and who has to do it — and the precedents (in legal terms: case law) that settle disputes. Definitions exist to serve those clauses, not to open the document.

> Core vs. Optional Extensions. Parts I–III (principles, precedents, > and the gather → consult → perform boundary) are the Core — complete > and self-contained on their own. Parts IV–V (Schedules and Articles) > are Optional Extensions to adopt incrementally when operational or > architectural drift becomes a real problem.

The principles, in plain words

  1. There are more parties than you first think: the people you name (user, admin) and the systems you don't (frontend, cache, database, each subsystem). List what each one promises, then turn every promise into a tested rule. More
  2. Give every business rule its own named function. More
  3. The main function reads like a list of steps, with almost no if/else. More
  4. Decide first, with pure functions. Then do the side effects: database writes, API calls, emails. More
  5. The tests describe the expected behavior. They are the spec. More
  6. Apply the same rules inside each function, but stop when a new name adds nothing. More
  7. A behavior change shows which rule changed and which test now gives a different result. More
  8. At the boundary: collect the facts, decide, then act on the decision. Do not decide again while acting. More
  9. Retries, caching, limits and permissions are policies: plain data, run by generic code. More
  10. If a test can check a rule, the rule is a test. The list of test names is the spec. No hand-written copy. More

Read the full pattern Repository

Companion papers