Guardrails, Not Prompts

How a SpaceX engineer's team merges thousands of pull requests a month, the coding rules I refuse to give up when a stack changes, and how I turned those rules into checks for a hackathon project in a framework I barely use.

Guardrails, Not Prompts

This post is part of my Programming talk blog series.

A team that merges 11,000 pull requests a month

Lauren Tan, a principal engineer at SpaceX, gave a talk called All Code is Slop Except Mine. She goes by poteto online. The numbers she put on screen: her team merged almost 11,000 pull requests in a month, and the share of commits they had to undo sat around half a percent. A team shipping that much is not reviewing every line by hand. So how does the code stay usable?

Her answer is a set of checks that make the bad version of the code fail before anyone reads it.

The 183 timers

She tells a story from Cursor's codebase. A menu flickers when it closes. The menu has two pieces of state that should agree, one in the menu and one in its parent, and they update one frame apart. On that frame, one side says closed while the other still says open, so the browser paints the wrong thing for a moment.

The agent fixes it by wrapping the close in a setTimeout with a delay of zero. That pushes the close to after the next paint, so the user never sees the bad frame. It leaves a comment saying the real fix would be a bigger change. The flicker is gone, so the diff gets approved, comment and all.

Five weeks later there were 183 of those timers. The next agent found the first one, read the comment as a justification, and copied the pattern into the modal, then the tooltip, then everywhere else. Her slide tracks one timer turning into 183.

That is pain relief, not a cure. The two sources of state still disagree. The timer only schedules the disagreement for later, and the codebase now contains a working example of the trick.

The Pragmatic Programmer called this the broken window. One flaw left alone tells the next person that it is fine to add another. With agents, the next person has no context beyond the repo. Every example in the codebase looks like the house style, including the bad ones. And a comment next to bad code reads like permission, because that is what it is.

In her talk she says her team deleted almost every comment in the product codebase, from roughly 66,000 down to about a dozen. The survivors explain a real decision. The rest were excuses that the next session would have copied.

The triangle she draws

Instead of writing more rules in a markdown file, every correction becomes a check. She ranks the checks in a triangle with the wide band on top:

  1. The codebase itself. API design and architecture, where the mistake cannot be expressed.
  2. Static analysis. Lint, types, the compiler, tests, CI.
  3. Verification. The agent runs the app and proves the behavior.
  4. Prose. Rules, skills, AGENTS.md.
  5. Human review at the bottom point.
The trust pyramid: codebase, static analysis, verification, prose, human review, with cost increasing downward

The arrow next to it points down and it is labeled cost. A mistake stopped in the top band costs one machine check that you set up once. A mistake that reaches the bottom costs a human reading every pull request that contains it.

The practical version of the triangle is a question I ask after every correction: can the code make this impossible? If not, can a check catch it? If not, can the agent prove the behavior somehow? Only then does it become a paragraph in AGENTS.md.

That ranking is independent of language or framework. So before I tell you what I did at the hackathon, here is what I refuse to give up in any project.

My non-negotiables

I write Java Spring Boot most days. Some of these habits come from that world, some are just what I consider good code. None of them are about a specific framework. They also double as constraints on what an agent is allowed to generate, because a session copies whatever pattern is easiest to find in the repo.

The database stops at the adapter

The UI gets a DTO built for the screen, never a row shape, never a type inferred from the schema, never a field named created_at. A schema change should not ripple into components, and a component should not need to know how a table is organized to render a form.

Think of a restaurant. The menu tells you what you can order and what it costs. It does not tell you which shelf the tomatoes sit on. The kitchen can rearrange its shelves without reprinting the menu, and the person reading the menu does not need to care. That is the boundary I want between the database and the screen.

sequenceDiagram
  autonumber
  actor Advisor
  participant UI as Page
  participant UC as Use case
  participant Port
  participant Adapter as Drizzle adapter
  participant DB as Postgres

  Advisor->>UI: open the claim
  UI->>UC: getClaimDetail(id)
  UC->>Port: find(id)
  Port->>Adapter: SQL
  Adapter->>DB: SELECT
  DB-->>Adapter: rows
  Adapter-->>Port: Claim
  Port-->>UC: Claim
  UC-->>UI: ClaimDetail (DTO)
  Note over Port,Adapter: the schema stops here
  UI-->>Advisor: fields on the screen

Hexagonal by feature, not by technical layer

One folder per feature, with four rooms inside:

src/features/claims/
├── domain/        pure rules, no framework
├── application/   use cases and ports
├── ui/            components for this feature
├── adapters/      database and third parties
└── index.ts       the only public door

The domain holds the rules that would survive a rewrite of the framework. The application layer holds the use cases and the ports, which are promises like "somebody can save a claim" without saying who or how. The adapters keep those promises with Drizzle or an HTTP client. The index.ts decides what the rest of the app is allowed to see.

The reason is locality. When a rule changes, the change stays inside the feature. When a boundary breaks, the import graph shows it. It also gives an agent a small, obvious place to put new code instead of a giant services folder where everything touches everything.

The framework is allowed to be transversal

I am not going to rebuild auth, pagination or form handling because a framework already solved them. Hexagonal purity is not worth a custom session layer. The line I care about is the one that leaks persistence into the view, not the one that lets the framework exist in every layer.

This is the part where Java instincts need a correction. Spring is already everywhere in a Spring app. Next.js is already everywhere in a Next app. Pretending otherwise produces ceremony, not architecture.

Errors get mapped once, at the boundary

A server action returns a result type. A route handler returns a problem document. A render crash hits an error page. The UI always receives a shape with a code, a safe message and whether the operation is retryable. Expected failures are return values, not exceptions.

sequenceDiagram
  actor User
  participant Door as Server action / route
  participant UC as Use case
  participant Map as Error mapper

  User->>Door: submit
  Door->>UC: run
  alt happy path
    UC-->>Door: data
    Door-->>User: ok: true, data
  else expected error
    UC-->>Door: AppError
    Door->>Map: toShape(error)
    Map-->>Door: code, message, retryable
    Door-->>User: ok: false, error
  else unexpected crash
    UC--xDoor: defect
    Door->>Map: toShape(defect)
    Map-->>Door: INTERNAL
    Door-->>User: error page
  end

The reception desk analogy works here. A visitor does not walk into the building and start opening doors until something breaks. They arrive at one desk, explain the problem, and leave with a form that says what happens next. The building maps every complaint to the same form.

Business state is not an error either. A claim waiting for documents is data on the screen, not a stack trace. If the UI has to classify failures to decide what to render, the mapping happens in the wrong place.

Test behavior, not functions

I do not trust a unit test that arranges five mocks to prove an ideal case. I want a scenario that runs the real app against a seeded database, with fake third parties. Unit tests are for the pieces a browser cannot drive, like a PDF adapter or retry classification.

A unit test checks one function against three mocks, while a BDD scenario drives a browser through the app and a real database with only the third parties mocked

A bench test can tell you the engine starts. It cannot tell you the car drives. Both are useful, but only one of them proves the thing a user does. Mocks mostly prove that the mocks match the code. A scenario proves the flow works.

Formatting is not a discussion

Code style is the cheapest disagreement to remove. I do not want to argue about braces in review, and I do not want an agent inventing its own style in every file. One formatter runs, and the build checks the result.

In Java I use Spotless with google-java-format. ./gradlew spotlessApply rewrites the code, and spotlessCheck fails the build when something is not formatted. In TypeScript and TSX I use Prettier. pnpm format writes the files, and pnpm format:check is the first step of pnpm verify.

The point is not the specific style. It is that nobody has to have the same opinion twice. The formatter decides, the build enforces, and the diff stays about behavior. For an agent this matters even more: it removes a whole class of noisy edits, and the next session does not have to guess how the last one formatted things.

Convention tests beat documentation

In Java I use ArchUnit to assert the shape of the code: layer dependencies, controller conventions, module boundaries. The build fails when someone imports the wrong thing, even if the code compiles.

A rule in a document is a suggestion. A rule in the build is a constraint. Documentation drifts, the build does not. This is also the difference between telling an agent "please keep the domain pure" and making a pure domain the only thing that builds.

A pull request must prove itself

New behavior goes on a branch, arrives through a pull request, and the PR shows what changed and how to verify it. I want the flow diagram and a recording, not a paragraph claiming it works. Here is a real one from the hackathon project: a Mermaid sequence diagram of the flow, the exact commands, and a video attached as a comment.

I think of a PR as a trailer for the change. A trailer does not replace the film, but it tells you in thirty seconds whether you want to watch it. Reviewing a diff is watching the film frame by frame. Watching a flow is watching the trailer.

My editor setup travels with me

I use opencode as my coding agent, and most of what I care about lives in global configuration instead of one repo. That means the behavior follows me from project to project.

The interesting part is the skills. A skill is a markdown file with a description, and the agent loads it when the task matches. They are not all active at once. I keep a small set that applies to almost anything:

  • caveman makes the agent answer in the shortest form that keeps the facts. I read replies in a terminal, and I do not want three paragraphs around a one-line answer.
  • grilling makes the agent interrogate me about a plan before writing code. It asks about boundaries, permissions, edge cases and things I assumed were obvious.
  • ponytail pushes for the smallest change that fully solves the task. It is my defense against a fifty-line abstraction for a five-line problem.
  • no-comments is a comment policy I invoke on a diff. It deletes comments that restate the code, and it has no patience for a comment that excuses a bad one.
  • cavecrew gives me three subagents: one finds code, one makes small edits, one reviews a diff. Their output comes back compressed, so my main context survives a long session.
  • unslop removes the tells that make writing sound generated. I run it on docs, PR descriptions and posts like this one.

The set is deliberately small. A skill that fires on every task competes with the task. A skill that fires on the right task feels like a colleague who already knows how I work.

A skill is just markdown, so it is meant to be edited. Most of mine are adapted from the upstream versions: I cut steps that do not match my workflow and change the ones that almost do. You do not need to install the whole collection from Matt Pocock or poteto. Take the two skills that solve a problem you actually have, change them until they fit, and leave the rest.

Bringing the rules to a stack I barely use

Last weekend I joined the FRANK Winter 2026 hackathon and built perito, an AI claims operator for Portuguese insurance advisors. The stack was Next.js 16, React 19, Effect, Drizzle and Postgres. I had not built anything serious in Next or Effect recently, and the repo started as a scaffold. There is a one-minute walkthrough if you want to see the product before the plumbing.

My first commits after the scaffold were a roadmap, then the guardrails, then the workflow. The guardrails commit landed about an hour after the scaffold. The first feature commit came almost four hours later.

The shape transferred directly. Features have domain, application, ui and adapters, with an index.ts as the only public API. The schema lives in src/db and only adapters, auth and scripts import it. The UI receives DTOs. The worker shares the composition root instead of importing the database client.

src/
├── app/                 pages, layouts, server actions
├── worker/              queue poller, one process
├── features/
│   ├── claims/          the product: domain, application, ui, adapters
│   ├── jobs/            the Postgres-backed queue
│   ├── llm/             port, fixture adapter, OpenRouter adapter
│   ├── email/           port and mock gateway
│   ├── insurer/         port and mock gateway
│   └── evals/           the 18-case pipeline suite
├── effect/              runtime and shared services
├── composition/         picks the adapters from the environment
├── db/                  schema and client only
└── lib/                 auth, env, errors, boundary wrappers

What changed was how the rules are enforced.

Rules the build can check

TypeScript has no bytecode, so ArchUnit does not exist here. I used dependency-cruiser instead. It reads the import graph and fails when a file imports something it is not allowed to touch. Think of it as a building inspector who checks which doors connect to which rooms, without running the program.

Nine rules went in. Three are hygiene:

  • no circular dependencies
  • no unresolvable imports
  • no dev dependencies leaking into src

Six are about layers:

  • domain stays pure
  • application stays framework-free
  • ui cannot reach persistence
  • only adapters and auth can import the schema
  • cross-feature imports go through the public index.ts
  • composition is the only place that wires adapters
Perito's import graph collapsed to the top-level folders, generated with dependency-cruiser and Graphviz. Blue is delivery, cream is features, green is infrastructure, peach is the composition root. Arrows are imports.

That picture is not a drawing I made for the post. It is the graph dependency-cruiser reads from the repo, collapsed to the top-level folders and rendered by Graphviz. The same config that produces it is the one that fails the build.

Then a folder of policy tests that read the AST and the file tree:

  • process.env only behind the env module
  • console only through the logger
  • runEffect out of server actions and React components
  • feature indexes that never export adapters
  • Drizzle row types that stay inside persistence
  • one contract test per schema enum, so the database and the domain cannot disagree

Both checks run inside pnpm verify. A schema import from a component fails the build before anyone reviews the diff.

What CI does on every pull request

CI is the robot that runs the checks on a clean machine. It does not trust my laptop, my installed packages or my memory. It starts from the repo, installs the dependencies, and runs the same commands a reviewer would.

pnpm verify handles formatting, lint, type generation, type checking, the architecture suite and the unit tests. pnpm verify:full adds the production build, a reset of the test database, the worker smoke test, the fixture evals and the browser scenarios. main is protected and requires the ci-gate check, so nothing merges red.

The checks tab of a real perito pull request: detect, verify, e2e and ci-gate passing

The PR process is part of the same gate. Feature branches follow feature/<epoch>-<slug>, fixes follow fix/<epoch>-<slug>, and two scripts create them so the convention survives. The template asks for what changed and why, one Mermaid sequence diagram per flow, the exact verification commands, and a recording. A script runs the tagged Gherkin scenarios with video on, slows the browser, and converts the result to H.264 MP4. Then gh pr create --attach uploads it, under GitHub's 10MB limit.

A green check does not prove the feature is good. It proves the feature did not break the rules we agreed on, which is a different and cheaper question.

Testing against the real thing

The browser layer is Playwright, a tool that opens a real browser and clicks through the app like a person. With playwright-bdd, the scenarios are written in Gherkin, which is close to plain English: given a claim with a missing document, when the advisor loads the packet, then the checklist shows the missing item.

The scenarios run against a real Next server and a real Postgres. The fake parts are the third parties: a fixture LLM, a mock email gateway, a mock insurer gateway. That is not a compromise on realism. The expensive, slow, non-deterministic parts are exactly the parts I want to replace in a test.

The composition root picks the adapters from the environment, which is the practical reason I care about dependency injection. Think of a power strip with the same socket and different plugs for each country. The application asks for "something that sends email". In tests it gets the mock. In the demo it gets the real one. Nothing else changes.

If you want the longer version of why this pattern pays off, Dependency Injection, The Best Pattern is one of my favorite videos on the subject.

If the adapter choice lives in one file, the suite can run the whole product offline. If it lives in every import, the test suite becomes a network sandbox and a prayer.

The file every session reads

AGENTS.md is a file at the repo root that the agent reads at the start of a session. In my projects it holds the current state, and every session pays for it in context, so it has to earn its space. I treat it as a map, not a rulebook.

It says what the product is, what works today, which commands exist, and the traps a static check cannot see, like Next 16 replacing middleware.ts with proxy.ts. It also says not to assume a feature exists because the README describes it. The README sells the product. AGENTS.md describes the current repo, including the parts that are not finished.

That file is cheap to write and expensive to keep true. Nothing fails when it drifts from the code, so the map slowly stops matching the territory. That is why prose sits below checks in the triangle. If a sentence can become an assertion, it should. If it cannot, keep it short and keep it honest about being prose.

How I run a session

The rules apply to how I drive the agent, not only to the code it writes.

First I read the plan and the current state of the repo, because a stale roadmap is worse than no roadmap. Then I verify the data before assuming anything about it: the database, the seed, the actual request. A spec that disagrees with the database is a bug in the spec until proven otherwise.

After that I want the agent to grill me on the ambiguities. What does "done" mean for this slice? Which permission applies? What happens to the existing rows? Silent assumptions are how a small task becomes a rewrite.

Then a plan in chat, in plain language, with the files it expects to touch and the checks it expects to run. I approve it or correct it. Only then does code get written, one increment at a time. One increment means one thing that can be verified on its own, not a branch with five features and a prayer.

Fix the loop before you automate it

Lauren's closing point is the one I keep repeating to myself. If the loop you already run produces slop, automating that loop produces more slop, faster. The fix is not a bigger prompt or a better model. It is one rule per correction, written where it fails, with an error message that says what to do instead. Then you delete the examples that contradict it, because the next session will find them.

I did not invent any of this. I copied a talk, a Java habit and a hackathon weekend into a repo. That weekend is what made me rethink how I automate my own loop, and the loop is still the part I work on the most.

If you want to see the current version, perito is public. The architecture doc and the CI gate are the two I would read first. Then steal the parts that fit your loop. Mine is still a work in progress, and I doubt it will ever stop being one.