# AI Developer Toolkit — Cookbook > The "Cookbook" section of the AI Developer Toolkit documentation (English). Full site index: https://developertoolkit.ai/llms.txt Generated: 2026-11-02T15:41:09.200Z Source: https://developertoolkit.ai Total documents: 41 --- # AI Developer Cookbook URL: https://developertoolkit.ai/en/cookbook/ Description: Copy-paste recipes for Claude Code, Codex, and Cursor by stack, each paired with the test, type, or build check that proves the agent's output. The AI Developer Cookbook is a set of copy-paste prompts for Claude Code, Codex, and Cursor, grouped by stack: frontend, backend, databases, data engineering, DevOps, mobile, and error handling. Each recipe pairs a prompt with the machine check that proves the result: a failing-first test, a type check, or a build, so you verify behaviour instead of reading every line. This hub is for developers and tech leads who already have an agent installed ([start here as a developer](/en/start/developer/)) and need the exact words for a real task. You have seen the pattern: the agent says "done", the diff is 600 lines, and you cannot tell whether it works without reading all of it. The recipes fix that by asking the agent for its evidence up front. ## Which cookbook section fits your task? Pick the section for your stack. Each section hub has a table that maps frameworks to recipe pages. | Your task | Section | What its recipes prove the output with | | --- | --- | --- | | React, Next.js, Vue, Nuxt, Angular UI | [Frontend recipes](/en/cookbook/frontend-recipes/) | Type, test, accessibility, and screenshot gates | | APIs and services in Node.js, Python, Go, Java, .NET, Rails, PHP, Rust, Elixir, serverless | [Backend recipes](/en/cookbook/backend-recipes/) | Integration tests on a real database, race detectors, contract diffs | | Migrations, ORMs, SQL tuning, NoSQL | [Database recipes](/en/cookbook/database-recipes/) | The change run on a real engine, before and after query plans | | dbt models, SQL pipelines, notebooks | [Data engineering recipes](/en/cookbook/data-recipes/) | A `dbt build` with data tests on a dev target | | Docker, Kubernetes, CI/CD, IaC, monitoring | [DevOps recipes](/en/cookbook/devops-recipes/) | Linters, dry runs, and plan output before anything applies | | Expo, React Native, Flutter, native iOS and Android | [Mobile development](/en/cookbook/mobile-development/) | Simulator and emulator runs, UI-test evidence | | Debugging, logging, recovery | [Error handling recipes](/en/cookbook/error-handling-recipes/) | A reproduction test that fails before the fix and passes after it | Every recipe follows the same shape: the scenario, the prompt in a tip box, the check that proves it, and what breaks. The recipes are self-contained, so read them in any order. ## Prepare your tool before the first recipe The recipes assume the agent knows your build, test, and lint commands. Without them, "run the tests" becomes a guess. Give the agent an instruction file first: **Claude Code** Run `claude` in the repository root, then `/init` to draft a `CLAUDE.md`. Paste recipes at the prompt. For large changes, start in plan mode (`/plan`) and approve the plan before any file changes. **Codex** Run `codex` in the repository root, then `/init` to draft an `AGENTS.md`. Codex reads `AGENTS.md` before it starts work, but since Codex 0.150.0 an untrusted project does not supply it, so trust the repository when Codex asks. `/plan` works the same way as in Claude Code. **Cursor** Open the agent panel and paste the recipe there. Put the commands in a project rule; [Cursor project rules](/en/cursor-ide/quick-start/project-rules/) covers the format and how to make a rule apply to every request. Use Plan Mode for multi-file changes. Start on your tool's default model. As of 2026-10-12 that is Claude Opus 5.5 in Claude Code from v2.1.280 (both release channels) and GPT-6.1 Sol in Codex (bundled default since CLI 0.159.1). Raise the effort level first (`/effort` in Claude Code; `/model` in Codex sets both model and reasoning effort) before you switch models, and see the [models hub](/en/ecosystem/models/) for when a switch pays off. **Copy-paste prompt: give the agent your gates before any recipe** ```text Read the build files, lockfile, CI workflows and test config of this repository. Write a "Commands" section for the agent instruction file with the exact type-check, lint, test, single-test and build commands this repo uses today, and a "Definition of done" section: all of them pass and your reply ends with the last lines of each. Then run every command you listed and report which ones failed or need a service (Docker, a database) that is not running. Do not change any source file in this step. ``` ## How do you verify a recipe's output without reading every line? Ask for proof, not for code. A recipe's result is trustworthy when three things hold: 1. **A test failed before the change and passes after it.** A test written after the code often asserts whatever the code happens to do. 2. **The gates from your instruction file pass,** and the agent pastes their output. 3. **CI runs the same commands** on the pull request as a required check. The instruction file is advice; CI decides. See [CI/CD pipelines](/en/workflows/ship/ci-cd-pipelines/). You still sign off on two things: the acceptance criteria before the agent starts, and irreversible steps after it finishes, such as a migration that drops a column. Collect both in the pull request's [evidence bundle](/en/workflows/ship/evidence-bundle/). **Copy-paste prompt: wrap any recipe in a proof requirement** ```text Before you change any code for the task above, write the tests that define "done" and run them to show they fail. Then implement until they pass. Do not edit or delete an existing test to make it pass; ask me first. Finish with a summary that lists: each new test and what it proves, the last lines of every command in the Definition of done, and anything you could not verify. ``` ## What goes wrong when you paste a recipe? - **The prompt names a stack you do not use.** The agent invents files to match it. Recovery: replace the framework, paths, and commands with yours before you paste, and keep the proof steps unchanged. - **The agent mocks the thing under test.** The tests pass against a fake database or a stubbed browser. Recovery: require a real engine in the Definition of done, as in [integration testing](/en/workflows/test/integration-testing/). - **The agent edits a test until it goes green.** Recovery: forbid it in the instruction file, review the test diff separately, and read [protect the oracle](/en/workflows/test/protect-the-oracle/). - **The code uses an API from an older framework version.** Recovery: give the agent current documentation through [Context7](/en/ecosystem/mcp/context7/) or the framework's own MCP server where the recipe names one. - **The agent reports "done" without running the gates.** Recovery: make the CI job a required check, and in Claude Code add a `Stop` hook that runs the tests ([hooks automation](/en/claude-code/automate/hooks-automation/)). ## Where to go next with the cookbook - [Backend recipes](/en/cookbook/backend-recipes/) - [Frontend recipes](/en/cookbook/frontend-recipes/) - [Writing acceptance criteria an agent can check](/en/workflows/plan/acceptance-criteria/) - [Making a codebase agent-ready](/en/workflows/harness/agent-ready-codebase/) - [Start here as a developer](/en/start/developer/) --- # Backend recipes URL: https://developertoolkit.ai/en/cookbook/backend-recipes/ Description: Pick the backend recipe for your stack, write its gate commands into AGENTS.md, and prove agent-written services with tests instead of line-by-line review. The backend recipes are 11 pages of copy-paste prompts for Claude Code, Codex, and Cursor: one for API design, nine for languages and frameworks, and one for serverless. Each recipe pairs the prompt with a machine check, such as an integration test on a real database, a race detector, or a contract test, that proves the output without a human reading every line. This hub is for developers who let an agent write server-side code. You know where it breaks: the unit tests pass, then production shows an N+1 query, a half-written order, a drained connection pool, or two requests that both win the same race. ## Which backend recipe fits your stack? Every recipe assumes the setup in the next section. | Your stack | Recipe | What the recipe covers and checks | | --- | --- | --- | | HTTP API design, any language | [API development patterns](/en/cookbook/backend-recipes/api-patterns/) | Idempotent `POST`s, keyset pagination, OpenAPI drift checks | | Node.js with Express, TypeScript | [Node.js/Express recipes](/en/cookbook/backend-recipes/node-patterns/) | Prisma transactions, token rotation, rate limiting, BullMQ jobs | | Python with FastAPI, Django | [Python workflow recipes](/en/cookbook/backend-recipes/python-patterns/) | FastAPI and Django REST, async SQLAlchemy 2.0, pytest API tests | | Go | [Go language patterns](/en/cookbook/backend-recipes/go-patterns/) | `go test -race`, goroutine-leak checks, sized connection pools | | Java with Spring Boot | [Java and Spring Boot patterns](/en/cookbook/backend-recipes/java-patterns/) | Testcontainers tests for JPA, resilience, security | | C# with ASP.NET Core, EF Core | [.NET and C# recipes](/en/cookbook/backend-recipes/dotnet-patterns/) | xUnit tests on real Postgres, analyzers that fail the build | | Ruby on Rails | [Ruby on Rails recipes](/en/cookbook/backend-recipes/ruby-rails-patterns/) | `bin/ci` as the definition of done, N+1 queries that fail specs | | PHP with Laravel, Symfony | [PHP development patterns](/en/cookbook/backend-recipes/php-patterns/) | Thin controllers, N+1 removal, PHPUnit tests | | Rust | [Rust development patterns](/en/cookbook/backend-recipes/rust-patterns/) | Compile-checked SQLx queries, borrow-checker fixes, clean async shutdown | | Elixir with Phoenix | [Elixir/Phoenix recipes](/en/cookbook/backend-recipes/elixir-patterns/) | `mix precommit` as the gate, OTP and Ecto tests | | AWS Lambda, Cloudflare Workers, Vercel | [Serverless development patterns](/en/cookbook/backend-recipes/serverless-patterns/) | Idempotent handlers, binding checks, cold-start triage | Schema changes, ORM code, and slow queries live in [database recipes](/en/cookbook/database-recipes/). ## Write the gate into the agent's instructions first Every recipe ends with "run the gate", so the repository must name the gate. Put the exact commands and a definition of done in the instruction file, for example in a TypeScript service: ```markdown title="AGENTS.md" ## Commands - Types: `npx tsc --noEmit` - Lint: `npm run lint` - Tests, unit and integration (needs Docker): `npm test` - One file: `npx vitest run src/orders/orders.test.ts` ## Definition of done Types, lint, and tests pass, and your reply ends with the last lines of each. Any change that touches the database adds an integration test against real Postgres, not a mocked client. Never edit an existing test to make it pass without asking first. ``` Where the file lives differs per tool: **Claude Code** Claude Code reads `CLAUDE.md`. From v2.1.277 (both release channels on 2026-10-12) it also reads `AGENTS.md` when the project has no `CLAUDE.md`. Once a `CLAUDE.md` exists, keep a line `@AGENTS.md` in it. To turn the definition of done into a mechanical check, add a `Stop` hook that runs the test command: see [hooks automation](/en/claude-code/automate/hooks-automation/). **Codex** Codex reads `AGENTS.md` before it starts work. Since Codex 0.150.0, an untrusted project does not supply its project-level `AGENTS.md`, so trust the repository when Codex asks. **Cursor** Add a project rule that applies to every agent request and repeats the Commands and Definition of done sections. [Cursor project rules](/en/cursor-ide/quick-start/project-rules/) covers the format. An instruction file is advice. The CI job that runs the same commands on every pull request is the gate that decides; see [CI/CD pipelines](/en/workflows/ship/ci-cd-pipelines/). For one source of truth across all three tools, see [shared agent rules](/en/cto-scorecard-guide/shared-agent-rules/). **Copy-paste prompt: write the gate section for an existing service** ```text Read the build files, lockfile, CI workflows and test config of this repository. Write a "Commands" section for AGENTS.md with the exact type-check, lint, test, single-test and migration commands this repo uses today, and a "Definition of done" section. Then run every command you listed and report which ones failed or need a service (Docker, a database) that is not running. Do not change any source file in this step. ``` ## How do you verify backend code without reading every line? Ask for the check that goes red for each failure, and require the agent to attach its output. | Failure | The check that catches it | | --- | --- | | N+1 queries | A test that counts queries per request and fails above a fixed number | | Missing transaction | A test that forces an error halfway through the operation and asserts nothing was written | | Leaked connections or goroutines | Pool statistics or a leak detector checked at test teardown | | Race on shared state | A race detector where the language has one (`go test -race`), plus a test that sends parallel requests for the same resource and asserts the invariant | | API contract drift | A generated OpenAPI spec diffed against the committed one in CI | A human signs off twice: on the acceptance criteria before the agent starts, and on irreversible steps after it finishes, such as a migration that drops data or an authentication change. Both approvals go into the pull request's [evidence bundle](/en/workflows/ship/evidence-bundle/). **Copy-paste prompt: an endpoint that proves itself** ```text Acceptance criteria: . Implement POST /orders so that it meets these acceptance criteria. Work test-first: 1. Write failing integration tests against the real database from the test setup (not mocks): happy path, validation error, duplicate Idempotency-Key returns the original order, and a forced error after the first insert leaves no rows behind. 2. Add a test that sends 10 parallel requests with the same Idempotency-Key and asserts exactly one order exists. 3. Assert the handler runs a fixed number of SQL queries, independent of the number of line items. 4. Implement until the full Definition of done in AGENTS.md passes, and paste the last lines of each command. Do not edit a test to make it pass. ``` **Copy-paste prompt: audit an existing handler** ```text Audit src/orders/ for four backend failures: N+1 queries, writes that are not wrapped in one transaction, database connections or clients that are not released on every error path, and shared state read and written without a lock or a conditional update. For each finding, give the file and line, then write a failing test that proves it before you change any code. ``` ## What breaks when agents write backend code? - **The tests pass because the agent mocked the database.** Recovery: the definition of done requires integration tests against a real engine; the [integration testing](/en/workflows/test/integration-testing/) guide shows the Testcontainers setup. - **The agent edits a test until it goes green.** Recovery: forbid it in the instruction file, review the test diff on its own, and read [protect the oracle](/en/workflows/test/protect-the-oracle/). - **The code uses a framework API from an older version.** Recovery: give the agent current documentation through [Context7](/en/ecosystem/mcp/context7/), or through the framework's own MCP server where the recipe names one. - **The gate is green locally and red in CI.** Recovery: make CI run the exact commands from the instruction file, and have the agent reproduce the failure with them before it fixes anything. - **The agent skips the gate and says "done".** Recovery: add the Claude Code `Stop` hook, and make the CI job a required check for every tool. ## Where to go next with backend recipes - [API development patterns](/en/cookbook/backend-recipes/api-patterns/) - [Database recipes](/en/cookbook/database-recipes/) - [API development with AI](/en/workflows/build/api-development/) - [Making a codebase agent-ready](/en/workflows/harness/agent-ready-codebase/) - [AI Developer Cookbook](/en/cookbook/) --- # API Development Patterns URL: https://developertoolkit.ai/en/cookbook/backend-recipes/api-patterns/ Description: Prompts for Claude Code, Codex, and Cursor that build idempotent POSTs, keyset pagination, and a drift-proof OpenAPI spec, plus the checks that prove them. API development patterns for coding agents are three production fixes: idempotency-key middleware so a retried `POST` never charges twice, keyset pagination on a unique composite key so no row is dropped at a page boundary, and an OpenAPI document generated from the handlers' Zod schemas. Each pattern ships with a test that proves it without a line-by-line review. This recipe is for backend developers who let an agent write endpoints and want proof that they hold under retries, concurrent writes, and schema changes. Your `POST /orders` charges a customer twice when the mobile app retries on a weak connection. Your "next page" skips an order whenever two orders share a `created_at`. The OpenAPI file drifted from the code three sprints ago, so the generated client is wrong for every frontend developer who trusts it. All three bugs pass code review, because the code looks correct. Only a test that runs the failure shows the bug. The anchor stack is Express, TypeScript, Zod, Postgres, and Redis. The prompts port to Fastify, NestJS, or Next.js Route Handlers with a one-line change. If you have not designed the contract yet, start with [spec-first API development with agents](/en/workflows/build/api-development/); this page picks up once the routes exist. ## What you'll walk away with from these API patterns - A convention-matching prompt for a new endpoint, and how to launch it in each tool. - An **idempotency-key middleware** prompt that claims the key before the handler runs, so two concurrent retries cannot both charge. - A **keyset pagination** prompt with a composite sort, a matching index, and a cursor that keeps microsecond precision. - An **OpenAPI 3.1 from Zod** prompt with a CI check that fails when the spec is stale. - A verification run that turns all of this into evidence you check instead of reading the handler code. ## How do you get an agent to follow your existing route conventions? Give the agent one existing route as the reference and forbid new abstractions. Agents that are not shown a reference invent their own error classes, response envelopes, and validation helpers. This prompt works in all three tools. **Copy-paste prompt: add an endpoint in the house style** ```text Read src/routes/users.ts and src/middleware/errors.ts first; they define our route conventions. Then add POST /orders in src/routes/orders.ts: - Validate the body with a Zod schema: items is a non-empty array of { sku: string, qty: int >= 1 }. - Require an Idempotency-Key header (UUID). Do not put the key in the body. - Return 201 with the created order. Return 400 with our existing error shape on validation failure. - Reuse the existing error middleware and logger. Do not create new error classes, helpers, or dependencies. - Add a Vitest + supertest test file next to the route covering 201, 400 (bad body), and 400 (missing header). Stop after the tests pass and list every file you changed. ``` How you launch it depends on the tool. Start in a planning mode, so you approve the file list before anything is written. **Cursor** In the Agent panel, reference the two convention files with `@src/routes/users.ts` and `@src/middleware/errors.ts`, and paste the prompt. Switch to **Plan Mode** first for a new route: it writes an implementation plan before any code, and you confirm the file list. Then let Agent run the tests and review the per-file diffs it shows. Look first at the test file, not the handler. **Claude Code** Run it from the repository root in plan mode, so Claude Code proposes the change before editing: ```bash claude --permission-mode plan "$(cat prompts/add-orders-route.txt)" ``` Approve the plan, and Claude Code reads the reference files, edits, and runs the test command. To run the same prompt unattended in CI, use `claude -p` with `--output-format json` and an explicit `--allowedTools` list. **Codex** Run it interactively with writes confined to the workspace. The permission profile below is beta in Codex CLI 0.157.1. OpenAI now prefers it over the legacy `--sandbox` flag, and the two do not compose, so do not combine them. ```bash codex -c 'default_permissions=":workspace"' -a on-request "$(cat prompts/add-orders-route.txt)" ``` For a non-interactive run, put `-a never` before the subcommand (`codex -a never exec …`) and add `-o result.md` to capture the agent's final report. Save the prompt as `prompts/add-orders-route.txt` so the whole team runs the same one. The same pattern applies to every prompt on this page. ## How do you stop a retried POST from charging twice? A client that times out cannot tell whether the server processed the request, so it retries. The fix is an `Idempotency-Key` header. The server records the first response under that key and replays it for every repeat. Agents write the happy path correctly. They miss the concurrent case, because the naive version stores the response only *after* the handler finishes. Two simultaneous retries both find an empty cache, and both charge. **Copy-paste prompt: idempotency-key middleware** ```text Write Express middleware idempotency() in TypeScript, using the ioredis client exported from src/lib/redis.ts. - Apply it to POST and PATCH. A missing Idempotency-Key header returns 400. - Fingerprint the request as sha256(method + path + canonical JSON body). - BEFORE calling the handler, claim the key atomically: SET idem:{key} '{"state":"processing","fp":""}' NX EX 86400. - If the claim fails, read the entry: - different fingerprint -> 422, regardless of state (the key was reused for a different request) - else state "processing" -> 409 with Retry-After: 1 - else state "done" -> replay the stored status and body with header Idempotent-Replay: true - After the handler responds with status < 500, overwrite the entry with {state:"done", fp, status, body}, keeping the TTL. - If the handler throws or returns 5xx, DEL the key so the client can retry. - Also add a unique constraint on orders.idempotency_key in a new migration, as the backstop if Redis loses the key. Tests (Vitest + supertest, real Redis from docker compose): 1. Same key twice in sequence: one row in orders, second response has Idempotent-Replay: true. 2. Same key, 10 requests in parallel with Promise.all: exactly one row, every response is 201 or 409. 3. Same key with a different body: 422. 4. Handler throws: key is released, a retry succeeds. 5. A different body sent while the first request is still processing: 422. ``` Two decisions stay with you, and neither is visible in the diff. First, the **retention window**: a 24-hour TTL means a retry on day two charges again. Match the TTL to the longest retry window of your slowest client, such as an offline mobile queue. Second, **Redis is a cache**. An eviction or a failover forgets keys, which is why the prompt asks for the unique constraint on `orders.idempotency_key`. The database refuses the second insert even when Redis has forgotten the first. Test 2 is the one that matters. If it passes with 10 parallel requests, the race is closed, whatever the middleware looks like inside. ## How do you paginate an API without dropping or repeating rows? Offset pagination (`?page=3&limit=20`) shifts every time a row is inserted while someone pages. Cursor (keyset) pagination fixes that, but agents introduce two quieter bugs. They sort on a non-unique column, so rows that share a `created_at` are skipped or repeated at the page boundary. They also round-trip the timestamp through a JavaScript `Date`, which keeps milliseconds while Postgres `timestamptz` stores microseconds. That produces the same skip on data that looks unique. **Copy-paste prompt: keyset pagination for GET /orders** ```text Implement cursor pagination for GET /orders (Express + TypeScript + pg) over orders(id uuid primary key, created_at timestamptz not null, ...). - Sort by (created_at DESC, id DESC). The cursor must identify one row uniquely. - The cursor is base64url of JSON {c: created_at, i: id}. Select created_at as text (to_char(created_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"')) so microseconds survive. Never pass it through a JS Date. - Query: WHERE (created_at, id) < ($1::timestamptz, $2::uuid) ORDER BY created_at DESC, id DESC LIMIT $3 + 1. The extra row sets hasNextPage. No OFFSET anywhere. Every value is a bound parameter. - limit defaults to 20, max 100. A malformed cursor returns 400 with our error shape. - Response: { data: [...], pageInfo: { nextCursor: string | null, hasNextPage: boolean } }. - Add a migration: CREATE INDEX orders_created_at_id_idx ON orders (created_at DESC, id DESC). Tests against a real Postgres (testcontainers or docker compose): 1. Insert 57 rows where groups of 5 share an identical created_at, including microsecond differences. Walk every page with limit 10. Assert the union of ids equals the inserted set with no duplicates, in the exact expected order. 2. Insert a new row between page 1 and page 2. Assert page 2 neither repeats nor skips an existing row. 3. In the test transaction, run SET LOCAL enable_seqscan = off (or seed >= 10,000 rows and ANALYZE orders), then EXPLAIN the page query and assert the plan uses orders_created_at_id_idx. ``` Test 3 switches off sequential scans (or seeds enough rows) because on a table of 57 rows the Postgres planner rightly prefers a sequential scan, so a bare EXPLAIN assertion would flake, and an agent that sees it flake will weaken it instead of fixing the query. You do not have to read the SQL to trust the result. Test 1 is a complete walk: if any row is lost or duplicated at any boundary, the set comparison fails. To widen it, turn the fixed 57 rows into a generated property ("for any multiset of timestamps and any page size, the walk returns every row once"), as described in [property-based testing with agents](/en/workflows/test/property-based-testing/). Test 3 guards the performance half of the pattern. Without the composite index, the keyset query is correct but scans the table, and that only shows up in production at scale. For index and query-plan work beyond this endpoint, see [SQL optimization patterns](/en/cookbook/database-recipes/sql-patterns/). ## How do you keep the OpenAPI spec from drifting away from the code? A hand-written spec drifts, because nothing fails when it goes stale. Generate it from the Zod schemas the handlers already validate against, commit the output, and let CI fail when the committed file differs from a fresh build. `@asteasolutions/zod-to-openapi` (npm, 9.1.0 on 2026-09-26) builds OpenAPI 3.x documents from registered Zod schemas. **Copy-paste prompt: OpenAPI 3.1 generated from Zod** ```text Every route in src/routes/ validates with Zod schemas defined next to the handler. Wire up @asteasolutions/zod-to-openapi (add it to package.json; check the version with npm view first): - Register each route's params, query, body, and every response status schema with one OpenAPIRegistry in src/openapi/registry.ts. Import the SAME schema objects the handlers use; do not redeclare them. - Add the bearer JWT security scheme and apply it to every route that uses our auth middleware. - Add a script "openapi:gen" that writes openapi.json (OpenAPI 3.1) at the repo root, with keys sorted so the output is deterministic. - Add a CI step: run openapi:gen, then `git diff --exit-code openapi.json`. The step fails if the committed spec is stale. - Do not hand-write any path, parameter, or response. If a route has no Zod schema, list it and stop. ``` The `git diff --exit-code` step is what keeps the spec current. It is more robust than an in-memory comparison test, because it checks the exact file that consumers download. Lint the result with `npx @redocly/cli lint openapi.json` (Redocly CLI 2.54.3 on 2026-09-26) to catch missing operation IDs and undeclared security. When a route has no schema, the prompt tells the agent to stop, not to invent one. An agent that "fills the gap" writes the hand-maintained spec you are trying to remove. ## How do you verify the agent's API code without reading every line? Run the service and attack it with its own contract. Schemathesis (PyPI, 4.28.0 on 2026-09-26) reads `openapi.json`, generates valid and invalid requests for every operation, and checks each response against the spec: server errors, status codes, response schemas, and whether invalid input is rejected. ```bash # Terminal, with the API running locally on port 3000 uvx schemathesis run openapi.json --url http://localhost:3000 --checks all --max-time 120 ``` A green Schemathesis run, the concurrency test, and the pagination walk together prove more than a careful read of the handlers. Hand the whole run to the agent, and ask for the result as evidence rather than as a summary. **Copy-paste prompt: produce the API evidence bundle** ```text Run these and report each result verbatim (command, exit code, last 20 lines of output). Do not fix anything yet: 1. npm test -- orders (idempotency and pagination suites) 2. npm run openapi:gen && git diff --stat openapi.json 3. npx @redocly/cli lint openapi.json 4. Start the API, then: uvx schemathesis run openapi.json --url http://localhost:3000 --checks all --max-time 120 Then write a section for the PR description titled "Evidence" with: - a table of the four checks and pass/fail, - the openapi.json diff summarised as added / changed / removed operations, marking any breaking change (removed field, narrowed type, new required parameter), - every test you added or changed, one line each with what it proves. If any check fails, stop and show the failure. Do not weaken a test or an assertion to make it pass. ``` What the reviewer reads changes as a result. The reviewer reads the `openapi.json` diff (the contract) and the evidence table, not the middleware. A contract change that removes or narrows a field needs sign-off from the team that consumes the API. A change with no contract diff and green checks needs only the owning team's approval. The page on [the evidence bundle an agent's pull request must carry](/en/workflows/ship/evidence-bundle/) turns this into a PR contract with a CI check. [Protecting the oracle](/en/workflows/test/protect-the-oracle/) covers the rule in the last line of the prompt: an agent must not edit the tests that judge it. ## How do you open the API pull request through the GitHub MCP server? When the spec changes, the agent can open the pull request, attach the evidence section, and request review from the consuming team through GitHub's official MCP server. The remote server at `https://api.githubcopilot.com/mcp/` takes a GitHub personal access token in an `Authorization` header in all three clients. The commands below use a PAT kept in an environment variable, never in a committed file. **Cursor** Add a `github` server with the URL `https://api.githubcopilot.com/mcp/` and an `Authorization: Bearer` header in `~/.cursor/mcp.json` (your user config, outside the repository). The [GitHub MCP server guide](/en/ecosystem/mcp/github-mcp/) has the exact JSON. **Claude Code** ```bash claude mcp add --transport http github https://api.githubcopilot.com/mcp/ \ -H "Authorization: Bearer $GITHUB_PAT" ``` **Codex** ```bash codex mcp add github --url https://api.githubcopilot.com/mcp/ --bearer-token-env-var GITHUB_PAT ``` If the agent already has the `gh` CLI and a shell, `gh pr create --body-file evidence.md` does the same job with fewer tokens. Use the MCP server when you want the agent to also read CI logs and review comments without shell access. ## When agent-written API patterns break in production **Failure modes and how to recover** - **The idempotency check races itself.** The response is stored after the handler runs, so parallel retries both charge. *Recover:* find duplicates with `SELECT idempotency_key, count(*) FROM orders GROUP BY 1 HAVING count(*) > 1`, refund them, add the unique constraint, and require the 10-way parallel test before merging. - **Keys vanish from Redis.** An eviction policy such as `allkeys-lru` removes idempotency entries under memory pressure. *Recover:* use a separate Redis database or instance with `noeviction` for idempotency keys, and rely on the database constraint as the backstop. - **Pagination skips rows that look unique.** The cursor carries a millisecond `Date` while the column stores microseconds. *Recover:* encode the timestamp as text from Postgres, and add microsecond-distinct rows to the walk test. - **`OFFSET` reappears in a later change.** A different agent session "simplifies" the query. *Recover:* the walk test with a mid-walk insert fails. Keep it in the default test run, not in a slow suite nobody runs. - **The spec goes stale anyway.** Someone adds a route without registering its schema, so the generator never sees it. *Recover:* add a test that lists the Express router's routes and fails for any route missing from the registry. - **The agent invents a package.** Plausible names such as `express-idempotent-middleware` do not exist on npm (checked 2026-09-26). *Recover:* run `npm view version` on every dependency the agent adds, and see [dependency verification](/en/workflows/test/dependency-verification/) for the CI gate. - **Error responses leak internals.** Generated handlers put the raw database error in `details`. *Recover:* return a stable error code and a `traceId`, log the database error server-side, and add a Schemathesis run to CI so that any 500 fails the build. - **Padding nobody asked for.** Asked for "RESTful best practices", agents add HATEOAS `_links` envelopes that no client reads. *Recover:* name the response shape in the prompt, as every prompt on this page does. ## Where to go next with API patterns - [Spec-first API development with agents](/en/workflows/build/api-development/): design the contract, auth, and versioning before the routes on this page exist. - [API test automation](/en/workflows/test/api-testing/): contract and consumer tests that extend the Schemathesis run. - [Node.js and Express recipes](/en/cookbook/backend-recipes/node-patterns/): JWT auth, rate limiting, and background jobs on the same stack. - [Serverless development patterns](/en/cookbook/backend-recipes/serverless-patterns/): deploying these APIs to functions and the edge, where idempotency matters even more. - [Reading evidence instead of code](/en/ladder/evidence-not-diffs/): why the reviewer on this page reads the contract and the checks rather than the code. --- # .NET and C# recipes URL: https://developertoolkit.ai/en/cookbook/backend-recipes/dotnet-patterns/ Description: Agent recipes for ASP.NET Core, EF Core and xUnit v3 — one AGENTS.md, test-first loops on real Postgres, and analyzers that fail the build, not the review. .NET and C# recipes for AI coding agents are a repository setup plus prompts that make Claude Code, Codex and Cursor ship trustworthy ASP.NET Core and EF Core changes: one `AGENTS.md` with the exact `dotnet` commands, xUnit v3 tests written before the code and run against real PostgreSQL, and Roslyn analyzers configured so a bad pattern fails the build. This page is for C# developers who already let an agent write most of a service. The situation it fixes: the agent's pull request compiles and its tests are green, but the tests use the EF Core in-memory provider, the new migration drops a column it meant to rename, a `.Result` blocks a thread in the middle of a request, and a fresh `#pragma warning disable` hides the one analyzer warning that would have caught it. C# gives you a compiler and an analyzer pipeline that most languages lack. The recipes below make the agent run into them on every turn, so you review evidence instead of diffs. If the repository has no `AGENTS.md` or CI gate yet, start with [Agent-ready codebase](/en/workflows/harness/agent-ready-codebase/). ## What you'll walk away with from these .NET recipes - A `Directory.Build.props` and `global.json` that turn nullable warnings, code-quality rules and code style into build errors, and pin the SDK and test runner the agent uses. - An `AGENTS.md` for a .NET solution, wired into Claude Code, Codex and Cursor. - A test-first loop for an ASP.NET Core endpoint: acceptance criteria, failing xUnit v3 tests on a Testcontainers PostgreSQL database, then the implementation. - A Claude Code `Stop` hook that refuses "done" until `dotnet build` and `dotnet test` pass, and the Codex and Cursor fallbacks: a Codex `Stop` hook or a scripted `codex exec` run, and the CI gate. - An EF Core migration recipe with a drift check and a human sign-off on destructive changes. - A banned-API list, an architecture test and a mutation-testing run that catch what agents get wrong in C#. - The failure modes specific to .NET agent work, with the prompt that recovers from each. ## Which .NET, EF Core and xUnit versions do these recipes assume? Agents are trained on years of .NET samples, so they mix APIs from different major versions. Tell the agent the versions, and pin them in the repository so it cannot drift. These were current on 2026-09-26: | Component | Version | Source (checked 2026-09-26) | | --- | --- | --- | | .NET (LTS) | .NET 10, runtime 10.0.12, SDK 10.0.401; supported until 2028-11-14 | `dotnet/core` releases index | | .NET 11 | Release candidate 1 (2026-09-08), standard-term support | `dotnet/core` releases index | | .NET 8 and .NET 9 | Both reach end of support on 2026-11-10 | `dotnet/core` releases index | | EF Core, `dotnet-ef`, `Microsoft.AspNetCore.Mvc.Testing` | 10.0.12 | NuGet | | `Npgsql.EntityFrameworkCore.PostgreSQL` | 10.0.3 | NuGet | | xUnit.net v3 core framework (`xunit.v3`) | 4.0.1 (published 2026-09-12) | NuGet | | `Testcontainers.PostgreSql` | 4.15.0 | NuGet | The recipes target .NET 10. If you are still on .NET 8 or 9, the upgrade is the first agent task worth running, because both lose support in November. Stay on your tool's default model for this work and raise effort before switching models. Current defaults and prices are on the [AI models hub](/en/ecosystem/models/). ## How do you make a .NET solution agent-ready? Put the gates in MSBuild, not in a prompt. An instruction such as "write clean code" is forgotten by the next session. A property in `Directory.Build.props` applies to every project, every session and every CI run. Three files at the solution root do most of the work. `Directory.Build.props` turns warnings into errors and raises the analyzer bar: ```xml net10.0 enable enable true latest-recommended true true ``` `AnalysisLevel` set to `latest-recommended` enables the recommended set of CA code-quality rules. `EnforceCodeStyleInBuild` makes the IDE code-style rules that your `.editorconfig` sets to `warning` or `error` run on `dotnet build`, so they reach the agent's terminal and not only the IDE. `RestorePackagesWithLockFile` writes `packages.lock.json`, which lets CI restore with `--locked-mode` and fail when the agent changes a dependency without committing the lock file. `global.json` pins the SDK and puts `dotnet test` on Microsoft Testing Platform (MTP), the mode xUnit v3's documentation describes for .NET SDK 10 and later: ```json { "sdk": { "version": "10.0.401", "rollForward": "latestFeature" }, "test": { "runner": "Microsoft.Testing.Platform" } } ``` A local tool manifest gives the agent the same `dotnet ef` version as CI, instead of whatever is installed globally: ```bash # terminal, at the solution root dotnet new tool-manifest dotnet tool install dotnet-ef dotnet new install xunit.v3.templates # adds the xunit3 project template ``` In MTP mode, `dotnet test` takes a project with `--project` and a solution with `--solution` instead of a bare path, and xUnit v3 filters become options such as `--filter-class`. Agents trained on VSTest-era samples write `dotnet test MyProject.csproj --filter …`, so put the new spelling in `AGENTS.md`. ## What goes in AGENTS.md for a .NET repository? Write the commands the agent must run, in the order it must run them, and the few rules a generic C# model gets wrong in your codebase. Keep it short; everything that MSBuild already enforces stays out. ```markdown title="AGENTS.md" # Orders service (.NET 10, ASP.NET Core minimal APIs, EF Core 10, PostgreSQL) ## Commands (run from the repo root) - Restore: `dotnet restore --locked-mode` (commit packages.lock.json if you add a package) - Build: `dotnet build --no-restore` (warnings are errors; fix the code, never add NoWarn or #pragma) - Test all: `dotnet test --no-build` (needs Docker: integration tests start PostgreSQL with Testcontainers) - Test one class: `dotnet test --project tests/Orders.Api.Tests --filter-class Orders.Api.Tests.CreateOrderTests` - Format: `dotnet format --verify-no-changes` - Migration drift: `dotnet ef migrations has-pending-model-changes --project src/Orders.Infrastructure --startup-project src/Orders.Api` ## Definition of done Build, tests, format and the drift check all pass. Report the commands you ran and their result. ## Rules - Tests are the specification. If a test fails, fix src/, not tests/. Ask before changing an assertion. - Integration tests use the ApiFactory fixture (real PostgreSQL). Never use the EF Core in-memory provider. - Package versions live in Directory.Packages.props. Never put Version= on a PackageReference. - Time comes from TimeProvider, never DateTime.Now or DateTime.UtcNow. - async all the way down: no .Result, .Wait() or GetAwaiter().GetResult(). - Read-only queries use AsNoTracking(). Queries that Include two or more collections use AsSplitQuery(). - Never edit an existing migration. Add a new one. ``` Each tool loads the same file differently: **Claude Code** Create a `CLAUDE.md` whose first line imports the shared file, then add any Claude-only lines below it: ```markdown title="CLAUDE.md" @AGENTS.md ``` Claude Code 2.1.277 and later also read `AGENTS.md` directly when a project has no `CLAUDE.md` (v2.1.281 on Bedrock, Google Cloud, Foundry and LLM gateways; both release channels on 2026-10-12). The import works on every version and channel. For code navigation, add the C# language server plugin described in [How do you give the agent current .NET docs and code navigation?](#how-do-you-give-the-agent-current-net-docs-and-code-navigation). **Codex** Codex reads `AGENTS.md` before it starts work. Run `/init` in the TUI to draft one, then replace the draft with the file above. Since codex-cli 0.150.0, a project Codex does not trust does not supply its `AGENTS.md`, so trust the repository when Codex asks. **Cursor** Add a project rule (Cursor's **Rules** feature, stored under `.cursor/rules/`) that applies to every agent request and tells the agent to follow `AGENTS.md`, or paste the Commands and Rules sections into it. Commit the rule with the repository. [Cursor project rules](/en/cursor-ide/quick-start/project-rules/) covers the file format and how to make a rule apply to every request. **Copy-paste prompt: draft AGENTS.md from an existing .NET solution** ```text Read the .sln or .slnx file, every .csproj, Directory.Build.props, Directory.Packages.props, global.json and .config/dotnet-tools.json. Write AGENTS.md with: (1) a one-line description of the solution and its target framework; (2) the exact restore, build, test, single-test-class, format and EF Core migration-drift commands for THIS repo, using `dotnet test --project ... --filter-class ...` if global.json selects Microsoft.Testing.Platform; (3) a "Definition of done" line; (4) at most eight rules, each one a convention you can see this codebase follows and a generic C# model would get wrong. Do not restate anything Directory.Build.props already enforces. Run every command you list and tell me which ones failed. ``` [Shared agent rules](/en/cto-scorecard-guide/shared-agent-rules/) explains how to keep one source of truth when a team uses all three tools. ## How do you run a test-first loop for an ASP.NET Core endpoint? Specify the behaviour, have the agent write failing tests, check that they fail for the right reason, and only then let it write the implementation. The tests become the oracle you trust, so they must hit the same database engine as production. EF Core's in-memory provider does not enforce unique indexes, foreign keys or transactions, so a test on it proves nothing about the behaviour you care about most. 1. **Write the acceptance criteria.** Three to six observable behaviours, each one a sentence a test can check. [Acceptance criteria an agent can verify](/en/workflows/plan/acceptance-criteria/) shows the format. 2. **Ask for failing tests only.** Use the first prompt below. Stop the agent after the tests compile and fail. 3. **Read the failures, not the code.** Each test should fail on its assertion (for example, `404` instead of `201`), not on a missing class or a container error. A test that fails for the wrong reason will pass for the wrong reason too. 4. **Ask for the implementation.** Use the second prompt. The loop ends when the full gate passes, not when the agent says it is done. 5. **Check test strength.** Run mutation testing on the changed code (see [Which analyzers and tests turn review comments into build failures?](#which-analyzers-and-tests-turn-review-comments-into-build-failures)). **Copy-paste prompt: failing xUnit v3 tests for an idempotent POST endpoint** ```text We are adding POST /orders to src/Orders.Api (minimal APIs, EF Core 10, PostgreSQL). Acceptance criteria: 1. A valid order returns 201 with a Location header and the order id in the body. 2. A second request with the same Idempotency-Key header returns 200 with the SAME order id, and only one row exists. 3. The same Idempotency-Key with a different body returns 422. 4. A missing or empty customerId returns 400 with a ProblemDetails body naming the field. 5. Two concurrent requests with the same Idempotency-Key create exactly one order. Write ONLY tests, in tests/Orders.Api.Tests, with xUnit v3. Use the existing ApiFactory fixture (WebApplicationFactory plus a Testcontainers PostgreSQL container); if it does not exist, create it with `new PostgreSqlBuilder("postgres:17-alpine")` (use the PostgreSQL major version you run in production) and apply migrations in InitializeAsync. Pass TestContext.Current.CancellationToken to every async call. Do not create or change anything under src/. Then run `dotnet test --project tests/Orders.Api.Tests --filter-class Orders.Api.Tests.CreateOrderTests` and show me each failure message. Stop there. ``` Check the fixture the agent writes against this shape. xUnit v3 changed `IAsyncLifetime` to `ValueTask`, and Testcontainers 4.x marks the parameterless builder constructor obsolete, so older patterns fail the build here. Set the image tag to the PostgreSQL major version you run in production; `postgres:17-alpine` is only the example: ```csharp // tests/Orders.Api.Tests/ApiFactory.cs public sealed class ApiFactory : WebApplicationFactory, IAsyncLifetime { private readonly PostgreSqlContainer _db = new PostgreSqlBuilder("postgres:17-alpine").Build(); public async ValueTask InitializeAsync() { await _db.StartAsync(); using var scope = Services.CreateScope(); await scope.ServiceProvider.GetRequiredService().Database.MigrateAsync(); } protected override void ConfigureWebHost(IWebHostBuilder builder) => builder.UseSetting("ConnectionStrings:Orders", _db.GetConnectionString()); public override async ValueTask DisposeAsync() { await _db.DisposeAsync(); await base.DisposeAsync(); } } ``` The fixture applies your real migrations, so every integration run also proves that the migrations apply to an empty database. If the test project cannot see `Program`, the agent may add `public partial class Program;` at the end of `Program.cs`; that is the only change to `src/` the test step should make. **Copy-paste prompt: implement until the gate is green** ```text Implement POST /orders in src/Orders.Api and src/Orders.Infrastructure so that every test in CreateOrderTests passes. Enforce idempotency with a unique index on (IdempotencyKey) and handle the unique-violation from PostgreSQL (PostgresException with SqlState 23505) so criterion 5 holds without a lock. Store a SHA-256 hash of the canonical request body next to the key; on a 23505 conflict, return 422 if the stored hash differs, else 200 with the existing order. Add an EF Core migration named AddOrderIdempotencyKey. Do not modify any file under tests/. When you think you are done, run in order: `dotnet build --no-restore`, `dotnet test --no-build`, `dotnet format --verify-no-changes`, and the migration drift check from AGENTS.md. Paste the last lines of each. If a test still fails, tell me which acceptance criterion the code violates instead of changing the test. ``` [Protect the oracle](/en/workflows/test/protect-the-oracle/) explains why the "do not modify tests" instruction needs a mechanical backstop as well, which the next section adds. ## How do you stop the agent from declaring done before the build is green? An instruction in `AGENTS.md` is advice. A hook or a CI check is a gate. Each tool gives you a different way to make the gate run on every turn. **Claude Code** A `Stop` hook runs when Claude finishes responding. Exit code 2 prevents the stop and shows the hook's stderr to Claude, which then keeps working. Claude Code overrides the block after eight consecutive continuations, so a loop cannot run forever; the `CLAUDE_CODE_STOP_HOOK_BLOCK_CAP` environment variable sets that cap (default 8; checked against Claude Code 2.1.283, still present in 2.1.286). ```bash title=".claude/hooks/dotnet-gate.sh" #!/usr/bin/env bash # Refuse "done" until the solution builds without warnings and the tests pass. cd "$CLAUDE_PROJECT_DIR" || exit 0 # Skip turns that changed no C#, project or gate files (a question, a plan). [ -z "$(git status --porcelain -- '*.cs' '*.csproj' '*.props' '*.targets' '*.sln' '*.slnx' '.editorconfig' 'BannedSymbols.txt' 'global.json' 'packages.lock.json')" ] && exit 0 if ! out=$(dotnet build --no-restore 2>&1); then echo "dotnet build failed. Fix the code; do not add NoWarn or #pragma." >&2 echo "If the error is NETSDK1004 or NU1xxx, run 'dotnet restore --locked-mode' (or update packages.lock.json) first." >&2 echo "$out" | grep -E ": (error|warning) " | sort -u | head -30 >&2 exit 2 fi if ! out=$(dotnet test --no-build 2>&1); then echo "dotnet test failed. Fix src/, never tests/:" >&2 echo "$out" | tail -40 >&2 exit 2 fi exit 0 ``` The skip test looks at uncommitted changes only: if the agent commits during the turn the gate does not run, so tell it not to commit (or compare against the session's starting HEAD). A tree that was already dirty runs the full gate on every turn, including pure questions. Register it in the project settings and make the script executable (`chmod +x`): ```json title=".claude/settings.json" { "hooks": { "Stop": [ { "hooks": [ { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/dotnet-gate.sh", "timeout": 600 } ] } ] } } ``` The script deliberately ignores `stop_hook_active`, the field Claude Code sets in the hook input once a stop has already been blocked. Exiting 0 whenever it is true would let the second attempt through with the build still red; the eight-block cap is the loop guard instead, so a stubborn failure can cost about nine build and test runs before Claude Code stops anyway. The hook costs a full build and test run on every turn that changed C# or project files, including Testcontainers, so keep Docker running during the session. If that is too slow locally, run only the tests that need no Docker and leave the full suite to CI. Under MTP the VSTest `--filter` spelling does not apply; use an xUnit v3 trait filter instead. Tag each integration test class with `[Trait("Category", "Integration")]`, then change the test line in `dotnet-gate.sh`: ```bash if ! out=$(dotnet test --no-build --filter-not-trait "Category=Integration" 2>&1); then ``` [Hooks automation](/en/claude-code/automate/hooks-automation/) covers the other events. **Codex** NuGet restore needs the network, and the `workspace-write` sandbox has no network access unless you enable it. Restore first, outside the agent, then run the loop without network: ```bash dotnet restore --locked-mode codex exec --sandbox workspace-write "Implement POST /orders so every test in CreateOrderTests passes. Do not modify tests/. Finish only when 'dotnet build --no-restore' and 'dotnet test --no-build' both pass; print the last lines of each." ``` If the agent must add a package, enable network for that run only with `-c sandbox_workspace_write.network_access=true`. This uses the legacy `--sandbox` system; if your config sets `default_permissions`, the two do not compose, so pick one (checked against codex-cli 0.157.1). Testcontainers also needs access to the Docker socket; if the sandbox blocks it, run the integration tests in CI and give the local loop the unit tests only. For an interactive session, Codex 0.157.1 also has a `Stop` hook event; [Codex automation](/en/codex/automate/) covers hook registration and trust. **Cursor** Paste the implementation prompt into the agent, in Plan Mode first if the change spans several projects. Put the Definition of done in the project rule so the agent runs the commands before it reports back. Cursor also has [Hooks](https://cursor.com/docs/hooks), scripts that exchange JSON with the agent over stdio, so a hook can run the same `dotnet build` and `dotnet test` commands locally; [Use hooks as deterministic guardrails](/en/developer-scorecard-guide/agent-hooks/) shows how to adapt the Claude Code script and keep it advisory until it is tested in a real Cursor session. Cursor's own gate runs after the pull request opens: the CI job below, plus Bugbot if your team uses it for review. Whatever runs locally, CI is the gate that decides. Run the same commands there with a read-only token: ```yaml title=".github/workflows/dotnet-gates.yml" name: dotnet-gates on: [pull_request] permissions: contents: read jobs: gates: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: persist-credentials: false - uses: actions/setup-dotnet@v6 with: global-json-file: global.json - run: dotnet restore --locked-mode - run: dotnet tool restore - run: dotnet format --verify-no-changes --no-restore - run: dotnet build --no-restore - run: dotnet test --no-build - run: dotnet ef migrations has-pending-model-changes --project src/Orders.Infrastructure --startup-project src/Orders.Api ``` ## How do you handle EF Core migrations with an agent? Migrations are the one place where a green test suite is not enough evidence. The agent can generate a migration that applies cleanly to an empty test database and still destroys data in production. The classic case: the agent renames a property, EF Core generates a `DropColumn` plus an `AddColumn`, the tests pass on a fresh database, and the column's data is gone on the first deploy. Split the work between gates and a person: | Check | How | Who decides | | --- | --- | --- | | Model and migrations agree | `dotnet ef migrations has-pending-model-changes` (EF Core 8 and later) fails when the model changed without a migration | CI | | Migrations apply from zero | The `ApiFactory` fixture runs `MigrateAsync()` on an empty PostgreSQL | CI | | The SQL is what you expect | `dotnet ef migrations script --idempotent` output attached to the pull request | A human reads the SQL, not the C# | | Destructive operations | `DropColumn`, `DropTable`, `AlterColumn` that narrows a type | A human, through `CODEOWNERS` on `**/Migrations/` | **Copy-paste prompt: a reviewed, non-destructive EF Core migration** ```text Rename the Order.Notes property to Order.CustomerNotes. Generate the migration with `dotnet ef migrations add RenameOrderNotes --project src/Orders.Infrastructure --startup-project src/Orders.Api`. Open the generated file: if it contains DropColumn plus AddColumn for this change, replace them with migrationBuilder.RenameColumn so no data is lost. Do not edit any earlier migration. Then run `dotnet ef migrations script --idempotent --project src/Orders.Infrastructure --startup-project src/Orders.Api -o artifacts/migration.sql` and show me only the SQL for this migration, plus the result of `dotnet ef migrations has-pending-model-changes`. List every statement that could lose data, or say "none". ``` For the wider rules on expand-and-contract changes and rollbacks, see [database migration patterns](/en/cookbook/database-recipes/migration-patterns/). EF Core 11 adds a `.config/dotnet-ef.json` file for default `--project` and `--startup-project` values; on EF Core 10, keep the flags in `AGENTS.md`. ## Which analyzers and tests turn review comments into build failures? Every comment you type twice on an agent's pull request is a rule you have not automated yet. In C#, most of them can become a compiler diagnostic or a test. Each gate below goes red for a specific bug: | Gate | Setup | Goes red when | | --- | --- | --- | | Nullable reference types | `enable` plus `TreatWarningsAsErrors` | The agent dereferences a value that can be null | | CA code-quality rules | `latest-recommended` | Code breaks a rule in the recommended CA set (design, reliability, performance, security and usage rules) | | Code style | `.editorconfig` severities plus `EnforceCodeStyleInBuild` | The agent ignores the team's naming or `var` conventions | | Banned APIs | `Microsoft.CodeAnalysis.BannedApiAnalyzers` (5.6.0) and a `BannedSymbols.txt` | Code calls `DateTime.Now`, `Task.Result` or anything else you list (diagnostic RS0030) | | Architecture | `NetArchTest.Rules` (1.3.2, last release May 2021; `TngTech.ArchUnitNET` 0.13.4 is the actively maintained alternative) in a test | The domain project references infrastructure or ASP.NET Core | | Test strength | `dotnet-stryker` (5.0.0) | Tests still pass after Stryker mutates the code under test | The banned-API list is the most direct way to encode "we never do that here". Add the package to the projects under `src/`, add ``, and list documentation IDs with a message the agent will read: ```text title="BannedSymbols.txt" P:System.DateTime.Now;Inject TimeProvider and call GetUtcNow() P:System.DateTime.UtcNow;Inject TimeProvider and call GetUtcNow() P:System.Threading.Tasks.Task`1.Result;Await the task instead of blocking M:System.Threading.Tasks.Task.Wait;Await the task instead of blocking M:System.Threading.Tasks.Task.Wait(System.Int32);Await the task instead of blocking M:System.Threading.Tasks.Task.Wait(System.TimeSpan);Await the task instead of blocking M:System.Threading.Tasks.Task.Wait(System.Threading.CancellationToken);Await the task instead of blocking M:System.Threading.Tasks.Task.Wait(System.Int32,System.Threading.CancellationToken);Await the task instead of blocking M:System.Runtime.CompilerServices.TaskAwaiter.GetResult;Await the task instead of blocking M:System.Runtime.CompilerServices.TaskAwaiter`1.GetResult;Await the task instead of blocking ``` An architecture test keeps a layered solution layered after 50 agent sessions: ```csharp [Fact] public void Domain_does_not_depend_on_infrastructure_or_web() { var result = Types.InAssembly(typeof(Order).Assembly) .ShouldNot().HaveDependencyOnAny("Orders.Infrastructure", "Microsoft.AspNetCore") .GetResult(); Assert.True(result.IsSuccessful, string.Join(", ", result.FailingTypeNames ?? [])); } ``` Mutation testing answers the question a green run cannot: would these tests notice if the code were wrong? Run `dotnet tool install dotnet-stryker`, then `dotnet stryker` in the test project's folder, and read the surviving mutants. [Oracle strength](/en/workflows/test/oracle-strength/) explains how to turn survivors into missing test cases. **Copy-paste prompt: turn repeated review comments into gates** ```text Here are review comments I keep leaving on agent pull requests in this solution: [paste 5-10 comments]. For each one, propose the cheapest mechanical gate: an .editorconfig severity, a CA rule set to error, an entry in BannedSymbols.txt, a NetArchTest rule, or an xUnit test. Show the exact change. Implement only the ones that make `dotnet build` or `dotnet test` fail on the current code, list which files would break, and do not fix those files yet. ``` Changes to `Directory.Build.props`, `.editorconfig`, `BannedSymbols.txt` and any `NoWarn` entry weaken the gates themselves, so give those paths a human owner in `CODEOWNERS`. The [evidence bundle](/en/workflows/ship/evidence-bundle/) page shows how to attach gate results and the migration SQL to the pull request so the reviewer checks proof, not code. ## How do you give the agent current .NET docs and code navigation? Two additions help most in .NET: current Microsoft documentation, because APIs change between major versions, and a language server, because text search is a poor way to find every caller in a large solution. **Microsoft Learn MCP server.** A remote server at `https://learn.microsoft.com/api/mcp`, no authentication, with three tools: `microsoft_docs_search`, `microsoft_docs_fetch` and `microsoft_code_sample_search`. The `?maxTokenBudget=2000` query parameter caps how much each answer adds to context; the Codex and Cursor snippets below include it. Popularity: about 1.9k GitHub stars on `MicrosoftDocs/mcp` (GitHub, read 2026-09-26). **Claude Code** Install Microsoft's plugin, which brings the MCP server and its skills together (run inside a session): ```text /plugin install microsoft-docs@claude-plugins-official ``` The plugin registers the uncapped URL. To add only the server, with the cap, run this in your shell instead: ```bash claude mcp add --transport http microsoft-learn "https://learn.microsoft.com/api/mcp?maxTokenBudget=2000" ``` For code navigation, install the C# language server and the plugin that registers it. The plugin does not bundle the binary: ```bash dotnet tool install --global csharp-ls claude plugin install csharp-lsp@claude-plugins-official ``` `csharp-lsp` had 43,741 installs in the claude.com plugin directory (read 2026-09-26). LSP plugins add no always-on context, because the server runs out of process. **Codex** ```bash codex mcp add microsoft-learn --url "https://learn.microsoft.com/api/mcp?maxTokenBudget=2000" ``` **Cursor** Add the server to `.cursor/mcp.json`: ```json { "mcpServers": { "microsoft-learn": { "url": "https://learn.microsoft.com/api/mcp?maxTokenBudget=2000" } } } ``` Before the server, the agent fills gaps from training data and writes, for example, the parameterless Testcontainers builder or VSTest-style `dotnet test` filters. With it, one prompt checks the current API first: **Copy-paste prompt: check .NET 10 guidance before writing code** ```text Using the Microsoft Learn MCP server, find the current guidance for (1) running `dotnet test` with Microsoft.Testing.Platform on the .NET 10 SDK and (2) integration testing minimal APIs with WebApplicationFactory. Quote the relevant lines and their URLs. Then compare them with tests/Orders.Api.Tests and our AGENTS.md, and list anything we do that the current docs no longer recommend. Do not change files. ``` The `microsoft/skills` README catalogues 175 SDK skills in language plugins for Python, .NET, TypeScript, Java and Rust. They sit below the repository root, so `npx skills add microsoft/skills --list` shows only 13 root skills; with `--full-depth` it finds 192, the SDK set plus the root and other nested skills (checked 2026-09-26). The README also warns that loading all of them causes context rot, so install only the Azure SDK skills your service uses. The [best backend and platform skills](/en/ecosystem/skills/top-skills-backend/) page compares them with the other vendor sets. ## What breaks when agents write .NET code? **The build breaks on an obsolete Testcontainers constructor** Symptom: `CS0618` on `new PostgreSqlBuilder()`, which `TreatWarningsAsErrors` turns into an error. Cause: Testcontainers 4.x marks the parameterless constructor obsolete in favour of one that takes the image. Recovery: "Replace every parameterless Testcontainers builder with the constructor that takes an explicit image tag, for example new PostgreSqlBuilder(\"postgres:17-alpine\"). Do not suppress CS0618." **The agent silences a warning instead of fixing it** Symptom: the build is green, and the diff adds `#pragma warning disable`, a `` entry or `[SuppressMessage]`. Recovery: fail CI when a pull request adds any of the three outside an approved list, and re-prompt: "Remove the suppression you added and fix the underlying diagnostic. If it is a false positive, explain why in the pull request instead." **NU1008 after the agent adds a package** Symptom: restore fails with `NU1008` in a solution that uses central package management. Cause: the agent wrote `` as older samples do. Recovery: move the version into `Directory.Packages.props` as a `PackageVersion` entry, remove `Version` from the project file, and restore again to update `packages.lock.json`. **Green tests on the in-memory provider, red in production** Symptom: a duplicate-key or foreign-key bug that no test caught. Cause: the agent used `UseInMemoryDatabase` because it is faster to set up. Recovery: move the tests onto the Testcontainers fixture and add a line to `AGENTS.md` that bans the in-memory provider. Criterion 5 above (concurrent requests with one key) is the test that exposes the difference. **A cartesian explosion from Include chains** Symptom: one endpoint loads 50 orders slowly and memory spikes. Cause: `Include(o => o.Lines).Include(o => o.Payments)` in a single query multiplies rows. Recovery: "Use AsSplitQuery() on queries that include two or more collections, AsNoTracking() on read-only queries, and add a test that asserts the number of SQL commands for GET /orders." For more EF Core query patterns, see [ORM patterns](/en/cookbook/database-recipes/orm-patterns/). **Sync over async and hidden clock reads** Symptom: thread-pool starvation under load, or tests that fail at midnight. Cause: `.Result` or `.Wait()` in request code, and `DateTime.UtcNow` in business logic. Recovery: the `BannedSymbols.txt` entries above make `.Result`, every `Task.Wait` overload listed, `GetAwaiter().GetResult()` on `Task` and `Task`, and the clock reads build errors; inject `TimeProvider` and use `FakeTimeProvider` in tests. **Codex cannot restore or reach Docker** Symptom: `dotnet restore` or Testcontainers fails inside `codex exec`. Cause: the `workspace-write` sandbox has no network by default. Recovery: restore before starting the session, build with `--no-restore`, and enable network for one run only when a package change is the task. ## Where to go next with .NET and agents - [Protect the oracle](/en/workflows/test/protect-the-oracle/) — Stop agents from editing the tests that judge them. - [Database migration patterns](/en/cookbook/database-recipes/migration-patterns/) — Expand-and-contract changes and rollbacks for the migrations above. - [API development patterns](/en/cookbook/backend-recipes/api-patterns/) — Idempotency keys, pagination and OpenAPI contracts for the endpoints you build. - [Java and Spring Boot patterns](/en/cookbook/backend-recipes/java-patterns/) — The same gates and loops on the JVM. - [Fitness functions](/en/workflows/test/fitness-functions/) — Architecture and performance checks that run on every agent change. - [Agent-ready codebase](/en/workflows/harness/agent-ready-codebase/) — The repository properties that make any agent more reliable. --- # Elixir/Phoenix Recipes URL: https://developertoolkit.ai/en/cookbook/backend-recipes/elixir-patterns/ Description: Agent recipes for Phoenix 1.8 and Elixir 1.20: mix precommit as the gate, Tidewave MCP, LiveView streams, OTP tests, Ecto.Multi, Oban and releases. Phoenix recipes for AI coding agents are a project setup and a set of prompts that make Claude Code, Codex and Cursor ship trustworthy Phoenix 1.8 changes: the generated `AGENTS.md` and `mix precommit` alias as the definition of done, Tidewave for runtime access, tests written before the code, and CI gates that fail on compiler warnings and security findings. This page is for Elixir developers who let an agent write most of a feature, and for tech leads who want the same gates enforced for the whole team (see the CI job and the sign-off table). The situation it fixes: the agent's pull request is green, but the LiveView keeps every order in socket assigns, the test that "proves" the GenServer works uses `Process.sleep(100)`, the payment call sits inside `Repo.transaction`, and a failing assertion was "fixed" by changing the expected value. Phoenix already gives you an agent rules file, a precommit alias and generators. The recipes below make the agent run into them on every turn, so you review evidence instead of diffs. ## What you'll walk away with from these Elixir recipes - A Phoenix project whose `AGENTS.md`, `mix precommit` alias and dependency rules keep the agent on current Phoenix idioms, wired into all three tools. - Tidewave MCP set up so the agent evaluates code in your running app, reads its logs and queries the dev database instead of guessing. - A Claude Code `Stop` hook that refuses "done" until `mix precommit` passes, and a CI job that is the mechanical gate for Codex and Cursor. - Eight copy-paste prompts: an `AGENTS.md` draft, a test-first context and JSON API (tests, then code), a LiveView with streams, an ETS rate limiter, an Ecto.Multi order transaction, an Oban worker and a Docker release. - A sign-off table that says which agent changes a person reviews and which the gates prove. ## Which Elixir, Phoenix and Hex versions do these recipes assume? Agents mix APIs from Phoenix 1.5 to 1.8 and LiveView 0.x to 1.x because their training data does. Pin the versions (`.tool-versions` or `mise.toml`, and `mix.lock`) and name them in `AGENTS.md`. These were current on 2026-09-26: | Component | Version | Source (checked 2026-09-26) | | --- | --- | --- | | Elixir / Erlang/OTP | 1.20.4 / 29.1.1 | hexpm/elixir image tags on Docker Hub | | `phoenix` / `phx_new` | 1.8.15 | hex.pm | | `phoenix_live_view` | 1.2.12 | hex.pm | | `ecto` / `ecto_sql` | 3.14.2 / 3.14.0 | hex.pm | | `oban` / `oban_web` | 2.24.1 / 2.13.0 | hex.pm | | `credo` / `sobelow` / `mix_audit` | 1.7.19 / 0.15.0 / 2.1.5 | hex.pm | | `stream_data` | 1.4.0 | hex.pm | | `tidewave` / `usage_rules` | 0.9.1 / 1.2.8 | hex.pm | The Phoenix behaviour described here (the generated `AGENTS.md`, the `precommit` alias, `phx.gen.release`) was read from the `phx_new` 1.8.15 installer source. Elixir flags come from the v1.20.4 Mix task docs. The hooks and CI steps follow each tool's documentation; run them on your project before you rely on them. Stay on your tool's default model for this work and raise effort before you switch models. Current defaults and prices are on the [AI models hub](/en/ecosystem/models/). ## How do you make a Phoenix project agent-ready? Start from what `mix phx.new` already generates. In Phoenix 1.8.15 it writes an `AGENTS.md` (skip it with `--no-agents-md`) that combines project guidelines with rules for Elixir, Phoenix, Ecto, HEEx and LiveView. Among them: use LiveView streams for collections, avoid LiveComponents without a specific need, start processes in tests with `start_supervised!/1`, never use `Process.sleep/1` in tests, and never call `String.to_atom/1` on user input. It also adds one alias that is the natural definition of done: ```elixir title="mix.exs (generated by phx.new 1.8.15)" def cli do [preferred_envs: [precommit: :test]] end defp aliases do [ # ... precommit: ["compile --warnings-as-errors", "deps.unlock --unused", "format", "test"] ] end ``` `mix precommit` compiles with warnings as errors, drops unused lock entries, formats and runs the suite. The first step matters more on Elixir 1.20: its type checker infers types across clauses and reports typing violations and dead code as compiler warnings, so the alias fails on a class of bug no test was written for. Add the checks an agent most often skips, and add their packages to `deps` with `only: [:dev, :test], runtime: false`: ```elixir title="mix.exs" precommit: [ "compile --warnings-as-errors", "deps.unlock --unused", "format", "credo --strict", "sobelow --exit Low --skip", "test" ] ``` For an app created before Phoenix 1.8, generate the same rules from your dependencies with `usage_rules`: add `{:usage_rules, "~> 1.2", only: [:dev]}`, set `usage_rules: [file: "AGENTS.md", usage_rules: [:elixir, :otp, "phoenix:ecto", "phoenix:liveview"]]` in `project/0`, and run `mix usage_rules.sync`. The sync re-writes its own section on every run, so rules follow `mix.lock` when a dependency ships new ones. Then add your project's own lines to `AGENTS.md`, below the generated block: ```markdown title="AGENTS.md (your additions)" ## Commands - One test or file: `mix test test/shop/orders_test.exs:42` - Failures from the last run: `mix test --failed` - Full gate: `mix precommit` (compile, format, Credo, Sobelow, tests) ## Definition of done `mix precommit` passes. Report the command you ran and its last lines. ## Rules - Generate contexts, schemas and migrations with `mix phx.gen.*` and `mix ecto.gen.migration`, never by hand. - Tests are the specification. If a test fails, fix lib/, not test/. Ask before changing an assertion. - Never call an external service inside `Repo.transaction` or `Ecto.Multi`. - Money is integer cents or `Decimal`, never float. ``` Each tool loads the file differently: **Claude Code** Create a `CLAUDE.md` whose first line is `@AGENTS.md`, then add any Claude-only lines below it. Claude Code 2.1.277 and later also read `AGENTS.md` directly when a project has no `CLAUDE.md` (both release channels on 2026-10-12); the import works on every version and channel. **Codex** Codex reads `AGENTS.md` before it starts work. Since codex-cli 0.150.0, a project Codex does not trust does not supply its `AGENTS.md`, so trust the repository when Codex asks. **Cursor** Add an always-applied project rule (the format is on [Cursor project rules](/en/cursor-ide/quick-start/project-rules/)) that repeats the Commands, Definition of done and Rules sections, plus the generated LiveView and Ecto rules you rely on. Commit the rule with the repository. **Copy-paste prompt: draft AGENTS.md for an existing Phoenix app** ```text Read mix.exs, mix.lock, .tool-versions (or mise.toml), config/config.exs, config/test.exs, test/test_helper.exs, test/support/*.ex and .credo.exs if present, and list the directories under lib/ and test/. Write AGENTS.md with: (1) one line naming the Elixir, OTP, Phoenix, LiveView and Ecto versions and the database; (2) the exact commands for one test, failed tests only, format, and the full gate, as they work in THIS repo; (3) a "Definition of done" line that names mix precommit (add the alias if it is missing: compile --warnings-as-errors, deps.unlock --unused, format, test); (4) at most eight rules, each a convention you can see this codebase follows and a generic Elixir model would get wrong. Do not restate what mix format or Credo already enforce. Run every command you list and tell me which ones failed. ``` [Shared agent rules](/en/cto-scorecard-guide/shared-agent-rules/) explains how to keep one source of truth when a team uses all three tools. ## How do you give the agent your running Phoenix app? An agent that can only read files guesses what `Orders.list_orders/1` returns and what the last request logged. [Tidewave](https://github.com/tidewave-ai/tidewave_phoenix) is an open-source MCP server from Dashbit that runs inside your Phoenix app in development. It exposes `project_eval` (run Elixir code in the running app), `execute_sql_query` (against the dev database), `get_logs`, `get_source_location` and `get_docs`, which reads documentation for the exact versions in `mix.lock`. Install it with `mix igniter.install tidewave` (after `mix archive.install hex igniter_new`), or add `{:tidewave, "~> 0.9", only: :dev}` and put `plug Tidewave` inside an `if Mix.env() == :dev do` block right above `if code_reloading? do` in `lib/my_app_web/endpoint.ex`. Start the server with `mix phx.server`, then connect your tool (port 4000 is the Phoenix default): **Claude Code** ```bash claude mcp add --transport http tidewave http://localhost:4000/tidewave/mcp ``` Check it with `/mcp` in a session. Tidewave 0.9.1 has no authentication (it accepts only localhost connections by default), so do not pick **Authenticate**. **Codex** ```bash codex mcp add tidewave --url http://localhost:4000/tidewave/mcp ``` `codex mcp list` shows the entry but does not test the connection; run `/mcp` in the TUI to see the tools. **Cursor** ```json title=".cursor/mcp.json" { "mcpServers": { "tidewave": { "url": "http://localhost:4000/tidewave/mcp" } } } ``` Start a new chat and ask the agent to list Tidewave's tools. The before and after is concrete. Without Tidewave, the agent reads a stack trace, edits a changeset and re-runs the suite. With it, the agent calls `Shop.Orders.create_order/2` with the failing input in the running app, reads the resulting log line and the `orders` row, and edits once. Tidewave accepts only local connections by default and must never run in production. ## How do you stop the agent from declaring done before the tests pass? An instruction in `AGENTS.md` is advice. A hook or a CI check is a gate. Claude Code gets a local gate from a `Stop` hook. The Codex and Cursor setups below are still instructions, so for them the CI job after the tabs is the only mechanical gate. **Claude Code** A `Stop` hook runs when Claude finishes responding. Exit code 2 blocks the stop and shows the hook's stderr to Claude, which keeps working: ```bash title=".claude/hooks/elixir-gate.sh" #!/usr/bin/env bash # Refuse "done" until mix precommit passes. input=$(cat) # Already continuing because of this hook: stop and report instead of looping. [ "$(echo "$input" | jq -r '.stop_hook_active')" = "true" ] && exit 0 cd "$CLAUDE_PROJECT_DIR" || exit 0 # Nothing under lib, test, config or priv changed: nothing to check. [ -z "$(git status --porcelain -- lib test config priv mix.exs mix.lock)" ] && exit 0 if ! out=$(mix precommit 2>&1); then echo "mix precommit failed. Fix lib/, never test/. Re-run failures with mix test --failed:" >&2 echo "$out" | tail -40 >&2 exit 2 fi exit 0 ``` Register it in `.claude/settings.json` under `hooks` → `Stop` as a `command` handler pointing at `${CLAUDE_PROJECT_DIR}/.claude/hooks/elixir-gate.sh` with `"timeout": 600`, and make the script executable. The script needs `jq`. Because it exits 0 when `stop_hook_active` is `true`, a failing gate forces one retry and then Claude reports instead of looping on a test that cannot pass, for example when PostgreSQL is down. `mix precommit` runs `format`, so the hook also rewrites unformatted files. [Hooks automation](/en/claude-code/automate/hooks-automation/) shows the full settings block and how to allow more retries. **Codex** Open the repository once in interactive `codex` and trust it before you run `codex exec`, or the run will not load `AGENTS.md`. Fetch dependencies outside the agent (Hex needs the network), then run the loop: ```bash mix deps.get codex exec --approve-for-me "Implement Shop.Orders so every test in test/shop/orders_test.exs passes. Do not modify anything under test/. Finish only when 'mix precommit' passes; print its last lines." ``` `--approve-for-me` runs the session in the `workspace-write` sandbox and routes approval requests, such as a command that needs to reach the test database outside the sandbox, through Codex's automatic review instead of waiting for you. The prompt is still an instruction: nothing stops the run from ending red. The CI job below is the mechanical gate for Codex. **Cursor** Paste the implementation prompt into the agent, in Plan Mode first if the change touches a context, a schema and a migration together. Put the Definition of done in the project rule so the agent runs `mix precommit` before it reports back. The rule is advice too. Cursor's mechanical gate runs after the pull request opens: the CI job below, plus Bugbot if your team uses it for review. CI decides, whatever ran locally. Run the same checks with a read-only token and a throwaway PostgreSQL service: ```yaml title=".github/workflows/elixir-gates.yml" name: elixir-gates on: pull_request: types: [opened, synchronize, reopened, labeled, unlabeled] permissions: contents: read jobs: gates: runs-on: ubuntu-latest services: postgres: image: postgres:17 env: POSTGRES_HOST_AUTH_METHOD: trust # disposable CI database, no credential ports: ["5432:5432"] options: --health-cmd="pg_isready" --health-interval=10s --health-timeout=5s --health-retries=5 env: MIX_ENV: test steps: - uses: actions/checkout@v7 with: persist-credentials: false fetch-depth: 2 # the PR merge commit and its base parent - name: Existing tests unchanged if: ${{ !contains(github.event.pull_request.labels.*.name, 'test-change-approved') }} run: | changed=$(git diff --name-only --diff-filter=MDR HEAD^1 HEAD -- test/) if [ -n "$changed" ]; then echo "Existing tests modified, moved or deleted; a reviewer must add the test-change-approved label:" echo "$changed" exit 1 fi - uses: erlef/setup-beam@v1 with: otp-version: "29.1.1" elixir-version: "1.20.4" - uses: actions/cache@v6 with: path: | deps _build key: mix-${{ runner.os }}-${{ hashFiles('mix.lock') }} - run: mix deps.get - run: mix deps.unlock --check-unused - run: mix hex.audit # retired packages - run: mix deps.audit # known advisories (mix_audit) - run: mix format --check-formatted - run: mix compile --warnings-as-errors - run: mix credo --strict - run: mix sobelow --exit Low --skip - run: mix ecto.create && mix ecto.migrate && mix ecto.rollback --step 1 && mix ecto.migrate - run: mix test --warnings-as-errors ``` The "Existing tests unchanged" step fails when the pull request modifies, renames or deletes a file that already exists under `test/`; new test files pass. After a person reviews the test change, they add the `test-change-approved` label, which starts a new run that skips the step (re-running the old job does not work, because it reuses the original event). The step is only a gate if the pull request cannot remove it: GitHub runs the workflow file from the pull request itself, so put `/.github/` under `CODEOWNERS` and require that review in branch protection or a ruleset. The rollback step proves the newest migration is reversible. Generated Phoenix apps use the `postgres` user by default, which the `trust` service accepts. ## Which Phoenix recipes should you hand to the agent? Every prompt below assumes the `AGENTS.md` and gate above. Each one names the tests first, because a test the agent wrote before the code is the cheapest oracle you have. ### Build a context and JSON API test-first Ask for the generator command and failing tests only, check that the new tests fail for the right reason, then ask for the implementation in a second prompt. Splitting the turns is what stops the agent from writing tests that match its own code. **Copy-paste prompt: failing tests for a Tasks context and JSON API** ```text We are adding a Tasks context and JSON API. Do not hand-write anything under lib/ in this turn. First propose the exact mix phx.gen.json command for a Task schema (title string, status enum todo/in_progress/done/cancelled, priority enum low/medium/high, due_date date) and wait for my OK. After I approve and you run it, add ONLY tests for the behaviour the generator does not cover: in test/shop/tasks_test.exs cover title required and 3..200 characters, the status transition done -> todo returning {:error, changeset} with an error on :status, due_date not in the past, and list_tasks/1 filtering by status and priority. In test/shop_web/controllers/task_controller_test.exs cover 201, 422 with errors rendered as {"errors": {"title": ["can't be blank"]}}, and 404. Run mix test on both files and show me each failure message. Stop there. ``` **Copy-paste prompt: implement until the gate passes** ```text Implement the Tasks context, schema changeset and controller so every test in test/shop/tasks_test.exs and test/shop_web/controllers/task_controller_test.exs passes. Do not modify anything under test/. Put the status-transition rule in a custom changeset validation, not in the controller. Build list_tasks/1 from small composable query functions (filter_by_status/2, filter_by_priority/2) that each take and return a queryable. Use mix test --failed while iterating. Finish only when mix precommit passes, and paste its last lines. ``` Keep the approval step in the first prompt: `mix phx.gen.json` writes a context, schema, migration, controller and tests at once, and approving one command is cheaper than reviewing the files it produces. ### Build a LiveView that does not grow without bound Older code keeps lists in assigns or uses `temporary_assigns`; the rules Phoenix 1.8 generates tell the agent to use streams for collections and to avoid LiveComponents unless there is a specific need. Hold the agent to them. **Copy-paste prompt: live orders dashboard with streams** ```text Build ShopWeb.OrdersDashboardLive at /admin/orders. In mount/3, subscribe to the "orders" PubSub topic only when connected?(socket), assign counts as plain assigns, and put the 20 most recent orders in a stream (stream(socket, :orders, orders)). Handle {:order_created, order} in handle_info/2 with stream_insert(socket, :orders, order, at: 0, limit: 20). Add a search input with phx-change and phx-debounce="300" that re-fetches and re-streams with reset: true. Use function components, not LiveComponents. Give every element a test needs a DOM id. Tests in test/shop_web/live/orders_dashboard_live_test.exs: the page renders the latest orders; broadcasting {:order_created, order} makes #orders-#{order.id} appear; search filters the list. Use has_element?/2 and element/2, never assertions on raw HTML. Finish when mix precommit passes. ``` ### Write OTP code the tests can trust The failure here is rarely the GenServer; it is the test. An agent that waits with `Process.sleep/1` produces a suite that passes on a laptop and flakes in CI. **Copy-paste prompt: ETS rate limiter without a GenServer bottleneck** ```text Implement Shop.RateLimiter for per-user limits. A GenServer owns a public named ETS table (read_concurrency and write_concurrency on) and runs a cleanup message every 60 seconds; callers increment with :ets.update_counter/4 in their own process, so the GenServer is not on the request path. API: check(user_id, limit, window_ms) returns :ok or {:error, :rate_limited, retry_after_ms}. Take the current time from an injectable clock function so tests control it. Start it under the application supervisor. Add ShopWeb.Plugs.RateLimit that returns 429 with a Retry-After header. Limits are per node; say so in the moduledoc. Tests: start the limiter with start_supervised!/1, never Process.sleep/1; synchronise with :sys.get_state/1 before asserting on cleanup; cover the limit, the window reset (advance the fake clock) and the 429 response. Finish when mix precommit passes. ``` ### Keep external calls out of Ecto transactions A transaction that calls a payment gateway holds a database connection for the whole network round trip, and it cannot roll back a charge that succeeded. Tell the agent where the boundary is. **Copy-paste prompt: order creation with Ecto.Multi** ```text Implement Shop.Orders.create_order(user, items) with Ecto.Multi and Repo.transaction/1. Steps: insert the order with status :pending_payment; insert the items with unit prices copied from the products; decrement stock for each product with one Repo.update_all per product whose query has where: p.id == ^id and p.stock >= ^qty, and fail the Multi with {:out_of_stock, product_id} when the returned row count is 0. Do not call the payment gateway inside the Multi. After the transaction commits, enqueue Shop.Workers.ChargeOrder (Oban) with the order id; that worker charges and marks the order paid or cancelled and restocks. Map Multi failures to {:error, :out_of_stock, product_id} or {:error, changeset}. Tests: happy path, insufficient stock rolls back every insert, and two concurrent orders for the last unit (Task.async in a non-async test with the sandbox in shared mode) where exactly one succeeds. Finish when mix precommit passes. ``` ### Add background jobs with Oban **Copy-paste prompt: an Oban worker with unique jobs** ```text Add Oban to this app if it is not configured: queues default: 10, mailers: 5; in config/test.exs set testing: :manual. Write Shop.Workers.OrderEmail (queue :mailers, max_attempts: 5) that sends the order confirmation through the existing Swoosh mailer, with unique: [period: 60, keys: [:order_id, :template]] so a retry storm cannot double-send. Return {:cancel, reason} when the order no longer exists instead of raising. Enqueue it in the same Multi that marks an order paid (Oban.insert/3 as a Multi step), so the job exists only if the transaction commits. Tests: use Oban.Testing, repo: Shop.Repo; perform_job/3 for the success and cancel paths; assert_enqueued/1 after the order is paid; a second insert inside 60 seconds does not create a second job. Finish when mix precommit passes. ``` ### Ship a release the agent can prove boots `mix phx.gen.release --docker` generates `lib/my_app/release.ex`, `rel/overlays/bin/migrate`, `rel/overlays/bin/server`, a `Dockerfile` and a `.dockerignore`. The Dockerfile builds from a `hexpm/elixir` Debian image pinned to the Elixir and OTP versions you generated it with. Let the generator write the files and ask the agent to prove they work. Container hardening beyond that is on [Docker patterns](/en/cookbook/devops-recipes/docker-patterns/). **Copy-paste prompt: generate and verify a Docker release** ```text Run mix phx.gen.release --docker. Do not rewrite the generated Dockerfile; only add a HEALTHCHECK that calls GET /health, and add that route (plain 200, no database call). Check config/runtime.exs raises a clear error when DATABASE_URL, SECRET_KEY_BASE or PHX_HOST is missing. Then prove it: build the image, start a throwaway postgres container on a user-defined network, run the image's /app/bin/migrate, start /app/bin/server, and curl /health until it returns 200 or 60 seconds pass. Paste the commands you ran, the migrate output and the curl result. Remove the containers afterwards. ``` ## How do you know the agent's tests would catch a bug? Green tests the agent wrote prove only that the code agrees with the agent. Three cheap checks raise the bar without you reading every line: - **Property tests on changesets and pure functions.** Add `{:stream_data, "~> 1.4", only: :test}` and ask: "For Task.changeset/2, write ExUnitProperties properties: any title shorter than 3 characters is invalid; any valid attrs round-trip through create_task/1 and get_task!/1; no status transition out of :done except to :cancelled is valid." Properties generate the inputs the agent did not think of. [Property-based testing](/en/workflows/test/property-based-testing/) covers the method. - **Break it on purpose.** Ask the agent in a separate session to introduce one bug per context function (flip a comparison, drop a `where`, skip a validation) and run the suite after each. Every bug the suite does not catch is a missing test; keep the tests, discard the bugs. - **Flaky-test hunt.** `mix test --repeat-until-failure 50 test/shop/rate_limiter_test.exs` (Elixir 1.17+) reruns a file until it fails, which exposes the `Process.sleep` and shared-state races the agent left behind. Then decide what a person still reviews: | Change | Proven by | Human sign-off | | --- | --- | --- | | Context functions, changesets, controllers, LiveViews | Tests written before the code, `mix precommit`, CI | Not needed when the gates pass and existing tests are unchanged | | Modified existing tests | The `test-change-approved` label | Yes: the person who adds the label | | Migrations that drop, rename or backfill | The rollback step in CI | Yes: check lock time and data loss (see [migration patterns](/en/cookbook/database-recipes/migration-patterns/)) | | Supervision tree and restart strategy | Tests that kill a child and assert siblings survive | Yes: a wrong strategy fails only under load | | Authentication, authorisation, `raw/1` in templates | Sobelow, tests for denied paths | Yes | Attach the `mix precommit` output and the CI run to the pull request as its [evidence bundle](/en/workflows/ship/evidence-bundle/), so the reviewer checks proof, not code. ## What breaks when agents write Elixir code? **The test passes locally and fails in CI** Symptom: a GenServer or LiveView test is green on the laptop and red intermittently in CI. Cause: `Process.sleep/1` used as synchronisation, or a process started with `start_link` outside `start_supervised!/1` and leaking into the next test. Recovery: re-prompt with "Replace every Process.sleep in test/ with Process.monitor plus assert_receive, or :sys.get_state/1; start every process with start_supervised!/1", then prove it with `mix test --repeat-until-failure 50` on that file. **LiveView memory grows with every connected user** Symptom: memory per LiveView process climbs as orders arrive. Cause: the agent keeps a list in assigns or appends to it in `handle_info/2`. Recovery: "Move the collection to a stream with a limit, keep counts as separate assigns, and re-stream with reset: true for filters." The generated LiveView rules already say this, so check the agent loaded `AGENTS.md`. **Parallel agents collide on the test database or port 4000** Symptom: two agents in separate worktrees get `database ... already exists` errors, random ownership errors or `eaddrinuse`. Cause: both use the same `shop_test` database and the same dev port. Recovery: generated `config/test.exs` appends `MIX_TEST_PARTITION` to the test database name, so give each worktree its own value (`MIX_TEST_PARTITION=2 mix test`) and its own `PORT`. For Tidewave across worktrees, its README suggests `mix tidewave.proxy` as a stdio MCP server that adds a port parameter to every tool. **Tidewave runs code outside the agent's sandbox** Symptom: none, until it matters. Cause: `project_eval` and `execute_sql_query` execute inside your Phoenix server process, not inside Claude Code's or Codex's sandbox, so a sandboxed agent can still write to the dev database or call external APIs through them. Recovery: keep Tidewave in `:dev` only, point dev config at local services and test credentials, and require approval for those two tools (for example, an `ask` permission rule for `mcp__tidewave__project_eval` in Claude Code). **The test changed to match the bug** Symptom: the diff touches `test/` in the same commit that fixes `lib/`, and an expected value moved. Cause: the agent optimised for green. Recovery: keep the "Existing tests unchanged" CI step, put `test/` under `CODEOWNERS`, and keep "Do not modify anything under test/" in every implementation prompt. [Protect the oracle](/en/workflows/test/protect-the-oracle/) has the other mechanical options. **Suppressions instead of fixes** Symptom: the gates are green and the diff adds `# credo:disable-for-next-line`, a `.sobelow-skips` entry or `@dialyzer :nowarn_function`. Recovery: give those files and patterns a human owner in `CODEOWNERS` and re-prompt: "Remove the suppression you added and fix the underlying issue. If it is a false positive, explain why in the pull request." ## Where to go next with Elixir and agents - [Backend recipes](/en/cookbook/backend-recipes/) — The other backend stacks, with the same gate-first approach. - [Protect the oracle](/en/workflows/test/protect-the-oracle/) — Stop agents from editing the tests that judge them. - [Database migration patterns](/en/cookbook/database-recipes/migration-patterns/) — Expand-and-contract changes and rollbacks for Ecto migrations. - [Docker patterns](/en/cookbook/devops-recipes/docker-patterns/) — Harden and scan the release image you generated. - [Evidence bundle](/en/workflows/ship/evidence-bundle/) — What an agent's pull request must prove before review. - [Ruby on Rails recipes](/en/cookbook/backend-recipes/ruby-rails-patterns/) — The same gates and loops for Rails. --- # Go Language Patterns URL: https://developertoolkit.ai/en/cookbook/backend-recipes/go-patterns/ Description: Prompts and gates for agent-written Go services — graceful shutdown, bounded goroutines, sized pgx pools, and race and leak checks you can trust. Go patterns for AI coding agents are prompts and verification gates that make Claude Code, Codex, and Cursor produce production-ready Go services: graceful shutdown, `errgroup`-bounded concurrency, sized pgx pools, table-driven and Testcontainers tests, and gRPC status mapping. Agent output is accepted on evidence from the race detector, goleak, golangci-lint, govulncheck, and a load test, not on line-by-line reading. Your Go service handles 200 requests per second in staging, then falls over the first time real traffic hits it. The per-request goroutines never exit, the pgx pool starves because a `rows.Close()` is missing, and a downstream call with no deadline piles up until the pod is OOM-killed. The agent's code looked idiomatic and passed its own happy-path tests. Nothing it produced was checked for the failure modes that only show up under concurrency. This recipe is for developers who build Go backends with an agent and want to stop reviewing every goroutine by eye. It front-loads the production details into the prompts, then makes the machine prove them. ## What you'll walk away with from these Go recipes - One Go rule block, in `AGENTS.md` for Claude Code and Codex and mirrored in a Cursor project rule, plus a `make check` gate the agent runs before it says "done" - Five copy-paste prompts: a chi HTTP server with graceful shutdown, a bounded `errgroup` batch, a pgx repository with sized pools and safe transactions, table-driven plus Testcontainers tests, and a gRPC service with status mapping - A verification table that tells you what each gate catches, so you read the gate output instead of the diff - Recovery prompts for the six ways agent-written Go breaks in production ## Set up Go conventions and a gate the agent must pass Two files do most of the work: a rules file the agent reads on every task, and a single command that fails when the code is not production-ready. Write them once per repository, before you ask for any code. 1. Pin a supported toolchain in `go.mod`. On 2026-09-26 the newest release is Go 1.27.1 (per `proxy.golang.org`), so Go 1.26 and 1.27 are the supported lines. An explicit `go` directive stops the agent from reaching for pre-1.22 idioms. ```go module github.com/yourorg/orders go 1.26 require ( github.com/go-chi/chi/v5 v5.3.2 github.com/jackc/pgx/v5 v5.11.0 github.com/stretchr/testify v1.12.1 go.uber.org/goleak v1.3.0 go.uber.org/zap v1.28.0 golang.org/x/sync v0.23.0 ) ``` The versions are the latest on `proxy.golang.org` on 2026-09-26. Let `go get -u ./...` move them later; the point is that the agent sees current majors. 2. Add the gate as a `make check` target. It is the definition of done for every prompt on this page. ```makefile .PHONY: check check: test -z "$$(gofmt -l .)" go vet ./... golangci-lint run ./... go test -race -shuffle=on -count=1 ./... govulncheck ./... ``` Install the two external tools once (terminal): ```bash go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.14.0 go install golang.org/x/vuln/cmd/govulncheck@latest ``` 3. Put the Go rules in `AGENTS.md` at the repository root. Codex reads `AGENTS.md` natively; the tool tabs below show how Claude Code loads the same file and how to mirror it as a Cursor rule. ```markdown ## Go conventions - Go 1.26+. Loop variables are per-iteration: never write `x := x` copies. - Layout: cmd/, internal/. No package-level mutable state. - Every blocking function takes ctx context.Context first. Never call context.Background() outside main() and tests. - Every `go` statement has a documented exit path on ctx cancellation. Prefer errgroup with SetLimit over raw goroutines. - Wrap errors with fmt.Errorf("op: %w", err). Compare with errors.Is/As, never ==. - Transactions use pgx.BeginFunc; do not hand-roll commit/rollback. - Tests are table-driven with t.Parallel(); use testify require/assert. - Never edit an existing *_test.go assertion or add t.Skip to make a test pass. If a test looks wrong, stop and say why. - Done means `make check` passes. Paste its last 20 lines in your final message. ``` The last two rules matter most. The first keeps the agent from weakening your tests to reach green; see [protect the oracle](/en/workflows/test/protect-the-oracle/) for why that is the most common way agent work fakes success. The second turns "I think it works" into evidence you can read in ten seconds. ### Wire the rules and gate into each tool The rules file and the prompts are identical across tools. What differs is how each tool loads the rules, runs the gate, and reviews the result. **Claude Code** From v2.1.277 (both release channels on 2026-10-12) Claude Code reads `AGENTS.md` when no `CLAUDE.md` exists. If you already have a `CLAUDE.md`, add the import. The `@path` import syntax expands the file into context at launch: ```markdown @AGENTS.md ``` Format every Go file the agent edits with a `PostToolUse` hook in `.claude/settings.json`: ```json { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "jq -r '.tool_input.file_path' | grep '\\.go$' | xargs -r gofmt -w" } ] } ] } } ``` Give the agent type-aware navigation with the `gopls-lsp` plugin from Anthropic's official marketplace. The plugin registers the server only, so install `gopls` first: ```bash go install golang.org/x/tools/gopls@latest claude plugin install gopls-lsp@claude-plugins-official ``` Before you open a pull request, run `/code-review` in the session for a second opinion on the diff. **Codex** Codex reads `AGENTS.md` directly, so no extra file is needed. Add the MCP server built into `gopls` (the `gopls mcp` subcommand, present in gopls v0.23.0) so the agent can query symbols, references, and diagnostics instead of grepping: ```bash go install golang.org/x/tools/gopls@latest codex mcp add gopls -- gopls mcp ``` Run a task interactively with workspace writes and approval prompts for anything wider: ```bash codex -s workspace-write -a on-request "Implement ProcessBatch as described in docs/tasks/batch.md. Done means make check passes." ``` Review the branch before you push it: ```bash codex review --base main ``` **Cursor** Create a project rule in Cursor's Rules settings with the same list as `AGENTS.md`, scoped to Go files, so the agent loads it whenever it touches a `.go` file. Add the `gopls` MCP server in Cursor's MCP configuration (`.cursor/mcp.json`): ```json { "mcpServers": { "gopls": { "command": "gopls", "args": ["mcp"] } } } ``` Use Plan Mode for the multi-file scaffolds on this page so you approve the file list before any code is written. Run independent tasks in Worktrees, and let Bugbot review the pull request. Start each tool on its default model and raise the effort setting before you switch models; the [models hub](/en/ecosystem/models/) lists the current defaults. ## Build a production Go service with an agent, step by step Each step below is one prompt, one excerpt of what a good answer looks like, and the gate that proves it. Run them in order: later prompts assume the server and repository exist. ### How do you scaffold a Go HTTP server that shuts down cleanly? The most common first-pass omission is shutdown. The agent starts `ListenAndServe` in a goroutine and exits without draining in-flight requests, so every deploy drops traffic. **Copy-paste prompt: chi server with graceful shutdown** ```text Create cmd/server/main.go using github.com/go-chi/chi/v5. Middleware: RequestID, RealIP, Recoverer, and Timeout(30s). Logging with go.uber.org/zap (production config). Routes: GET /healthz returns 200; mount the API under /api/v1. Set ReadHeaderTimeout, ReadTimeout, WriteTimeout, and IdleTimeout on http.Server. Graceful shutdown: listen in a goroutine, block on signal.NotifyContext for SIGINT and SIGTERM, then call srv.Shutdown with a fresh 10s context; put that step in a shutdown function main calls. Add cmd/server/main_test.go that starts the server with httptest, sends a request that sleeps 2s, calls the same shutdown function mid-request, and asserts three things: the request completes with 200, Shutdown returns nil, and Shutdown returns only after the handler finishes (record both times; require handlerDone <= shutdownReturned). Done means make check passes. ``` A good answer has this core: ```go ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) defer stop() go func() { if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { logger.Fatal("listen", zap.Error(err)) } }() <-ctx.Done() shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() if err := srv.Shutdown(shutdownCtx); err != nil { logger.Error("shutdown", zap.Error(err)) } ``` You do not need to audit this by eye. The shutdown test fails if `Shutdown` reuses the cancelled `ctx`, because `Shutdown` then returns `context.Canceled` before the in-flight request finishes. The server timeouts matter because `http.Server` has no read or write deadline by default, and `go vet` will not tell you that. ### How do you bound goroutines so a batch cannot exhaust the database? "Process these items concurrently" produces an unbounded `go func()` fan-out. Under load it opens one database connection per item and exhausts the pool or the file-descriptor limit. **Copy-paste prompt: bounded batch with errgroup** ```text Implement (s *Service) ProcessBatch(ctx context.Context, items []Item) error in internal/orders. Use golang.org/x/sync/errgroup: derive the group with errgroup.WithContext so the first error cancels the rest, and cap concurrency with g.SetLimit(8). Each task checks ctx.Err() before work and passes ctx down. We are on Go 1.26: do not add item := item copies. Add internal/orders/main_test.go with goleak.VerifyTestMain(m), and table-driven tests for: all succeed, one fails and the rest are cancelled, parent ctx cancelled before start. Done means make check passes. ``` ```go func (s *Service) ProcessBatch(ctx context.Context, items []Item) error { g, ctx := errgroup.WithContext(ctx) g.SetLimit(8) for _, item := range items { g.Go(func() error { if err := ctx.Err(); err != nil { return err } return s.processItem(ctx, item) }) } if err := g.Wait(); err != nil { return fmt.Errorf("process batch: %w", err) } return nil } ``` The proof here is `goleak.VerifyTestMain`: it fails the package if any goroutine is still running when the tests finish. Combined with `-race` in `make check`, it catches the two concurrency bugs you cannot see in a diff. ### How do you get an agent to write a pgx repository that survives load? Pool exhaustion is the classic "works in dev, dies in prod" bug. One detail agents rarely know: pgxpool's default `MaxConns` is the greater of 4 and `runtime.NumCPU()` (pgx v5.11.0 source), so a two-vCPU container gets four connections unless you size the pool. **Copy-paste prompt: pgx repository with sized pool and safe transactions** ```text Create internal/storage/users.go with a UserRepository backed by *pgxpool.Pool. Constructor: pgxpool.ParseConfig(dsn), then set MaxConns=20, MinConns=2, MaxConnLifetime=1h, MaxConnIdleTime=30m, and call pgxpool.NewWithConfig. Methods: - CreateUser(ctx, u) (int64, error): INSERT ... RETURNING id. If the error is a *pgconn.PgError with Code "23505" (unique_violation), return the sentinel ErrDuplicateEmail, wrapped with %w. - GetUser(ctx, id) (User, error): map pgx.ErrNoRows to the sentinel ErrNotFound. - TransferCredits(ctx, from, to, amount) error: run both UPDATEs inside pgx.BeginFunc so rollback on error or panic is handled by pgx, not by us. Every rows result from Query is closed with defer rows.Close() and checked with rows.Err(). Do not change any existing test. Done means make check passes. ``` The prompt names `pgx.BeginFunc` on purpose. Left alone, agents hand-roll a `WithTx` helper with a deferred `recover()` and a named return, which is correct only if every branch is right. `BeginFunc` commits when the callback returns `nil` and rolls back otherwise, including when the callback panics, so there is less agent code for anyone to review. The prompt also asks for `23505`, not `pgx.ErrNoRows`, for duplicate emails. An `INSERT` that hits a unique constraint returns a `*pgconn.PgError`; it never returns `ErrNoRows`, and mapping the wrong one produces a 500 where the client expected a 409. To let the agent read your real schema instead of guessing column names, connect a database MCP server to a **development** database only. The [database MCP guide](/en/ecosystem/mcp/database-mcp/) compares the options and their read-only switches. Do not use `@modelcontextprotocol/server-postgres`: the package is deprecated on npm and archived. ### How do you generate Go tests that catch real bugs? Name the cases, or you get happy-path-only coverage. Then add one integration test against a real Postgres, because a mocked repository cannot catch a wrong SQL column or a missing unique index. **Copy-paste prompt: table-driven unit tests** ```text Write table-driven tests for UserService.GetUser in internal/users/service_test.go. Use testify require/assert and t.Parallel() in every subtest; use t.Context() for contexts. Cases: cache hit (repository not called); cache miss then repository hit (assert the value is written back to cache); repository returns ErrNotFound (assert with assert.ErrorIs and that nothing is cached); repository returns a wrapped context.DeadlineExceeded (assert it propagates). Use small hand-written fakes, not a mocking framework. List the cases in your final message before the code. ``` **Copy-paste prompt: Testcontainers integration test** ```text Write internal/storage/users_integration_test.go, skipped when testing.Short(). Start Postgres with postgres.Run(ctx, "postgres:17-alpine", postgres.WithDatabase("app"), postgres.WithUsername("app"), postgres.WithPassword("app"), postgres.BasicWaitStrategies()) from github.com/testcontainers/testcontainers-go/modules/postgres. Register cleanup with testcontainers.CleanupContainer(t, ctr). Get the DSN with ctr.ConnectionString(ctx, "sslmode=disable"), apply the migrations in ./migrations, then assert: CreateUser returns an id; a second CreateUser with the same email returns ErrDuplicateEmail; GetUser on a missing id returns ErrNotFound. ``` The function names in the second prompt are from testcontainers-go v0.44.0 (checked 2026-09-26). The older `RunContainer` entry point still compiles, so without the explicit names the agent often reaches for it. Asking the agent to list the cases before the code gives you the one thing worth reading: the test list. If the list covers the behaviour you care about and `make check` is green, you have not needed to read the test bodies. For more on test design with agents, see [unit testing with agents](/en/workflows/test/unit-testing/) and [integration testing](/en/workflows/test/integration-testing/). ### How do you stand up a gRPC service without leaking internal errors? A generated handler that returns the raw `err` can send a client the failing SQL statement, so ask for one function that owns the mapping from domain errors to gRPC status codes. **Copy-paste prompt: gRPC service with interceptors and health** ```text Create a gRPC UserService from proto/user/v1/user.proto (GetUser, CreateUser, ListUsers with page_token pagination). Generate code with buf using protoc-gen-go and protoc-gen-go-grpc; show buf.gen.yaml. In cmd/grpc/main.go add logging and recovery unary interceptors via grpc.ChainUnaryInterceptor, register the standard grpc_health_v1 health server, and stop with GracefulStop on SIGTERM. Map domain errors to status codes in one function: ErrNotFound -> codes.NotFound, ErrDuplicateEmail -> codes.AlreadyExists, context.DeadlineExceeded -> codes.DeadlineExceeded, anything else -> codes.Internal with a generic message. Add a bufconn test per mapping. ``` A good answer has this core: ```go func toStatus(err error) error { switch { case errors.Is(err, users.ErrNotFound): return status.Error(codes.NotFound, "user not found") case errors.Is(err, users.ErrDuplicateEmail): return status.Error(codes.AlreadyExists, "email already registered") case errors.Is(err, context.DeadlineExceeded): return status.Error(codes.DeadlineExceeded, "deadline exceeded") default: slog.Error("unmapped error", "err", err) // detail stays in your logs return status.Error(codes.Internal, "internal error") } } ``` The mapping function is the part that matters: every error leaves the service through it, and the `default` branch keeps internal detail in your logs instead of in the client's response. The bufconn tests prove every mapping without a network or a human reading the handlers. ## How do you verify agent-written Go without reading every line? Read the gate output and the test list, not the diff. Each gate below catches a class of bug that looks fine in review, which is why reading is the weakest check for Go concurrency code. | Gate | Command | What it catches | | --- | --- | --- | | Format and vet | `gofmt -l .`, `go vet ./...` | Unformatted files, misused `Printf` verbs, copied locks, unreachable code | | Lint | `golangci-lint run ./...` | Unchecked errors (`errcheck`), ineffective assignments, `staticcheck` findings; `==` on wrapped errors once you enable `errorlint` | | Race detector | `go test -race -shuffle=on -count=1 ./...` | Data races and order-dependent tests | | Goroutine leaks | `goleak.VerifyTestMain(m)` in each concurrent package | Goroutines with no exit path | | Vulnerabilities | `govulncheck ./...` | Known CVEs in code paths you actually call | | Integration | Testcontainers tests without `-short` | Wrong SQL, missing constraints, bad migrations | | Load | Twice expected peak against staging, for example `echo "GET https://staging.example.com/api/v1/items" \| vegeta attack -rate=400 -duration=60s \| vegeta report` | Pool exhaustion, missing timeouts, memory growth | | Review agent | `/code-review` (Claude Code), `codex review --base main` (Codex), Bugbot (Cursor) | Logic errors and missing cases the gates cannot express | Run the first six in CI on every pull request; see [CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/) for the workflow file. The engineer who owns the service signs off on three things: the test-case list, a green gate, and the load-test graph. Human reading goes to the hunks the review agent flags and to any code that touches transactions or goroutines. [Agent PR review](/en/workflows/ship/agent-pr-review/) covers how to split that work across a team. ## When agent-written Go breaks in production Each failure below passes a happy-path test suite. Each one has a symptom you can detect and a recovery you can paste. - **Goroutine leak.** Symptom: `go_goroutines` in your metrics climbs and never falls. Cause: a `go func()` blocked on a channel send with no receiver, or with no `ctx.Done()` case. Recovery: add `goleak.VerifyTestMain` to the package, then prompt: "Audit every `go` statement in this package. For each one, name its exit path under context cancellation, and fix any that have none. Done means `make check` passes." - **Context dropped mid-stack.** Symptom: requests keep running after the client disconnects, and deadlines do nothing. Cause: `context.Background()` or `context.TODO()` deep in a handler. Recovery: `grep -rn "context.Background()\|context.TODO()" --include=*.go internal/` and prompt the agent to thread `ctx` through every function it finds. - **Pool exhaustion.** Symptom: latency spikes, then requests hang waiting to acquire a connection. Cause: a missing `rows.Close()`, a query on `pool` inside a transaction (two connections per request), or the default pool size. Recovery: set `MaxConns` deliberately, check `pool.Stat()` in a debug endpoint, and prompt: "Find every `Query` call whose rows are not closed on every path, and every pool query made while a `pgx.Tx` is open." - **Stale idioms from old training data.** Symptom: `item := item` copies, `ioutil` imports, or `interface{}` everywhere. Cause: the model is drawing on pre-1.22 code. Recovery: the `go` directive and the `AGENTS.md` rule prevent most of it; for the rest, prompt: "Modernise this package for Go 1.26: remove loop-variable copies, replace `ioutil`, and use `any`. Change no behaviour." - **The agent weakens a test to reach green.** Symptom: an assertion loosened, a case deleted, or a `t.Skip` added in the same diff as the fix. Recovery: revert the test file, restate the rule from `AGENTS.md`, and make CI fail when a pull request modifies, renames or deletes an existing `*_test.go` without a `test-change` label. The step is only a gate if the pull request cannot remove it: GitHub runs the workflow file from the pull request itself, so put `/.github/` under `CODEOWNERS` and require that review in branch protection or a ruleset. This step assumes `actions/checkout` with `fetch-depth: 0`; [Protect the oracle](/en/workflows/test/protect-the-oracle/) covers the wider policy. ```yaml - name: Block edits to existing tests without a test-change label if: ${{ !contains(github.event.pull_request.labels.*.name, 'test-change') }} # Needs actions/checkout with fetch-depth: 0: origin/main... diffs from the merge base. run: | # --name-status lists a rename as R OLD NEW; field 2 is the path that existed before if git diff --name-status --diff-filter=MDR origin/main... | awk -F'\t' '{print $2}' | grep '_test\.go$'; then echo "Existing tests changed without the test-change label"; exit 1 fi ``` - **golangci-lint fails before it lints.** Symptom: an error that the Go version used to build golangci-lint is lower than the targeted version, or a config error on a `.golangci.yml` the agent wrote in the v1 format. Recovery: install a golangci-lint v2 built with a Go release at least as new as your `go` directive, and run `golangci-lint migrate` on an old config. "It compiles and the tests pass" is the weakest possible evidence for Go concurrency code. A service can pass every unit test while leaking a goroutine per request. Treat the race detector, goleak, and a load test as part of the definition of done, not as optional hardening. ## Where to go next with Go services - Make the repository agent-ready first, if it is not yet: [agent-ready codebase](/en/workflows/harness/agent-ready-codebase/). - Harden the data layer: [SQL optimization patterns](/en/cookbook/database-recipes/sql-patterns/) and [database migration patterns](/en/cookbook/database-recipes/migration-patterns/). - Ship the service: [Docker patterns](/en/cookbook/devops-recipes/docker-patterns/) and [Kubernetes patterns](/en/cookbook/devops-recipes/kubernetes-patterns/). - Decide what the agent may run unattended: [permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/). - Compare with another compiled backend: [Rust development patterns](/en/cookbook/backend-recipes/rust-patterns/), or return to the [backend recipes overview](/en/cookbook/backend-recipes/). --- # Java & Spring Boot Patterns URL: https://developertoolkit.ai/en/cookbook/backend-recipes/java-patterns/ Description: Get Spring Boot 4.1 code from Claude Code, Codex or Cursor that avoids removed APIs, N+1 queries and swallowed errors, proven by Testcontainers and ArchUnit. Java and Spring Boot recipes for AI coding agents work in three moves: pin Spring Boot 4.1, Hibernate 7 and Spring Security 7 in the agent's context so it stops writing removed APIs, prompt for failure behavior rather than "CRUD", and let Testcontainers, a query-count test and ArchUnit rules prove the result instead of a line-by-line review. This recipe is for Java developers who let Claude Code, Codex or Cursor write Spring Boot services. The agent's controller compiles and its mocked tests pass. Then the build breaks on `@Where`, which Hibernate 7 no longer ships, the orders list fires one query per row, and a payment timeout turns into a 500 because the circuit breaker was never wired. ## What these Spring Boot recipes give you - A version pin block that stops the agent from writing Spring Boot 3, Hibernate 6 and Security 6 code - Copy-paste prompts for a REST resource, soft-deleting JPA entities, a resilient downstream client, JWT resource-server security, and a Testcontainers suite - A query-count test that fails the build on an N+1 regression - ArchUnit rules that reject field injection, repository access from controllers and entity leaks without anyone reading the diff - A failure-mode list with the recovery for each one ## Pin the Spring versions in the agent's context first Models were trained on years of Spring Boot 2 and 3 code, so an unpinned prompt produces APIs that no longer exist. Current versions, from the `spring-boot-dependencies` 4.1.1 BOM on Maven Central (released 2026-08-20, checked 2026-09-26): Spring Framework 7.0.9, Spring Security 7.1.1, Spring Kafka 4.1.1, Hibernate ORM 7.4.5, Jackson 3.1.5 and Testcontainers 2.0.5. Spring Boot 4.1 needs Java 17 or later. Put this block in the file your agent reads on every run: ```text ## Stack (do not downgrade, do not use older APIs) - Spring Boot 4.1.x, Java 25, Maven wrapper (./mvnw) - Spring Framework 7, Spring Security 7 (lambda DSL only), Hibernate ORM 7, Jackson 3, Testcontainers 2 - Starters: spring-boot-starter-webmvc (not -web, deprecated), spring-boot-starter-security-oauth2-resource-server - Banned: @Where (removed in Hibernate 7; use @SoftDelete or @SQLRestriction), WebSecurityConfigurerAdapter, .and() and authorizeRequests() in security config, ListenableFuture/addCallback on KafkaTemplate, @MockBean (use @MockitoBean), org.testcontainers.containers.PostgreSQLContainer (use org.testcontainers.postgresql) ## Conventions - Constructor injection only; no @Autowired fields - Controllers return DTO records, never entities; no business logic or try/catch in controllers - One @RestControllerAdvice returning ProblemDetail (application/problem+json) - @Transactional on public service methods only; readOnly = true for reads - Every endpoint ships with a Testcontainers integration test ``` **Claude Code** Save the block in `CLAUDE.md` at the repository root. Claude Code loads it at the start of every session. See [project initialization](/en/claude-code/quick-start/project-initialization/) for the rest of that file. **Codex** Save the block in `AGENTS.md` at the repository root. Codex reads it on every task. See [writing AGENTS.md for Codex](/en/codex/quick-start/agents-md/). **Cursor** Save the block as an always-applied project rule. See [Cursor project rules](/en/cursor-ide/quick-start/project-rules/) for the file format. ## Scaffold a Spring Boot 4.1 service with an agent Spring Initializr at `start.spring.io` is the source of truth for the dependency tree. Have the agent download from it rather than write a `pom.xml` from memory, because a hand-written POM is where old starter names and stale versions come back. The prompt is the same in every tool; only where you run it differs. **Claude Code** ```bash claude "Download a Spring Boot 4.1 Maven project for Java 25 from start.spring.io with web, data-jpa, validation, security, oauth2-resource-server, actuator, postgresql, flyway and testcontainers. Then check pom.xml against the Stack section of CLAUDE.md and fix any starter or version that differs. Run ./mvnw -q verify and show me the result." ``` **Codex** ```bash codex --worktree "Download a Spring Boot 4.1 Maven project for Java 25 from start.spring.io with web, data-jpa, validation, security, oauth2-resource-server, actuator, postgresql, flyway and testcontainers. Then check pom.xml against the Stack section of AGENTS.md and fix any starter or version that differs. Run ./mvnw -q verify and show me the result." ``` `--worktree` runs the session in a new managed Git worktree, so the scaffold does not collide with your current branch. **Cursor** Paste the same prompt into the Agent panel, replacing `AGENTS.md` with "the project rules". Review the proposed `pom.xml` diff before you accept it: that file decides every version the rest of this page relies on. The run is done when `./mvnw verify` passes and `pom.xml` names `spring-boot-starter-webmvc` rather than the deprecated `spring-boot-starter-web`. ## Generate a REST resource that fails correctly Ask for the failure behavior, not "CRUD". Without it the agent returns entities, scatters `try/catch` blocks that log and return `null`, and answers a validation error with a stack trace. **Copy-paste prompt: Product REST resource** ```text Create a Product REST resource at /api/v1/products following CLAUDE.md / AGENTS.md. 1. Product JPA entity: id, name, slug (unique), description, price BigDecimal, stock int, @Version for optimistic locking. A ProductResponse record DTO; never return the entity. 2. Endpoints: GET / (Pageable, default size 20, optional ?search= over name and description), GET /{id}, POST / (201 with Location header), PUT /{id}, DELETE /{id} (204). 3. CreateProductRequest / UpdateProductRequest records with Jakarta Validation: @NotBlank @Size(min=2,max=200) name, @Positive price, @PositiveOrZero stock. @Valid on every @RequestBody. 4. One @RestControllerAdvice returning ProblemDetail: validation -> 422 with a field-errors list, not found -> 404, duplicate slug (DataIntegrityViolationException) -> 409, OptimisticLockingFailureException -> 409, anything else -> 500 with no stack trace in the body. 5. Service with constructor injection, @Transactional(readOnly = true) on reads, @Transactional on writes. 6. Testcontainers integration tests for: create (201 + Location), 422 with the field name, 409 on duplicate slug, 404 on a missing id. Run ./mvnw verify and paste the summary. ``` A correct controller stays thin. If the generated one maps fields, catches exceptions or injects an `EntityManager`, send it back with "move mapping and error handling out of the controller; rely on the advice": ```java @RestController @RequestMapping("/api/v1/products") class ProductController { private final ProductService products; ProductController(ProductService products) { // constructor injection, no @Autowired this.products = products; } @GetMapping Page list(@PageableDefault(size = 20) Pageable pageable, @RequestParam(required = false) String search) { return products.search(search, pageable); // mapping lives in the service } } ``` ## Soft-delete JPA entities on Hibernate 7 Ask for soft delete and agents often emit the Hibernate 5 pair `@SQLDelete` plus `@Where`. `@Where` is not in Hibernate ORM 7.4.5 at all (checked in the published JAR on 2026-09-26), so that code does not compile. Hibernate's managed `@SoftDelete` replaces both annotations and filters deleted rows from every query. **Copy-paste prompt: Order entity with soft delete** ```text Add an Order entity (table "orders") using Hibernate 7's @SoftDelete. Do not use @SQLDelete or @Where. - ManyToOne Customer (LAZY, not null), OneToMany OrderItem (cascade ALL, orphanRemoval), OrderStatus enum stored as STRING, @CreatedDate / @LastModifiedDate via AuditingEntityListener with @EnableJpaAuditing. - A Flyway migration for the table, including the soft-delete column Hibernate expects. - An OrderRepository with JpaSpecificationExecutor. The list query is paged, so put an @EntityGraph on the ManyToOne customer only; never fetch-join the items collection. Load items with spring.jpa.properties.hibernate.default_batch_fetch_size=50. - A GET /api/v1/orders list endpoint (Pageable) returning OrderResponse records. - Tests on Testcontainers Postgres: a deleted order disappears from findAll() but its row still exists (check with JdbcTemplate), and listing 50 orders runs a fixed number of SQL statements (Hibernate statistics), not one per order. ``` ```java @Entity @Table(name = "orders") @SoftDelete // Hibernate 6.4+: replaces @SQLDelete + @Where on every query @EntityListeners(AuditingEntityListener.class) class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @ManyToOne(fetch = FetchType.LAZY, optional = false) private Customer customer; // items, status, auditing fields } ``` For deeper JPA work, including lazy-loading traps across ORMs, see [ORM best practices](/en/cookbook/database-recipes/orm-patterns/). For the Flyway side, see [database migration patterns](/en/cookbook/database-recipes/migration-patterns/). ## Catch N+1 queries with a query-count test N+1 queries are a frequent performance defect in generated JPA: a `LAZY` association read in a loop fires one query per row, and it looks fine with five rows of test data. A test that counts statements turns it into a red build. Enable statistics in the test profile with `spring.jpa.properties.hibernate.generate_statistics=true`, then assert on the count: ```java @Test void listingOrdersDoesNotScaleQueriesWithRows() { fixtures.createOrders(50); // enough rows for an N+1 to show var stats = entityManagerFactory.unwrap(SessionFactory.class).getStatistics(); stats.clear(); mockMvc.perform(get("/api/v1/orders?size=50")).andExpect(status().isOk()); assertThat(stats.getPrepareStatementCount()).isLessThanOrEqualTo(3); } ``` When the test goes red, paste the failure back: "the list endpoint runs 51 statements; fix it with an `@EntityGraph` on to-one associations and batch fetching for collections, not by raising the limit." Do not accept a `JOIN FETCH` of a collection on a paged query: Hibernate then pages in memory (see the failure modes below). ## Make downstream calls resilient with Resilience4j A service that calls payment or inventory synchronously needs timeouts and a circuit breaker. Spring Framework 7.0 ships `@Retryable` and `@ConcurrencyLimit` in `org.springframework.resilience.annotation` (enabled with `@EnableResilientMethods`), but it has no circuit breaker, so use Resilience4j's `resilience4j-spring-boot4` 2.4.0 for that. On Kafka, `KafkaTemplate.send()` returns a `CompletableFuture`; the old `ListenableFuture.addCallback(...)` does not compile. **Copy-paste prompt: resilient payment client and Kafka publisher** ```text Implement PaymentServiceClient following CLAUDE.md / AGENTS.md. 1. Spring RestClient with connect timeout 2s and read timeout 5s, configured in one @Bean. 2. processPayment(PaymentRequest) wrapped with Resilience4j (resilience4j-spring-boot4): @CircuitBreaker(name = "payment", fallbackMethod = "fallback") and @Retry(name = "payment"), 3 attempts with exponential backoff, retrying only on 5xx and I/O errors, never on 4xx. The fallback returns a PENDING payment and logs at WARN with the order id. 3. application.yml: sliding window 10, failure-rate threshold 50, wait duration in open state 30s; expose circuit-breaker state through Actuator health. 4. OrderEventPublisher: kafkaTemplate.send(...).whenComplete(...), never addCallback. Publish after the transaction commits (@TransactionalEventListener(phase = AFTER_COMMIT)). 5. Tests: WireMock returns 503 until the breaker opens; assert the fallback fires and the downstream stops receiving calls. A second test proves a 400 is not retried. ``` The publisher should look like this: `whenComplete`, and only after commit, so a rolled-back order never produces an event: ```java @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) void onOrderCreated(OrderCreatedEvent event) { var message = OrderEvent.from(event); kafkaTemplate.send("order-events", message.orderId(), message).whenComplete((result, ex) -> { if (ex != null) log.error("Failed to publish {}", message.eventId(), ex); }); } ``` For retries, idempotency keys and compensation across services, see [recovery patterns](/en/cookbook/error-handling-recipes/recovery-patterns/). ## Secure the API with Spring Security 7 and JWT Spring Security 7.1.1 has no `WebSecurityConfigurerAdapter`, no `and()` and no `authorizeRequests()`: every `HttpSecurity` method takes a lambda `Customizer` (checked in the published `spring-security-config` JAR on 2026-09-26). Agents also like to hand-write a `OncePerRequestFilter` that parses JWTs. Do not accept that. The OAuth2 resource server validates signature, expiry, issuer and audience for you. **Copy-paste prompt: stateless JWT security** ```text Configure Spring Security 7 for a stateless API using spring-boot-starter-security-oauth2-resource-server. Do not write a custom JWT filter and do not use WebSecurityConfigurerAdapter, and(), or authorizeRequests(). 1. One SecurityFilterChain bean, lambda DSL: CSRF disabled (stateless API), SessionCreationPolicy.STATELESS, permit /api/auth/** and /actuator/health, require ROLE_ADMIN on /api/admin/**, authenticate the rest. 2. oauth2ResourceServer(jwt) with issuer-uri from configuration; map the "roles" claim to ROLE_ authorities with a JwtAuthenticationConverter. 3. @EnableMethodSecurity so @PreAuthorize works on service methods. 4. 401 and 403 returned as ProblemDetail JSON, matching the @RestControllerAdvice format. 5. @WebMvcTest slice tests with SecurityMockMvcRequestPostProcessors.jwt(): no token -> 401, a USER token on /api/admin/** -> 403, an ADMIN token -> 200, an expired token -> 401. ``` For security testing beyond the filter chain, see [security testing with AI](/en/workflows/test/security-testing/). ## Prove it on real Postgres with Testcontainers 2 Mocked repositories pass while the real query is broken, so the conventions require a real database. Testcontainers 2 moved the Postgres module to the `testcontainers-postgresql` artifact and the `org.testcontainers.postgresql` package; the old `org.testcontainers.containers.PostgreSQLContainer` is deprecated. With `@ServiceConnection`, Spring Boot wires the datasource from the container, so the test needs no `@DynamicPropertySource`. **Copy-paste prompt: shared Testcontainers suite** ```text Create the integration-test base for this service. - A @TestConfiguration(proxyBeanMethods = false) with one @Bean @ServiceConnection org.testcontainers.postgresql.PostgreSQLContainer("postgres:17"), reused by every test class. - Tests use @SpringBootTest + @AutoConfigureMockMvc and import that configuration. Add the Boot 4 test starters the slices need (spring-boot-starter-webmvc-test, spring-boot-starter-data-jpa-test) instead of guessing packages. - Flyway runs the real migrations against the container; no ddl-auto=create. - Clean state between tests by truncating tables, not by @DirtiesContext. - Cover the Product and Order endpoints: happy path, 422, 409, 404, the soft-delete test and the query-count test. Use @MockitoBean, never @MockBean. - Run ./mvnw verify twice in a row and confirm both runs pass (no order dependence). ``` ```java @TestConfiguration(proxyBeanMethods = false) class PostgresTestConfig { @Bean @ServiceConnection PostgreSQLContainer postgres() { // org.testcontainers.postgresql, not .containers return new PostgreSQLContainer("postgres:17"); } } ``` For Testcontainers patterns beyond the database layer, see [integration testing with AI](/en/workflows/test/integration-testing/). ## Give the agent the live schema through a Postgres MCP server For index and query work the agent does better when it reads real indexes and `EXPLAIN` output than when it guesses from your entity classes. Postgres MCP Pro (PyPI `postgres-mcp` 0.3.0, from Crystal DBA) provides that. Its last PyPI release was in May 2025, so check the project's activity before you standardise on it; [database MCP servers](/en/ecosystem/mcp/database-mcp/) covers the alternatives, DBHub and MCP Toolbox. Point it at a development database with a read-only role: ```bash claude mcp add -s project postgres -e 'DATABASE_URI=${DEV_DATABASE_URL}' \ -- uvx postgres-mcp --access-mode=restricted ``` The single quotes keep the placeholder literal, so `.mcp.json` stores `${DEV_DATABASE_URL}` and Claude Code expands it from your environment at launch; the credentials never reach the repository. Codex (`codex mcp add … --env …`) and Cursor take the same command and arguments in their own MCP configuration. [Database MCP servers](/en/ecosystem/mcp/database-mcp/) has all three configurations and the read-only role to create first. **Do not install the archived reference Postgres server** Agents still suggest `@modelcontextprotocol/server-postgres`. It is deprecated and archived with the other reference servers. Use Postgres MCP Pro in `restricted` mode, and make the database role read-only whichever server you choose. ## How to verify agent-written Spring code without reading every line Read the migration SQL, the security rules and the test names. Let gates check the rest. ArchUnit 1.5.1 turns the conventions into tests, so a convention the agent ignores fails the build instead of waiting for a reviewer to notice: ```java @AnalyzeClasses(packages = "com.example.shop") class ArchitectureTest { @ArchTest static final ArchRule noFieldInjection = GeneralCodingRules.NO_CLASSES_SHOULD_USE_FIELD_INJECTION; @ArchTest static final ArchRule controllersNeverTouchRepositories = noClasses() .that().areAnnotatedWith(RestController.class) .should().dependOnClassesThat() // Spring Data's interface, not the @Repository annotation: with the annotation, // areAssignableTo never matches and the rule passes vacuously .areAssignableTo(org.springframework.data.repository.Repository.class); @ArchTest static final ArchRule controllersNeverReturnEntities = noMethods() .that().areDeclaredInClassesThat().areAnnotatedWith(RestController.class) .should().haveRawReturnType(annotatedWith(Entity.class)); } ``` The entity rule checks the raw return type only. A controller returning `Page` or `List` passes it, so cover generic returns with a custom `ArchCondition` that inspects the type arguments. Add the banned-API check from the pin block to CI as one step. It exits non-zero when any match is found: ```bash ! git grep -nE '@Where\b|WebSecurityConfigurerAdapter|authorizeRequests\(|\.addCallback\(|@MockBean\b|org\.testcontainers\.containers\.PostgreSQLContainer' -- '*.java' ``` | Gate | What it proves | Runs in | | --- | --- | --- | | `./mvnw verify` with Testcontainers | Endpoints, validation, 409/404 paths and soft delete work on real Postgres | Pre-push and CI | | Query-count tests | No N+1 regression on list endpoints | CI | | ArchUnit rules | No field injection, no repository access from controllers, no entity returned from a controller | CI | | The banned-API `git grep` above | No removed API slipped back in | CI | | Security slice tests | 401, 403 and role mapping behave as specified | CI | | Circuit-breaker test | The fallback fires and 4xx is never retried | CI | | A human read of the Flyway SQL and `SecurityFilterChain` | Locks, drops and access rules are intended | PR review | The developer who opens the pull request owns the test names and the invariants they encode. The reviewer signs off on the migration, the security configuration and the gate results, not on every generated line. To package that evidence for review, see [the evidence bundle](/en/workflows/ship/evidence-bundle/). For why this replaces reading the diff, see [evidence, not diffs](/en/ladder/evidence-not-diffs/). ## When agent-written Spring Boot code breaks - **The code targets an unsupported major version (Spring Boot 3 / Hibernate 6).** Symptoms: `cannot find symbol: class Where`, `WebSecurityConfigurerAdapter` not found, `addCallback` undefined on `CompletableFuture`, or `com.fasterxml.jackson.databind` imports failing under Jackson 3. Recovery: add the pin block to `CLAUDE.md` or `AGENTS.md`, paste the compiler error back with "this is Spring Boot 4.1 / Hibernate 7", then add the banned-API `git grep` step above to CI. - **Test slices do not compile.** Symptom: `@WebMvcTest` or `@DataJpaTest` cannot be resolved after the upgrade. Recovery: Spring Boot 4 split test auto-configuration into modules; add `spring-boot-starter-webmvc-test` or `spring-boot-starter-data-jpa-test` rather than letting the agent guess package names. - **`@Transactional` does nothing.** Symptom: a partial write survives an exception. Cause: the annotation sits on a `private` method or on a method called from inside the same class, so Spring's proxy never sees the call. Recovery: move it to a `public` service method (and keep it off controllers: transactions belong to the service layer), and add a test that throws mid-write and asserts no row exists. - **Validation never runs.** Symptom: blank names reach the database. Cause: `@Valid` is missing on the `@RequestBody`. Recovery: the 422 test from the REST prompt should already be red; if it is green, the test posts a valid body. - **An `@Async` method swallows its exception.** Symptom: a job silently stops. Recovery: return `CompletableFuture` or register an `AsyncUncaughtExceptionHandler`, and assert the failure path in a test. - **Events for rolled-back orders.** Symptom: downstream services see orders that do not exist. Recovery: publish from `@TransactionalEventListener(phase = AFTER_COMMIT)` or move to a transactional outbox. - **Hibernate pages the list in memory.** Symptom: the log shows warning `HHH90003004` (firstResult/maxResults specified with collection fetch; applying in memory), and memory grows with table size rather than page size. Cause: a `JOIN FETCH` or `@EntityGraph` on the `items` collection of a paged query, so Hibernate loads every matching row and pages in the JVM. Recovery: fetch only to-one associations in the paged query and load collections with `default_batch_fetch_size` or a second query by id; set `hibernate.query.fail_on_pagination_over_collection_fetch=true` in tests to turn the warning into an exception. - **The N+1 returns after a refactor.** Symptom: latency grows with page size. Recovery: the query-count test should be red; if it is green, the fixture has too few rows, so seed more. ## Where to go next with Spring Boot - [Backend recipes](/en/cookbook/backend-recipes/): the hub for the other languages and frameworks - [API development patterns](/en/cookbook/backend-recipes/api-patterns/): cross-language REST design, versioning and error envelopes - [ORM best practices](/en/cookbook/database-recipes/orm-patterns/): the N+1 and lazy-loading playbook across ORMs - [SQL optimization patterns](/en/cookbook/database-recipes/sql-patterns/): `EXPLAIN` plans and index design when a query is slow rather than repeated - [.NET and C# recipes](/en/cookbook/backend-recipes/dotnet-patterns/): the same recipes for ASP.NET Core - [Kubernetes orchestration patterns](/en/cookbook/devops-recipes/kubernetes-patterns/): deploying these services to a cluster --- # Node.js/Express Recipes URL: https://developertoolkit.ai/en/cookbook/backend-recipes/node-patterns/ Description: Prompts and gates for agent-written Node.js services on Express 5: clean shutdown, validation, token rotation, Prisma transactions, queues, and safe logs. Node.js recipes for AI coding agents are prompts and verification gates that make Claude Code, Codex, and Cursor produce production-ready Express 5 services in TypeScript: clean shutdown, validated input, refresh-token rotation, rate limits, Prisma transactions that hold under concurrency, BullMQ jobs, and redacted logs. Output is accepted on gate evidence, not line-by-line reading. Your Express API passes every test the agent wrote, then the first deploy drops in-flight requests, two customers buy the last item in stock at the same moment, and a refresh token shows up in plain text in your log search. The code looked idiomatic. Each bug is a production detail that the happy-path tests never exercised. This page is for developers who build Node.js backends with an agent and want to stop reviewing every middleware by eye. It puts the production details into the prompts, then makes the machine prove them. ## What you'll walk away with from these Node.js recipes - An `AGENTS.md` rule block for TypeScript on Node.js that all three tools follow, and an `npm run check` gate the agent runs before it says "done" - Seven copy-paste prompts: an Express 5 skeleton with clean shutdown, validation and error mapping, refresh-token rotation, rate limiting, a Prisma order transaction, a BullMQ worker, and redacted structured logging - A verification table that tells you which gate catches which bug, so you read gate output instead of the diff - Recovery steps for the six ways agent-written Node.js most often breaks ## Set up Node.js conventions and a gate the agent must pass Two artifacts do most of the work: a rules file the agent reads on every task, and one command that fails when the code is not ready. Write both before you ask for any code. 1. Pin a supported runtime. On the [Node.js release schedule](https://github.com/nodejs/Release/blob/main/schedule.json), Node.js 24 is Active LTS until 2026-10-20, when it enters Maintenance LTS, Node.js 22 is Maintenance LTS, and Node.js 20 reached end of life on 2026-04-30. Node.js 26 is scheduled to become LTS on 2026-10-28. Pin 24 in `.nvmrc` and in `package.json`: ```json { "type": "module", "engines": { "node": ">=24" } } ``` An explicit version stops the agent from reaching for workarounds that current Node.js no longer needs, such as `dotenv` where `node --env-file=.env` works. 2. Add the gate to `package.json`. It is the definition of done for every prompt on this page. ```json { "scripts": { "typecheck": "tsc --noEmit", "lint": "eslint .", "test": "vitest run", "check": "npm run typecheck && npm run lint && npm run test && npm audit --omit=dev --audit-level=high" } } ``` Current majors on npm on 2026-09-26: `express` 5.2.1, `zod` 4.6.5, `vitest` 5.0.2, `supertest` 7.3.0, `pino` 10.3.1, `bullmq` 6.3.9, `@prisma/client` 7.10.0, `testcontainers` 12.1.0. Two packages need care, and the failure-modes section explains why: install `typescript@~6.0.3` rather than `latest` if you use `typescript-eslint` type-aware rules, and install `prisma` and `@prisma/client` at the same version. 3. Put the Node.js rules in `AGENTS.md` at the repository root. Codex reads `AGENTS.md` natively; the tabs below show how Claude Code loads it and how Cursor gets a copy. ```markdown ## Node.js conventions - Node.js 24, ESM, TypeScript strict. Express 5, never Express 4 idioms. - Express 5 forwards rejected promises from handlers to the error middleware. Do not add express-async-errors or a catchAsync wrapper. - Named wildcards only: app.all('/*splat', ...), never app.get('*', ...). - Config comes from one Zod-validated module, src/config.ts. No process.env reads anywhere else. - One PrismaClient for the process, created in src/db.ts. Never per request. - Every error response uses { error: { code, message } }; no stack traces outside development. - Tests: Vitest and supertest. Database tests use Testcontainers, not mocks. - Never edit an existing test assertion, add .skip, or add .only to make a test pass. If a test looks wrong, stop and say why. - Done means `npm run check` passes. Paste its last 20 lines in your final message. ``` The last two rules matter most. The first stops the agent from weakening your tests to reach green; see [protect the oracle](/en/workflows/test/protect-the-oracle/) for why that is the most common way agent work fakes success. The second turns "I think it works" into evidence you can read in ten seconds. ### Wire the rules and gate into each tool The rules and the prompts are identical across tools. What differs is how each tool loads the rules, formats edits, and reviews the result. **Claude Code** Claude Code reads `CLAUDE.md` first, so create one that imports the shared file. The `@path` syntax expands the file into context at launch: ```markdown @AGENTS.md ``` Without a `CLAUDE.md`, Claude Code v2.1.277 and later (both release channels on 2026-10-12) reads `AGENTS.md` directly (v2.1.281 on Bedrock, Google Cloud, Foundry and LLM gateways; toggle under Project instructions in `/config`); the import matters once you also keep Claude-specific rules. Format each TypeScript file the agent edits with a `PostToolUse` hook in `.claude/settings.json` (requires Prettier in `devDependencies`: `npm install -D prettier`): ```json { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "jq -r '.tool_input.file_path' | grep -E '\\.(ts|js)$' | xargs -r npx --no-install prettier --write" } ] } ] } } ``` Give the agent find-references and diagnostics through the `typescript-lsp` plugin from Anthropic's official marketplace. The plugin registers the server only, so install the language server first. Pin `typescript@6`: TypeScript 7.0.2 ships only `tsc` and no `tsserver`, which the language server needs (checked 2026-09-26). In a terminal: ```bash npm install -g typescript-language-server typescript@6 claude plugin install typescript-lsp@claude-plugins-official ``` Before you open a pull request, run `/code-review` in the session for a second opinion on the diff. **Codex** Codex reads `AGENTS.md` directly, so no extra file is needed. Run a task with workspace writes and approval prompts for anything wider (terminal): ```bash codex -s workspace-write -a on-request "Implement POST /api/v1/orders as described in docs/tasks/orders.md. Done means npm run check passes." ``` Review the branch against `main` before you push it: ```bash codex review --base main ``` **Cursor** Create a project rule in Cursor's **Rules** settings with the same list, scoped to `*.ts` files, so the agent loads it whenever it touches TypeScript. Use Plan Mode for the multi-file prompts on this page so you approve the file list before any code is written. Run independent recipes in Worktrees, and let Bugbot review the pull request. Start each tool on its default model and raise the effort setting before you switch models; the [models hub](/en/ecosystem/models/) lists the current defaults. ## Build a production Express 5 API with an agent, step by step Each step is one prompt and the check that proves it. Run them in order: later prompts assume the skeleton and the database module exist. ### How do you scaffold an Express 5 service that shuts down cleanly? The most common first-pass omission is shutdown. The agent calls `app.listen()` and nothing else, so every deploy cuts off in-flight requests and leaves database connections open. **Copy-paste prompt: Express 5 skeleton with clean shutdown** ```text Create an Express 5 service in TypeScript (ESM, Node.js 24). Files: src/config.ts parses process.env with a Zod schema (PORT, DATABASE_URL, REDIS_URL, JWT_SECRET min 32 chars, NODE_ENV) and exits with a readable error if it fails. src/app.ts builds the app without listening: helmet, express.json({ limit: '100kb' }), GET /healthz returning 200, and the API mounted under /api/v1. src/server.ts listens on config.PORT and handles SIGTERM and SIGINT once: stop accepting connections with server.close(), wait for in-flight requests, disconnect Prisma and Redis, then exit 0. Force exit 1 after 10 seconds with an unref'd timer. Add src/server.test.ts: start the server on port 0, send a request to a test route that waits 2 seconds, send SIGTERM mid-request, and assert the request still gets 200 and the process exits 0. Done means npm run check passes. ``` A good answer has this core: ```ts const server = app.listen(config.PORT); function shutdown(signal: NodeJS.Signals) { logger.info({ signal }, 'shutting down'); setTimeout(() => process.exit(1), 10_000).unref(); server.close(async (err) => { await prisma.$disconnect(); await redis.quit(); process.exit(err ? 1 : 0); }); } process.once('SIGTERM', shutdown); process.once('SIGINT', shutdown); ``` You do not need to audit this by eye: the test fails if the request is cut off or the process hangs. Separating `app.ts` from `server.ts` also lets supertest drive the app without opening a port. ### How do you get validation and error responses clients can rely on? Agents trained on Express 4 wrap every handler in `catchAsync` or install `express-async-errors`. Express 5 already routes rejected promises from handlers to the error middleware, so those wrappers are dead code, and the rule in `AGENTS.md` keeps them out. **Copy-paste prompt: Zod validation and one error handler** ```text Add a users resource at /api/v1/users (list, get, create, update, delete). Validate body, params, and query with Zod 4 schemas through one validate({ body, params, query }) middleware. On failure return 422 with { error: { code: 'VALIDATION', message, details: [{ path, message }] } } built from result.error.issues. Define AppError subclasses NotFoundError (404), ConflictError (409), UnauthorizedError (401), ForbiddenError (403). Write one error middleware in src/http/errors.ts that maps them, maps Prisma error P2002 to 409 and P2025 to 404, and returns 500 with a generic message for anything else, logging the real error. Never send err.message or a stack for a 500 when NODE_ENV is production. Handlers are plain async functions: no catchAsync, no express-async-errors. Supertest cases: each status code above, a 500 in production mode whose body contains no stack, and a rejected promise inside a handler reaching the error middleware. List the test cases before the code. ``` The Prisma mapping is the part agents skip. Without it, a duplicate email becomes a 500 and the client retries a request that can never succeed. The test for a production-mode 500 is what proves that no internal detail reaches the client. ### How do you make an agent write refresh-token rotation you can trust? Authentication code is where reading the diff feels safest and is least reliable. Specify the attack cases as tests and let them carry the proof. **Copy-paste prompt: JWT access tokens with refresh-token rotation** ```text Implement authentication in src/auth/ using jose for JWTs and argon2 for password hashes. POST /api/v1/auth/login returns a 15-minute access token (sub, role) and a refresh token. Store only a SHA-256 hash of each refresh token in a RefreshToken table with userId, familyId, expiresAt, and revokedAt. POST /api/v1/auth/refresh issues a new pair and revokes the old token inside one Prisma transaction. If a revoked refresh token is presented again, revoke every token in its family and return 401. POST /api/v1/auth/logout revokes the family. requireAuth middleware verifies the Bearer token and sets req.user; requireRole('admin') returns 403. Send the refresh token only in an HttpOnly, Secure, SameSite=Strict cookie. Tests: login, refresh, reuse of a rotated token revokes the family, an expired access token returns 401, a token signed with another secret returns 401, a user token on an admin route returns 403, and no log line contains a raw token. ``` The reuse test is the one that matters. Without it, an implementation that never revokes the old token passes every other case. For a second, independent check on this code, add a security gate that runs a review agent on every pull request; [agent security gates](/en/ecosystem/observability/agent-security-gates/) covers the options per tool. ### How do you rate-limit an Express API behind a load balancer? The generated limiter usually works locally and fails in production in one of two ways: counts live in process memory, so each replica allows the full limit, or every request appears to come from the load balancer's IP address. **Copy-paste prompt: rate limits with a shared Redis store** ```text Add rate limiting with express-rate-limit 8 and rate-limit-redis using the existing ioredis client, so limits are shared across replicas. Global limiter: 300 requests per minute per IP, standardHeaders 'draft-8', legacyHeaders false. Login: 5 attempts per 15 minutes keyed by IP plus lower-cased email. Forgot-password: 3 per hour keyed by email. Set app.set('trust proxy', 1) because we run behind exactly one load balancer, and explain in a comment what breaks if that number is wrong. 429 responses use our { error } format. Tests with supertest against a Testcontainers Redis: the 6th login attempt returns 429 with a RateLimit header, a different email from the same IP is not blocked, and two app instances sharing one Redis share the count. ``` The two-instance test proves the shared store; a single-process test passes with the in-memory default and proves nothing about production. ### How do you get Prisma transactions that hold under concurrent orders? The agent's first attempt at "check stock, then decrement" reads the stock, compares it in JavaScript, and writes it back. Two concurrent orders both read `stock = 1` and both succeed. A mocked repository cannot show this bug; only a real database under concurrent requests can. **Copy-paste prompt: order transaction that cannot oversell** ```text Implement createOrder(userId, items: { productId, quantity }[]) in src/orders/service.ts with Prisma 7. Inside prisma.$transaction(async (tx) => ...), for each item run tx.product.updateMany({ where: { id, stock: { gte: quantity } }, data: { stock: { decrement: quantity } } }) and throw OutOfStockError if count is 0, so the check and the decrement are one atomic statement. Then create the Order and OrderItems with unitPrice copied from the product, and compute total with Prisma Decimal, never JavaScript numbers. Use the single client from src/db.ts. Write an integration test with @testcontainers/postgresql that applies migrations, sets a product's stock to 1, fires 10 createOrder calls at once with Promise.allSettled, and asserts exactly one succeeds, nine reject with OutOfStockError, and stock is 0. ``` Two Prisma details the agent may not know. Prisma 7 requires a driver adapter: the client is created as `new PrismaClient({ adapter: new PrismaPg({ connectionString }) })` with the `prisma-client` generator and a `prisma.config.ts`, so pool settings belong to the adapter, not to the connection string. And on 2026-09-26 the npm `latest` tag of the `prisma` CLI points at `8.0.0-rc.17`, a release candidate of the new Prisma CLI for the Prisma Developer Platform, while `@prisma/client` `latest` is 7.10.0. Prisma 8 ships its own agent skills (`npx prisma skills sync` installs them into `.claude/skills/`, `.cursor/skills/`, and `.agents/skills/`), which makes it attractive for new projects. Choose it deliberately, not because `npm install prisma` picked it. To let the agent read your real schema instead of guessing column names, connect a database MCP server to a development database with a read-only role. The [database MCP guide](/en/ecosystem/mcp/database-mcp/) compares the servers and their read-only switches. Do not use `@modelcontextprotocol/server-postgres`: npm marks it deprecated. ### How do you move slow work to a BullMQ queue without losing jobs? The agent's first version does the work inside the request, or retries a non-idempotent job and sends the email twice. **Copy-paste prompt: BullMQ worker with retries and clean shutdown** ```text Move image processing out of the upload request into BullMQ 6. Install bullmq and ioredis (ioredis is an optional peer dependency in BullMQ 6). src/queue/images.ts exports a typed Queue with defaultJobOptions { attempts: 5, backoff: { type: 'exponential', delay: 1000 }, removeOnComplete: 1000 }. src/workers/images.ts runs a Worker with concurrency 4 on its own ioredis connection created with maxRetriesPerRequest: null. Make the processor idempotent: it checks whether the output already exists before it writes. BullMQ has no dead-letter queue: on the final failed attempt, record the job in a FailedJob table and log at error level. Schedule the nightly cleanup with queue.upsertJobScheduler, not the old repeat option. On SIGTERM call worker.close() so active jobs finish. Tests against a Testcontainers Redis: a job that throws twice then succeeds completes on attempt 3, a job that always throws lands in FailedJob, and re-running a completed job writes nothing new. ``` The idempotency test is what makes retries safe. Without it, the retry that follows a timeout after a successful write produces duplicate files, emails, or charges. ### How do you get structured logs that never leak secrets? The agent's first version logs `req.body`, so passwords and tokens reach your log search. **Copy-paste prompt: Pino request logging with redaction** ```text Add pino and pino-http. JSON to stdout in every environment; pretty output only when NODE_ENV is development. genReqId takes X-Request-Id when present, otherwise crypto.randomUUID(), and echoes it in the response header. Redact with censor '[REDACTED]' these paths: req.headers.authorization, req.headers.cookie, *.password, *.token, *.refreshToken, *.secret. Pass req.log into services instead of importing a global logger, so every line carries the request ID. Log errors once, in the error middleware. Tests capture log output through a destination stream and assert that a login request's logs contain no password or token value and that every line of one request shares the same reqId. ``` A redaction test is the only way to know redaction works; a path that does not match the real object shape fails silently. For dashboards, alerts, and tracing on top of these logs, see [monitoring and logging patterns](/en/cookbook/devops-recipes/monitoring-logging/). ## How do you verify agent-written Node.js without reading every line? Read the gate output and the test-case lists, not the diff. Each gate below catches a class of bug that looks fine in review. | Gate | Command | What it catches | | --- | --- | --- | | Types | `tsc --noEmit` | Wrong shapes between layers, unhandled `undefined`, misspelled fields | | Lint | `eslint .` with `typescript-eslint` type-aware rules | Floating promises (`no-floating-promises`), misused promises in callbacks (`no-misused-promises`), unsafe `any` | | Unit and HTTP tests | `vitest run` with supertest | Status codes, error bodies, validation, redaction, shutdown | | Integration tests | Testcontainers Postgres and Redis | Wrong SQL, missing unique constraints, races such as overselling, shared rate-limit counts | | Dependencies | `npm audit --omit=dev --audit-level=high` | Known vulnerabilities in runtime dependencies | | Load | `npx autocannon -c 100 -d 30 https://staging.example.com/api/v1/orders` against staging | Pool exhaustion, event-loop blocking, memory growth | | Review agent | `/code-review` (Claude Code), `codex review --base main` (Codex), Bugbot (Cursor) | Logic errors and missing cases the gates cannot express | `no-floating-promises` deserves special mention: a promise the agent forgot to `await` becomes an unhandled rejection, and Node.js has terminated the process on unhandled rejections by default since Node.js 15. For stronger evidence that the tests themselves are good, see [mutation testing and oracle strength](/en/workflows/test/oracle-strength/). Run the first five in CI on every pull request; [CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/) has the workflow file. The engineer who owns the service signs off on three things: the test-case lists, a green gate, and the load-test result. Human reading goes to the hunks the review agent flags and to code that touches authentication, money, or transactions. [Agent PR review](/en/workflows/ship/agent-pr-review/) covers how to split that work across a team. ## When agent-written Node.js breaks in production Each failure below passes a happy-path test suite. Each has a symptom you can detect and a recovery you can apply. - **Overselling or double-processing under load.** Symptom: negative stock, duplicate orders, or duplicate emails after a traffic spike. Cause: read-then-write logic outside a single atomic statement, or a non-idempotent job that was retried. Recovery: add the concurrent Testcontainers test from the Prisma recipe, then prompt: "Find every place that reads a value, decides in JavaScript, and writes it back. Replace each with a conditional update or a row lock, and add a concurrent test for each." - **Connection exhaustion.** Symptom: requests hang, then time out, while database CPU is low. Cause: a `new PrismaClient()` per request or per module, often introduced when the agent adds a new file. Recovery: `grep -rn "new PrismaClient" src/` must return one line. A bare grep exits 0 either way, so make the count the test: add `"check:prisma": "test $(grep -rn 'new PrismaClient' src/ | wc -l) -eq 1"` to `scripts` and append `&& npm run check:prisma` to `check`, so the gate fails on a second client. - **Express 4 idioms in an Express 5 app.** Symptom: the server fails to start with a `path-to-regexp` "Missing parameter name" error, or a `catchAsync` wrapper hides a bug. Cause: training data dominated by Express 4. Recovery: prompt: "Migrate this codebase to Express 5 idioms: name every wildcard route (`/*splat`), delete catchAsync and express-async-errors, and change no behaviour. Done means npm run check passes." - **Everyone is rate-limited at once.** Symptom: a spike of 429s for all users, or express-rate-limit logs a validation error about `X-Forwarded-For`. Cause: `trust proxy` is missing or does not match the number of proxies, so every client shares the load balancer's IP. Recovery: set `trust proxy` to your real hop count and assert in a test that `req.ip` is the client address when `X-Forwarded-For` is set. - **The install breaks on version tags.** Symptom: `npm install` fails with `ERESOLVE` because `typescript-eslint` 8.70.1 declares `typescript` `<6.1.0` while `typescript@latest` is 7.0.2, or `prisma generate` output no longer matches the client because the CLI came from the Prisma 8 release candidate. Recovery: pin both with exact versions in `package.json`, commit the lockfile, and tell the agent in `AGENTS.md` not to change pinned versions without asking. - **The agent weakens a test to reach green.** Symptom: a loosened assertion, a deleted case, or an added `.skip` in the same diff as the fix. Recovery: revert the test file, restate the `AGENTS.md` rule, and make CI fail when a pull request changes an existing `*.test.ts` without a `test-change` label. "The tests pass" is weak evidence for Node.js concurrency. Every recipe on this page passes a single-request test even when it is wrong. Treat the concurrent integration tests and the load test as part of the definition of done, not as optional hardening. ## Where to go next with Node.js services - Make the repository agent-ready first, if it is not yet: [agent-ready codebase](/en/workflows/harness/agent-ready-codebase/). - Design the API contract before the handlers: [API development patterns](/en/cookbook/backend-recipes/api-patterns/). - Harden the data layer: [ORM best practices](/en/cookbook/database-recipes/orm-patterns/) and [database migration patterns](/en/cookbook/database-recipes/migration-patterns/). - Ship the service: [Docker patterns](/en/cookbook/devops-recipes/docker-patterns/) and [CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/). - Decide what the agent may run unattended: [permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/). - Compare with another backend stack: [Python workflow recipes](/en/cookbook/backend-recipes/python-patterns/), or return to the [backend recipes overview](/en/cookbook/backend-recipes/). --- # PHP Development Patterns URL: https://developertoolkit.ai/en/cookbook/backend-recipes/php-patterns/ Description: Agent recipes for Laravel 13 and Symfony — Laravel Boost context, tests first, Pint, PHPStan and PHPUnit as the gate, strict Eloquent and safe legacy rewrites. PHP development patterns for AI coding agents are the settings, prompts and gates that make Claude Code, Codex and Cursor ship Laravel 13 and Symfony code accepted on evidence: Laravel Boost for framework context, tests written before the code, Pint, PHPStan and PHPUnit as the definition of done, strict Eloquent against N+1 queries, and characterization tests before any legacy rewrite. This page is for PHP developers who already let an agent write most of a feature, and for tech leads who want the same gates enforced in CI for the whole team. The situation it fixes: the agent's pull request is green, but its `composer.json` pins PHPUnit 13 on PHP 8.3, half its tests use `@test` annotations that PHPUnit 13 never runs, the product list lazy-loads a category per row, and the "modernized" legacy repository still interpolates `$id` into SQL. The recipes below make the agent run into those problems on every turn, so you review test results and gate output instead of reading every line. ## What these PHP recipes give you - A version table with the PHP constraint each current package really needs. - Laravel Boost wired into Claude Code, Codex and Cursor, with its two sharp edges named. - An `AGENTS.md` for a Laravel app and a prompt that drafts one from your repository. - A tests-first loop for a thin-controller Laravel endpoint. - A Claude Code `Stop` hook and a GitHub Actions job that refuse "done" until Pint, PHPStan and PHPUnit pass. - Eloquent strict mode plus a query-count test, so N+1 queries fail tests instead of production. - A legacy `mysql_*` modernization recipe that pins behaviour first and checks for surviving SQL injection. - A PHPUnit 13 test that runs without deprecations, and mutation testing with Infection to show the tests can fail. ## Which PHP, Laravel and Symfony versions do these recipes assume? Agents mix APIs from Laravel 8 to 13 and from PHPUnit 9 to 13, because their training data does. Tell the agent the versions and let `composer.lock` pin them. These were the latest stable releases on Packagist in late September 2026: | Package | Latest release | PHP it requires | | --- | --- | --- | | `laravel/framework` | 13.33.0 (2026-09-22); 13.0.0 shipped 2026-03-17 | `^8.3` | | `phpunit/phpunit` | 13.3.5 (2026-09-25) | `>=8.4.1` | | `symfony/symfony` | 8.1.7 (2026-09-15); 7.4.19 on the long-term-support branch | `>=8.4.1` (8.1), `>=8.2` (7.4) | | `phpstan/phpstan` · `larastan/larastan` | 2.2.16 · 3.12.2 | `^7.4\|^8.0` · `^8.2` | | `laravel/pint` | 1.32.1 | `^8.3.0` | | `laravel/boost` | 2.10.0 (2026-09-23) | `^8.2` | | `infection/infection` | 0.35.4 (2026-09-02) | `^8.3` | The row that bites: Laravel 13 runs on PHP 8.3, but PHPUnit 13 needs PHP 8.4.1 or later. The fresh Laravel 13 skeleton therefore pins `"phpunit/phpunit": "^12.5.12"`. If the agent "upgrades" to PHPUnit 13 while `composer.json` still says `"php": "^8.3"`, Composer cannot resolve the dependencies on a PHP 8.3 machine. Pick one: stay on PHPUnit 12.5 for PHP 8.3, or require `"php": "^8.4"` and move to PHPUnit 13. ## How do you give the agent Laravel context with Laravel Boost? Laravel Boost is Laravel's own package for AI agents. It writes framework guidelines and skills into your repository and runs a local MCP server. A new Laravel 13 skeleton already ships an `AGENTS.md` and a `CLAUDE.md` that tell the agent to install Boost before doing anything else, so an agent opening a fresh app asks for it anyway. Install it from the application root: ```bash composer require laravel/boost --dev php artisan boost:install ``` `boost:install` asks which agents you use and which parts to install (`--guidelines`, `--skills` and `--mcp` select them non-interactively). The defaults in the Boost 2.10.0 source, each overridable in `config/boost.php`: | Agent | MCP server registered in | Guidelines written to | Skills written to | | --- | --- | --- | --- | | Claude Code | `.mcp.json` | `AGENTS.md` | `.claude/skills` | | Codex | `.codex/config.toml` | `AGENTS.md` | `.agents/skills` | | Cursor | `.cursor/mcp.json` | `AGENTS.md` | `.cursor/skills` | The MCP server (`php artisan boost:mcp`) gives the agent tools that read the database schema, run read-only SQL, search documentation for the exact package versions in your lock file, read the last exception and the application log, and execute PHP through Tinker. The schema tool is the one that changes results most: generated migrations, casts and factories stop guessing column names. Run `php artisan boost:update` after upgrading Laravel or Boost to refresh the guidelines and skills. Two things the Boost docs do not put in front of you: - **Boost only starts in a local environment or with `APP_DEBUG=true`.** On a staging or production-like host, where `APP_ENV` is not `local` and `APP_DEBUG=false`, the MCP server does not register its tools, so an agent running there has no schema access. That is the right behaviour; do not turn debug on to "fix" it. - **The SQL tool is read-only; Tinker is not.** Boost's query tool rejects anything but `SELECT`, `SHOW`, `EXPLAIN`, `DESCRIBE` and `WITH … SELECT`, and runs it in a transaction it rolls back. The Tinker tool runs arbitrary PHP in your application, including `Product::query()->delete()`. Point `.env` at a disposable local database, never a copy of production with customer data. On Symfony there is no Boost equivalent. Write the `AGENTS.md` below by hand and connect a read-only database server from [database MCP servers](/en/ecosystem/mcp/database-mcp/) so the agent reads the real schema. ## What goes in AGENTS.md for a Laravel app? Boost's guidelines cover Laravel conventions. Your file adds what only your codebase knows: the commands the agent must run, in the order it must run them, and the few rules a generic model gets wrong here. Leave out anything Pint or PHPStan already enforces. Put it in the file Boost writes to, above or below Boost's generated block. ```markdown title="AGENTS.md" # Shop (Laravel 13, PHP 8.4, MySQL 8, PHPUnit 13) ## Commands (run from the repo root) - One test: `php artisan test --filter=ProductIndexTest` - Style check: `vendor/bin/pint --test` (fix with `vendor/bin/pint --dirty`) - Static analysis: `vendor/bin/phpstan analyse` (Larastan, level 8) - Full gate: `vendor/bin/pint --test && vendor/bin/phpstan analyse && php artisan test` ## Definition of done The full gate passes. Report the command you ran and its last lines. ## Rules - Create classes with `php artisan make:*`, never by hand; every model gets a migration and a factory. - Controllers only validate (Form Request), call one service method and return an API Resource. - Tests are the specification. If a test fails, fix app/, not tests/. Ask before changing an assertion. - Test attributes (`#[Test]`, `#[DataProvider]`), never doc-comment annotations. - Every query that feeds a collection eager-loads with `with()`; strict mode throws on lazy loading. - Raw SQL only through bound parameters; never interpolate a variable into a query string. - Money is integer cents (`*_cents`), never float. ``` Each tool loads the file differently: **Claude Code** Create a `CLAUDE.md` whose first line imports the shared file, then add any Claude-only lines below it: ```markdown title="CLAUDE.md" @AGENTS.md ``` The skeleton's `CLAUDE.md` holds only the Boost bootstrap text, so replace it after `boost:install`. Claude Code 2.1.277 and later also read `AGENTS.md` directly when a project has no `CLAUDE.md` (first-party sessions, both release channels on 2026-10-12); the import works on every version and channel. **Codex** Codex reads `AGENTS.md` before it starts work. Since codex-cli 0.150.0, a project Codex does not trust does not supply its `AGENTS.md`, so trust the repository when Codex asks. **Cursor** Add an always-applied project rule (the format is on [project rules in Cursor](/en/cursor-ide/quick-start/project-rules/)) that repeats the Commands and Rules sections above, and commit it. Then ask the agent to quote the Definition of done back to you, which proves the rule loaded. **Copy-paste prompt: draft AGENTS.md from an existing PHP app** ```text Read composer.json, composer.lock, phpunit.xml, phpstan.neon (or phpstan.neon.dist), pint.json if present, .env.example, and list the directories under app/ (or src/), tests/ and database/. Write AGENTS.md with: (1) a one-line description naming the PHP, framework and PHPUnit versions from composer.lock and the database; (2) the exact commands for one test, the style check, static analysis and the full gate, as they work in THIS repo; (3) a "Definition of done" line; (4) at most eight rules, each a convention this codebase visibly follows that a generic Laravel or Symfony model would get wrong. Do not restate what Pint or PHPStan already enforce. Run every command you list and tell me which ones failed and why. ``` [Shared agent rules](/en/cto-scorecard-guide/shared-agent-rules/) explains how to keep one source of truth when a team uses all three tools. ## How do you build a thin-controller Laravel endpoint the agent cannot fake? Asking for "a Product API" gets you a 200-line controller with query building, validation and response shaping inline, plus tests written afterwards to match whatever the code does. Reverse the order. Write the acceptance criteria, have the agent turn them into failing feature tests, review only the tests, and then let it implement against tests it may not edit. [Acceptance criteria](/en/workflows/plan/acceptance-criteria/) covers writing the criteria themselves. **Copy-paste prompt: failing feature tests from acceptance criteria** ```text Acceptance criteria for GET /api/v1/products: - Returns 15 products per page by default; ?per_page accepts 1-100, anything else is a 422. - ?search filters by name, case-insensitive. - Each item has id, name, price_cents and category {id, name}. - Anonymous requests get 401; more than 60 requests a minute from one user get 429. Write tests/Feature/ProductIndexTest.php with one test per criterion using PHPUnit attributes, RefreshDatabase and model factories. Create the factories if they are missing, with php artisan make:factory. Do not write any application code. Run php artisan test --filter=ProductIndexTest and show me that every test fails for the right reason (404 or missing class), not because of a typo in the test. ``` Read the tests, not the implementation that follows. Then: **Copy-paste prompt: implement a thin-controller endpoint against locked tests** ```text Make every test in tests/Feature/ProductIndexTest.php pass without modifying anything under tests/. Generate classes with php artisan make:* (model with migration and factory, controller with --api, form request, resource). The controller validates through a Form Request, calls ProductService::paginate() and returns ProductResource::collection(). The service owns the query, including with('category'). Register the route under /api/v1 with auth:sanctum and throttle:60,1 (run php artisan install:api first if Sanctum is not installed). When done, run vendor/bin/pint --test, vendor/bin/phpstan analyse and php artisan test, and paste the last lines of each. ``` The shape to accept is a controller that only delegates: ```php // app/Http/Controllers/Api/V1/ProductController.php final class ProductController extends Controller { public function __construct(private readonly ProductService $products) {} public function index(IndexProductRequest $request): AnonymousResourceCollection { return ProductResource::collection( $this->products->paginate( perPage: $request->integer('per_page', 15), search: $request->string('search')->toString(), ), ); } } ``` `RefreshDatabase` runs your migrations before the tests, so a model generated without its migration fails here rather than in production. ## How do you stop the agent from declaring done before the gate passes? An instruction in `AGENTS.md` is advice; a hook or a CI check is a gate. Claude Code gets a local gate from the `Stop` hook below. Codex has hooks with a `Stop` event too (codex-cli 0.157.1, with persisted trust required), and Cursor has Hooks, but the setups below give those two a prompt and a rule, so for them the CI job after the tabs is the gate. **Claude Code** A `Stop` hook runs when Claude finishes responding. Exit code 2 blocks the stop and shows the hook's stderr to Claude, which keeps working: ```bash title=".claude/hooks/php-gate.sh" #!/usr/bin/env bash # Refuse "done" until Pint, PHPStan and PHPUnit pass. input=$(cat) # Already continuing because of this hook: stop and report instead of looping. [ "$(echo "$input" | jq -r '.stop_hook_active')" = "true" ] && exit 0 cd "$CLAUDE_PROJECT_DIR" || exit 0 # Skip only when the branch has no code, test or schema changes against its base, # committed, uncommitted or untracked: committing during the turn does not hide work. dirs="app src tests database config routes" base=$(git merge-base HEAD origin/HEAD 2>/dev/null || git merge-base HEAD origin/main 2>/dev/null || git rev-parse HEAD) if git diff --quiet "$base" -- $dirs && [ -z "$(git ls-files --others --exclude-standard -- $dirs)" ]; then exit 0; fi if ! out=$(vendor/bin/pint --test 2>&1); then echo "Pint found style violations. Run vendor/bin/pint --dirty:" >&2 echo "$out" | tail -20 >&2; exit 2 fi if ! out=$(vendor/bin/phpstan analyse --no-progress --error-format=raw 2>&1); then echo "PHPStan failed. Fix the code; never add ignoreErrors or @phpstan-ignore:" >&2 echo "$out" | head -30 >&2; exit 2 fi if ! out=$(php artisan test 2>&1); then echo "Tests failed. Fix app/, never tests/:" >&2 echo "$out" | tail -40 >&2; exit 2 fi exit 0 ``` The script needs `jq`; on Symfony replace `php artisan test` with `vendor/bin/phpunit`. The skip compares the branch with its base (`origin/HEAD`, else `origin/main`), so work the agent commits during the turn is still checked. The cost: on a branch that already has PHP changes, the gate runs on every turn, including pure questions. If neither remote ref exists, it falls back to uncommitted changes only. Because it exits 0 when `stop_hook_active` is `true`, a failing gate forces one retry, and then Claude stops and reports instead of looping on a test that cannot pass. Register it in `.claude/settings.json` and make it executable (`chmod +x`): ```json title=".claude/settings.json" { "hooks": { "Stop": [ { "hooks": [ { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/php-gate.sh", "timeout": 600 } ] } ] } } ``` [Hooks automation](/en/claude-code/automate/hooks-automation/) covers retry counting and the other events. **Codex** `composer install` needs the network, and the `workspace-write` sandbox has none unless you enable it. Install dependencies first, outside the agent, then run the loop: ```bash composer install codex exec --sandbox workspace-write "Make every test in tests/Feature/ProductIndexTest.php pass without modifying tests/. Finish only when vendor/bin/pint --test, vendor/bin/phpstan analyse and php artisan test all pass; print the last lines of each." ``` The skeleton's `phpunit.xml` runs tests on in-memory SQLite, which works inside the sandbox. If your tests need a MySQL server the sandbox cannot reach, run those in CI. When the task is adding a package, enable network for that run only with `-c sandbox_workspace_write.network_access=true`. **Cursor** Paste the implementation prompt into the agent, in Plan Mode first if the change touches models, controllers and migrations together. The Definition of done in your project rule tells the agent to run the full gate before it reports back, but a rule is still advice. The mechanical gate for Cursor is the CI job below, plus Bugbot if your team uses it for review. Whatever runs locally, CI decides. This job runs with a read-only token and fails when the pull request edits an existing test without a reviewer's label: ```yaml title=".github/workflows/php-gates.yml" name: php-gates on: pull_request: types: [opened, synchronize, reopened, labeled, unlabeled] permissions: contents: read jobs: gates: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: persist-credentials: false fetch-depth: 2 # the PR merge commit and its base parent - name: Existing tests unchanged if: ${{ !contains(github.event.pull_request.labels.*.name, 'test-change-approved') }} run: | changed=$(git diff --name-only --diff-filter=MDR HEAD^1 HEAD -- tests/) if [ -n "$changed" ]; then echo "Existing tests modified, moved or deleted; a reviewer must add the test-change-approved label:" echo "$changed"; exit 1 fi - uses: shivammathur/setup-php@v2 with: php-version: '8.4' coverage: none - run: composer install --no-interaction --no-progress --prefer-dist - run: composer audit - run: vendor/bin/pint --test - run: vendor/bin/phpstan analyse --no-progress - run: cp .env.example .env && php artisan key:generate - run: php artisan test ``` New test files pass the "Existing tests unchanged" step; edits, renames and deletions under `tests/` fail it until a person reviews them and adds the `test-change-approved` label, which starts a fresh run. The step is only a gate if the pull request cannot remove it: GitHub runs the workflow file from the pull request itself, so put `/.github/` under `CODEOWNERS` and require that review in branch protection or a ruleset. [Protecting the oracle](/en/workflows/test/protect-the-oracle/) goes further, with deny rules that stop the agent from editing tests in the first place. ## How do you catch N+1 queries in agent-written Eloquent? A typical regression in agent-written Laravel is a resource or Blade loop that lazy-loads a relationship per row: fast with five rows in the demo, a timeout with 500 in production. Turn it into an exception outside production: ```php // app/Providers/AppServiceProvider.php use Illuminate\Database\Eloquent\Model; public function boot(): void { // Throws on lazy loading, on assigning non-fillable attributes and on reading missing attributes. Model::shouldBeStrict(! $this->app->isProduction()); } ``` With strict mode on, any test that touches a lazy-loaded relationship throws `LazyLoadingViolationException`, and the Stop hook and CI job above turn that into a failed gate. Strict mode does not catch a per-row query that is not a relationship, such as a `count()` inside an accessor, so pin the query count of each list endpoint as well: **Copy-paste prompt: prove an endpoint's query count does not grow** ```text For GET /api/v1/products, add a test to tests/Feature/ProductIndexTest.php that seeds 3 products, records the query count with DB::enableQueryLog(), then seeds 40 more and asserts the count is identical. Then add a second test that uses $this->expectsDatabaseQueryCount() with the count you measured. If the count grows with rows, fix the query in ProductService (with(), withCount(), loadMissing()) and never the test. Show me the SQL from the query log before and after your fix. ``` ## How do you add caching without serving stale data? The naive caching prompt scatters `Cache::remember()` across the codebase with no invalidation, and the product page shows last week's price. Make invalidation, and the test that proves it, part of the request: **Copy-paste prompt: Redis cache with tested invalidation** ```text Add caching to ProductService::find(int $id) with the Laravel Cache facade on the redis store: key "product:{id}", TTL one hour, tagged "products" and "category:{category_id}". Do not cache null. Invalidate in exactly one place: a ProductObserver handling saved and deleted, which forgets the item key and flushes the category tag. Write a feature test that reads a product, updates its price through the API, reads it again and asserts the new price. Tell me which reads can still be stale after your change and for how long. ``` Cache tags only work on stores that support them, such as Redis and Memcached; the `file` and `database` stores throw. Run the test against the store you use in production, not the `array` store that `phpunit.xml` sets by default. ## How do you modernize legacy mysql_* code with an agent? The `mysql_*` extension was removed in PHP 7.0, so code that still calls it runs only on PHP 5.x. The syntax conversion is mechanical, so agents handle it quickly; the risk is elsewhere. The agent can "modernize" the syntax while keeping `"... WHERE id = $id"` inside a PDO call, or silently change what the function returns for an edge case your callers depend on. So pin today's behaviour first with [characterization tests](/en/workflows/test/characterization-tests/), and lock them before the rewrite. The old code cannot run on the PHP 8.4 toolchain the rest of this page uses, so record its behaviour where it still runs: call the function for each case in a PHP 5.6 container (the official `php:5.6-cli` image plus `docker-php-ext-install mysql`, pointed at a disposable copy of the database) and save the return values as a JSON fixture. The tests then run on PHP 8.4 and assert that the new code returns what the fixture recorded. **Claude Code** Run from the repo root so Claude Code can search every caller, not only the open file: ```bash claude "Modernize get_user() in legacy/users.php. First record its current behaviour: write scripts/record-get-user.php, which calls get_user() for an existing id, a missing id, id 0 and a non-numeric string and writes the return values to tests/Characterization/fixtures/get_user.json; run it in a php:5.6-cli container with the mysql extension against a disposable copy of the test database, and show me the fixture. Then write tests/Characterization/GetUserTest.php, which runs on PHP 8.4 and asserts that the new code returns data equivalent to those recorded values (same fields, same result for a missing id). Then create App\\Repository\\UserRepository::findById(int \$id): ?User using PDO prepared statements with bound parameters, wrap PDOException in RepositoryException, update every caller repo-wide, and make the characterization tests pass against the new code without editing them. Finish with vendor/bin/phpstan analyse and the full test suite." ``` **Codex** Run it non-interactively in the workspace sandbox so the change stays inside the repository until you review the diff: ```bash codex exec --sandbox workspace-write "Modernize get_user() in legacy/users.php. First record its current behaviour: write scripts/record-get-user.php, which calls get_user() for an existing id, a missing id, id 0 and a non-numeric string and writes the return values to tests/Characterization/fixtures/get_user.json; run it in a php:5.6-cli container with the mysql extension against a disposable copy of the test database, and show me the fixture. Then write tests/Characterization/GetUserTest.php, which runs on PHP 8.4 and asserts that the new code returns data equivalent to those recorded values (same fields, same result for a missing id). Then create App\\Repository\\UserRepository::findById(int \$id): ?User with PDO prepared statements and bound parameters, wrap PDOException in RepositoryException, update every caller, and make the characterization tests pass without editing them. Finish with vendor/bin/phpstan analyse and the full test suite." ``` **Cursor** Open `legacy/users.php`, switch the agent to Plan Mode and paste the Claude Code prompt from the first tab. Review the plan's list of callers before it writes code: a missed caller in a file the agent did not open is the usual failure. Then let it execute and run the suite. The target shape has a bound parameter and a typed return: ```php // app/Repository/UserRepository.php declare(strict_types=1); namespace App\Repository; use App\Entity\User; use PDO; use PDOException; final class UserRepository { public function __construct(private readonly PDO $connection) {} public function findById(int $id): ?User { try { $statement = $this->connection->prepare( 'SELECT id, email, name, created_at FROM users WHERE id = :id' ); $statement->execute(['id' => $id]); $row = $statement->fetch(PDO::FETCH_ASSOC); return $row === false ? null : User::fromArray($row); } catch (PDOException $e) { throw new RepositoryException("Failed to fetch user {$id}", 0, $e); } } } ``` Before you merge, run a first-pass search for SQL that still builds a query from a variable. This grep flags query-building calls (PDO, mysqli and the Laravel raw-SQL methods) whose argument list contains a variable (`$`). A concatenation with a constant or a function call is not flagged: ```bash grep -rnE '(query|prepare|exec|select|statement|whereRaw|selectRaw|orderByRaw)\s*\([^)]*\$' app/ src/ legacy/ ``` A hit is a line to fix or justify; an empty result is not proof. The grep cannot follow a query string built on an earlier line, a heredoc, or a value passed in from another function. The real gate is a data-flow check in CI: Psalm's taint analysis (`vendor/bin/psalm --taint-analysis`) traces request input into SQL sinks such as `PDO::exec()`, or a Semgrep rule does the same for your query helpers. Together with the characterization tests above, that is the evidence a reviewer accepts. For the wider strategy (strangler seams, sequencing a large rewrite), see [legacy modernization](/en/workflows/build/legacy-modernization/). ## How do you know the agent's PHPUnit tests would catch a bug? Agents write tests that pass. Whether they fail when the code is wrong is a separate question, and two PHPUnit changes make agent tests quietly weaker than they look: - **Annotations no longer run.** PHPUnit 12 removed doc-comment metadata. A method named `annotation_only()` with only a `/** @test */` above it is not a test in PHPUnit 13: the runner skips it without an error, so the count simply drops. - **Prophecy is not bundled.** PHPUnit 10 and later ship no Prophecy integration; `ProphecyTrait` comes from `phpspec/prophecy-phpunit`. Without that package the test class does not load. PHPUnit's own `createMock()` and `createStub()` need nothing extra. Ask for the shape below. `Order` here is a plain domain value object with an `(int $id, OrderStatus $status)` constructor, not an Eloquent model, whose constructor takes an attributes array. With that class, it passes on PHPUnit 13.3.5 with zero deprecations. Note `expects()` before `with()` on `find`: PHPUnit 13 deprecates `with()` on a mock without `expects()`, and PHPUnit 14 will reject it. ```php // tests/Unit/OrderServiceTest.php declare(strict_types=1); namespace Tests\Unit; use App\Domain\Order; use App\Enums\OrderStatus; use App\Exceptions\InvalidOrderStateException; use App\Repositories\OrderRepository; use App\Services\{NotificationService, OrderService}; use PHPUnit\Framework\Attributes\{DataProvider, Test}; use PHPUnit\Framework\TestCase; final class OrderServiceTest extends TestCase { #[Test] public function it_completes_a_processing_order_and_notifies_once(): void { $order = new Order(123, OrderStatus::Processing); $orders = $this->createMock(OrderRepository::class); $orders->expects($this->once())->method('find')->with(123)->willReturn($order); $orders->expects($this->once())->method('save')->with($order); $notifications = $this->createMock(NotificationService::class); $notifications->expects($this->once())->method('sendOrderCompleted')->with($order); $result = (new OrderService($orders, $notifications))->completeOrder(123); $this->assertSame(OrderStatus::Completed, $result->status); } #[Test] #[DataProvider('nonCompletableStatuses')] public function it_refuses_to_complete_from(OrderStatus $status): void { $orders = $this->createStub(OrderRepository::class); $orders->method('find')->willReturn(new Order(123, $status)); $notifications = $this->createMock(NotificationService::class); $notifications->expects($this->never())->method('sendOrderCompleted'); $this->expectException(InvalidOrderStateException::class); (new OrderService($orders, $notifications))->completeOrder(123); } public static function nonCompletableStatuses(): array { return [ 'completed' => [OrderStatus::Completed], 'cancelled' => [OrderStatus::Cancelled], 'refunded' => [OrderStatus::Refunded], ]; } } ``` Mutation testing answers the question directly. Infection changes your code (flips a condition, removes a call) and reruns the tests; a mutant that survives is a bug your tests would miss. It needs a coverage driver (PCOV or Xdebug). Run it on the lines the agent changed: ```bash vendor/bin/infection --git-diff-filter=AM --git-diff-base=origin/main --min-msi=80 --threads=max ``` **Copy-paste prompt: kill surviving mutants** ```text Run vendor/bin/infection --git-diff-filter=AM --git-diff-base=origin/main --threads=max --show-mutations=max. For each escaped mutant, explain which behaviour it changes and add or strengthen a test in tests/ so the mutant is killed. Do not change any file under app/ and do not delete or weaken an existing assertion. Rerun Infection and report the Mutation Score Indicator before and after. ``` A tech lead signs off on the test changes and on the mutation score threshold, not on every line of the implementation. See [oracle strength](/en/workflows/test/oracle-strength/) for choosing that threshold. ## What changes on Symfony? The recipes carry over; the primitives change. Symfony 8.1 needs PHP 8.4.1, and 7.4 is the long-term-support branch for teams that cannot follow six-month minors. Generate code with `php bin/console make:*` (from `symfony/maker-bundle`) instead of writing it by hand, and generate migrations from the entity diff with `php bin/console doctrine:migrations:diff` rather than letting the agent write SQL. Doctrine's lazy loading does not throw the way strict Eloquent does, so a query-count test is your only N+1 gate. Assert it in a functional test through the profiler's Doctrine collector: ```php // tests/Controller/ProductIndexTest.php use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; final class ProductIndexTest extends WebTestCase { public function testListQueryCountStaysFlat(): void { $client = static::createClient(); // Seed 40+ products here with your fixtures or factories. $client->enableProfiler(); $client->request('GET', '/api/products'); self::assertResponseIsSuccessful(); $profile = $client->getProfile(); self::assertNotFalse($profile, 'The profiler is not enabled in the test environment.'); self::assertLessThanOrEqual(3, $profile->getCollector('db')->getQueryCount()); } } ``` `getProfile()` returns `false` unless the profiler is enabled in the `test` environment; the `symfony/web-profiler-bundle` recipe sets `framework.profiler.collect: false` there, and `enableProfiler()` switches collection on for the next request only. Pick the bound (3 here) by measuring the endpoint with a handful of rows, then seed many more and keep the assertion unchanged. Tests run with `vendor/bin/phpunit`, so swap that into the Stop hook and CI job. ## What breaks when agents write PHP? **Common failures and how to recover** **Composer cannot resolve after a PHPUnit bump.** Symptom: `phpunit/phpunit 13.x requires php >=8.4.1` on a PHP 8.3 machine. Recovery: either return to `^12.5` or raise `"php"` to `^8.4` in `composer.json` and the CI `php-version` together. **The test count dropped and nobody noticed.** Cause: the agent wrote `/** @test */` methods without the `test` prefix, which PHPUnit 12 and later skip. Recovery: ask the agent to convert every annotation to attributes, and compare the test count before and after each change. **`Trait "Prophecy\PhpUnit\ProphecyTrait" not found`.** Recovery: rewrite with `createMock()`, or add `phpspec/prophecy-phpunit` to `require-dev` if the team wants Prophecy. **`LazyLoadingViolationException` in tests after enabling strict mode.** That is strict mode working. Recovery: eager-load in the service query, not with a `load()` inside the resource. **The agent's migration is missing.** Symptom: `no such table` in feature tests. Recovery: generate with `php artisan make:model Product --migration --factory` and keep `RefreshDatabase` in feature tests so the gap fails locally. **PSR-4 casing works on a Mac and breaks in CI.** The agent writes `App\services\OrderService` in `app/Services/`. macOS file systems are case-insensitive by default; Linux is not. Recovery: `composer dump-autoload --optimize --strict-psr` fails on the mismatch, so add it to the gate. **SQL injection survives the modernization.** Cause: the query is built on an earlier line or with concatenation, which a grep does not see. Recovery: run Psalm's taint analysis or a Semgrep rule on every legacy change in CI, keep the grep as a quick local check, and reject any `prepare()` whose string contains `$`. **The agent has no Boost tools on staging or production-like hosts.** Boost does not start when `APP_ENV` is anything other than `local` and `APP_DEBUG=false`. A CI job that copies the skeleton's `.env.example` (as the one above does) gets `APP_ENV=local`, so Boost can start there. Recovery: none needed; run schema-dependent work locally. **`composer install` fails inside `codex exec`.** The `workspace-write` sandbox has no network by default. Recovery: install before the session, and enable network for one run only when adding a package is the task. ## Where to go next with PHP and agents - [API development patterns](/en/cookbook/backend-recipes/api-patterns/) — Contracts, versioning and error shapes for the REST endpoints on this page - [Database MCP servers](/en/ecosystem/mcp/database-mcp/) — Give the agent read-only access to the real schema on Symfony and other stacks - [Characterization tests](/en/workflows/test/characterization-tests/) — Pin legacy behaviour before an agent refactors it - [Unit testing workflows](/en/workflows/test/unit-testing/) — Agent-written unit tests that fail when the code is wrong --- # Python Workflow Recipes URL: https://developertoolkit.ai/en/cookbook/backend-recipes/python-patterns/ Description: Prompts and gates for agent-written Python backends: FastAPI lifespan, Pydantic v2, async SQLAlchemy 2.1, Celery, httpx, structlog, and Django tenant scoping. Python backend recipes for AI coding agents are prompts plus verification gates that make Claude Code, Codex, and Cursor produce production-ready FastAPI and Django services: validated settings, Pydantic v2 schemas, async SQLAlchemy 2.1 that holds under concurrency, idempotent Celery tasks, resilient HTTP clients, and redacted logs. You accept the output on gate evidence, not on line-by-line reading. Your FastAPI service passes every test the agent wrote. Then the first load test freezes the event loop because a handler calls `requests.get()`, an async query raises `MissingGreenlet` on a relationship nobody loaded, and a retried Celery task charges a customer twice. The code looked idiomatic, and the tests ran against SQLite with mocks, so they never had a chance to catch any of it. This page is for developers who build Python backends with an agent and want to stop reviewing every handler by eye. It puts the production details into the prompts, then makes the machine prove them. ## What these Python recipes give you - An `AGENTS.md` rule block for typed, async Python that all three tools follow, and a `make check` gate the agent runs before it says "done" - Eight copy-paste prompts: a FastAPI skeleton with lifespan and settings, Pydantic v2 validation, an async SQLAlchemy repository that cannot oversell, idempotent Celery tasks, an httpx client with timeouts and retries, structlog with redaction, a Django REST Framework API with tenant scoping, and a legacy-idiom cleanup - A verification table that tells you which gate catches which bug, so you read gate output instead of the diff - Recovery steps for the seven ways agent-written Python most often breaks ## Set up Python conventions and a gate the agent must pass Two artifacts do most of the work: a rules file the agent reads on every task, and one command that fails when the code is not ready. Write both before you ask for any code. 1. Pin the interpreter and the toolchain. Python 3.14 is the current stable line, and [PEP 790](https://peps.python.org/pep-0790/) schedules Python 3.15.0 for 2026-10-01. Pin 3.14 until your dependencies declare 3.15 support. With [uv](https://docs.astral.sh/uv/) (terminal): ```bash uv python pin 3.14 uv add fastapi "pydantic-settings" "sqlalchemy[postgresql-asyncpg]" alembic structlog httpx uv add --dev pytest pytest-asyncio pytest-cov "testcontainers[postgres]" respx ruff mypy ``` Current releases on PyPI on 2026-09-26: `fastapi` 0.141.1, `pydantic` 2.13.5, `pydantic-settings` 2.15.0, `sqlalchemy` 2.1.1, `alembic` 1.20.0, `pytest` 9.1.1, `pytest-asyncio` 1.4.0, `ruff` 0.16.9, `mypy` 2.3.1, `testcontainers` 4.15.0, `celery` 5.6.3, `django` 6.1.1. The `[postgresql-asyncpg]` extra matters: SQLAlchemy 2.1 no longer installs `greenlet` by default, and the async extension cannot run without it. 2. Configure the tools in `pyproject.toml`. Two settings do most of the catching: the `ASYNC` rules flag blocking calls inside `async def`, and `filterwarnings = ["error"]` turns every deprecation warning, including Pydantic v1 idioms, into a failing test. ```toml [tool.ruff] target-version = "py314" [tool.ruff.lint] select = ["E", "F", "I", "B", "UP", "ASYNC", "S", "RUF"] [tool.ruff.lint.per-file-ignores] "tests/**" = ["S101"] [tool.mypy] strict = true plugins = ["pydantic.mypy"] [tool.pytest.ini_options] asyncio_mode = "auto" asyncio_default_fixture_loop_scope = "function" filterwarnings = ["error"] ``` 3. Add the gate. It is the definition of done for every prompt on this page. In a `Makefile` (recipe lines start with a tab): ```make check: uv run ruff format --check . uv run ruff check . uv run mypy app uv run pytest --cov=app --cov-fail-under=80 uv export --locked --no-dev --no-emit-project --format requirements.txt -o .audit.txt uvx pip-audit --disable-pip -r .audit.txt ``` The last two lines audit the locked runtime dependencies without installing them. Add `.audit.txt` to `.gitignore`. 4. Put the Python rules in `AGENTS.md` at the repository root. Codex reads `AGENTS.md` natively; the tabs below show how Claude Code and Cursor pick up the same text. ```markdown ## Python conventions - Python 3.14, uv, fully typed. mypy --strict must pass; no bare `Any`, no `# type: ignore` without a reason in the same comment. - Pydantic v2 only: model_config = ConfigDict(...), @field_validator, @model_validator, model_dump(). Never class Config, @validator, or .dict(). - Settings come from one pydantic-settings class in app/core/config.py. No os.getenv or os.environ anywhere else. - Inside async def: no requests, no time.sleep, no sync SQLAlchemy sessions, no blocking file I/O. Use httpx.AsyncClient, asyncio.sleep, AsyncSession. - SQLAlchemy 2.x style: select(), Mapped[], mapped_column(). Relationships use lazy="raise"; load them explicitly with selectinload(). - Every outbound HTTP call has an explicit timeout. - Tests: pytest with pytest-asyncio in auto mode. Database tests use Testcontainers Postgres, not SQLite and not mocks. - Never edit an existing test assertion, add pytest.mark.skip or xfail, or loosen filterwarnings to make a test pass. If a test looks wrong, stop and say why. - Done means `make check` passes. Paste its last 20 lines in your final message. ``` The last two rules matter most. The first stops the agent from weakening your tests to reach green; see [protect the oracle](/en/workflows/test/protect-the-oracle/) for why that is the most common way agent work fakes success. The second turns "I think it works" into evidence you can read in ten seconds. ### Wire the rules and gate into each tool The rules and the prompts are identical across tools. What differs is how each tool loads the rules, formats edits, and reviews the result. **Claude Code** Claude Code reads `CLAUDE.md` first, so create one that imports the shared file. The `@path` syntax expands the file into context at launch: ```markdown @AGENTS.md ``` Format and auto-fix each Python file the agent edits with a `PostToolUse` hook in `.claude/settings.json`: ```json { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "jq -r '.tool_input.file_path' | grep -E '\\.py$' | xargs -r sh -c 'uv run ruff format \"$@\" && uv run ruff check --fix \"$@\"' _" } ] } ] } } ``` Give the agent go-to-definition and type diagnostics through the `pyright-lsp` plugin from Anthropic's official marketplace. The plugin registers the server only, so install Pyright first (terminal): ```bash uv tool install pyright claude plugin install pyright-lsp@claude-plugins-official ``` Before you open a pull request, run `/code-review` in the session for a second opinion on the diff. **Codex** Codex reads `AGENTS.md` directly, so no extra file is needed. Run a task with workspace writes and approval prompts for anything wider (terminal): ```bash codex -s workspace-write -a on-request "Implement POST /api/v1/orders as described in docs/tasks/orders.md. Done means make check passes." ``` Review the branch against `main` before you push it: ```bash codex review --base main ``` **Cursor** Create a project rule in Cursor's **Rules** settings with the same list, scoped to `*.py` files, so the agent loads it whenever it touches Python. Use Plan Mode for the multi-file prompts on this page so you approve the file list before any code is written. Run independent recipes in Worktrees, and let Bugbot review the pull request. Start each tool on its default model and raise the effort setting before you switch models; the [models hub](/en/ecosystem/models/) lists the current defaults. ### Give the agent current library docs The Python stack on this page moved faster than most training data: FastAPI dropped `pydantic.v1` support in 0.128.0 (2025-12-27), pytest-asyncio 1.0 removed the `event_loop` fixture, and SQLAlchemy 2.1 changed its async install. The [Context7 MCP server](/en/ecosystem/mcp/context7/) serves version-specific docs to the agent. Its API key is optional, so the plain remote URL works (terminal): **Claude Code** ```bash claude mcp add --transport http context7 https://mcp.context7.com/mcp ``` **Codex** ```bash codex mcp add context7 --url https://mcp.context7.com/mcp ``` **Cursor** Add a server named `context7` with the URL `https://mcp.context7.com/mcp` in `.cursor/mcp.json` or in Cursor's MCP settings. Then end a prompt with "use context7 for SQLAlchemy 2.1 and pytest-asyncio 1.x". Each MCP server adds its tool definitions to the context, so connect it in the projects that need it rather than globally. ## Build a production FastAPI service with an agent, step by step Each step is one prompt and the check that proves it. Run them in order: later prompts assume the skeleton, the settings module, and the database module exist. ### How do you scaffold a FastAPI service that starts and stops cleanly? The most common first-pass omissions are startup validation and shutdown. The agent reads environment variables wherever it needs them and creates the database engine at import time, so a missing variable surfaces as a 500 on the first request and the engine is never disposed. **Copy-paste prompt: FastAPI skeleton with settings and lifespan** ```text Create a FastAPI service in app/ (Python 3.14, uv). app/core/config.py: a pydantic-settings Settings class with DATABASE_URL (PostgresDsn), REDIS_URL, SECRET_KEY (SecretStr, min 32 chars), ENV (Literal development/staging/production), ALLOWED_ORIGINS (list[str]), and a get_settings() cached with functools.cache. app/main.py: create_app() builds the app with a lifespan context manager that creates the async engine and session factory on startup, stores them on app.state, and awaits engine.dispose() on shutdown. No module-level engine and no @app.on_event. Add GET /healthz (no DB) and GET /readyz (runs SELECT 1). Mount routers under /api/v1. Exception handlers return {"error": {"code": ..., "message": ...}} and never include a traceback when ENV is production. Tests with httpx.AsyncClient(transport=ASGITransport(app=app)) inside asgi_lifespan.LifespanManager: /readyz returns 200 against Testcontainers Postgres, create_app() fails at startup with a message naming SECRET_KEY when it is missing, and a production-mode 500 body contains no traceback. Done means make check passes. ``` A good answer has this core: ```python @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[None]: settings = get_settings() engine = create_async_engine(str(settings.DATABASE_URL), pool_pre_ping=True) app.state.sessionmaker = async_sessionmaker(engine, expire_on_commit=False) yield await engine.dispose() ``` `ASGITransport` alone does not run the lifespan, which is why the prompt names `LifespanManager` (PyPI `asgi-lifespan`). Without it, tests that pass may never have created the engine they claim to exercise. ### How do you get Pydantic v2 validation that rejects bad input precisely? Agents trained on years of Pydantic v1 code still write `class Config`, `@validator`, and `.dict()`. The `filterwarnings = ["error"]` setting makes each of those a failing test, because Pydantic v2 emits a deprecation warning for them. **Copy-paste prompt: Pydantic v2 schemas with cross-field rules** ```text In app/schemas/product.py create Pydantic v2 models. ProductCreate: name (2-200 chars, stripped), price (Decimal, gt 0, max 2 decimal places), compare_at_price (Decimal | None, must be greater than price: use @model_validator(mode="after")), category_id (UUID), tags (list[str], max 10 items, each 1-50 chars, deduplicated), variants (list[VariantCreate], min 1). VariantCreate: sku matching ^[A-Z0-9-]+$, size (StrEnum), stock (int, ge 0). ProductRead adds id, slug, created_at, and uses model_config = ConfigDict(from_attributes=True). Page[T] is a generic paginated response with items, total, page, page_size. Pydantic v2 APIs only. Tests: one parametrized case per invalid field asserting the exact loc and type in exc.errors(), the cross-field failure, and a round trip from an ORM object through ProductRead.model_validate(). List the test cases before the code. ``` Asserting on `loc` and `type`, not on the message text, keeps the tests stable across Pydantic releases while still failing when a rule disappears. ### How do you get async SQLAlchemy queries that hold under concurrent orders? The agent's first attempt at "check stock, then decrement" loads the product, compares in Python, and writes it back. Two concurrent orders both read `stock = 1` and both succeed. SQLite with a single connection cannot show this bug; only Postgres under concurrent sessions can. **Copy-paste prompt: order service that cannot oversell** ```text Implement create_order(session, user_id, items: list[OrderItemIn]) in app/services/orders.py with SQLAlchemy 2.1 async (Mapped[], mapped_column(), select()). Relationships use lazy="raise". Inside one session.begin() block, for each item execute update(Product).where(Product.id == item.product_id, Product.stock >= item.quantity).values(stock=Product.stock - item.quantity) .returning(Product.price) and raise OutOfStockError if no row comes back, so the check and the decrement are one statement. Then insert the Order and OrderItems with unit_price from the returned price, totals as Decimal. Generate the Alembic migration with autogenerate and review it for server defaults and indexes. Integration test with PostgresContainer from testcontainers.community.postgres (driver="asyncpg"): run the migrations, set a product's stock to 1, run 10 create_order calls concurrently with asyncio.gather(return_exceptions=True), each with its own session, and assert exactly one succeeds, nine raise OutOfStockError, and stock is 0. ``` `lazy="raise"` turns the classic async bug, an implicit lazy load that fails with `MissingGreenlet` in production, into an immediate error in the first test that touches the relationship. The import path matters too: in `testcontainers` 4.15.0 the old `testcontainers.postgres` module emits a deprecation warning, which your `filterwarnings` setting turns into a failure. To let the agent read your real schema instead of guessing column names, connect a database MCP server to a development database with a read-only role. The [database MCP guide](/en/ecosystem/mcp/database-mcp/) compares the servers and their read-only switches. For migration safety on large tables, see [database migration patterns](/en/cookbook/database-recipes/migration-patterns/). ### How do you move slow work to Celery without duplicate side effects? Celery retries are only safe when the task is idempotent. With `acks_late`, a worker crash or a task that outlives the Redis broker's visibility timeout gets the task delivered again, and the second run repeats every side effect. **Copy-paste prompt: idempotent Celery task with real-worker tests** ```text Move report generation out of the request into Celery 5.6 with a Redis broker. app/worker/celery_app.py: JSON serializer only, task_acks_late=True, task_reject_on_worker_lost=True, worker_prefetch_multiplier=1, soft time limit 300 s, hard limit 360 s. generate_report(report_id: str) takes only IDs, never ORM objects. It claims the report row with UPDATE ... WHERE status = 'pending' RETURNING id and exits quietly if no row comes back, so a redelivered task does nothing. Retry on httpx.TransportError with autoretry_for, retry_backoff=True, max_retries=5. POST /api/v1/reports returns 202 with the report id; GET /api/v1/reports/{id} returns its status. Tests: add pytest_plugins = ("celery.contrib.pytest",) to tests/conftest.py and use the celery_app and celery_worker fixtures with a Testcontainers Redis. Assert a task delivered twice produces one report, a task that fails twice then succeeds completes, and passing a non-JSON-serializable argument fails in the test. ``` Two details the agent tends to miss. `celery.contrib.pytest` is not registered as a pytest plugin automatically, so its fixtures do not exist until `conftest.py` names it. And `task_always_eager` runs the task inside the test process, so it cannot show broker redelivery or worker loss; keep eager mode for unit tests of the task body only. On Django 6, the built-in `django.tasks` framework defines and queues tasks, but running them in the background still needs a third-party worker backend; the built-in backends only run tasks immediately or discard them. ### How do you call external APIs without freezing the event loop? Agent-written clients fail in three ways: a synchronous `requests` call inside `async def`, no timeout, or a retry loop that retries a 400 forever. Ruff's `ASYNC` rules catch the first one in the gate; the prompt handles the other two. **Copy-paste prompt: httpx client with timeouts, retries, and respx tests** ```text Create app/clients/base.py with a BaseClient wrapping one shared httpx.AsyncClient created in the lifespan and closed on shutdown. Timeouts: httpx.Timeout(10.0, connect=3.0). Retry with tenacity: up to 3 attempts, exponential backoff with jitter, only on httpx.TransportError and 502/503/504, never on other 4xx or on POST without an Idempotency-Key header. Raise typed exceptions (UpstreamTimeout, UpstreamRejected with status and body excerpt) and log each attempt with the upstream name and duration, never the request body. Build PaymentsClient.create_refund(payment_id, amount) on it, sending an Idempotency-Key. Tests with respx: a 503 then 200 succeeds on attempt 2, a 400 is not retried, a POST without a key is not retried, a timeout raises UpstreamTimeout, and no test performs a real network call. ``` The "not retried" cases are the ones that matter. An implementation that retries everything passes every success-path test and multiplies refunds in production. ### How do you get structured logs that never leak secrets? **Copy-paste prompt: structlog with request IDs and redaction** ```text Configure structlog in app/core/logging.py: JSON renderer in every environment except development, which uses ConsoleRenderer. Add a pure ASGI middleware that reads X-Request-Id or generates uuid4, binds it with structlog.contextvars.bind_contextvars, echoes it in the response header, and clears contextvars when the request ends. Add a processor that replaces the value of any key named password, token, secret, authorization, cookie, or api_key with "[REDACTED]", including inside nested dicts. Log each unhandled exception once, in the exception handler. Tests with structlog.testing.capture_logs: a login request logs no password or token value, nested secrets are redacted, and every event from one request carries the same request_id while two concurrent requests keep different ones. ``` The concurrent-requests assertion proves the context variables are cleared and scoped per request. A redaction processor that is never tested fails silently when the key names drift. ### How do you keep a Django REST Framework API tenant-safe? In a multi-tenant Django app, the dangerous bug is one viewset that forgets to filter by organisation. It passes every test written from the owner's point of view. **Copy-paste prompt: DRF viewsets with tenant scoping and a permission matrix** ```text In the projects app (Django 6.1, Django REST Framework), create a TenantScopedMixin whose get_queryset() filters by request.user's organization and whose perform_create() sets it, and make ProjectViewSet and TaskViewSet use it. Owners can do everything, members can read and update tasks, everyone else gets 404, not 403, so IDs from other tenants are not revealed. Task status transitions are validated in the serializer: done cannot go back to todo. Use cursor pagination for tasks and django-filter for status, assignee, and due-date range. Add a test that iterates over every registered route in the API router and fails if its viewset does not use TenantScopedMixin. With pytest-django, write a parametrized matrix of role (owner, member, other-tenant, anonymous) x action (list, retrieve, create, update, destroy) with the expected status for each cell. ``` The route-iterating test is the gate that scales: when the agent adds a new viewset next month and forgets the mixin, the suite fails without anyone reading the new file. ### How do you clean up legacy Python idioms an agent keeps reintroducing? Run this prompt once on an existing codebase before you start the recipes, and again whenever the deprecation gate turns red after a dependency bump. **Copy-paste prompt: migrate legacy idioms without changing behaviour** ```text Run make check and fix only what it reports, without changing behaviour: Pydantic v1 idioms (class Config, @validator, .dict(), .parse_obj()) become their v2 equivalents; any custom event_loop fixture is removed and loop scope is set with loop_scope or asyncio_default_fixture_loop_scope (pytest-asyncio 1.x); imports from testcontainers.postgres move to testcontainers.community.postgres; @app.on_event handlers move into the lifespan; blocking calls flagged by ruff ASYNC rules become async equivalents. Do not edit test assertions, do not add skips, and do not change filterwarnings. Report each change grouped by rule. ``` ## How do you verify agent-written Python without reading every line? Read the gate output and the test-case lists, not the diff. Each gate below catches a class of bug that looks fine in review. | Gate | Command | What it catches | | --- | --- | --- | | Format and lint | `ruff format --check`, `ruff check` with `ASYNC`, `S`, `B`, `UP` | Blocking calls in `async def`, hard-coded secrets, SQL built from strings, outdated syntax | | Types | `mypy --strict` with the Pydantic plugin | Wrong shapes between layers, unhandled `None`, missing awaits on typed coroutines | | Deprecations | `filterwarnings = ["error"]` | Pydantic v1 idioms, removed pytest-asyncio patterns, deprecated imports | | Unit and HTTP tests | `pytest` with `httpx.AsyncClient` and `respx` | Status codes, error bodies, validation, retries, redaction | | Integration tests | Testcontainers Postgres and Redis | Races such as overselling, missing constraints, redelivered Celery tasks, tenant leaks | | Coverage floor | `pytest --cov-fail-under=80` | Whole modules the agent never tested | | Dependencies | `pip-audit` on the locked export | Known vulnerabilities in runtime dependencies | | Review agent | `/code-review` (Claude Code), `codex review --base main` (Codex), Bugbot (Cursor) | Logic errors and missing cases the gates cannot express | Coverage proves that lines ran, not that the assertions are strong. For stronger evidence that the tests themselves are good, see [mutation testing and oracle strength](/en/workflows/test/oracle-strength/). Run the gate in CI on every pull request; [CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/) has the workflow file. The engineer who owns the service signs off on three things: the test-case lists the agent wrote before the code, a green gate, and the concurrency and permission-matrix results. Human reading goes to the hunks the review agent flags and to code that touches authentication, money, or tenant boundaries. [Agent PR review](/en/workflows/ship/agent-pr-review/) covers how to split that work across a team, and [agent security gates](/en/ecosystem/observability/agent-security-gates/) adds an independent security reviewer. ## When agent-written Python breaks in production Each failure below passes a happy-path test suite. Each has a symptom you can detect and a recovery you can apply. - **The event loop stalls under load.** Symptom: p99 latency jumps for every endpoint when one slow upstream is called, while CPU stays low. Cause: a blocking call (`requests`, `time.sleep`, a sync ORM session, `open()`) inside `async def`. Recovery: enable ruff's `ASYNC` rules if they are off, then prompt: "Fix every ASYNC finding with an async equivalent, or move the call to `asyncio.to_thread` with a comment saying why. Done means make check passes." - **`MissingGreenlet` in production only.** Symptom: `sqlalchemy.exc.MissingGreenlet` on an endpoint that worked in tests. Cause: an implicit lazy load of a relationship in async code, often in a response serializer. Recovery: set `lazy="raise"` on every relationship, run the tests, and add `selectinload()` wherever one now fails. - **Async SQLAlchemy fails at startup after an upgrade.** Symptom: an error saying the `greenlet` library is required. Cause: SQLAlchemy 2.1 moved `greenlet` into the `[asyncio]` extra. Recovery: depend on `sqlalchemy[postgresql-asyncpg]` (or `sqlalchemy[asyncio]`) and commit the updated `uv.lock`. - **Overselling or double side effects.** Symptom: negative stock, duplicate reports, or duplicate refunds after a spike or a worker restart. Cause: read-then-write logic in Python, or a non-idempotent task that was redelivered. Recovery: add the concurrent Testcontainers test from the order recipe, then prompt: "Find every place that reads a value, decides in Python, and writes it back. Replace each with a conditional UPDATE or a row lock, and add a concurrent test for each." - **The test suite errors after a pytest-asyncio upgrade.** Symptom: failures mentioning the `event_loop` fixture. Cause: the agent wrote the pre-1.0 pattern of overriding `event_loop`, which pytest-asyncio 1.0 removed. Recovery: run the legacy-idiom cleanup prompt above; it replaces the fixture with `loop_scope`. - **One tenant sees another tenant's data.** Symptom: a support ticket, or an access log showing IDs from another organisation. Cause: a new viewset or query without the tenant filter. Recovery: add the route-iterating mixin test from the Django recipe so the gap cannot recur, and audit logs for the affected window. - **The agent weakens a test to reach green.** Symptom: a loosened assertion, a deleted case, an added `skip` or `xfail`, or an edited `filterwarnings` in the same diff as the fix. Recovery: revert the test file, restate the `AGENTS.md` rule, and make CI fail when a pull request changes an existing `test_*.py` file or the pytest configuration without a `test-change` label. "The tests pass" is weak evidence for async Python. Tests against SQLite, mocked repositories, or Celery eager mode pass even when the production code races, blocks, or double-charges. Treat the Testcontainers integration tests as part of the definition of done, not as optional hardening. ## Where to go next with Python services - Make the repository agent-ready first, if it is not yet: [agent-ready codebase](/en/workflows/harness/agent-ready-codebase/). - Design the API contract before the handlers: [API development patterns](/en/cookbook/backend-recipes/api-patterns/). - Harden the data layer: [ORM best practices](/en/cookbook/database-recipes/orm-patterns/) and [database migration patterns](/en/cookbook/database-recipes/migration-patterns/). - Build pipelines and batch jobs in Python: [data engineering recipes](/en/cookbook/data-recipes/). - Ship the service: [Docker patterns](/en/cookbook/devops-recipes/docker-patterns/) and [monitoring and logging patterns](/en/cookbook/devops-recipes/monitoring-logging/). - Decide what the agent may run unattended: [permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/). - Compare with another backend stack: [Node.js/Express recipes](/en/cookbook/backend-recipes/node-patterns/), or return to the [backend recipes overview](/en/cookbook/backend-recipes/). --- # Ruby on Rails Recipes URL: https://developertoolkit.ai/en/cookbook/backend-recipes/ruby-rails-patterns/ Description: Agent recipes for Rails 8.1 — generators over hand-written files, RSpec loops, bin/ci as the definition of done, safe migrations and N+1 checks that fail specs. Ruby on Rails recipes for AI coding agents are prompts and project settings that make Claude Code, Codex and Cursor ship trustworthy Rails 8.1 changes: generators instead of hand-written boilerplate, RSpec request specs written before the code, `bin/ci` as the definition of done, migrations checked for reversibility and lock safety, and N+1 queries that fail a spec. This page is for Rails developers who already let an agent write most of a feature, and for tech leads who want the same gates enforced in CI for the whole team. The situation it fixes: the agent's pull request is green, but it hand-wrote a migration with a timestamp from last year, edited `db/schema.rb` directly, rendered a list with `order.customer.name` in the loop, and "fixed" a failing spec by changing the expected value. The recipes below make the agent run into Rails' conventions, generators and CI runner on every turn, so you review evidence instead of diffs. ## What these Rails recipes give you - A `config/ci.rb` that turns `bin/ci` into the gate the agent must pass: RuboCop, Brakeman, RSpec and a migration-reversibility step. - An `AGENTS.md` for a Rails app, wired into Claude Code, Codex and Cursor. - A generator-first prompt that stops the agent from hand-writing migrations, models and specs. - A spec-first loop for a Rails endpoint, from acceptance criteria to failing request specs to the implementation. - A Claude Code `Stop` hook that refuses "done" until RuboCop and RSpec pass, and a CI job that is the mechanical gate for Codex and Cursor. - N+1 detection that fails specs, with the choice between Bullet, Prosopite and `strict_loading` tested on Rails 8.1.4. - A migration recipe with `strong_migrations`, a schema-drift check and a human sign-off on destructive changes. - Mutation testing with `mutant` to show whether the agent's specs would catch a bug. ## Which Ruby, Rails and gem versions do these recipes assume? Agents mix APIs from Rails 5, 6, 7 and 8 because their training data does. Tell the agent the versions and pin them (`.ruby-version`, `Gemfile.lock`) so it cannot drift. These were current on 2026-09-26: | Component | Version | Source (checked 2026-09-26) | | --- | --- | --- | | Ruby | 4.0.7 (2026-09-15) | ruby-lang.org releases | | Rails | 8.1.4 (2026-09-24); requires Ruby 3.2 or later | rubygems.org | | `rspec-rails` / `factory_bot_rails` | 8.0.4 / 6.5.1 | rubygems.org | | `rubocop` / `rubocop-rails` / `rubocop-rails-omakase` | 1.91.0 / 2.38.0 / 1.1.0 | rubygems.org | | `brakeman` | 8.0.6 | rubygems.org | | `bullet` / `prosopite` | 8.2.0 / 2.2.0 | rubygems.org | | `strong_migrations` | 2.8.0 | rubygems.org | | `mutant` / `mutant-rspec` | 0.17.0 | rubygems.org | | `ruby-lsp` | 0.26.11 | rubygems.org | The Rails, RSpec, Bullet, Prosopite, `strict_loading` and `mutant` results come from a fresh Rails 8.1.4 app (Ruby 3.3.6, SQLite, `rspec-rails` 8.0.4) on 2026-09-26. Rails 8.1.4 requires Ruby 3.2.0 or later, so it installs on Ruby 4.0, but the recipes were not rerun on 4.0.7. The PostgreSQL workflow and the `strong_migrations` steps follow the gems' documentation. Stay on your tool's default model and raise effort before switching models. Current defaults and prices are on the [AI models hub](/en/ecosystem/models/). ## How do you make a Rails app agent-ready? Put the gates in files the agent cannot forget. Rails 8.1 already generates most of them: `rails new` writes `.rubocop.yml` (inheriting `rubocop-rails-omakase`), `bin/brakeman`, `bin/bundler-audit` and a local CI runner, `bin/ci`, that reads its steps from `config/ci.rb` and exits non-zero when any step fails. Add the two steps an agent most often skips: ```ruby title="config/ci.rb" # Run using bin/ci CI.run do step "Setup", "bin/setup --skip-server" step "Style: Ruby", "bin/rubocop" step "Security: Gem audit", "bin/bundler-audit" step "Security: Brakeman code analysis", "bin/brakeman --quiet --no-pager --exit-on-warn --exit-on-error" step "Tests: RSpec", "bin/rspec" step "Migrations: reversible", "bin/rails db:migrate:redo STEP=1" end ``` The last step rolls back the newest migration and applies it again. On a test app, an agent-written `remove_column :orders, :total_cents` without a type raised `ActiveRecord::IrreversibleMigration` in that step and `bin/ci` exited with status 1. Create the `bin/rspec` binstub with `bundle binstubs rspec-core`. Rails defaults to Minitest. If you use RSpec, add `rspec-rails` to the `:development, :test` group, run `bin/rails generate rspec:install`, and tell the generators which specs you want, so `bin/rails generate` stops producing view and helper specs nobody maintains: ```ruby title="config/application.rb" config.generators do |g| g.test_framework :rspec, view_specs: false, helper_specs: false, routing_specs: false g.helper false end ``` With this block, `bin/rails generate scaffold Invoice number:string order:references` creates only a model spec and a request spec. Uncomment `config.example_status_persistence_file_path = "spec/examples.txt"` in `spec/spec_helper.rb` (the generated file ships it inside a `=begin` block). Without it, `bin/rspec --only-failures` has nothing to read, and the agent re-runs the whole suite on every iteration. ## What goes in AGENTS.md for a Rails app? Write the commands the agent must run, in the order it must run them, and the few rules a generic Rails model gets wrong in your codebase. Leave out anything RuboCop or `config/ci.rb` already enforces. ```markdown title="AGENTS.md" # Shop (Rails 8.1, Ruby 4.0, PostgreSQL, RSpec, Hotwire) ## Commands (run from the repo root) - One spec file or example: `bin/rspec spec/requests/orders_spec.rb:12` - Failures from the last run: `bin/rspec --only-failures` - Lint with safe autocorrect: `bin/rubocop -a` - Full gate: `bin/ci` (RuboCop, Brakeman, bundler-audit, RSpec, migration redo) - Preview a generator: add `--pretend` to any `bin/rails generate` command ## Definition of done `bin/ci` passes. Report the command you ran and its last lines. ## Rules - Create models, migrations, controllers, jobs and mailers with `bin/rails generate`, never by hand. - Never edit db/schema.rb or an existing migration. Add a new migration and run `bin/rails db:migrate`. - Specs are the specification. If a spec fails, fix app/, not spec/. Ask before changing an expectation. - Request specs, not controller specs. Use FactoryBot factories from spec/factories. - Any action that renders a collection uses `includes` or `preload`; the N+1 detector fails the spec otherwise. - Never add `# rubocop:disable`, a Brakeman ignore entry or `safety_assured` without asking. - Money is integer cents (`*_cents`), never Float. ``` Each tool loads the same file differently: **Claude Code** Create a `CLAUDE.md` whose first line imports the shared file, then add any Claude-only lines below it: ```markdown title="CLAUDE.md" @AGENTS.md ``` Claude Code 2.1.277 and later also read `AGENTS.md` directly when a project has no `CLAUDE.md` (first-party sessions; v2.1.281 on Bedrock, Google Cloud, Foundry and LLM gateways; both release channels on 2026-10-12). The import works on every version and channel. **Codex** Codex reads `AGENTS.md` before it starts work. Run `/init` in the TUI to draft one, then replace the draft with the file above. Since codex-cli 0.150.0, a project Codex does not trust does not supply its `AGENTS.md`, so trust the repository when Codex asks. **Cursor** Add an always-applied project rule (the format is on [Cursor project rules](/en/cursor-ide/quick-start/project-rules/)) that repeats the Commands and Rules sections of the file above. Commit the rule with the repository. **Copy-paste prompt: draft AGENTS.md from an existing Rails app** ```text Read Gemfile, Gemfile.lock, .ruby-version, config/application.rb, config/ci.rb (if present), .rubocop.yml, spec/rails_helper.rb and spec/spec_helper.rb, and list the directories under app/ and spec/. Write AGENTS.md with: (1) a one-line description naming the Rails and Ruby versions, the database and the test framework; (2) the exact commands for one spec example, failed specs only, lint with safe autocorrect, the full gate and a generator dry run, as they work in THIS repo; (3) a "Definition of done" line; (4) at most eight rules, each one a convention you can see this codebase follows and a generic Rails model would get wrong. Do not restate anything RuboCop already enforces. Run every command you list and tell me which ones failed. ``` [Shared agent rules](/en/cto-scorecard-guide/shared-agent-rules/) explains how to keep one source of truth when a team uses all three tools. ## How do you make the agent use Rails generators instead of writing files by hand? A hand-written migration can break Rails in ways specs do not show: a timestamp that sorts before migrations already in production, a `Migration[7.0]` superclass copied from training data, or a model without its spec. Generators produce the file names, the migration version and the spec skeletons your configuration asks for. The `--pretend` flag shows what a generator would create without writing anything, which makes it a cheap plan step: ```bash # terminal: show the plan, write nothing bin/rails generate model Refund order:references amount_cents:integer reason:string --pretend ``` **Copy-paste prompt: generator-first feature scaffolding** ```text We need a Refund model: belongs to Order, amount_cents integer (not null, > 0), reason string (not null), status string with the values requested, approved and rejected, default requested. First run the bin/rails generate command you intend to use with --pretend and show me its output. Do not write any file by hand that a generator can create. After I approve, run the generator without --pretend, then edit the generated migration to add null: false, the default and a check constraint for amount_cents > 0, and add the model validations and the enum. Run bin/rails db:migrate and bin/rspec spec/models/refund_spec.rb, and show me the diff of db/schema.rb that the migration produced. ``` The last line matters: the `db/schema.rb` diff is the shortest honest summary of what a migration does. Read that, not the Ruby. ## How do you run a spec-first loop for a Rails endpoint? Specify the behaviour, have the agent write failing request specs, check that they fail for the right reason, and only then let it write the implementation. Request specs go through routing, middleware and the database, so they are the oracle closest to what a user sees. 1. **Write the acceptance criteria.** Three to six observable behaviours, each one a sentence a spec can check. [Acceptance criteria an agent can verify](/en/workflows/plan/acceptance-criteria/) shows the format. 2. **Ask for failing specs only.** Use the first prompt below. Stop the agent once the specs load and fail. 3. **Read the failures, not the code.** Each spec should fail on its expectation (`expected 201, got 404`), not on a missing factory or a load error. A spec that fails for the wrong reason will pass for the wrong reason too. 4. **Ask for the implementation.** Use the second prompt. The loop ends when `bin/ci` passes, not when the agent says it is done. 5. **Check spec strength.** Run `mutant` on the changed methods (see [How do you know the agent's specs would catch a bug?](#how-do-you-know-the-agents-specs-would-catch-a-bug)). **Copy-paste prompt: failing request specs for a refund endpoint** ```text We are adding POST /orders/:order_id/refunds (JSON). Acceptance criteria: 1. A valid refund returns 201 with the refund id and status "requested". 2. amount_cents greater than the order's remaining refundable amount returns 422 with an error on amount_cents, and no row is created. 3. A missing or blank reason returns 422 with an error on reason. 4. A refund for another customer's order returns 404, not 403. 5. Listing GET /orders/:order_id/refunds for an order with 5 refunds runs a constant number of queries (the N+1 detector must stay silent). Write ONLY specs, in spec/requests/refunds_spec.rb, with FactoryBot factories in spec/factories (create any that are missing). Do not create or change anything under app/, config/ or db/. Then run bin/rspec spec/requests/refunds_spec.rb and show me each failure message. Stop there. ``` **Copy-paste prompt: implement until bin/ci is green** ```text Implement the refunds endpoints so every example in spec/requests/refunds_spec.rb passes. Use bin/rails generate for any new controller or migration. Scope the order lookup through the current customer so criterion 4 holds. Do not modify any file under spec/. Iterate with bin/rspec --only-failures. When you think you are done, run bin/ci and paste its last 20 lines. If a spec still fails, tell me which acceptance criterion the code violates instead of changing the spec. ``` [Protect the oracle](/en/workflows/test/protect-the-oracle/) explains why the "do not modify spec/" instruction needs a mechanical backstop as well, which the next section adds. ## How do you stop the agent from declaring done before the specs pass? An instruction in `AGENTS.md` is advice. A hook or a CI check is a gate. Claude Code gets a local gate from the `Stop` hook below. Codex and Cursor have hooks too, but the setups below use a prompt and a project rule, so for them the CI job after the tabs remains the gate. **Claude Code** A `Stop` hook runs when Claude finishes responding. Exit code 2 prevents the stop and shows the hook's stderr to Claude, which then keeps working. Run the fast part of the gate here and leave the full `bin/ci` (which also audits gems over the network) to the end of the task and to CI: ```bash title=".claude/hooks/rails-gate.sh" #!/usr/bin/env bash # Refuse "done" until RuboCop and RSpec pass. input=$(cat) # Already continuing because of a stop hook: stop and report instead of looping. [ "$(echo "$input" | jq -r '.stop_hook_active')" = "true" ] && exit 0 cd "$CLAUDE_PROJECT_DIR" || exit 0 # No changes to code, specs or schema since the branch left main: nothing to check. base=$(git merge-base HEAD origin/main 2>/dev/null || echo HEAD) [ -z "$(git status --porcelain -- app spec db config lib)" ] && git diff --quiet "$base" -- app spec db config lib && exit 0 if ! out=$(bin/rubocop 2>&1); then echo "RuboCop failed. Fix the code; run bin/rubocop -a for safe fixes; never add rubocop:disable:" >&2 echo "$out" | grep -E "^[^ ].+:[0-9]+:[0-9]+: " | head -30 >&2 exit 2 fi if ! out=$(bin/rspec 2>&1); then echo "RSpec failed. Fix app/, never spec/. Re-run with bin/rspec --only-failures:" >&2 echo "$out" | tail -40 >&2 exit 2 fi exit 0 ``` The script needs `jq`. Because it exits 0 when `stop_hook_active` is `true`, a failing gate forces one retry, and then Claude stops and reports instead of looping on a spec that cannot pass. The guard skips the run when nothing under `app`, `spec`, `db`, `config` or `lib` differs from `origin/main`, whether the change is uncommitted or already committed; change `origin/main` if your default branch has another name. [Hooks automation](/en/claude-code/automate/hooks-automation/) explains how to allow more than one retry and covers the other events. Register it in the project settings and make the script executable (`chmod +x`): ```json title=".claude/settings.json" { "hooks": { "Stop": [ { "hooks": [ { "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/rails-gate.sh", "timeout": 600 } ] } ] } } ``` On a large suite, replace `bin/rspec` with the spec files that match the changed files, and keep the full run in CI. **Codex** `bundle install` needs the network, and the `workspace-write` sandbox has no network access unless you enable it. Install gems first, outside the agent, then run the loop without network: ```bash bundle install codex exec --sandbox workspace-write "Implement the refunds endpoints so every example in spec/requests/refunds_spec.rb passes. Do not modify spec/. Finish only when 'bin/rubocop' and 'bin/rspec' both pass; print the last lines of each." ``` An SQLite test database is a file in the workspace, so it works inside the sandbox. If your specs need a PostgreSQL server and the sandbox blocks the connection, run the database specs in CI and give the local loop the model specs only. If the task is adding a gem, enable network for that run only with `-c sandbox_workspace_write.network_access=true`. The prompt is still an instruction: nothing stops the run from ending with red specs. For a local gate, run the same RuboCop and RSpec checks from a Codex `Stop` hook (`hooks` is a stable feature in 0.157.1; check it with `/hooks`, and note that hooks need persisted trust). Otherwise the CI job below is the mechanical gate for Codex. **Cursor** Paste the implementation prompt into the agent, in Plan Mode first if the change touches models, controllers and migrations together. Put the Definition of done in the project rule so the agent runs `bin/ci` before it reports back. The mechanical gate for Cursor runs after the pull request opens: the CI job below, plus Bugbot if your team uses it for review. Whatever runs locally, CI is the gate that decides. Run the same checks there with a read-only token and a throwaway PostgreSQL service: ```yaml title=".github/workflows/rails-gates.yml" name: rails-gates on: pull_request: types: [opened, synchronize, reopened, labeled, unlabeled] permissions: contents: read jobs: gates: runs-on: ubuntu-latest services: postgres: image: postgres:17 env: POSTGRES_HOST_AUTH_METHOD: trust # disposable CI database, no credential ports: ["5432:5432"] options: --health-cmd="pg_isready" --health-interval=10s --health-timeout=5s --health-retries=3 env: RAILS_ENV: test DATABASE_URL: postgres://postgres@localhost:5432/shop_test steps: - uses: actions/checkout@v7 with: persist-credentials: false fetch-depth: 2 # the PR merge commit and its base parent - name: Existing specs unchanged if: ${{ !contains(github.event.pull_request.labels.*.name, 'spec-change-approved') }} run: | changed=$(git diff --name-only --diff-filter=MDR HEAD^1 HEAD -- spec/) if [ -n "$changed" ]; then echo "Existing specs modified, moved or deleted; a reviewer must add the spec-change-approved label:" echo "$changed" exit 1 fi - uses: ruby/setup-ruby@v1 with: bundler-cache: true - run: bin/rubocop - run: bin/bundler-audit - run: bin/brakeman --quiet --no-pager --exit-on-warn --exit-on-error - run: bin/rails db:create db:migrate - run: git diff --exit-code db/schema.rb # migrations and schema.rb agree - run: bin/rails db:migrate:redo STEP=1 # newest migration is reversible - run: bin/rspec ``` The "Existing specs unchanged" step fails when the pull request modifies, renames or deletes an existing file under `spec/`, so the agent cannot quietly move an expected value or drop a failing spec; new spec files pass. After reviewing the spec change, a person adds the `spec-change-approved` label, which starts a new run that skips the step (re-running the old job does not work, because it reuses the original event and does not see the label). The step is only a gate if the pull request cannot remove it: GitHub runs the workflow file from the pull request itself, so put `/.github/` under `CODEOWNERS` and require that review in branch protection or a ruleset. The `git diff` step fails when the agent edited `db/schema.rb` by hand or committed a migration without the schema it produces. ## How do you catch N+1 queries in agent-written Rails code? Agents readily write the N+1 loop, because `@orders.each { |o| o.customer.name }` is correct Ruby and every spec with one record passes. The fix is a detector that turns the pattern into a failing spec. Each row below was tested on Rails 8.1.4 on 2026-09-26: | Detector | Setup | What it caught in our test | Choose it when | | --- | --- | --- | --- | | Bullet 8.2.0 | `Bullet.enable`, `Bullet.raise = true` in `config/environments/test.rb` | The `order.customer` loop in a request spec, on SQLite, with the fix in the message: `Add to your query: .includes([:customer])` | Any database, including Rails 8's default SQLite. Request specs work through its Rack middleware; model specs need `Bullet.start_request` and `Bullet.end_request` around each example | | Prosopite 2.2.0 | `Prosopite.raise = true`, `Prosopite.scan` and `Prosopite.finish` around each example, plus the `pg_query` gem unless you use MySQL or MariaDB | The same loop on SQLite, but as `PgQuery::ParseError: syntax error at or near "LIMIT"` instead of an N+1 report | PostgreSQL or MySQL. It flags repeated identical queries, so it also catches N+1s that do not go through an association | | `strict_loading` (built in) | `Order.strict_loading` on a relation, or `self.strict_loading_by_default = true` in a model | The loop, as `ActiveRecord::StrictLoadingViolationError`, when set on the relation. With `strict_loading_by_default = true` and `strict_loading_mode = :n_plus_one_only`, it raised for none of the loops we tried | New models and hot queries where every lazy load is a bug, including single-record ones | For most teams, Bullet in the test environment is the first gate, with `strict_loading` on the relations behind your busiest pages: ```ruby title="config/environments/test.rb" Rails.application.configure do config.after_initialize do Bullet.enable = true Bullet.bullet_logger = true Bullet.raise = true # an N+1 in any request spec fails that spec end # ... end ``` The detector only fires when a spec loads more than one record, so add a collection example to every index action. Criterion 5 in the refund prompt above is that example. **Copy-paste prompt: find and fix N+1 queries in the index actions** ```text Bullet raises on N+1 queries in the test environment. For every controller action under app/controllers that renders a collection (index actions, and any view that iterates over an association), check spec/requests for an example that creates at least three records with the associations the view touches. Add the missing examples first and run them: each N+1 must fail with Bullet::Notification::UnoptimizedQueryError. Then fix each one with includes, preload or eager_load, choosing the one Bullet suggests unless the view filters on the association. Do not set Bullet.raise to false, do not add Bullet safelist entries, and do not change the new examples to create fewer records. Show me the Bullet messages before and the bin/rspec result after. ``` For the database side of the same problem, including `EXPLAIN` plans and indexes, see [SQL patterns](/en/cookbook/database-recipes/sql-patterns/) and [ORM patterns](/en/cookbook/database-recipes/orm-patterns/). ## How do you handle Rails migrations with an agent? Specs alone cannot vouch for a migration: the agent can write a migration that applies cleanly to an empty test database and still locks a large table or breaks the running app during deploy. The classic case: the agent renames a column with `rename_column`, the specs pass, and the app servers still running the old code raise errors on every query that uses the old name. `strong_migrations` turns those cases into an error at `bin/rails db:migrate` time, with the safe alternative in the message. It supports PostgreSQL, MySQL and MariaDB (not SQLite). Install it with `bundle add strong_migrations` and `bin/rails generate strong_migrations:install`. Removing a column, for example, fails with instructions to add the column to `self.ignored_columns`, deploy, and only then remove it inside `safety_assured { ... }`. Split the rest of the work between gates and a person: | Check | How | Who decides | | --- | --- | --- | | Unsafe operation | `strong_migrations` raises on the migration | CI, and the agent reads the message | | Schema and migrations agree | `bin/rails db:migrate` on a fresh database, then `git diff --exit-code db/schema.rb` | CI | | The newest migration is reversible | `bin/rails db:migrate:redo STEP=1` | CI (`bin/ci` and the workflow above) | | The change is what you expect | The `db/schema.rb` diff attached to the pull request | A human reads the schema diff, not the Ruby | | `safety_assured`, destructive or data-backfill migrations | `CODEOWNERS` on `db/migrate/` | A human | **Copy-paste prompt: rename a column without downtime** ```text Rename orders.notes to orders.customer_notes without downtime, as an expand-and-contract change in separate pull requests. In THIS pull request do only the expand step: generate a migration that adds customer_notes, write to both columns from the model, backfill existing rows in batches with in_batches in a separate migration, and read from customer_notes with a fallback to notes. Do not remove or rename notes and do not use safety_assured. Run bin/rails db:migrate, bin/rails db:migrate:redo STEP=1 and bin/rspec. Show me the db/schema.rb diff and list every statement that could lock the orders table, or say "none". Then write the steps for the contract pull request as a checklist in the PR description. ``` For the wider rules on expand-and-contract changes and rollbacks, see [database migration patterns](/en/cookbook/database-recipes/migration-patterns/). ## How do you know the agent's specs would catch a bug? A green run does not tell you the specs would fail if the code were wrong, and specs written by the same agent that wrote the code are the ones most likely to share its blind spots. Mutation testing answers the question: `mutant` changes the code under test in small ways and reports every change the specs did not notice. On the test app, one spec for `Order#large?` (`total_cents >= 10_000`) passed, and `mutant` reported 7 surviving mutations out of 18, 61.11% coverage. The first survivor was the boundary: `total_cents > 10000`. No spec checked an order of exactly 10,000 cents. ```bash # terminal: mutation-test only the subjects changed since main bundle exec mutant run --integration rspec --usage opensource \ --require ./config/environment --since main -- 'Order*' ``` Add `mutant-rspec` to the `:development, :test` group with `require: false`. `mutant` is free for open-source projects (`--usage opensource`); private, commercial code needs a paid subscription and `--usage commercial`. Run it on the changed subjects rather than the whole app, because every mutation re-runs the selected specs. [Oracle strength](/en/workflows/test/oracle-strength/) explains how to turn survivors into missing examples. **Copy-paste prompt: turn surviving mutants into missing specs** ```text Run: bundle exec mutant run --integration rspec --usage opensource --require ./config/environment --since main -- 'Refund*' 'RefundsController*' For each surviving mutation, decide: (A) the mutated code is equally correct and the original is redundant, or (B) a spec is missing. For every B, add one example to the existing spec file that fails against the mutated code and passes against the original. Do not change anything under app/. Re-run mutant and show me the before and after Alive counts, and list any A cases for me to decide. ``` ## How do you give the agent Rails-aware code navigation? Text search finds `def total` but not every caller of an association, a scope or a route helper. Two additions help most in Rails: a language server that understands Ruby, and an MCP server that reads routes, schema and model relationships. **Ruby LSP.** Shopify's language server (`ruby-lsp` gem, 0.26.11) includes its Rails add-on automatically when it detects a Rails app. In Claude Code, the `ruby-lsp` plugin in the official marketplace registers it; the plugin does not bundle the binary. LSP plugins add no always-on context, because the server runs out of process. **Rails MCP Server.** The `rails-mcp-server` gem (2.0.0) exposes three tools, `switch_project`, `search_tools` and `execute_tool`, and behind them analyzers such as `get_routes`, `get_schema` and `analyze_models`. With `--single-project` it serves the current directory without a `projects.yml`. Popularity: 261,700 total downloads on rubygems.org (read 2026-09-26). It is a community project, so read its source before you give it a production database. Its always-on tool-definition cost is small; the analyzers load only when called through `execute_tool`. **Claude Code** ```bash # terminal gem install ruby-lsp claude plugin install ruby-lsp@claude-plugins-official gem install rails-mcp-server claude mcp add rails -- rails-mcp-server --single-project ``` **Codex** ```bash # terminal, from the app's root gem install rails-mcp-server codex mcp add rails -- rails-mcp-server --single-project ``` **Cursor** Add the MCP server to `.cursor/mcp.json` in the app's root: ```json { "mcpServers": { "rails": { "command": "rails-mcp-server", "args": ["--single-project"] } } } ``` Without them, the agent's grep for `has_many :refunds` misses a scope defined in a concern. With them, one prompt maps the blast radius first: **Copy-paste prompt: map a change before editing** ```text Using the rails MCP server and the language server, find every route, controller action, model scope, job and view that reads or writes orders.status. Show the list with file and line, and mark which ones have a spec that exercises them. Do not change files. ``` [Code intelligence MCP servers](/en/ecosystem/mcp/code-intelligence-mcp/) compares language-server and index-based options for larger codebases. ## What breaks when agents write Rails code? **Prosopite reports a PgQuery::ParseError on SQLite** Symptom: a spec fails with `PgQuery::ParseError: syntax error at or near "LIMIT"` from inside Prosopite. Cause: Prosopite fingerprints queries with `pg_query`, a PostgreSQL parser, and SQLite's `?` placeholders do not parse; the error is an N+1 in disguise (Prosopite 2.2.0, pg_query 6.2.3, checked 2026-09-26). Recovery: use Bullet on SQLite, and move to Prosopite when the app runs on PostgreSQL or MySQL. **strict_loading is on and nothing raises** Symptom: `config.active_record.strict_loading_mode = :n_plus_one_only` is set, and an obvious N+1 loop still passes. Cause: with strict loading on, that mode only reports some nested lazy loads; on Rails 8.1.4 it raised for none of the top-level loops we tried. Recovery: call `strict_loading` on the relation (`Order.strict_loading.includes(...)`) or keep the default `:all` mode on the models where every lazy load is a bug, and run Bullet for the rest. **The agent edits db/schema.rb or an old migration** Symptom: the schema looks right on the branch and production is missing a column, or a colleague's database is out of step. Cause: the agent edited the generated file instead of adding a migration. Recovery: the `git diff --exit-code db/schema.rb` step in CI catches it; re-prompt: "Revert your edits to db/schema.rb and db/migrate/*, generate a new migration for the change, run bin/rails db:migrate and commit the schema it produces." **A migration that passes locally and fails redo** Symptom: `bin/ci` fails on the reversible step with `ActiveRecord::IrreversibleMigration`. Cause: `remove_column` without a type, `change_column`, or an `execute` inside `change`. Recovery: "Rewrite the migration with separate up and down methods, or pass the column type to remove_column so change can reverse it. Run bin/rails db:migrate:redo STEP=1 until it passes." **The spec changed to match the bug** Symptom: the diff touches `spec/` in the same commit that fixes `app/`, and an expected value moved. Cause: the agent optimised for green. Recovery: put `spec/` under `CODEOWNERS`, keep the "do not modify spec/" line in every implementation prompt, and keep the "Existing specs unchanged" step from the CI job above. [Protect the oracle](/en/workflows/test/protect-the-oracle/) has the other mechanical options. **Suppressions instead of fixes** Symptom: the gates are green and the diff adds `# rubocop:disable`, an entry in `config/brakeman.ignore`, a Bullet safelist entry or `safety_assured`. Recovery: give those files and patterns a human owner in `CODEOWNERS` and re-prompt: "Remove the suppression you added and fix the underlying offense. If it is a false positive, explain why in the pull request instead." ## Where to go next with Rails and agents - [Protect the oracle](/en/workflows/test/protect-the-oracle/) — Stop agents from editing the specs that judge them. - [Database migration patterns](/en/cookbook/database-recipes/migration-patterns/) — Expand-and-contract changes and rollbacks for the migrations above. - [API development patterns](/en/cookbook/backend-recipes/api-patterns/) — Idempotency keys, pagination and contracts for the endpoints you build. - [Python workflow recipes](/en/cookbook/backend-recipes/python-patterns/) — The same gates and loops for Django and FastAPI. - [Evidence bundle](/en/workflows/ship/evidence-bundle/) — Attach gate results and the schema diff so the reviewer checks proof, not code. - [Agent-ready codebase](/en/workflows/harness/agent-ready-codebase/) — The repository properties that make any agent more reliable. --- # Rust Development Patterns URL: https://developertoolkit.ai/en/cookbook/backend-recipes/rust-patterns/ Description: Prompts and gates for agent-written Rust services — ownership without clone spam, errors mapped to HTTP, compile-checked SQLx, and clean Tokio shutdown. Rust patterns for AI coding agents are rules, prompts, and gates that make Claude Code, Codex, and Cursor produce Axum, SQLx, and Tokio services the compiler accepts without `.clone()` spam: explicit ownership, one `thiserror` error type mapped to HTTP, `query_as!` checked against the real schema, and clean shutdown. Output is accepted on clippy, test, SQLx, and mutation-testing evidence. You ask the agent for a user endpoint. It returns code that clones every `String` to quiet the borrow checker, registers the route as `/users/:id` (which panics at startup on axum 0.8), and writes a `query_as!` whose `SELECT` list does not match the struct. CI then fails because `DATABASE_URL` is not set there. Each fix takes another round, and you end up reading every line anyway. This recipe is for developers who build Rust backends with an agent. It puts the constraints the compiler cares about into the prompts, and makes the toolchain, not your eyes, prove the result. ## What an agent-proof Rust setup gives you - One `AGENTS.md` rule block for Rust that Claude Code, Codex, and Cursor all follow, plus a `make check` gate the agent must pass before it reports "done" - Six copy-paste prompts: ownership refactors, a canonical domain model, a schema-aware SQLx repository, an error type mapped to HTTP, graceful shutdown, and database plus property tests - A read-only Postgres MCP setup so the agent reads your schema before it writes a query - A verification table that tells you which gate catches which bug, so you read gate output instead of the diff - Recovery steps for the seven ways agent-written Rust breaks ## Set up Rust conventions and a gate the agent must pass Write three files once per repository, before you ask for any code: a toolchain pin, a workspace manifest with current crate versions, and a rules file with a single definition of done. 1. Pin the toolchain in `rust-toolchain.toml`. On 2026-09-26 the current stable release is Rust 1.98.1 (per the `static.rust-lang.org` stable channel manifest). A pin stops the agent from assuming an older compiler, and it matters for SQLx: `sqlx` 0.9.0 declares `rust-version = 1.94` on crates.io. ```toml [toolchain] channel = "1.98.1" components = ["rustfmt", "clippy", "rust-analyzer"] ``` 2. Declare the stack once in the workspace `Cargo.toml`. The versions are the latest on crates.io on 2026-09-26. Caret requirements let `cargo update` move patch releases; for a `0.x` crate such as `"0.9"`, the caret stays inside `0.9.*`. ```toml [workspace] members = ["api", "db"] resolver = "3" [workspace.package] edition = "2024" [workspace.dependencies] axum = "0.8" tokio = { version = "1", features = ["full"] } tokio-util = { version = "0.7", features = ["rt"] } # "rt" enables TaskTracker serde = { version = "1", features = ["derive"] } serde_json = "1" sqlx = { version = "0.9", default-features = false, features = [ "runtime-tokio", "tls-rustls", "postgres", "macros", "migrate", "chrono", ] } chrono = { version = "0.4", features = ["serde"] } thiserror = "2" anyhow = "1" tracing = "0.1" argon2 = "0.6" proptest = "1" ``` Two features are easy to miss. Without `chrono` on `sqlx`, a `DateTime` field does not compile in `query_as!`. Without `rt` on `tokio-util`, `TaskTracker` does not exist. 3. Add the gate as a `make check` target. It needs `DATABASE_URL` pointing at a local development Postgres, because both `cargo sqlx prepare --check` and `#[sqlx::test]` connect to a server. ```makefile .PHONY: check check: cargo fmt --all -- --check cargo clippy --workspace --all-targets -- -D warnings cargo sqlx prepare --workspace --check cargo nextest run --workspace cargo test --workspace --doc cargo deny check ``` Install the tools once in your terminal, then generate a starting `deny.toml`: ```bash cargo install --locked cargo-nextest cargo-deny sqlx-cli cargo-mutants cargo deny init ``` `cargo nextest` does not run doctests, which is why the gate runs `cargo test --doc` separately. `cargo deny check` covers RustSec advisories, licences, and banned or duplicate crates in one command. 4. Put the Rust rules in `AGENTS.md` at the repository root. Codex reads it natively; the tabs below show how Claude Code and Cursor pick up the same text. ```markdown ## Rust conventions - Edition 2024, toolchain from rust-toolchain.toml. Stack: axum 0.8 + sqlx 0.9 (Postgres) + tokio. Do not add actix-web, diesel, rocket, or sea-orm. - axum 0.8 routes use `/{id}`, never `/:id`. Extractors implement FromRequestParts without #[async_trait]. - Borrow by default (&str, &[T]). Take ownership only when the callee stores the value. Never add .clone(), Arc, or Rc just to satisfy the borrow checker; change the signature and explain why instead. - Every fallible function returns Result. No .unwrap() or .expect() outside #[cfg(test)] and main(). - SQL uses sqlx::query_as! / query! macros only. After any query or migration change, run `cargo sqlx prepare --workspace` and commit .sqlx/. - CPU-heavy or blocking work (password hashing, std::fs) runs in tokio::task::spawn_blocking. - Never delete or loosen an existing test, and never add #[ignore], to reach green. If a test looks wrong, stop and say why. - Done means `make check` passes. Paste its last 20 lines in your final message. ``` The last two rules carry the most weight. The first stops the agent from weakening your tests to reach green; see [protect the oracle](/en/workflows/test/protect-the-oracle/) for why that is the most common way agent work fakes success. The second turns "it compiles" into evidence you can read in ten seconds. ### Wire the rules and gate into each tool The rules file and the prompts are identical across tools. What differs is how each tool loads the rules, formats code, and reviews the result. **Claude Code** Create a `CLAUDE.md` that imports the shared file. The `@path` import expands it into context at launch: ```markdown @AGENTS.md ``` From v2.1.277 (both release channels on 2026-10-12), Claude Code also reads `AGENTS.md` on its own when a project has no `CLAUDE.md`. The import works on every version. Format every Rust file the agent edits with a `PostToolUse` hook in `.claude/settings.json`. Pass `--edition 2024`, because `rustfmt` run on a single file does not read the edition from `Cargo.toml`: ```json { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [ { "type": "command", "command": "jq -r '.tool_input.file_path' | grep '\\.rs$' | xargs -r rustfmt --edition 2024" } ] } ] } } ``` Give the agent type-aware navigation and compiler diagnostics with the `rust-analyzer-lsp` plugin from Anthropic's official marketplace. The plugin registers the server only; the `rust-analyzer` component from step 1 provides the binary: ```bash claude plugin install rust-analyzer-lsp@claude-plugins-official ``` Before you open a pull request, run `/code-review` in the session for a second opinion on the diff. **Codex** Codex reads `AGENTS.md` directly, so no extra file is needed. Run a task with workspace writes and approval prompts for anything wider: ```bash codex -s workspace-write -a on-request "Implement UserRepository as described in docs/tasks/users.md. Done means make check passes." ``` If `cargo` cannot download crates from inside the sandbox, run `cargo fetch` in your own terminal first so the agent builds from the local registry cache. Review the branch before you push it: ```bash codex review --base main ``` **Cursor** Create a project rule in Cursor's Rules settings with the same list as `AGENTS.md` and attach it to Rust files. Install the rust-analyzer extension so the editor reports compiler diagnostics. Use Plan Mode for the multi-crate scaffolds on this page so you approve the file list before any code is written. Run independent tasks in Worktrees, and let Bugbot review the pull request. Start each tool on its default model and raise the effort setting before you switch models; the [models hub](/en/ecosystem/models/) lists the current defaults. ## Build an Axum and SQLx service with an agent, step by step Each step is one prompt, an excerpt of what a good answer looks like, and the gate that proves it. Run them in order: later prompts assume the model and repository exist. ### How do you stop the agent from cloning its way past the borrow checker? When an agent hits an ownership error, its default fix is `.clone()` or `Arc::new`. Both compile, and both hide the design question the error was asking. Name the ownership story you want and forbid the escape hatch. **Copy-paste prompt: ownership refactor without clones** ```text In db/src/filters.rs, active_emails takes Vec but every caller needs the users afterwards. Change it to take &[User] and return Vec<&str> borrowed from the input, so no String is copied. Do not add .clone(), .to_owned(), Arc, or Rc anywhere to satisfy the borrow checker; change signatures instead. Update every call site, and for each one state in one line which borrow it now holds and why the compiler accepts it. Done means make check passes. ``` A good answer changes the signature, not the call sites' data: ```rust // Before: consumes the vector, so callers clone it first. pub fn active_emails(users: Vec) -> Vec { users.into_iter().filter(|u| u.active).map(|u| u.email).collect() } // After: borrows; the returned &str values live as long as `users`. pub fn active_emails(users: &[User]) -> Vec<&str> { users.iter().filter(|u| u.active).map(|u| u.email.as_str()).collect() } ``` You do not need to audit lifetimes by eye: if the borrow is wrong, the build fails. What the compiler cannot tell you is whether the agent smuggled a clone back in elsewhere, so count them in the diff (see the verification section). ### How do you pin the domain model so `query_as!` compiles? Agent-written Rust often drifts: `CreateUser` has three fields in one file and two in another, and a `query_as!` fails because the `SELECT` list omits a column the struct declares. Define the types once and tell the agent they are the only definitions allowed. ```rust use chrono::{DateTime, Utc}; /// One row of the `users` table, field for field. #[derive(Debug, Clone, serde::Serialize)] pub struct User { pub id: i64, pub email: String, pub name: String, pub active: bool, #[serde(skip_serializing)] pub password_hash: String, pub created_at: DateTime, pub updated_at: DateTime, } /// Request body for creation. Carries the plaintext password; the repository hashes it. #[derive(Debug, serde::Deserialize)] pub struct CreateUser { pub email: String, pub name: String, pub password: String, } ``` `#[serde(skip_serializing)]` on `password_hash` is the line that keeps a hash out of every JSON response. Put it in the canonical type so no handler can forget it. **Copy-paste prompt: enforce one domain model** ```text The canonical types are User and CreateUser in db/src/model.rs. Do not define another struct with these names or a subset of their fields anywhere. Refactor the repository, the handlers in api/src/users.rs, and the test factories to use exactly these types. Every query_as!(User, ...) must SELECT or RETURN all seven User columns in declaration order. List any file that still used a divergent definition before your change. Done means make check passes. ``` ### How do you give the agent your real schema before it writes SQLx queries? `query_as!` checks each query against a live database at compile time, so a guessed column name fails the build. The agent guesses because it cannot see your schema. A read-only Postgres MCP server lets it inspect the real tables first, so the query matches on the first attempt instead of the fourth. This recipe uses [Postgres MCP Pro](https://github.com/crystaldba/postgres-mcp), a Python package (`postgres-mcp` 0.3.0 on PyPI, Python 3.12 or later) that runs with `uvx`. Its `--access-mode=restricted` flag limits it to read-only transactions. The only difference between tools is where the configuration lives. **Claude Code** ```bash claude mcp add postgres -e DATABASE_URI=postgresql://localhost/myapp_dev \ -- uvx postgres-mcp --access-mode=restricted ``` The default scope is `local`: the server is stored for this project in your user configuration, not in the repository. Add `-s project` only if you want it in a shared `.mcp.json`, and never commit a connection string with a password in it. Check the connection with `claude mcp list`. **Codex** ```bash codex mcp add postgres --env DATABASE_URI=postgresql://localhost/myapp_dev \ -- uvx postgres-mcp --access-mode=restricted ``` This writes an `[mcp_servers.postgres]` entry to `~/.codex/config.toml`. Check it with `codex mcp list`. **Cursor** `.cursor/mcp.json`: ```json { "mcpServers": { "postgres": { "command": "uvx", "args": ["postgres-mcp", "--access-mode=restricted"], "env": { "DATABASE_URI": "postgresql://localhost/myapp_dev" } } } } ``` Point the server at a development database with a least-privilege role, never production. The README's own examples use `--access-mode=unrestricted`, so change the flag every time you copy one. The last PyPI release is from 2025-05-16; the [database MCP guide](/en/ecosystem/mcp/database-mcp/) compares maintained alternatives and their read-only switches. Do not use `@modelcontextprotocol/server-postgres`: it is deprecated and archived. **Copy-paste prompt: schema-aware SQLx repository** ```text Use the postgres MCP server to read the columns, types, nullability, and constraints of the users table before writing any SQL. Then create db/src/users.rs with a UserRepository holding a sqlx::PgPool and two methods: find_by_email(&self, email: &str) -> Result> using fetch_optional, and create(&self, input: &CreateUser) -> Result using INSERT ... RETURNING. Use query_as! only. Hash the password with argon2 inside tokio::task::spawn_blocking, never on the async thread. Map a unique-violation on email to AppError::Conflict. Run cargo sqlx prepare --workspace afterwards. Done means make check passes. ``` The core of a good answer: ```rust pub async fn find_by_email(&self, email: &str) -> Result> { let user = sqlx::query_as!( User, "SELECT id, email, name, active, password_hash, created_at, updated_at \ FROM users WHERE email = $1", email ) .fetch_optional(&self.pool) .await?; Ok(user) } ``` `fetch_optional` matters: `fetch_one` returns `sqlx::Error::RowNotFound` for a missing user, which the next section has to turn into a 404 instead of a 500. The `cargo sqlx prepare --workspace --check` step in the gate fails if the committed `.sqlx/` metadata no longer matches the queries, which is what keeps CI buildable with `SQLX_OFFLINE=true`. ### How do you map errors to HTTP status codes without leaking internals? Define the error enum once with `thiserror`, then implement `IntoResponse` so axum turns each variant into a status code. Two bugs are common in agent output: `RowNotFound` returned as a 500, and the raw database error text sent to the client. ```rust use axum::{http::StatusCode, response::{IntoResponse, Response}, Json}; #[derive(Debug, thiserror::Error)] pub enum AppError { #[error("{0} not found")] NotFound(&'static str), #[error("validation failed: {0}")] Validation(String), #[error("{0} already exists")] Conflict(&'static str), #[error("unauthorized")] Unauthorized, #[error(transparent)] Database(#[from] sqlx::Error), #[error(transparent)] Internal(#[from] anyhow::Error), } pub type Result = std::result::Result; impl IntoResponse for AppError { fn into_response(self) -> Response { let status = match &self { AppError::NotFound(_) | AppError::Database(sqlx::Error::RowNotFound) => StatusCode::NOT_FOUND, AppError::Validation(_) => StatusCode::BAD_REQUEST, AppError::Conflict(_) => StatusCode::CONFLICT, AppError::Unauthorized => StatusCode::UNAUTHORIZED, AppError::Database(_) | AppError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR, }; // Log the detail; send the client a generic message for every 5xx. let message = if status.is_server_error() { tracing::error!(error = ?self, "request failed"); "internal error".to_string() } else { self.to_string() }; (status, Json(serde_json::json!({ "error": message }))).into_response() } } ``` **Copy-paste prompt: replace panics with typed errors** ```text In the db and api crates, replace every .unwrap() and .expect() outside #[cfg(test)] and main() with ? propagation into AppError. Map sqlx::Error::RowNotFound to AppError::NotFound naming the resource, and a Postgres error with code 23505 to AppError::Conflict. Every 5xx response body must be {"error":"internal error"}; the detail goes to tracing::error! only. Add one handler test per AppError variant that asserts the status code and that the body of a Database error does not contain the word "relation" or any SQL text. Done means make check passes. ``` The handler tests are the proof. They fail if a variant maps to the wrong status or if database text reaches a client, and you never read `into_response` to find out. ### How do you shut down an axum service cleanly? Ask for "graceful shutdown" and agents often hand-roll a `oneshot` channel: the server stops accepting connections, but spawned background tasks keep running with nothing to wait for them. Use axum's `with_graceful_shutdown` for requests, and a `CancellationToken` plus `TaskTracker` from `tokio-util` for everything else. **Copy-paste prompt: graceful shutdown with TaskTracker** ```text In api/src/main.rs, serve the router with axum::serve(listener, app) .with_graceful_shutdown(signal) where signal completes on Ctrl+C or SIGTERM. Create one tokio_util::sync::CancellationToken and one tokio_util::task::TaskTracker. Spawn the outbox worker with tracker.spawn; the worker's loop must select! on token.cancelled() and finish its current job before returning. After the server future returns: cancel the token, call tracker.close(), and await tracker.wait() with a 10-second timeout. Add an integration test that starts the app, queues a job that takes 2 seconds, triggers shutdown, and asserts the job completed. Done means make check passes. ``` ```rust axum::serve(listener, app) .with_graceful_shutdown(shutdown_signal()) .await?; token.cancel(); // tell background workers to stop taking new work tracker.close(); // no new tasks may be spawned if tokio::time::timeout(Duration::from_secs(10), tracker.wait()).await.is_err() { tracing::warn!("background tasks did not finish within 10s"); } ``` The integration test is the evidence: it fails if the tracker is never awaited, because shutdown returns before the job finishes and the completion assertion sees an unfinished job. ### How do you generate Rust tests that catch real bugs? Name the cases, or you get happy-path tests only. Then add one test against a real Postgres, because a mocked repository cannot catch a wrong column or a missing unique index. `#[sqlx::test]` creates an isolated test database per test and applies `./migrations` automatically when the `migrate` feature is on. **Copy-paste prompt: repository tests against real Postgres** ```text Add db/tests/users.rs with #[sqlx::test] tests for UserRepository, each taking pool: PgPool. Cases: create then find_by_email returns the same id and email; find_by_email for an unknown address returns Ok(None); a second create with the same email returns AppError::Conflict; the returned User never serializes a password_hash field. Do not hand-roll database setup or teardown. List the cases in your final message before the code. ``` **Copy-paste prompt: property test for input validation** ```text Add a proptest to api/src/validation.rs for validate_create_user. Properties: (1) it never panics for any String inputs up to 1,000 characters, including non-ASCII; (2) every input it accepts has an email containing exactly one '@' and a name that is non-empty after trimming; (3) validation is idempotent, so validating an accepted value again returns the same value. Keep the default 256 cases. If a property fails, show the shrunk input before fixing the code. ``` Asking for the case list before the code gives you the one thing worth reading: the test list. For more on test design with agents, see [integration testing](/en/workflows/test/integration-testing/) and [property-based testing](/en/workflows/test/property-based-testing/). ## How do you verify agent-written Rust without reading every line? Read the gate output and the test list, not the diff. The compiler already rules out memory-safety bugs and data races in safe code, so human attention goes to what it cannot see: logic, error mapping, and whether the tests would notice a regression. | Gate | Command | What it catches | | --- | --- | --- | | Format | `cargo fmt --all -- --check` | Unformatted files the hook missed | | Lint | `cargo clippy --workspace --all-targets -- -D warnings` | Needless borrows and conversions, common correctness and performance lints; `.unwrap()` in production code once you enable `clippy::unwrap_used` | | Query metadata | `cargo sqlx prepare --workspace --check` | `.sqlx/` out of date with the queries, which breaks `SQLX_OFFLINE` builds in CI | | Tests | `cargo nextest run --workspace` and `cargo test --doc` | Wrong behaviour, wrong status codes, missing constraints | | Supply chain | `cargo deny check` | RustSec advisories, disallowed licences, duplicate or banned crates | | Test strength | `cargo mutants --in-diff pr.diff` | Changed code whose tests still pass when the code is broken | | Clone count | `git diff main -- '*.rs' \| grep -c '^+.*\.clone()'` | Clones the agent added to escape the borrow checker | | Review agent | `/code-review` (Claude Code), `codex review --base main` (Codex), Bugbot (Cursor) | Logic errors the gates cannot express | Generate `pr.diff` with `git diff main > pr.diff`. Mutation testing matters most here: a green suite proves only that the tests pass, and `cargo mutants` shows whether they fail when the changed code is broken. Run the first five gates in CI on every pull request ([CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/) has the workflow file) and the mutation run on the diff. The engineer who owns the service signs off on four things: the test-case list, a green gate, a mutation report with no missed mutants in changed code, and a clone count they can explain. Human reading goes to the hunks the review agent flags and to any `unsafe`, `spawn_blocking`, or transaction code. [Agent PR review](/en/workflows/ship/agent-pr-review/) covers how to split that work across a team. ## When agent-written Rust breaks Each failure below survives a quick look at the diff. Each one has a symptom you can detect and a recovery you can paste. - **Clone and `Arc` spam.** Symptom: the clone count in the diff jumps, or `Arc>` appears around data that only one task touches. Recovery: prompt "Remove every `.clone()` and `Arc` you added in this branch. For each one, either change the signature to borrow or explain in one line why ownership must move. Done means `make check` passes." - **Stale axum 0.7 idioms.** Symptom: the server panics at startup on a route such as `/users/:id`, or an extractor carries `#[async_trait]`. Cause: axum 0.8.0 changed path syntax to `/{id}` (the old syntax panics deliberately), and axum-core replaced `#[async_trait]` with return-position `impl Trait` in traits. Recovery: keep the axum rule in `AGENTS.md`, and prompt "Migrate this crate to axum 0.8: `/{param}` route syntax, no `#[async_trait]` on extractors. Change no behaviour." - **`query_as!` fails in CI but not locally.** Symptom: `set DATABASE_URL to use query macros online, or run cargo sqlx prepare`. Cause: the agent changed a query without refreshing `.sqlx/`. Recovery: run `cargo sqlx prepare --workspace` against a development database, commit `.sqlx/`, and set `SQLX_OFFLINE=true` in CI. The gate's `--check` step stops it recurring. - **The async runtime stalls under load.** Symptom: latency spikes on every endpoint while one endpoint is busy. Cause: argon2 hashing, `std::fs`, or a blocking HTTP client called directly in an `async fn`. Recovery: prompt "Find every CPU-heavy or blocking call inside an `async fn` in this workspace and move it into `tokio::task::spawn_blocking`. List each call you moved." - **Internal errors leak to clients.** Symptom: a 500 response body contains SQL, a table name, or a file path. Cause: `self.to_string()` used for every status. Recovery: the generic 5xx message in `into_response`, plus the handler test that asserts no SQL text in the body. - **"Zero-copy" that copies.** Symptom: the agent labels a parser zero-copy but it calls `.to_vec()` or collects into `Vec` per frame. Recovery: ask for `bytes::BytesMut::split_to(n).freeze()`, which hands out a reference-counted `Bytes` view into the same allocation, or for `tokio_util::codec::LengthDelimitedCodec` instead of hand-rolled framing. Prove the gain with a benchmark, not the label. - **The agent weakens a test to reach green.** Symptom: an assertion loosened, a case deleted, or `#[ignore]` added in the same diff as the fix. Recovery: revert the test file, restate the rule from `AGENTS.md`, and make CI fail when a pull request modifies, renames or deletes an existing test without a `test-change` label: `git diff --name-status --diff-filter=MDR origin/main... -- '*tests/*' | awk -F'\t' '{print $2}'` lists those files by the path they had before the change, and [protect the oracle](/en/workflows/test/protect-the-oracle/) shows the full check. "It compiles" is stronger evidence in Rust than in most languages, and it is still not proof of correct behaviour. The borrow checker cannot tell a 404 from a 500, see a leaked error message, or notice a test that asserts nothing. Treat the handler tests, `#[sqlx::test]` tests, and the mutation run as part of the definition of done. ## Where to go next with Rust services - Make the repository agent-ready first, if it is not yet: [agent-ready codebase](/en/workflows/harness/agent-ready-codebase/). - Choose and lock down a database MCP server: [database MCP servers](/en/ecosystem/mcp/database-mcp/). - Harden the data layer: [SQL optimization patterns](/en/cookbook/database-recipes/sql-patterns/) and [database migration patterns](/en/cookbook/database-recipes/migration-patterns/). - Design the HTTP surface: [API development patterns](/en/cookbook/backend-recipes/api-patterns/). - Decide what the agent may run unattended: [permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/). - Compare with another compiled backend: [Go language patterns](/en/cookbook/backend-recipes/go-patterns/), or return to the [backend recipes overview](/en/cookbook/backend-recipes/). --- # Serverless Development Patterns URL: https://developertoolkit.ai/en/cookbook/backend-recipes/serverless-patterns/ Description: Agent recipes for AWS Lambda, Cloudflare Workers and Vercel — idempotent handlers, binding checks, cold-start triage, and tests that prove it. Serverless development patterns for AI coding agents are recipes that make Claude Code, Codex and Cursor produce AWS Lambda, Cloudflare Workers and Vercel code that survives production: handlers that stay idempotent when events are redelivered, Worker bindings that match `wrangler.toml`, and cold-start fixes that come before provisioned concurrency. Each recipe ends in a test or gate, not a manual read. This page is for backend developers who already ship functions and now let an agent write most of them. The situation it fixes: your image-processing Lambda fires twice on the same S3 upload, CloudWatch is a wall of unstructured `console.log`, and the p99 spike every morning was "fixed" by provisioned concurrency on every function, which doubled the bill. Serverless removes the servers, not the distributed-systems problems. Retries, idempotency, cold starts and per-platform limits are still your code, and an agent writes the happy path unless you ask for more. The recipes assume a TypeScript project with Vitest; if you do not have that toolchain yet, set it up with [Node.js patterns](/en/cookbook/backend-recipes/node-patterns/) first, or pick another stack from the [backend recipes hub](/en/cookbook/backend-recipes/). ## What you'll walk away with from these serverless recipes - A prompt that produces an idempotent S3-to-Lambda handler, plus the corrected handler shape to check it against. - A test prompt that proves the handler survives a duplicate delivery and a mid-flight failure, so you verify behaviour instead of reading the diff. - A Cloudflare Worker API gateway prompt with a matching `wrangler.toml`, and two commands that catch binding drift and bundle bloat before deploy. - Per-tool setup for the Cloudflare MCP server and the Cloudflare skills, with the context cost of the MCP server. - A cold-start triage prompt that tells you when provisioned concurrency is worth paying for. - The failure modes that reach production (duplicate SQS deliveries, recursive S3 triggers, Workers CPU limits, stuck idempotency claims) and how to recover from each. ## How do you scaffold a serverless service with an agent? Give the agent one concrete service, a region, a runtime and the event sources. All three tools drive the same framework CLIs (Serverless Framework, AWS SAM, Wrangler), so pick the tool by where the work lives, not by capability. The scaffold prompt below uses Serverless Framework v4 (`serverless` 4.43.0 on npm, checked 2026-09-26) and Node.js 22. **Claude Code** Run from the empty repo in a terminal. For the first run, pass `--permission-mode manual` to approve each edit yourself (from v2.1.283, on both release channels on 2026-10-12, interactive sessions otherwise start in auto mode). Switch to `--permission-mode acceptEdits`, as below, once you trust the plan. ```bash claude --permission-mode acceptEdits "Set up a Serverless Framework v4 service in TypeScript for AWS eu-central-1: one HTTP Lambda behind API Gateway (GET /health), one S3-triggered image Lambda that only fires for the uploads/ prefix, and a DynamoDB table 'media' (PK id) plus a 'dedupe' table with TTL on 'ttl'. esbuild bundling, Node.js 22 runtime, dev and prod stages. Add a vitest setup and an npm 'test' script. Do not deploy." ``` Use `claude -p` with the same prompt when the scaffold has to be reproducible in a script. **Codex** Keep writes inside the workspace and let Codex ask before anything wider: ```bash codex --sandbox workspace-write -a on-request "Set up a Serverless Framework v4 service in TypeScript for AWS eu-central-1: one HTTP Lambda behind API Gateway (GET /health), one S3-triggered image Lambda that only fires for the uploads/ prefix, a DynamoDB table 'media' (PK id) and a 'dedupe' table with TTL on 'ttl'. esbuild, Node.js 22, dev and prod stages, vitest with an npm 'test' script. Do not deploy." ``` Permission profiles (`-c default_permissions=":workspace"`, beta) are the newer control; `--sandbox` still works in codex-cli 0.157.1. Do not combine the two. To run the same task in Codex Cloud and review a branch instead, `codex cloud exec --env ENV_ID ""` submits it (`--env` is required in codex-cli 0.157.1; list environments with `codex cloud`). **Cursor** Paste the same prompt into Cursor's agent in the open repository and review the proposed diff file by file before you accept it. For a larger scaffold, ask for a plan first with Plan Mode, then let the agent execute it. Stay on your tool's default model for this work and raise effort before switching models. The current defaults and prices live on the [AI models hub](/en/ecosystem/models/). ## How do you make an AWS Lambda handler idempotent? S3, SQS and EventBridge deliver events at least once. A handler with side effects (writes, emails, charges) must claim a stable key before it acts, skip the work when the claim already exists, and release the claim when the work fails, so the retry can run. Generated handlers often get the first two right and miss the third: they write the dedupe record, crash in `sharp`, and every retry is then skipped as a "duplicate". The object is never processed. **Copy-paste prompt: idempotent S3 to Lambda image processor** ```text Write an AWS Lambda handler in TypeScript (Node.js 22) for an S3 ObjectCreated trigger on the uploads/ prefix. It resizes the image to 256, 512 and 1024px WebP with sharp and writes them under derived/ in a SEPARATE destination bucket (never the source bucket, to avoid a recursive trigger). Idempotency: URL-decode the object key (S3 encodes spaces as '+'). Before any side effect, claim pk = /# with a DynamoDB PutItem using ConditionExpression 'attribute_not_exists(pk)' and a 'ttl' attribute 7 days out. If the condition fails, log status 'duplicate-skipped' and continue. If the resize or write fails, DELETE the claim, log status 'failed', and rethrow so the event reaches the on-failure destination. Logging: exactly one JSON line per record with requestId, bucket, key, pk, status and durationMs. Then give me the serverless.yml function block: memorySize 1024, timeout 30, the s3 event with the uploads/ prefix rule, an SQS on-failure destination, and IAM limited to GetObject on the source, PutObject on derived/ in the destination, and PutItem/DeleteItem on the dedupe table. ``` Check the output against this shape. The order of operations is what matters, not the style: ```typescript // handler.ts: claim, work, release on failure import type { S3Event } from 'aws-lambda'; import { DynamoDBClient, PutItemCommand, DeleteItemCommand } from '@aws-sdk/client-dynamodb'; import { resizeAndWrite } from './resize'; const ddb = new DynamoDBClient({}); const TABLE = process.env.DEDUPE_TABLE!; export const handler = async (event: S3Event) => { for (const rec of event.Records) { const start = Date.now(); const bucket = rec.s3.bucket.name; const key = decodeURIComponent(rec.s3.object.key.replace(/\+/g, ' ')); const pk = `${bucket}/${key}#${rec.s3.object.eTag}`; const log = { requestId: rec.responseElements['x-amz-request-id'], bucket, key, pk }; try { await ddb.send(new PutItemCommand({ TableName: TABLE, Item: { pk: { S: pk }, ttl: { N: String(Math.floor(start / 1000) + 7 * 86400) } }, ConditionExpression: 'attribute_not_exists(pk)', })); } catch (err) { if ((err as Error).name !== 'ConditionalCheckFailedException') throw err; console.log(JSON.stringify({ ...log, status: 'duplicate-skipped' })); continue; } try { await resizeAndWrite(bucket, key); console.log(JSON.stringify({ ...log, status: 'ok', durationMs: Date.now() - start })); } catch (err) { await ddb.send(new DeleteItemCommand({ TableName: TABLE, Key: { pk: { S: pk } } })); console.error(JSON.stringify({ ...log, status: 'failed', error: (err as Error).message })); throw err; } } }; ``` A timeout can still kill the function between the claim and the release, which leaves a claim that blocks every retry. If you would rather not hand-roll a lease with an expiry, ask the agent to use `@aws-lambda-powertools/idempotency` (2.35.0 on npm, checked 2026-09-26) instead: it stores an in-progress record with its own expiry and a completed record with the result, which covers that case. ## How do you prove the handler survives a duplicate delivery? Do not read the handler line by line. Write down the four behaviours that matter and make a test fail if any of them breaks. Tell the agent the tests are the specification, so a failing test leads to a handler fix and not to an edited assertion. [Protect the oracle](/en/workflows/test/protect-the-oracle/) explains why that instruction matters. **Copy-paste prompt: duplicate-delivery and failure tests** ```text Write a vitest suite for src/handler.ts using aws-sdk-client-mock (mock DynamoDBClient) and vi.mock('./resize'). Build S3Event fixtures by hand. Cover exactly these behaviours: 1. The same S3 event delivered twice: resizeAndWrite is called once, and the second invocation logs status 'duplicate-skipped'. 2. resizeAndWrite throws: the handler sends DeleteItemCommand for the same pk and rethrows. 3. A key 'uploads/my+photo.jpg' reaches resizeAndWrite as 'uploads/my photo.jpg'. 4. A DynamoDB error other than ConditionalCheckFailedException is rethrown without calling resizeAndWrite. Do not modify src/handler.ts to make a test pass. If a test fails, stop and tell me which behaviour the handler gets wrong. ``` Then run the gates. Each one goes red for a specific bug, which is what lets you trust the result without reviewing every line: | Gate | Command (terminal or CI) | Goes red when | | --- | --- | --- | | Behaviour tests | `npx vitest run` | A duplicate is processed twice, the claim is not released after a failed resize, or a key is not decoded | | Types | `npx tsc --noEmit` | The handler reads a field the event type does not have | | Package | `npx serverless package --stage dev` | `serverless.yml` does not parse or a handler path is wrong | | Worker bindings | `npx wrangler types`, then `npx tsc --noEmit` | Worker code reads a binding that `wrangler.toml` does not declare | | Worker bundle | `npx wrangler deploy --dry-run --outdir dist` | The printed `Total Upload` exceeds the size budget a CI step compares it against (for example, fail above 1 MiB); the dry run itself never fails on size, and nothing is uploaded | | Production signal | CloudWatch Logs Insights: `stats count(*) by status` | The `duplicate-skipped` or `failed` count moves after a release | You own the tests and the gates. Changes to IAM policies, on-failure destinations and stage configuration go to a human reviewer, because a wrong IAM grant passes every test above. Deploys run from CI, not from an agent session. The [evidence bundle](/en/workflows/ship/evidence-bundle/) page shows how to attach the gate results to the pull request. To have the agent run the gates and fix what fails without supervision: **Claude Code** ```bash claude -p "Run npx vitest run and npx tsc --noEmit. If anything fails, fix src/, never tests/, and rerun until both pass. Print which behaviour was wrong and what you changed." \ --permission-mode acceptEdits \ --allowedTools "Bash(npx vitest *)" "Bash(npx tsc *)" \ --disallowedTools "Edit(tests/**)" "Write(tests/**)" ``` **Codex** ```bash codex exec --sandbox workspace-write "Run npx vitest run and npx tsc --noEmit. If anything fails, fix src/, never tests/, and rerun until both pass. Print which behaviour was wrong and what you changed." ``` **Cursor** Paste the same instruction into the agent. To run it on every pull request instead, use a Cloud Agent automation with a Source control trigger, and let Bugbot review the resulting pull request, as described in [Cursor CI/CD](/en/cursor-ide/ship/ci-cd/). The prompt alone only asks the agent to leave `tests/` alone. In Claude Code, `--disallowedTools` makes that a rule the session cannot break. For Codex and Cursor, enforce it outside the agent: a CODEOWNERS entry that requires a human review for `tests/`, or a CI check that fails when an agent branch changes files under `tests/`. ## How do you build a Cloudflare Worker API gateway with matching bindings? Workers have no Node.js runtime by default, a CPU-time budget per request, and bindings instead of SDK clients. Ask for the Worker and its config in one prompt so the binding names in code and in `wrangler.toml` come from the same answer. **Copy-paste prompt: Cloudflare Worker API gateway** ```text Write a Cloudflare Worker in TypeScript (ES modules) that acts as an API gateway: proxy GET /v1/* to the origin in the ORIGIN var with fetch, check a bearer token against the TOKENS KV namespace, rate-limit each token to 100 requests per minute with a Durable Object class RateLimiter, and cache successful GETs in the Cache API for 60 seconds. Return JSON errors { error, requestId } with correct status codes. Keep synchronous CPU work small: move heavy CPU work out of the request into a Queue consumer or a Durable Object, and use ctx.waitUntil only for non-blocking I/O such as logging and analytics. Then give me wrangler.toml with the KV binding, the Durable Object binding and its migration, and the ORIGIN var, and add a test with @cloudflare/vitest-pool-workers that asserts 401 without a token and 429 on the 101st request. ``` ```toml # wrangler.toml: binding names must match the Worker's Env type name = "api-gateway" main = "src/index.ts" compatibility_date = "2026-09-01" [vars] ORIGIN = "https://origin.internal.example.com" [[kv_namespaces]] binding = "TOKENS" id = "KV_NAMESPACE_ID" [[durable_objects.bindings]] name = "RATE_LIMITER" class_name = "RateLimiter" [[migrations]] tag = "v1" new_sqlite_classes = ["RateLimiter"] ``` Replace `KV_NAMESPACE_ID` with the id that `npx wrangler kv namespace create TOKENS` prints. Then run `npx wrangler types`: it regenerates the `Env` type from this file, so a Worker that reads `env.TOKEN` instead of `env.TOKENS` fails `tsc` instead of failing at runtime. ## How do you give the agent live Cloudflare state? Generated code is half the job. The other half is the state it runs against: a mistyped namespace id, a stale KV value, a route that throws in production. Cloudflare offers two ways to put that in front of the agent, and they solve different problems. - **The Cloudflare MCP server** reads and changes your live account. The recommended Code Mode server at `https://mcp.cloudflare.com/mcp` exposes three tools (`search`, `execute`, `docs`) over the whole Cloudflare API. Cloudflare puts its schema cost at about 1,000 tokens, against about 244,000 for native tool schemas of the same API (Cloudflare, `cloudflare/mcp` README, read 2026-09-26). Results are capped at about 6,000 tokens by default. Domain servers such as `https://observability.mcp.cloudflare.com/mcp` cover one area each. - **The Cloudflare skills** (`cloudflare/skills`, 14 skills for Workers, Wrangler, Durable Objects and more) teach the agent the platform's conventions. The plugin form bundles the same Code Mode MCP server. The MCP server needs a URL entry per tool. Authentication is OAuth on first use, or a Cloudflare API token sent as a bearer token. **Claude Code** ```bash claude mcp add --transport http cloudflare https://mcp.cloudflare.com/mcp # or the plugin, which brings the skills and the MCP server together: # /plugin marketplace add cloudflare/skills # /plugin install cloudflare@cloudflare ``` Leave out `--transport http` and Claude Code 2.1.283 still saves the URL as a stdio command. It prints a warning, but the entry is written and fails at connect time. **Codex** ```bash codex mcp add cloudflare --url https://mcp.cloudflare.com/mcp # or the plugin: codex plugin marketplace add cloudflare/skills codex plugin add cloudflare@cloudflare ``` **Cursor** Add the server to `.cursor/mcp.json`: ```json { "mcpServers": { "cloudflare": { "url": "https://mcp.cloudflare.com/mcp" } } } ``` For the skills alone, `npx skills add https://github.com/cloudflare/skills` installs them for Cursor and other agents. Before MCP, finding a stale token meant copying namespace ids between dashboard tabs. With it, one prompt answers from the live account: **Copy-paste prompt: read live Worker state** ```text Using the Cloudflare MCP server: list the bindings of the api-gateway Worker, confirm the TOKENS KV namespace id matches the one in wrangler.toml, and show the last hour of errors for api-gateway grouped by route. Read only: do not change any resource. ``` Pick the skill when the agent only needs to know `wrangler` commands and conventions. Pick the MCP server when it has to read or change live state, and keep write access out of sessions where you do not need it. For AWS, the equivalent is AWS's own plugin set (`aws/agent-toolkit-for-aws`, with an `aws-core` plugin for serverless and CDK work). In Claude Code, install it with `/plugin install aws-core@claude-plugins-official`. In Codex, run `codex plugin marketplace add aws/agent-toolkit-for-aws`, then install `aws-core` from `/plugins`. The full server list and OAuth details are on the [Cloudflare MCP](/en/ecosystem/mcp/cloudflare-mcp/) page. ## More serverless prompts: cold starts, queues and Vercel **Copy-paste prompt: cold-start triage before provisioned concurrency** ```text My Lambda image-processor (Node.js 22, 1024 MB, in a VPC) has a p99 of 4 s in the morning and about 300 ms the rest of the day. Write a CloudWatch Logs Insights query that splits REPORT lines into Init Duration and Duration and shows how many invocations were cold. Then rank the likely causes: bundle size, SDK clients created at module scope, VPC networking, unused dependencies. Propose the cheapest fixes first (esbuild tree-shaking, dropping unused packages, lazy imports, removing the VPC if it is only there for DynamoDB). Recommend provisioned concurrency, with a concrete number, only if those fixes cannot bring p99 under 1 s, and say how to measure the result. ``` **Copy-paste prompt: SQS consumer with partial batch failures** ```text Write an SQS to Lambda consumer in TypeScript for order events with batchSize 10 and functionResponseType ReportBatchItemFailures, so one poison message does not fail the whole batch. Validate each message with a zod schema. Make the handler idempotent on orderId with a DynamoDB conditional write that is released on failure. Give me the serverless.yml for the queue and a DLQ with maxReceiveCount 3, a replay.ts script that moves DLQ messages back to the main queue, and vitest tests for: one invalid message in a batch of ten, and the same orderId delivered twice. ``` **Copy-paste prompt: Vercel Function with geolocation A/B routing** ```text Write a Vercel Function that assigns a stable A/B variant: read the visitor country with geolocation(request) from @vercel/functions; bucket visitors whose country is in the comma-separated AB_COUNTRIES environment variable into the experiment, with the variant derived from a hash of a 'variant' cookie (set one if it is missing), and send everyone else to variant A; then stream the chosen origin's HTML through unchanged. Set the cookie on the first visit only. Use Web standard Request, Response and streams so the code has no Node.js-only APIs. Add tests that the same cookie always yields the same variant and that a visitor from a country outside AB_COUNTRIES always gets variant A. ``` ## What breaks when agent-written serverless code reaches production? **Duplicate processing on retries** A frequent serverless bug, and happy-path output rarely handles it. Symptom: two emails, two charges, or thumbnails overwritten. Recovery: find the stable key (S3 `eTag`, SQS `messageId`, your own `orderId`), then re-prompt: "This handler is not idempotent. Add a DynamoDB conditional-write claim on KEY before any side effect, release it on failure, and add a test that delivers the same event twice." **An idempotency claim that never clears** Symptom: an object is never processed and every retry logs `duplicate-skipped`. Cause: the claim was written, then the function timed out or crashed before the release ran. Recovery: delete the stuck record, then replace the plain claim with a lease that expires (an in-progress status plus an expiry shorter than the retry window), or switch to `@aws-lambda-powertools/idempotency`. **A recursive S3 trigger** Symptom: invocation count and bill climb within minutes. Cause: the function writes its output into the bucket that triggers it. Recovery: set the function's reserved concurrency to 0 to stop it, then write output to a separate bucket or restrict the trigger to an input prefix such as `uploads/`. Add that constraint to every S3 prompt. Lambda's recursive loop detection, on by default, covers loops through Amazon S3 and stops the function after about 16 invocations in the same chain, but only when the function uses a supported AWS SDK version (AWS Lambda recursive loop detection docs, checked 2026-09-26). Treat it as a backstop, not the fix: the separate bucket or prefix is what prevents the loop. **Cloudflare Workers CPU limits, not wall-clock limits** Workers cap CPU time per request, not time spent waiting on `fetch`: 10 ms on the Free plan, and on the Paid plan 30 seconds by default, raisable to 5 minutes with `limits.cpu_ms` (Cloudflare Workers limits page, checked 2026-09-26). A Worker that parses large JSON or hashes in a loop fails with Error 1102 even though it is fast on your laptop. Recovery: ask the agent to "profile the synchronous CPU work in the request path, move heavy CPU work out of the request into a Queue consumer or a Durable Object, and use ctx.waitUntil only for non-blocking I/O such as logging". **DynamoDB hot partitions** A low-cardinality partition key (for example `status#PENDING`) sends all traffic to one partition, and you get `ProvisionedThroughputExceededException` under load while average utilisation looks low. Recovery: ask the agent to "check the partition-key cardinality and propose a write-sharding suffix or a GSI" instead of raising capacity. **Provisioned concurrency as a reflex** Enabling it on every function is how the bill doubles. It pays off only on a latency-sensitive synchronous path with predictable traffic. Asynchronous handlers such as the S3 and SQS consumers above rarely need it. Run the cold-start triage prompt first and measure `Init Duration` before and after each fix. ## Where to go next with serverless - [API development patterns](/en/cookbook/backend-recipes/api-patterns/) — Idempotency keys, pagination and OpenAPI for the routes behind the gateway Worker. - [NoSQL patterns](/en/cookbook/database-recipes/nosql-patterns/) — DynamoDB key design and access patterns for the tables these handlers use. - [Infrastructure as code](/en/cookbook/devops-recipes/infrastructure-as-code/) — Promote these stacks to Terraform or Pulumi with multi-stage deploys. - [Monitoring and observability](/en/workflows/operate/monitoring-observability/) — Turn the structured log lines into alerts and dashboards. - [Cloudflare MCP](/en/ecosystem/mcp/cloudflare-mcp/) — Code Mode, the domain servers, OAuth and per-tool setup. - [Best backend and platform skills](/en/ecosystem/skills/top-skills-backend/) — Cloudflare, AWS and database skills compared. --- # Data Engineering Recipes URL: https://developertoolkit.ai/en/cookbook/data-recipes/ Description: Copy-paste recipes for dbt models, SQL pipelines, notebooks and data tests with Claude Code, Codex or Cursor, each proven by a dbt build on a dev target. The data engineering recipes are copy-paste prompts for Claude Code, Codex, and Cursor covering dbt models, SQL pipelines, notebooks, and data tests. Every recipe follows the same contract: the agent reads the project through the dbt MCP server, builds only on a dev target, and returns `dbt build` output plus a row-level diff instead of SQL for a human to read. It is for developers and analytics engineers who let an agent change a pipeline, and it guards against one failure: the model compiles, then the revenue dashboard moves because a join fanned out. ## Which data engineering recipe fits your task? | Your task | Recipe | The gate that proves it | | --- | --- | --- | | Add or change a dbt model | [Build a dbt model test-first](#build-a-dbt-model-test-first) | Unit tests written before the SQL; `dbt build` on the model and everything downstream | | Refactor a model without changing its numbers | [Refactor with a row-level diff](#refactor-a-dbt-model-without-changing-the-numbers) | `audit_helper` comparison against production: zero changed rows | | Clean up or productionize a Jupyter notebook | [Keep notebooks reviewable](#keep-notebooks-reviewable-and-runnable) | Paired `.py` diff plus `pytest --nbval-lax` on a clean kernel | | Tune a slow warehouse query or plan a schema change | [SQL optimization](/en/cookbook/database-recipes/sql-patterns/) and [migration patterns](/en/cookbook/database-recipes/migration-patterns/) | Query plan and timing before and after; up, down, up on a copy | For ingestion jobs and APIs in Python, use the [Python workflow recipes](/en/cookbook/backend-recipes/python-patterns/); for everything else, the [AI Developer Cookbook](/en/cookbook/). ## Give the agent your data rules before any recipe Without rules, an agent runs `dbt run` against the default target and "fixes" a failing test by deleting it. Write the rules once, where each tool loads them: ```markdown ## Data rules - Never run dbt against the prod target. Use --target dev; the default target in profiles.yml is dev. - Select only what changed: --select state:modified+ --defer --state prod-artifacts - Never delete, disable, or loosen a data test (severity, where:, error_if) to make a build pass. Report the failure and stop. - Never SELECT raw columns tagged pii; profile them with counts and null rates only. - After any change, run scripts/verify-dbt.sh and paste the full output in your summary. ``` **Claude Code** Add the block to `CLAUDE.md` at the repository root. Claude Code loads it in every session, including headless `claude -p` runs. **Codex** Add the block to `AGENTS.md` at the repository root. An untrusted project does not supply its project-level `AGENTS.md` (Codex 0.150.0 and later), so mark the repository as trusted: add `[projects."/abs/path/to/repo"]` with `trust_level = "trusted"` to `~/.codex/config.toml` (key checked in the Codex 0.157.1 source). **Cursor** Save the same text as a project rule. [Cursor's Rules documentation](https://cursor.com/docs/rules) shows where project rules live and how to make one apply to every request. `prod-artifacts/` holds the last production `manifest.json`, so only your changes build. Before each run, download that `manifest.json` from your last production run's CI artifacts into `prod-artifacts/`; `state:modified` and `--defer` fail without it. ## Connect the dbt MCP server and the dbt agent skills The **dbt MCP server** from dbt Labs (PyPI `dbt-mcp`, requires Python 3.12 or 3.13) gives the agent lineage, node details, `list`, `compile`, and `show`. The **dbt agent skills** (`dbt-labs/dbt-agent-skills`) teach dbt conventions such as unit tests. The commands below disable the server's `run`, `build`, `test`, `clone`, and `docs` tools, so every build goes through the gate script: **Claude Code** ```bash # Terminal, from the dbt project root. Requires uv and dbt on PATH (or set DBT_PATH). claude mcp add dbt -e DBT_PROJECT_DIR="$PWD" -e DISABLE_TOOLS=run,build,test,clone,docs -- uvx dbt-mcp # In the Claude Code prompt: install the skills as a plugin /plugin marketplace add dbt-labs/dbt-agent-skills /plugin install dbt@dbt-agent-marketplace ``` **Codex** ```bash # Terminal, from the dbt project root. Requires uv and dbt on PATH (or set DBT_PATH). codex mcp add dbt --env DBT_PROJECT_DIR="$PWD" --env DISABLE_TOOLS=run,build,test,clone,docs -- uvx dbt-mcp npx skills add dbt-labs/dbt-agent-skills --skill using-dbt-for-analytics-engineering --skill adding-dbt-unit-test -a codex ``` **Cursor** Add the server to `.cursor/mcp.json`, with the absolute path of your dbt project: ```json { "mcpServers": { "dbt": { "command": "uvx", "args": ["dbt-mcp"], "env": { "DBT_PROJECT_DIR": "/Users/you/code/analytics", "DISABLE_TOOLS": "run,build,test,clone,docs" } } } } ``` Then install the skills: `npx skills add dbt-labs/dbt-agent-skills --skill using-dbt-for-analytics-engineering --skill adding-dbt-unit-test -a cursor`. The `show` tool still runs SQL through `profiles.yml`, so the default target must be dev. For warehouse access outside dbt, see [database MCP servers](/en/ecosystem/mcp/database-mcp/). ## Build a dbt model test-first Write the expected rows before the SQL. dbt unit tests (`unit_tests:`, dbt Core 1.8 and later) assert the output for fixed input rows, so guessing cannot pass. This is the [test-driven loop](/en/method/principles/test-driven-development/) applied to SQL. **Copy-paste prompt: a new dbt model, test-first** ```text I need a model fct_daily_revenue: one row per order_date and currency, summing net revenue from stg_orders (exclude status = 'cancelled') and refunds from stg_refunds, converted to EUR with stg_fx_rates on the order date. 1. Use the dbt MCP server to read the lineage and columns of every input. Print the grain and primary key of each input as a table. 2. Before writing SQL, add a unit test in models/marts/_fct_daily_revenue.yml with fixed input rows covering: a cancelled order, a partial refund, a missing FX rate, and two currencies on one day. Show me the expected rows. 3. Write the model. Add a dbt_utils.unique_combination_of_columns test on (order_date, currency) and not_null tests on both columns. dbt_utils must already be in packages.yml; if it is not, stop and ask me. 4. Run scripts/verify-dbt.sh and paste the full output. Stop and ask me if an input's grain makes the join fan out. ``` ## Refactor a dbt model without changing the numbers Data proves a refactor, not the diff. The `audit_helper` package (dbt Hub `dbt-labs/audit_helper`) compares the dev build with the production relation row by row. The prompt aggregates the result, because `dbt show` prints five rows by default and the macro returns at most 20 sample rows per status. **Copy-paste prompt: refactor with a row-level proof** ```text Refactor models/marts/fct_orders.sql: replace the three nested subqueries with CTEs and move the currency logic into int_orders_converted. The output must not change. 1. Add dbt-labs/audit_helper to packages.yml if it is missing, then run dbt deps. 2. Build the refactored model with --target dev. 3. Write analyses/compare_fct_orders.sql using audit_helper.compare_and_classify_relation_rows to compare the dev relation with the production relation on primary key order_id. Wrap it as select dbt_audit_row_status, max(dbt_audit_num_rows_in_status) from (...) group by 1 and run dbt show --select compare_fct_orders --limit -1. 4. Report the row count of each relation and the row count per status. Done means the only status is identical and both row counts are equal. If not, show five examples and stop; do not edit tests or the comparison. ``` ## Keep notebooks reviewable and runnable Agents edit `.ipynb` JSON poorly. Pair each notebook with a script via Jupytext (`jupytext --set-formats ipynb,py:percent notebook.ipynb`), let the agent edit the `.py` file, and prove the result with nbval on a clean kernel. **Copy-paste prompt: clean up a notebook before it becomes a pipeline** ```text Work on notebooks/churn_analysis.py (the Jupytext pair of the .ipynb), never the .ipynb JSON. Make it run top to bottom on a fresh kernel: remove cells that depend on execution order, replace hard-coded file paths with a DATA_DIR variable, and move the feature-engineering cells into src/features/churn.py with pytest tests. Then run jupytext --sync notebooks/churn_analysis.py and pytest --nbval-lax notebooks/churn_analysis.ipynb, and paste both outputs. List any cell whose output changed and why. ``` ## How do you verify agent-written data changes without reading every line? Put the gates in one script that every tool, human, and CI runs. It refuses prod and builds with zero rows before the real build: ```bash #!/usr/bin/env bash # scripts/verify-dbt.sh: dev target only. Delete the lines your project does not use. set -euo pipefail TARGET="${DBT_TARGET:-dev}" if [ "$TARGET" = "prod" ]; then echo "refusing to run against prod"; exit 1; fi SEL=(--select state:modified+ --defer --state prod-artifacts --target "$TARGET") [ -d dbt_packages ] || dbt deps # needs network; skipped once packages are installed dbt parse --warn-error --target "$TARGET" dbt build "${SEL[@]}" --empty dbt build "${SEL[@]}" sqlfluff lint models/ pytest --nbval-lax notebooks/ echo "PASS all data gates" ``` Make the script executable once, so the allow rules below can call it without a `bash` prefix: ```bash chmod +x scripts/verify-dbt.sh ``` A human signs off on two things only: the row-level comparison for any change to a model that feeds a dashboard or an export, and any `--full-refresh` of an incremental model. Both go in the pull request's [evidence bundle](/en/workflows/ship/evidence-bundle/). To run the gates unattended, save this fix-until-green prompt as `prompts/dbt-gates.txt`: **Copy-paste prompt: prompts/dbt-gates.txt** ```text Run scripts/verify-dbt.sh exactly as written, with no ./ or bash prefix. If it fails, fix only the model SQL. Never edit tests, test YAML, packages.yml, profiles.yml, or scripts/verify-dbt.sh. Rerun until it prints PASS all data gates, or stop after 3 failed attempts. Then paste the final output of the script and list every file you changed. ``` **Claude Code** ```bash # Terminal, on a trusted branch. Edits allowed; shell limited to the gate # script; dbt MCP tools allowed (run/build/test/clone/docs are disabled on the server). claude -p "$(cat prompts/dbt-gates.txt)" \ --allowedTools "Read,Grep,Glob,Edit,Bash(scripts/verify-dbt.sh),Bash(./scripts/verify-dbt.sh),mcp__dbt" \ --output-format json > dbt-gates.json ``` **Codex** ```bash # Terminal. dbt deps runs outside the sandbox; -o saves the final summary. dbt deps # Local DuckDB target: the permission profile (beta) keeps writes in the workspace. codex exec -c default_permissions=":workspace" -o dbt-gates.md "$(cat prompts/dbt-gates.txt)" # Cloud warehouse, only where the agent's credentials reach dev schemas alone. codex exec --sandbox workspace-write -c sandbox_workspace_write.network_access=true \ -o dbt-gates.md "$(cat prompts/dbt-gates.txt)" ``` The sandbox blocks outbound network by default (`workspace-write` ships with `network_access = false`, Codex 0.157.1 source), so install packages first; the script then skips `dbt deps`. The cloud form adds the network override because dbt must reach the warehouse. The permission profile and the legacy `--sandbox` do not compose, so use one or the other in a single call, never both. **Cursor** Paste the prompt into the agent and accept the diff only after `PASS`. ## What breaks when agents write data pipelines? **Data recipe failure modes and recovery** - **A join that fans out** and doubles revenue. Recovery: a `unique` test on the model's grain. - **A green build because a test was weakened** (`severity: warn`, a `where:` filter, a deleted test). Recovery: revert, and require code-owner approval on test YAML; see [protecting the oracle](/en/workflows/test/protect-the-oracle/). - **The agent built into production.** Recovery: default target dev, the gate script, and no production write grant for the agent's credentials; see [permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/). - **An incremental model that drifts from its full rebuild** (the `is_incremental()` branch was not updated). Recovery: `--full-refresh` in dev, compared with the refactor recipe. - **Tests that pass on toy data.** Recovery: realistic, masked fixtures; see [test data management](/en/workflows/test/test-data-management/). ## Where to go next with data engineering - [Database recipes](/en/cookbook/database-recipes/) — Migrations, ORM code, and SQL tuning for the transactional side. - [Protecting the oracle](/en/workflows/test/protect-the-oracle/) — Keep the data tests out of the agent's reach, so a green build still means something. - [Database design and queries](/en/workflows/build/database-development/) — The end-to-end workflow around schema changes. - [Installing, sharing and pinning skills](/en/ecosystem/skills/installing-managing/) — How skills load and update in all three tools. - [Evidence bundle](/en/workflows/ship/evidence-bundle/) — What a pull request carries so a reviewer checks results, not lines. --- # Database recipes URL: https://developertoolkit.ai/en/cookbook/database-recipes/ Description: Pick the right database recipe for migrations, ORMs, SQL tuning or NoSQL, ground the agent in your real schema, and prove each change on a real engine. The database recipes are four pages of copy-paste prompts for Claude Code, Codex, and Cursor: schema migrations, ORM code, SQL optimization, and NoSQL data models. Every recipe assumes two things: the agent reads the real schema through a read-only connection, and a real database engine, not a human reading the SQL, proves each change safe. This hub is for developers who let an agent write the database half of a feature. You know the failure: the migration passes on an empty local database, then locks a 40-million-row table in production, or the agent invents a column because it guessed the schema from a model file. ## Which database recipe fits your task? Pick by the job in front of you, not by the order of the list. | Your task | Recipe | The gate that proves it | | --------------------------------------------------- | -------------------------------------------------------------------------- | ---------------------------------------------------------------- | | Rename, split, or backfill a column without downtime | [Database migration patterns](/en/cookbook/database-recipes/migration-patterns/) | Squawk lint, a parity query that returns zero rows, a rollback per phase | | Prisma or TypeORM models, N+1 queries, transactions | [ORM best practices](/en/cookbook/database-recipes/orm-patterns/) | Integration tests on real Postgres; query count per request | | A slow query or a missing index | [SQL optimization patterns](/en/cookbook/database-recipes/sql-patterns/) | Postgres `EXPLAIN (ANALYZE, BUFFERS)` / MySQL `EXPLAIN ANALYZE` before and after, on realistic data | | MongoDB, DynamoDB, Neo4j, or vector data models | [NoSQL patterns and strategies](/en/cookbook/database-recipes/nosql-patterns/) | Access-pattern tests against the real engine | For the end-to-end workflow around these recipes (spec, schema review, rollout), read [database development with AI agents](/en/workflows/build/database-development/). ## Connect the agent to your schema before any recipe A recipe run against a guessed schema produces confident, wrong SQL. Give the agent a read-only view of a local or staging database first. DBHub (Bytebase, npm `@bytebase/dbhub` 1.3.1 on 2026-09-26) covers Postgres, MySQL, SQL Server, MariaDB, Oracle, and SQLite with one server. Connect it with a role that can only read. The missing write grants are what enforce read-only; `default_transaction_read_only` only catches accidents, because a session can switch it off. The default-privileges line keeps tables created by later migrations visible to the agent: ```sql -- Run once in psql on the local or staging database, as the role that runs migrations. -- \password prompts for the password, so it never lands in shell history. CREATE ROLE agent_ro LOGIN; \password agent_ro GRANT CONNECT ON DATABASE app TO agent_ro; GRANT USAGE ON SCHEMA public TO agent_ro; GRANT SELECT ON ALL TABLES IN SCHEMA public TO agent_ro; ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO agent_ro; ALTER ROLE agent_ro SET default_transaction_read_only = on; ``` DBHub 1.3.1 reads its connection string from the `DSN` environment variable, so the password never lands in shell history or a committed file. Export `AGENT_RO_DSN` in your shell from your secret manager or an untracked `.env` file (the value has the form `postgres://agent_ro:@localhost:5432/app`). Registration differs only in syntax across the three tools: **Claude Code** ```bash claude mcp add dbhub -e DSN="$AGENT_RO_DSN" -- npx @bytebase/dbhub@1.3.1 --transport stdio ``` **Codex** ```bash codex mcp add dbhub --env DSN="$AGENT_RO_DSN" -- npx @bytebase/dbhub@1.3.1 --transport stdio ``` **Cursor** Add the server to `.cursor/mcp.json`. The file holds only a reference to the variable, so it is safe to commit: ```json { "mcpServers": { "dbhub": { "command": "npx", "args": ["@bytebase/dbhub@1.3.1", "--transport", "stdio"], "env": { "DSN": "${env:AGENT_RO_DSN}" } } } } ``` The Claude Code and Codex commands save the expanded DSN in plain text in `~/.claude.json` (local scope by default) or `~/.codex/config.toml`, outside the repository; treat those files as secrets. Cursor's MCP documentation describes `${env:NAME}` interpolation in `mcp.json`; confirm it works on your Cursor version (for example, check that the server connects) before you commit the file. DBHub also has its own guardrails, including a read-only mode and a row limit (see its README). Treat them as a second layer; the role's missing write grants are the control that holds. Engine-specific servers (Supabase, Neon, Postgres MCP Pro, MongoDB) are compared on [database MCP servers](/en/ecosystem/mcp/database-mcp/). **Copy-paste prompt: ground the agent in the real schema** ```text Before writing any SQL or ORM code, use the dbhub MCP server to inspect the tables this feature touches: columns, types, nullability, indexes, foreign keys, and approximate row counts. Print them as a table. Then list every assumption you would otherwise have made from the model files that the live schema contradicts. Do not write code in this step. ``` ## How do you verify database changes without reading every line? Make the database the reviewer. A change is done when it passes the gate in the table above and the agent attaches the output, not when the SQL looks right. - **Migrations:** lint every new migration file with Squawk, then apply, roll back, and re-apply on a disposable copy with production-like volume, and run the parity query until it returns zero. Set `lock_timeout` so a statement that waits for a lock fails fast instead of queuing every write behind it. - **Data backfills:** compare row counts and a checksum of the affected columns before and after. - **Queries:** attach Postgres `EXPLAIN (ANALYZE, BUFFERS)` or MySQL `EXPLAIN ANALYZE` output before and after, run on realistic data. `EXPLAIN ANALYZE` executes the statement, so for writes wrap it in `BEGIN … ROLLBACK` on the disposable copy. - **ORM code:** integration tests against the real engine, for example in a Testcontainers Postgres; see [integration testing](/en/workflows/test/integration-testing/) and [test data management](/en/workflows/test/test-data-management/). A human signs off on one thing: any destructive step (a `DROP`, the contract phase of expand-contract). That approval goes into the pull request's [evidence bundle](/en/workflows/ship/evidence-bundle/). **Copy-paste prompt: a migration that proves itself** ```text Write this schema change as expand-contract migrations: expand now, contract in a separate later migration. Then, against a local Docker Postgres restored from an anonymised production-sized snapshot (not the MCP connection, which is read-only): 1. Run npx squawk-cli@2.66.0 on each new migration file; fix every error. 2. Prepend SET lock_timeout = '2s'; to each migration file, so it fails fast in production instead of queuing writes behind a lock. 3. Apply, roll back, and re-apply each migration; paste the output. 4. Using the Squawk output and the row counts from the dbhub inspection, list every statement that takes an ACCESS EXCLUSIVE lock on a table over 1M rows. 5. For any backfill, print row counts and an md5 of the affected columns before and after. Stop and ask me before writing any DROP or the contract migration. ``` ## What breaks when agents write database code? - **Invented columns or wrong types.** The agent read the ORM model, not the database. Recovery: run the grounding prompt and make "cite the live schema" a rule in `CLAUDE.md` or `AGENTS.md`. - **A migration that is green locally and locks production.** The local table had 50 rows. Recovery: rerun the gate on a production-sized copy with `lock_timeout` set, and split the change with the [migration patterns](/en/cookbook/database-recipes/migration-patterns/) recipe. - **An ORM rename generated as drop-and-add.** The model diff hides the data loss. Recovery: review the generated SQL, not the model file, and require the row-count check on every migration. - **An index that helps one query and slows writes.** Recovery: the [SQL optimization](/en/cookbook/database-recipes/sql-patterns/) recipe has the agent estimate the write-amplification cost of every new index and reject duplicates of existing ones. - **The agent wrote to a shared database.** Recovery: connect only through the read-only role above, and see [permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/) for the agent-side limits. ## Where to go next with database recipes - [Database migration patterns](/en/cookbook/database-recipes/migration-patterns/) - [ORM best practices](/en/cookbook/database-recipes/orm-patterns/) - [SQL optimization patterns](/en/cookbook/database-recipes/sql-patterns/) - [NoSQL patterns and strategies](/en/cookbook/database-recipes/nosql-patterns/) - [Backend recipes](/en/cookbook/backend-recipes/) — Language and framework recipes for the service around the database. --- # Database Migration Patterns URL: https://developertoolkit.ai/en/cookbook/database-recipes/migration-patterns/ Description: Zero-downtime Postgres migrations with Claude Code, Codex, and Cursor, proven by a Squawk lint gate, a parity query, and a rollback plan for each phase. Zero-downtime database migrations with AI agents split every risky schema change into expand, backfill, and contract phases, each deployed separately. Claude Code, Codex, or Cursor writes the SQL against a live schema read through a read-only MCP server, and a migration linter, a parity query, and a per-phase rollback prove it safe without a line-by-line review. This recipe is for the developer who owns a Postgres schema change and the tech lead who has to approve it. You asked an agent to change `products.price` from dollars to integer cents. It returned one tidy `ALTER TABLE products ALTER COLUMN price TYPE integer USING round(price * 100)`, the tests passed, and at 2 p.m. Postgres took an `ACCESS EXCLUSIVE` lock to rewrite a 40-million-row table. Every checkout query queued behind it. The migration was correct. It was not safe, and nothing in your pipeline was checking the difference. ## What you'll get from this recipe - A lock table that tells you which Postgres statements block traffic and what to write instead - An **expand-contract prompt** that produces separate, independently deployable migrations, the dual-write code, and a rollback for each phase - A **read-only Postgres MCP server** wired into Claude Code, Codex, and Cursor, so the agent plans against the real schema - A **verification gate** you can put in CI: the Squawk migration linter, a throwaway-database apply, and a parity query that must return zero before the contract phase ships - A recovery runbook for lock queues, half-finished backfills, invalid indexes, and stale rows written by old application versions ## Why does a correct migration still take production down? Postgres runs most DDL under an `ACCESS EXCLUSIVE` lock, which blocks reads and writes on the table. A statement that holds that lock for milliseconds is harmless. A statement that holds it while it rewrites or scans a large table is an outage. Worse, a DDL statement that is merely **waiting** for the lock blocks every query that arrives after it, so a long-running report can turn a millisecond `ALTER` into a queue that stalls the whole table. Agents write the short, obvious form of each statement because it is correct on an empty test database. The table below is the review knowledge the agent lacks; put it in the prompt and in the lint gate. | Statement the agent writes | What it does on a large, busy table | Write this instead | | --- | --- | --- | | `ALTER COLUMN … TYPE` (most type changes) | Rewrites the table under `ACCESS EXCLUSIVE` | Expand-contract: new column, backfill, switch, drop | | `ALTER COLUMN … SET NOT NULL` | Scans the whole table under `ACCESS EXCLUSIVE` | `CHECK (col IS NOT NULL) NOT VALID`, then `VALIDATE CONSTRAINT`, then `SET NOT NULL` | | `CREATE INDEX` | Blocks writes for the whole build | `CREATE INDEX CONCURRENTLY`, in its own non-transactional migration | | `ADD FOREIGN KEY` / `ADD CHECK` | Scans while blocking writes | Add as `NOT VALID`, then `VALIDATE CONSTRAINT` separately | | One `UPDATE` over every row | Long transaction, row locks, table bloat | Batches of about 1,000 rows by primary key, resumable | | Any DDL with no timeout | Can queue behind a long query and block everything behind it | `SET lock_timeout = '5s'` first, then retry on failure | `VALIDATE CONSTRAINT` takes only a `SHARE UPDATE EXCLUSIVE` lock, so reads and writes continue while it scans. The `NOT NULL` sequence in the third column works on PostgreSQL 12 and later: once a validated `CHECK` constraint proves the column has no nulls, `SET NOT NULL` skips the scan. We ran the full sequence below on PostgreSQL 16 on 2026-09-26 with `SET client_min_messages = debug1`, and Postgres reported at `DEBUG1` "existing constraints on column "products.price_cents" are sufficient to prove that it does not contain nulls". ## Split a risky change into expand, backfill, and contract Expand-contract (also called parallel change) never mutates a column in place. You add the new shape, write to both shapes, copy the old data across, switch reads, and remove the old shape in a later release. Every phase is its own deploy, so you can stop, observe, and roll back between any two of them. The order matters more than the SQL. The backfill runs **after** every application instance dual-writes; otherwise an old instance can update `price` after the backfill has passed that row, and `price_cents` silently goes stale. 1. **Expand.** Add the nullable column. This is a metadata-only change, so it holds its lock for milliseconds. ```sql -- 001_expand_add_price_cents.sql SET lock_timeout = '5s'; SET statement_timeout = '5s'; ALTER TABLE products ADD COLUMN IF NOT EXISTS price_cents integer; ``` 2. **Deploy dual-write.** Ship application code that writes both columns and reads the new one with a fallback. Wait until no instance of the old version is running. ```javascript // node-postgres. The ::integer casts are required: without them Postgres // rejects the statement with "inconsistent types deduced for parameter $1". async function setProductPrice(productId, priceCents) { await db.query( `UPDATE products SET price_cents = $1::integer, price = $1::integer / 100.0 WHERE id = $2`, [priceCents, productId], ); } async function getProductPriceCents(productId) { // Round in SQL, exactly as the backfill does. In JavaScript 1.005 * 100 is // 100.49999..., so Math.round would return 100 where Postgres returns 101. const { rows } = await db.query( 'SELECT coalesce(price_cents, round(price * 100)::integer) AS cents FROM products WHERE id = $1', [productId], ); return rows[0].cents; } ``` 3. **Backfill in batches.** Run this statement outside a transaction, repeatedly, until it updates zero rows. Each run is a short transaction, and a crashed run resumes where it stopped. The `price IS NOT NULL` filter matters: without it, rows with no price are "updated" to NULL and selected again on every run, so the loop never ends. ```sql -- 002_backfill_price_cents.sql UPDATE products SET price_cents = round(price * 100) WHERE id IN ( SELECT id FROM products WHERE price_cents IS NULL AND price IS NOT NULL ORDER BY id LIMIT 1000 ); ``` Rows where `price` is NULL stay NULL in `price_cents`, and the contract phase below cannot make that column `NOT NULL` while they exist. Count them now (`SELECT count(*) FROM products WHERE price IS NULL`) and decide before the contract release: fill them with an explicit default, or keep `price_cents` nullable, leave out the check and `SET NOT NULL` in 003a to 003c, and still drop `price`. 4. **Prove parity.** This query is the oracle for the whole migration. It must return `0` before reads switch, and again at the start of the contract release, while every instance still writes both columns. ```sql SELECT count(*) AS mismatched FROM products WHERE price_cents IS DISTINCT FROM round(price * 100); ``` 5. **Switch reads to `price_cents` and keep dual-writing.** Deploy code that reads only `price_cents` and still writes both columns. Run the parity query again after the deploy. Because `price` is still written, rolling the application back to the dual-write version stays safe for as long as this phase lasts. 6. **Contract.** In a later release, confirm parity is `0`, then run three files, each in **its own transaction**. Most migration tools (Flyway, Rails, Prisma, node-pg-migrate, golang-migrate on Postgres) wrap each file in one transaction. If `ADD CONSTRAINT` and `VALIDATE CONSTRAINT` share a transaction, the `ACCESS EXCLUSIVE` lock from the first statement is held through the whole validation scan, which is exactly the outage this page prevents. `lock_timeout` does not help there: it limits how long a statement waits for a lock, not how long the scan holds it. ```sql -- 003a_contract_add_check.sql SET lock_timeout = '5s'; SET statement_timeout = '5s'; ALTER TABLE products ADD CONSTRAINT price_cents_not_null CHECK (price_cents IS NOT NULL) NOT VALID; ``` ```sql -- 003b_contract_validate_check.sql (SHARE UPDATE EXCLUSIVE: reads and writes continue) SET lock_timeout = '5s'; SET statement_timeout = '30min'; -- sized to the full scan, not to the lock wait ALTER TABLE products VALIDATE CONSTRAINT price_cents_not_null; ``` Then deploy the code that stops writing `price`, and run the last file straight after it. From this deploy on, `price` goes stale, so it is the point of no cheap return. ```sql -- squawk-ignore-file adding-not-nullable-field, ban-drop-column -- 003c_contract_drop_price.sql SET lock_timeout = '5s'; SET statement_timeout = '5s'; ALTER TABLE products ALTER COLUMN price_cents SET NOT NULL; -- skips the scan: the check proves it ALTER TABLE products DROP CONSTRAINT IF EXISTS price_cents_not_null; ALTER TABLE products DROP COLUMN IF EXISTS price; ``` The first line silences two Squawk rules for this file only, on purpose. `adding-not-nullable-field` cannot see the `CHECK` that 003b validated, so it reports a table scan that Postgres does not run. `ban-drop-column` warns about the drop, which is the intended contract step. Leave every other rule on. You do not have to write this sequence yourself. The agent writes it; your job is to hand it the constraints above and to check the result with the gate described later. **Copy-paste prompt: generate an expand-contract migration** ```text Read the current definition of the products table (use the postgres MCP server if it is connected; otherwise read db/schema.sql). The table has about 40 million rows and constant checkout traffic on PostgreSQL 16. Replace products.price (numeric dollars) with products.price_cents (integer cents) with zero downtime, using expand-contract. Write separate files in db/migrations/: 1. expand: SET lock_timeout = '5s', then add price_cents as a nullable column. 2. backfill: batches of 1000 rows by id where price IS NOT NULL, safe to re-run until it updates 0 rows, run outside a transaction. Tell me how many rows have a NULL price; I decide on a default or a nullable price_cents before the contract phase. 3. contract (for a later release), as three files that each run in a separate transaction: (a) CHECK (price_cents IS NOT NULL) NOT VALID; (b) VALIDATE CONSTRAINT; (c) SET NOT NULL, drop the check, drop price. Tell me whether our migration tool wraps several files in one transaction. Also write: - dual-write setProductPrice and fallback-read getProductPriceCents for node-postgres, with explicit ::integer casts on reused parameters; - read-switch code that still writes both columns, and the code change that stops writing price, to ship in the contract release right before file (c); - the parity query that must return 0 before the contract phase; - a rollback statement for each migration file. For every statement, name the lock it takes and say whether it can run at peak traffic. Do not use ALTER COLUMN ... TYPE, a bare CREATE INDEX, or an unbatched UPDATE. Do not run anything against the database. ``` ## Give the agent the live schema through a read-only MCP server The prompt above is only as good as the schema the agent reads. If you paste an old `\d products` output, the agent plans a migration for a table that no longer exists. A Postgres MCP server lets the agent read column types, row estimates, and existing indexes itself, and choose batch sizes to match. [Postgres MCP Pro](https://github.com/crystaldba/postgres-mcp) (PyPI `postgres-mcp`, from Crystal DBA) has an explicit access mode: `--access-mode=restricted` limits it to read-only transactions with an execution-time limit. Run it with `uvx`. Two cautions from our check on 2026-09-26: the latest PyPI release is 0.3.0 from 2025-05-16, so pin it and watch the repository, and the npm package also named `postgres-mcp` is unrelated, so do not start it with `npx`. The old `@modelcontextprotocol/server-postgres` package is deprecated on npm and archived; do not use it. The server configuration is the same for all three tools; only the way you register it differs. **Claude Code** ```bash # Terminal, in the repository root. Put the server name BEFORE -e: # -e takes several values, so a name after it is read as another variable. claude mcp add postgres -e DATABASE_URI=postgresql://agent_ro@localhost:5432/app_staging \ -- uvx postgres-mcp --access-mode=restricted ``` Add `--scope project` to write it to `.mcp.json` so the whole team gets the same server. We ran both orders on Claude Code 2.1.283: the one above works, and `--env KEY=value postgres -- …` fails with "Invalid environment variable format: postgres". **Codex** ```bash # Terminal. Registers the server in Codex's config.toml. codex mcp add postgres --env DATABASE_URI=postgresql://agent_ro@localhost:5432/app_staging \ -- uvx postgres-mcp --access-mode=restricted ``` `codex mcp list` shows the result. Checked against `codex mcp add --help` in Codex CLI 0.157.1. **Cursor** Add the server to `.cursor/mcp.json` in the project, the same `mcpServers` shape Claude Code writes to `.mcp.json`: ```json { "mcpServers": { "postgres": { "command": "uvx", "args": ["postgres-mcp", "--access-mode=restricted"], "env": { "DATABASE_URI": "postgresql://agent_ro@localhost:5432/app_staging" } } } } ``` **Read-only in two places, and never the production primary** Restricted mode enforces read-only in the server, and the Postgres MCP Pro README notes that unsafe stored-procedure languages can get around it. Enforce it in the database too: connect as a role that has only `SELECT` (the `agent_ro` above), on a staging copy or a read replica. The agent reads the schema; the migration itself runs only through your version-controlled migration tool. See [how to scope database MCP servers safely](/en/ecosystem/mcp/database-mcp/) and [the MCP security checklist](/en/ecosystem/mcp/mcp-security/). If you want Postgres review knowledge rather than a live connection, a skill is lighter. Supabase's `supabase-postgres-best-practices` skill covers Postgres performance and row-level security; install it with `npx skills add supabase/agent-skills --skill supabase-postgres-best-practices` (the `skills` CLI was 1.7.0 on npm on 2026-09-26). A skill does not read your database, so use it alongside the MCP server, not instead of it. [Installing and managing skills](/en/ecosystem/skills/installing-managing/) covers scopes and updates. ## Gate every migration with a linter, a real apply, and a parity query Asking the agent to review its own migration catches some hazards, but the same model that wrote the SQL judges it. Put a deterministic gate in front of the merge instead, and let the human review the evidence the gate produces. [Squawk](https://github.com/sbdchd/squawk) is a linter for PostgreSQL migrations (npm `squawk-cli`, 2.66.0 on 2026-09-26). We ran it on a file containing the four dangerous statements from the lock table. It flagged all four, including "Setting a column `NOT NULL` blocks reads while the table is scanned", added `require-lock-timeout` warnings, and exited with status 1, which is what fails a CI job. Squawk exits 1 on warnings as well as errors, so a green job means zero findings, not zero errors. ```bash # CI or terminal: lint only the migrations this branch adds. npx squawk-cli@2.66.0 $(git diff --name-only --diff-filter=A origin/main -- 'db/migrations/*.sql') # Apply the chain to a throwaway Postgres. The backfill does 1,000 rows per run, # so repeat it until no row is left, then check parity. The counter stops a loop # that never converges (1,000 runs covers a 1-million-row seed). psql "$TEST_DATABASE_URL" -v ON_ERROR_STOP=1 -f db/migrations/001_expand_add_price_cents.sql runs=0 until [ "$(psql "$TEST_DATABASE_URL" -At -c \ 'SELECT count(*) FROM products WHERE price_cents IS NULL AND price IS NOT NULL')" = 0 ]; do runs=$((runs + 1)) [ "$runs" -le 1000 ] || { echo "backfill did not converge" >&2; exit 1; } psql "$TEST_DATABASE_URL" -v ON_ERROR_STOP=1 -f db/migrations/002_backfill_price_cents.sql done psql "$TEST_DATABASE_URL" -At -c \ "SELECT count(*) FROM products WHERE price_cents IS DISTINCT FROM round(price * 100)" ``` Three settings make Squawk fit your migration tool. If the tool wraps each file in a transaction, pass `--assume-in-transaction` so Squawk reasons about the real execution. In that mode Squawk 2.66.0 flags a `VALIDATE CONSTRAINT` in the same file as its `NOT VALID` add ("Using `NOT VALID` and `VALIDATE CONSTRAINT` in the same transaction will block all reads while the constraint is validated"), which is the trap the three contract files avoid; we checked this on 2026-09-26. Rules that do not apply to you go in `.squawk.toml` or `--exclude`, each with a reason. With the configuration below, all five files on this page pass Squawk 2.66.0 with exit status 0; we checked on 2026-09-26. ```toml # .squawk.toml, in the repository root # Our migration tool wraps each file in its own transaction. assume_in_transaction = true # price_cents holds cents: int4 allows about 21 million dollars per product. excluded_rules = ["prefer-bigint-over-int"] ``` Squawk can also comment on the pull request with `squawk upload-to-github`, or through the [squawk-action](https://github.com/sbdchd/squawk-action). Who signs off, and on what: - **CI** blocks the merge on any Squawk finding (warnings included), any failed apply, or a non-zero parity count on the seeded test database. - **The migration owner** reviews the lock-per-statement list the agent produced and the Squawk output, not every line of SQL. - **The contract release** needs one more artifact in the pull request: the parity query result from production (run through the read-only role) showing `0`. That goes in the [evidence bundle for agent pull requests](/en/workflows/ship/evidence-bundle/). **Copy-paste prompt: make a migration pass the lock gate** ```text Run `npx squawk-cli@2.66.0 --assume-in-transaction` on every migration file this branch adds under db/migrations/ and fix each finding. The products table has about 40 million rows and constant writes on PostgreSQL 16. Specifically: 1. Put SET lock_timeout = '5s' before any statement that takes ACCESS EXCLUSIVE. 2. Replace ALTER COLUMN ... TYPE with an expand-contract sequence. 3. Replace SET NOT NULL with CHECK ... NOT VALID, VALIDATE CONSTRAINT, SET NOT NULL. 4. Use CREATE INDEX CONCURRENTLY in its own file, and tell me whether our migration tool wraps files in a transaction (it must not, for that file). 5. Add foreign keys and checks as NOT VALID, and validate them in a separate migration file, so the validation runs in its own transaction. 6. Batch any UPDATE or DELETE that touches the whole table. 7. Put SET statement_timeout before slow statements, sized to the operation. 8. Do not rewrite 003c's SET NOT NULL; it is covered by the CHECK validated in 003b, and the file's squawk-ignore-file line records that. Squawk exits 1 on warnings as well as errors. Re-run it until it exits 0. If you keep a finding on purpose, add it to .squawk.toml with a one-line reason. Finish with a table: file, statement, lock taken, safe at peak (yes/no). ``` ## Run the migration loop in Claude Code, Codex, or Cursor The prompts and the gate are identical across tools. What differs is how you run the loop unattended and where you review the result. **Claude Code** Generate, lint, and apply in one headless run. `--allowedTools` pre-approves exactly these tools. A `claude -p` session starts in Manual mode, or in auto mode on third-party providers or with telemetry off (from v2.1.285), where a classifier decides instead of the allow list, so `--permission-mode dontAsk` is what refuses every other tool call that would prompt on every provider. ```bash # Terminal or CI. TEST_DATABASE_URL points at a local throwaway database. claude -p "Write an expand-contract migration in db/migrations/ that replaces \ products.price with products.price_cents, following docs/migrations.md. Then run \ exactly 'npx squawk-cli@2.66.0 --assume-in-transaction ', apply them \ with 'npm run db:migrate' against the test database, run 'npm test -- migrations', \ and report the lock each statement takes." \ --permission-mode dontAsk \ --allowedTools "Read" "Edit" "Write" "Bash(npx squawk-cli@2.66.0 *)" \ "Bash(npm run db:migrate)" "Bash(npm test *)" \ --output-format json > migration-run.json ``` Each `Bash(...)` rule matches a command prefix, so `Bash(npx squawk-cli *)` would refuse the pinned `npx squawk-cli@2.66.0`; keep the rule and the prompt on the same spelling. `--allowedTools` skips prompts for the listed tools; to remove every other tool from the session entirely, use `--tools` instead. Keep `migration-run.json` as the CI record of what ran. Flags checked against `claude --help` 2.1.283. **Codex** Run the change in a new managed Git worktree so it never touches your working checkout. ```bash # Terminal. network_access lets the sandboxed commands reach the local test database. codex exec --worktree --sandbox workspace-write \ -c sandbox_workspace_write.network_access=true \ "Write an expand-contract migration in db/migrations/ replacing products.price with \ products.price_cents: expand, batched backfill run outside a transaction, and contract \ split into add-check, validate and drop files that each run in their own transaction. Run npx squawk-cli@2.66.0 on the new files, apply them to TEST_DATABASE_URL, run the \ migration tests, and list the lock each statement takes." ``` In `workspace-write`, network access is off unless you set `sandbox_workspace_write.network_access`, so without it the apply step cannot reach Postgres. Export `TEST_DATABASE_URL` before the run. If the apply step reports that the variable is empty, your `shell_environment_policy` is filtering it out of sandboxed commands: add `-c shell_environment_policy.inherit=all` (the form `codex --help` shows) or write the URL into the prompt. Add `--json` for a JSONL event log. Flags checked against `codex exec --help` in Codex CLI 0.157.1. **Cursor** Start in Plan Mode with the expand-contract prompt, so the agent proposes the file split before it writes anything. Check two things in the plan: the contract step is split into **separate files** (add check, validate, drop), apart from expand, and the backfill has a `LIMIT` and a resumable `WHERE` clause. Then let the agent write the files and review the multi-file diff before you accept it. Run the same Squawk and apply commands from the gate section in the integrated terminal, or leave them to CI. Commit before you accept a large edit, so `git restore` is always your way back. ## Copy data between tables with a resumable, validated batch job When you reshape data rather than a column, such as moving `legacy_users` into `users`, the agent should produce a batch job with four properties: keyset pagination, idempotent writes, rejected rows recorded instead of crashing the run, and a reconciliation query at the end. ```javascript // Batched copy from legacy_users to users. db is a node-postgres client. async function migrateUsers({ batchSize = 1000, startAfterId = 0 } = {}) { let cursor = startAfterId; const rejected = []; for (;;) { const { rows } = await db.query( 'SELECT id, email_address FROM legacy_users WHERE id > $1 ORDER BY id LIMIT $2', [cursor, batchSize], ); if (rows.length === 0) break; for (const row of rows) { const email = row.email_address?.trim().toLowerCase(); if (!email?.includes('@')) { rejected.push({ id: row.id, reason: 'invalid email' }); continue; } await db.query( 'INSERT INTO users (email, legacy_id) VALUES ($1, $2) ON CONFLICT (legacy_id) DO NOTHING', [email, row.id], ); } cursor = rows[rows.length - 1].id; // log this: it is your resume point } return { lastId: cursor, rejected }; } ``` `WHERE id > $1 ORDER BY id` stays fast at any depth, where `OFFSET` gets slower with every page. `ON CONFLICT (legacy_id) DO NOTHING` makes a re-run safe, provided `users.legacy_id` has a unique constraint. The job is done when this query returns only the rows you rejected on purpose: ```sql SELECT l.id FROM legacy_users l LEFT JOIN users u ON u.legacy_id = l.id WHERE u.legacy_id IS NULL; ``` For MySQL, ask the agent to drive a proven online schema change tool rather than hand-writing triggers. [`pt-online-schema-change`](https://docs.percona.com/percona-toolkit/pt-online-schema-change.html) copies the table and keeps it in sync with triggers. [`gh-ost`](https://github.com/github/gh-ost) is triggerless: it replays changes from the binary log, which keeps trigger overhead off a write-heavy source table. ## How do you roll back each migration phase? Expand-contract gives you a cheap rollback at every phase except the last. Put this table in the pull request so the on-call engineer does not have to work it out at 2 a.m. | Phase | Roll back with | Data at risk | | --- | --- | --- | | Expand | `ALTER TABLE products DROP COLUMN IF EXISTS price_cents;` | None; the column held no data yet | | Dual-write deploy | Redeploy the previous application version | None; `price` is still written | | Backfill | Stop the job; nothing to undo | None; re-run later | | Switch reads | Redeploy the dual-write version | None; `price` is still written in this phase | | Contract: add and validate the check (003a, 003b) | `ALTER TABLE products DROP CONSTRAINT IF EXISTS price_cents_not_null;` | None; both columns are still written | | Contract: stop writing `price`, then 003c | Before 003c: re-backfill `price` from `price_cents`, then redeploy the dual-write version. After 003c: restore from backup, or re-add `price` and fill it from `price_cents` | High: `price` goes stale from the deploy on, and `DROP COLUMN` is the one step you cannot undo cleanly | That last row is why the contract phase waits a release, needs the production parity result, and runs 003c straight after the deploy that stops writing `price`. Take a backup, or at least a `pg_dump --table=products` of the table you are about to change, before it runs. ## When database migrations break **Queries time out the moment the migration starts** A DDL statement is waiting for its lock behind a long query, and every new query is queued behind the DDL. Cancel the migration first; the queue drains at once. Find the blocker with `SELECT pid, now() - xact_start AS age, state, query FROM pg_stat_activity WHERE state <> 'idle' ORDER BY age DESC;`, then add `SET lock_timeout = '5s'` to the migration and retry it in a quieter window. If Squawk were in CI, the missing timeout would have been flagged by `require-lock-timeout`. **The backfill slows the database or dies halfway** Stop the runner. Lower the batch size to 500 and add a pause between batches so autovacuum can keep up with the dead rows. Because the backfill filters on `price_cents IS NULL` (or pages by `id > cursor`), re-running it skips rows already done. Ask the agent: "Rewrite this backfill to process 500 rows per batch with a 50 ms pause, log the last id every 10 batches, and accept a start id so it can resume." **The parity query returns rows after the backfill finished** An application instance still running the old version wrote `price` without `price_cents`, or the backfill started before dual-write reached every instance. Confirm every instance runs the dual-write version, then run a repair batch with `WHERE price_cents IS DISTINCT FROM round(price * 100)` instead of `IS NULL`. Repeat the parity query until it returns `0`. Do not ship the contract phase until it does. **CREATE INDEX CONCURRENTLY failed and left an invalid index** A failed concurrent build leaves an `INVALID` index that still slows every write. Find it with `SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;`, remove it with `DROP INDEX CONCURRENTLY`, and run the build again. Retrying without the drop leaves a second invalid index. If the build failed with "cannot run inside a transaction block", your migration tool wrapped the file in a transaction; move the statement to a file that opts out. **You are unsure which phase is live** This is the safe failure of expand-contract: while the old column exists and the application still writes it, nothing is broken. That holds until the contract release deploys the code that stops writing `price`; if that deploy is live and 003c is not, finish 003c rather than rolling the application back. Check the columns (`\d products`), check which application version each instance runs, run the parity query, and continue from the first phase that is not complete. Never skip ahead to contract to "finish the job". ## Where to go next - Before this page: [database development with an MCP server](/en/workflows/build/database-development/) covers schema design and query work with a live connection. - [Database MCP servers compared](/en/ecosystem/mcp/database-mcp/): which server fits your database and how to scope its access. - [ORM patterns](/en/cookbook/database-recipes/orm-patterns/): the same safety rules when Prisma or TypeORM generates the migration. - [SQL optimization patterns](/en/cookbook/database-recipes/sql-patterns/): index choices driven by `EXPLAIN ANALYZE`, which your concurrent index builds should follow. - Tool deep dives: [migrations in Claude Code](/en/claude-code/build/migrations/) and [database work in Codex](/en/codex/build/database-work/). - After this page: [progressive delivery](/en/workflows/ship/progressive-delivery/) for rolling the dual-write and read-switch deploys out gradually, and [the evidence bundle](/en/workflows/ship/evidence-bundle/) for what the migration pull request must prove. --- # NoSQL Patterns and Strategies URL: https://developertoolkit.ai/en/cookbook/database-recipes/nosql-patterns/ Description: Design MongoDB, DynamoDB, Neo4j, and vector data models with Claude Code, Codex, or Cursor from real access patterns, and prove every query with tests. NoSQL data modeling with Claude Code, Codex, or Cursor works when the agent designs from a written list of access patterns, reads the live schema through a read-only MongoDB or Neo4j MCP server, and returns an access-pattern map plus tests proving that every query uses an index. A NoSQL schema without that evidence is a guess. This page is for developers who let an agent design or change a document, key-value, graph, or vector data model. The failure it prevents looks like this: the MongoDB schema was clean in the demo, one `user` document with embedded orders, addresses, and a cart. Six months later the orders array holds 4,000 entries, the document is creeping toward MongoDB's 16 MB limit, and every profile read drags the whole thing over the wire. The agent that wrote the schema never saw your access patterns, so it optimized for the demo. NoSQL gives you no relational schema to hide behind. The data model *is* the design, and a wrong embed-versus-reference call or a wrong partition key is expensive to unwind once traffic arrives. The recipes below make the agent justify each call and then prove it on a real engine, so you review a table and a test report instead of every query. ## What you'll walk away with from these NoSQL recipes - A read-only MCP setup for MongoDB and Neo4j in Claude Code, Codex, and Cursor, with the one flag that makes MongoDB reject collection scans - An embed-versus-reference prompt that forces the agent to argue from access patterns and growth bounds - An aggregation prompt that treats the `explain` plan as part of the deliverable - A single-table DynamoDB prompt that maps every access pattern to a key condition or a GSI - Neo4j 5 and Atlas Vector Search prompts that avoid the removed syntax agents still produce - An access-pattern test suite, written by the agent, that CI runs so nobody has to read every query ## How does the NoSQL recipe loop work? Every store follows the same four steps. The store changes; the loop does not. 1. **Write the access patterns first.** A numbered list of the reads and writes the feature needs, with rough frequency. This list is the spec, and it is the thing you approve. 2. **Have the agent produce the design as an artifact.** A table that maps each access pattern to a document shape, key condition, or index, not a paragraph of prose. 3. **Validate on a real engine.** The agent reads the real schema and runs `explain` through MCP, or runs against DynamoDB Local, instead of guessing field names. 4. **Lock it in with tests.** One test per access pattern asserts the result and the plan (index used, no scan). CI runs them on every change. ## Step 1: Connect the agent to your real schema Without a database connection the agent invents collection and field names. With one, it samples a document first, sees that you already store `customerId` rather than `userId`, and follows your convention. The general setup, read-only roles, and the other database servers are covered in [database MCP servers](/en/ecosystem/mcp/database-mcp/); this step is the NoSQL-specific part. Two servers cover this page, both verified on 2026-09-26: - **MongoDB MCP Server** (npm `mongodb-mcp-server` 3.0.4, official). Tools include `collection-schema`, `collection-indexes`, `find`, `aggregate`, and `explain`. `--readOnly` removes the create, update, and delete tools. `--indexCheck` rejects any query that would do a collection scan, which turns "use an index" from advice into a hard failure the agent has to fix. - **Neo4j Cypher MCP server** (PyPI `mcp-neo4j-cypher` 0.6.0, from `neo4j-contrib`). Tools are `get_neo4j_schema` (needs the APOC plugin), `read_neo4j_cypher`, and `write_neo4j_cypher`; `--read-only` removes the write tool. It is a Python package, so it runs with `uvx`, not `npx`. The servers behave the same in all three tools; only the place the config lives differs. **Claude Code** Run in the terminal at the repo root. `-s project` writes `.mcp.json`, and the single-quoted `${NEO4J_PASSWORD}` is expanded from your shell when the server starts, so the secret stays out of the file: ```bash claude mcp add -s project mongodb \ -e MDB_MCP_CONNECTION_STRING=mongodb://localhost:27017/shop \ -- npx -y mongodb-mcp-server@3.0.4 --readOnly --indexCheck claude mcp add -s project neo4j \ -e NEO4J_URI=bolt://localhost:7687 -e NEO4J_USERNAME=neo4j \ -e 'NEO4J_PASSWORD=${NEO4J_PASSWORD}' \ -- uvx mcp-neo4j-cypher@0.6.0 --read-only ``` **Codex** Run in the terminal. `codex mcp add` writes the entry to `~/.codex/config.toml`: ```bash codex mcp add mongodb \ --env MDB_MCP_CONNECTION_STRING=mongodb://localhost:27017/shop \ -- npx -y mongodb-mcp-server@3.0.4 --readOnly --indexCheck codex mcp add neo4j \ --env NEO4J_URI=bolt://localhost:7687 --env NEO4J_USERNAME=neo4j \ --env NEO4J_PASSWORD="$NEO4J_PASSWORD" \ -- uvx mcp-neo4j-cypher@0.6.0 --read-only ``` The resulting entries, which you can also write by hand: ```toml [mcp_servers.mongodb] command = "npx" args = ["-y", "mongodb-mcp-server@3.0.4", "--readOnly", "--indexCheck"] [mcp_servers.mongodb.env] MDB_MCP_CONNECTION_STRING = "mongodb://localhost:27017/shop" [mcp_servers.neo4j] command = "uvx" args = ["mcp-neo4j-cypher@0.6.0", "--read-only"] [mcp_servers.neo4j.env] NEO4J_URI = "bolt://localhost:7687" NEO4J_USERNAME = "neo4j" NEO4J_PASSWORD = "your-local-password" ``` The shell expands `"$NEO4J_PASSWORD"` once, when you run `codex mcp add`, so the password is stored as a literal in `~/.codex/config.toml`. That file is per-user and outside the repo; keep it that way. `codex mcp get mongodb` prints the parsed entry with the connection string masked. **Cursor** Add to `~/.cursor/mcp.json` (user-level, outside the repo). The Neo4j entry holds a literal password, so never put it in the project's `.cursor/mcp.json`, which gets committed. A MongoDB entry without credentials, like the local one below, can live in the project file: ```json { "mcpServers": { "mongodb": { "command": "npx", "args": ["-y", "mongodb-mcp-server@3.0.4", "--readOnly", "--indexCheck"], "env": { "MDB_MCP_CONNECTION_STRING": "mongodb://localhost:27017/shop" } }, "neo4j": { "command": "uvx", "args": ["mcp-neo4j-cypher@0.6.0", "--read-only"], "env": { "NEO4J_URI": "bolt://localhost:7687", "NEO4J_USERNAME": "neo4j", "NEO4J_PASSWORD": "your-local-password" } } } } ``` **Read-only against anything shared** Keep `--readOnly` and `--read-only` on every connection to staging or production. With them on, the agent cannot create an index either, which is what you want: it writes the index into a migration file that goes through review and CI (see [database migration patterns](/en/cookbook/database-recipes/migration-patterns/)). Drop the flag only on a local, disposable database seeded with realistic data, where the agent may create and drop indexes while it iterates. MongoDB's README recommends the environment variable over `--connectionString` because command-line arguments are visible in process lists. ## Step 2: Decide embed versus reference from access patterns The most consequential document-store decision is whether related data is embedded or referenced. The agent gets it right when you hand it the access patterns, the write pattern, and the growth bounds, instead of asking for "a good schema". **Copy-paste prompt: embed versus reference for an order model** ```text Design the MongoDB data model for an e-commerce Order. First read the existing `orders` and `customers` collections through the MongoDB MCP server (collection-schema, collection-indexes) and follow their field names. Access patterns, in priority order: 1. Load one order with all line items for the order-detail page (95% of reads). 2. List a customer's last 20 orders, summary fields only, newest first. 3. Daily revenue by product category (a nightly job). Writes: line items are immutable once the order is placed; status changes about 3 times per order. Deliver: - A table: access pattern -> document shape or collection -> index that serves it. - For line items and for the customer reference, decide embed vs reference and name the rule you applied (bounded vs unbounded growth, read-together, atomicity, update frequency). - The exact createIndex calls, following equality-sort-range order, and say which patterns (if any) can be covered queries. - A $jsonSchema validator for the collection. - Flag any array that can grow without bound toward the 16 MB document limit. Do not create anything; write the indexes and validator into a migration file. ``` A good answer embeds line items (bounded, immutable, always read together), stores a `customer: { id, name }` snapshot instead of running `$lookup` on every read, and serves pattern 2 with a compound index on `{ customerId: 1, createdAt: -1 }`. Pattern 1 returns the whole document, so it cannot be a covered query; an agent that claims otherwise has not reasoned about projections, and you should send it back. The access-pattern table is the artifact you approve. The code follows from it. ## Step 3: Make every aggregation prove its index Aggregation pipelines are where the agent saves the most time and where it most often ships a query that returns correct results while scanning the whole collection. Make the execution plan part of the deliverable. **Copy-paste prompt: aggregation pipeline with plan evidence** ```text Write a MongoDB aggregation on `orders` that returns monthly revenue by product category for the trailing 12 months, active products only, sorted by revenue descending. Check the schema through the MongoDB MCP server first; if a denormalized `category` field exists on the order line, do not use $lookup. Then run the pipeline through the MCP `explain` tool with executionStats. Report: the winning plan's first stage (IXSCAN or COLLSCAN), totalDocsExamined, totalKeysExamined, and nReturned. If the first $match does not use an index, propose the index in the migration file and explain why its key order fits the $match and $sort. Stop and ask me if the only fix is a schema change. ``` Because the server runs with `--indexCheck`, a pipeline whose first `$match` scans the collection fails outright instead of returning a plausible answer. The agent sees the failure, proposes the index, and on your local database (where you dropped `--readOnly`) creates it and re-runs `explain` until the plan starts with `IXSCAN`. The ratio of `totalDocsExamined` to `nReturned` is the number to read: close to 1 is healthy, hundreds to one means the index is the wrong shape. ## Step 4: Design a single-table DynamoDB schema DynamoDB punishes vague prompts hardest. A low-cardinality partition key creates a hot partition that throttles under load, and a missing access pattern means a `Scan` in production. There is no read-only schema to introspect here, so the agent works from the list and proves the design against DynamoDB Local (the `amazon/dynamodb-local` Docker image). **Copy-paste prompt: single-table DynamoDB design** ```text Design a single-table DynamoDB schema for a multi-tenant SaaS with Organizations, Users, Projects, and Tasks. Access patterns I must serve: 1. Get an org and all its users. 2. Get a user by email for login. 3. List tasks assigned to a user across projects, sorted by due date. 4. List a project's open tasks. Deliver a table: access pattern -> table or GSI -> key condition. Use one overloaded PK/SK plus the minimum number of GSIs; justify each GSI and give its projection (KEYS_ONLY, INCLUDE with named attributes, or ALL) with the write-cost trade-off. Flag any pattern that can create a hot partition and propose write sharding. Use AWS SDK for JavaScript v3 (@aws-sdk/lib-dynamodb) only. Every access pattern must be a Query or GetItem; a Scan is a design failure. Write one test per pattern against DynamoDB Local. ``` The executable part is small. This is the query for pattern 3, using AWS SDK v3 (`@aws-sdk/lib-dynamodb` 3.1141.0 on npm, 2026-09-26); the v2 `.query(params).promise()` chain does not apply: ```javascript import { DynamoDBClient } from '@aws-sdk/client-dynamodb'; import { DynamoDBDocumentClient, QueryCommand } from '@aws-sdk/lib-dynamodb'; const ddb = DynamoDBDocumentClient.from(new DynamoDBClient({})); // GSI1: GSI1PK = USER#, GSI1SK = TASK## export async function getUserTasks(userId, fromDate) { const { Items } = await ddb.send( new QueryCommand({ TableName: 'SaaSPlatform', IndexName: 'GSI1', KeyConditionExpression: 'GSI1PK = :pk AND GSI1SK >= :start', ExpressionAttributeValues: { ':pk': `USER#${userId}`, ':start': `TASK#${fromDate}`, }, ScanIndexForward: true, // ascending by due date }), ); return Items; } ``` Batch writes use `BatchWriteCommand`, which still takes at most 25 items per request. ## Step 5: Model a graph in Neo4j 5 syntax For highly connected data (social graphs, recommendations, fraud rings), ask for the node and relationship model first, then the Cypher. Insist on Neo4j 5 syntax: training data is full of the Neo4j 4 constraint form `CREATE CONSTRAINT ON ... ASSERT`, which Neo4j 5 rejects. **Copy-paste prompt: graph model and recommendation query** ```text Read the current graph through the Neo4j MCP server (get_neo4j_schema) and keep its labels and relationship types. Model User, Post, and Tag nodes with FRIENDS, POSTED, LIKED, VIEWED, and TAGGED_WITH relationships, with timestamps where they matter. Then write a query: posts my friends liked in the last 7 days that I have not viewed, ranked by the number of distinct friends who liked each one. Neo4j 5 syntax only: constraints use CREATE CONSTRAINT ... FOR (n:Label) REQUIRE n.prop IS UNIQUE, and negative patterns use NOT EXISTS { ... }. Run EXPLAIN on every query through read_neo4j_cypher and report whether the plan starts from a NodeUniqueIndexSeek or an AllNodesScan. Cap the friend fan-out if a user can have more than 5,000 FRIENDS relationships. ``` The shape of a correct answer: ```cypher CREATE CONSTRAINT user_id IF NOT EXISTS FOR (u:User) REQUIRE u.id IS UNIQUE; CREATE CONSTRAINT post_id IF NOT EXISTS FOR (p:Post) REQUIRE p.id IS UNIQUE; // Posts friends liked in the last 7 days that this user has not viewed MATCH (user:User {id: $userId})-[:FRIENDS]-(friend:User)-[l:LIKED]->(post:Post) WHERE l.at > datetime() - duration('P7D') AND NOT EXISTS { (user)-[:VIEWED]->(post) } WITH post, count(DISTINCT friend) AS friendLikes RETURN post.id, post.content, friendLikes ORDER BY friendLikes DESC LIMIT 10; ``` The `user_id` constraint gives the query its starting point: `EXPLAIN` should show `NodeUniqueIndexSeek` on `:User(id)`. An `AllNodesScan` means the constraint is missing or the label is misspelled. ## Step 6: Add vector search on MongoDB Atlas Storing embeddings next to documents gives you semantic search without a separate vector database. On MongoDB Atlas, query with the `$vectorSearch` aggregation stage against an index of type `vectorSearch`. The older `knnVector` field mapping belongs to Atlas Search, is deprecated, and does not serve `$vectorSearch`, yet agents still generate it. ```python from pymongo.operations import SearchIndexModel # A vectorSearch index needs SearchIndexModel(type="vectorSearch"). # A plain-dict create_search_index() call creates an Atlas Search index instead. db.products.create_search_index( model=SearchIndexModel( definition={ "fields": [ {"type": "vector", "path": "text_embedding", "numDimensions": 384, "similarity": "cosine"}, {"type": "filter", "path": "price"}, {"type": "filter", "path": "categories"}, ] }, name="product_embeddings", type="vectorSearch", ) ) pipeline = [ {"$vectorSearch": { "index": "product_embeddings", "path": "text_embedding", "queryVector": query_embedding, # 384 floats from the same model "numCandidates": 200, "limit": 10, "filter": {"price": {"$lte": 100}}, }}, {"$addFields": {"score": {"$meta": "vectorSearchScore"}}}, {"$project": {"text_embedding": 0}}, ] ``` **Copy-paste prompt: vector index and retrieval check** ```text My Atlas collection `products` stores a `text_embedding` field and I query it with $vectorSearch. Read a sample document through the MongoDB MCP server and report the embedding length. Generate the index with the vectorSearch index type: a `fields` array with {type: "vector", path, numDimensions, similarity} plus filter entries for `price` and `categories`. Create it in PyMongo with SearchIndexModel(type="vectorSearch"), never the knnVector mapping. Then write a test with 20 golden queries and their expected product ids that fails if recall@10 drops below the value we record today, and a test that fails if any stored embedding length differs from numDimensions. ``` ## How do you verify a NoSQL design without reading every query? You approve two things: the access-pattern table from the design step, and the test report. You do not read each pipeline, key condition, or Cypher query, because the tests assert what a reviewer would look for, on a real engine, every time CI runs. This is the same shift the site describes in [reading evidence instead of code](/en/ladder/evidence-not-diffs/). | Store | What the test asserts | How it fails | | --- | --- | --- | | MongoDB | Each access pattern returns the right documents, and its `explain` output contains no `COLLSCAN` | A missing or wrongly ordered index | | MongoDB | The `$jsonSchema` validator rejects a document with a missing required field | The shape drifted from the approved design | | DynamoDB | Each access pattern is served by `Query` or `GetItem`; a middleware throws on any `ScanCommand` | An access pattern the key design does not cover | | Neo4j | `EXPLAIN` on each query shows no `AllNodesScan`; `SHOW CONSTRAINTS` lists every unique key | A dropped constraint or a misspelled label | | Vector | recall@10 on the golden queries stays at or above the recorded baseline; every embedding length equals `numDimensions` | A model change without re-embedding | The plan assertion is a check over the whole plan, so it survives the differences between a `find` plan and an aggregation plan: ```javascript const plan = await db.collection('orders').aggregate(pipeline).explain('executionStats'); expect(JSON.stringify(plan)).not.toContain('COLLSCAN'); ``` Run these tests against a real engine in CI: a MongoDB container through Testcontainers (`@testcontainers/mongodb` 12.1.0 on npm, 2026-09-26), DynamoDB Local, and a Neo4j container. A mocked driver cannot produce a query plan, so it proves nothing here. The wider setup is in [integration test patterns](/en/workflows/test/integration-testing/), and seeding realistic volumes is in [test data strategies](/en/workflows/test/test-data-management/). **Copy-paste prompt: access-pattern test suite** ```text Write one integration test per access pattern in docs/data-model.md. Run them against a real engine started by the test setup (Testcontainers for MongoDB and Neo4j, DynamoDB Local for DynamoDB), seeded with at least 10,000 documents or items so the query planner behaves as it does in production. Each test asserts the returned data AND the plan: - MongoDB: explain('executionStats') contains no COLLSCAN. - DynamoDB: register client middleware that throws on ScanCommand. - Neo4j: EXPLAIN contains no AllNodesScan. Add one negative test per collection proving the $jsonSchema validator rejects a document without its required fields. Run the suite, paste the summary, and do not weaken an assertion to make a test pass; stop and tell me instead. ``` Who signs off: the developer who owns the feature approves the access-pattern table before any code exists, and CI must be green before merge. A reviewer reads the table, the test names, and the report. When the agent changes an assertion instead of a query, treat that as a failed change, as described in [protecting the test oracle](/en/workflows/test/protect-the-oracle/). ## When NoSQL data models break - **An array grows without bound toward the 16 MB limit.** Symptom: profile reads slow down month over month, then writes fail. Recovery: move the array into a child collection keyed by the parent id (or bucket it by month), backfill with a migration, and add the unbounded-growth question to the design prompt so the next model gets it. - **A DynamoDB partition runs hot.** A key such as `TENANT#` throttles once one tenant's traffic exceeds a single partition's throughput limit, which extra provisioned capacity does not raise. Recovery: add a shard suffix (`TENANT##<0-9>`), write to a random shard, and scatter-gather on read. - **A GSI projection misses an attribute.** Queries against the index return items without the field, and the code reads `undefined`. You cannot change a GSI's projection after creation. Recovery: create a new GSI with the right projection, switch reads, then delete the old one. - **A Neo4j supernode.** A user with millions of `FRIENDS` relationships turns every traversal from that user into a scan. Recovery: cap fan-out in the query (`WITH friend LIMIT 1000`), or model the hot relationship as its own node. - **Stale embeddings.** Vector results degrade silently after you change embedding models without re-embedding existing documents. Recovery: the dimension test catches a changed length; for a same-length model swap, re-embed everything and re-record the recall baseline in the same change. - **The agent invents schema.** Queries reference fields you do not have. Recovery: check that the MCP server is connected (`/mcp` in Claude Code, `codex mcp list` in Codex) and tell the agent to call `collection-schema` or `get_neo4j_schema` before writing anything. - **The agent tries to write through MCP.** With `--readOnly` the write tools do not exist, so the attempt fails harmlessly. Recovery: keep the flag and route the change through a migration; never remove it to get past the error. The broader threat model is in [securing MCP servers](/en/ecosystem/mcp/mcp-security/). ## Where to go next with NoSQL data modeling - [Database recipes](/en/cookbook/database-recipes/): the hub for all four database recipe pages - [Database MCP servers](/en/ecosystem/mcp/database-mcp/): read-only roles and setup for Postgres, Supabase, Neon, and MongoDB - [Database migration patterns](/en/cookbook/database-recipes/migration-patterns/): ship the indexes and validators from this page through review and CI - [SQL optimization patterns](/en/cookbook/database-recipes/sql-patterns/): when a relational model is the better call - [ORM best practices](/en/cookbook/database-recipes/orm-patterns/): type-safe data access with Prisma and TypeORM --- # ORM Best Practices URL: https://developertoolkit.ai/en/cookbook/database-recipes/orm-patterns/ Description: Get Prisma 7 and TypeORM 1.x code from Claude Code, Codex or Cursor that cannot oversell, cause N+1 queries or call a removed API, proven on real Postgres. ORM best practices for AI agents come down to three moves: pin the Prisma 7 or TypeORM 1.x version in the agent's context so it stops writing removed APIs, prompt for query shapes and invariants rather than code, and let integration tests on a real Postgres prove the result. A query-count assertion catches N+1 regressions; a concurrency test catches overselling. This recipe is for developers who let Claude Code, Codex or Cursor write the ORM layer of a TypeScript service. The agent's schema looks right and its tests pass against mocks. Then production shows an N+1 on the orders list, two customers buy the last unit of stock, and a snippet that uses `prisma.$use` fails at startup because Prisma 7 no longer has it. ## What these ORM recipes give you - A version-pin block for `AGENTS.md` or `CLAUDE.md` that stops the agent from generating Prisma 6 or TypeORM 0.3 code - A prompt for a multi-tenant Prisma 7 schema, plus the Prisma 7 config and client setup agents still get wrong - A query-count test that turns an N+1 regression into a red CI run - An order-placement flow that cannot oversell and never holds a row lock across a payment call - A Testcontainers suite the agent can run and fix in a loop, and a table of the gates that sign the change off **Versions checked on 2026-09-26** `@prisma/client` 7.10.0, `@prisma/adapter-pg` 7.10.0, `typeorm` 1.1.1 and `@testcontainers/postgresql` 12.1.0 (npm registry). One trap: the `latest` tag of the `prisma` CLI package points at an 8.0.0 release candidate (`8.0.0-rc.17` on 2026-09-26), so an unpinned `npm install -D prisma` or a fresh `npx prisma` pulls a release candidate. Pin `prisma@7.10.0` next to `@prisma/client@7.10.0`. ## Pin the ORM version in the agent's context first Agents were trained on years of Prisma 4–6 and TypeORM 0.2–0.3 code. Without a version pin they reproduce it confidently. Put the versions and the banned APIs in the project context file that your tool reads (`AGENTS.md` for Codex and Cursor, `CLAUDE.md` for Claude Code, or both), so every session starts from them: ```markdown ## Database layer - Prisma 7.10 (`prisma-client` generator, output in src/generated/prisma) with @prisma/adapter-pg. TypeORM 1.1 in services/billing. - The datasource URL lives in prisma.config.ts, not schema.prisma. PrismaClient always gets an `adapter`. - Never use: prisma.$use, prisma.$metrics, `url =` in the datasource block, @EntityRepository, getCustomRepository, getManager(), new Connection(). Use $extends, OpenTelemetry, prisma.config.ts, Repository.extend(), new DataSource(). - Money: Decimal @db.Decimal(12, 2) plus a currency column. Never @db.Money or Float. - Every data-access change ships with an integration test on Postgres (Testcontainers), not a mock. ``` The removed APIs below were checked against the published type definitions of the pinned versions: | Agent writes | Status | Write instead | | --- | --- | --- | | `url = env("DATABASE_URL")` in the `datasource` block | Moved to `prisma.config.ts` in Prisma 7.0.0 | `datasource: { url: env('DATABASE_URL') }` in `prisma.config.ts` | | `new PrismaClient()` with no options | Prisma 7 requires a driver adapter or `accelerateUrl` | `new PrismaClient({ adapter })` | | `prisma.$use(...)` middleware | Not in the `@prisma/client` 7.10.0 client | a `query` extension through `$extends` | | `prisma.$metrics` | Metrics preview removed in Prisma 7.0.0 | OpenTelemetry tracing | | `@EntityRepository`, `getCustomRepository`, `AbstractRepository` | Not exported by `typeorm` 1.1.1 | `dataSource.getRepository(User).extend({...})` | | `getManager()`, `new Connection(...)` | Not exported by `typeorm` 1.1.1 | `dataSource.manager`, `new DataSource(...)` | ## Design a Prisma 7 schema the agent cannot misread Agents reason about relations and indexes quickly. Your job is to state the tenancy model, the soft-delete rule and the queries you actually run, so the indexes match real query shapes instead of guesses. **Copy-paste prompt: multi-tenant Prisma 7 schema** ```text Design a Prisma 7.10 schema (generator provider "prisma-client", output "../src/generated/prisma"; datasource block with provider only, the URL lives in prisma.config.ts) for a multi-tenant shop. - Every tenant-scoped model has organizationId and deletedAt DateTime? (soft delete). - Models: Organization, User (role enum), Product, ProductVariant (sku, stockQuantity Int), Order (status enum, total Decimal @db.Decimal(12, 2), currency, paymentId String?), OrderItem. - Money is Decimal @db.Decimal(12, 2) with currency String @db.Char(3). Never @db.Money or Float. - Composite indexes for exactly these queries: active products by org + category; user by email; an org's orders by status, newest first. - @@map every model to a snake_case table. Output the schema, then list every index you added that I did not ask for and why. Finish by running `npx prisma validate` and fix anything it reports. ``` A good response looks like this excerpt. Note the provider-only `datasource`, the `Decimal` column and the composite index ordered to match the query: ```prisma generator client { provider = "prisma-client" output = "../src/generated/prisma" } datasource db { provider = "postgresql" } model Product { id String @id @default(cuid()) organizationId String slug String category String basePrice Decimal @db.Decimal(12, 2) currency String @default("USD") @db.Char(3) deletedAt DateTime? organization Organization @relation(fields: [organizationId], references: [id]) variants ProductVariant[] @@unique([organizationId, slug]) @@index([organizationId, category, deletedAt]) @@map("products") } ``` The connection string now lives in `prisma.config.ts`, and the client gets a driver adapter. Prisma 7 also stopped loading `.env` automatically, so load it yourself: ```typescript // prisma.config.ts import 'dotenv/config'; import { defineConfig, env } from 'prisma/config'; export default defineConfig({ schema: 'prisma/schema.prisma', migrations: { path: 'prisma/migrations' }, datasource: { url: env('DATABASE_URL') }, }); // src/db.ts import { PrismaPg } from '@prisma/adapter-pg'; import { PrismaClient } from './generated/prisma/client'; const adapter = new PrismaPg({ connectionString: process.env.DATABASE_URL, max: 10 }); export const prisma = new PrismaClient({ adapter }); ``` **Two schema traps the agent will not flag** **Money.** PostgreSQL's `money` type formats output according to the server's `lc_monetary` locale and stores no currency. Agents still suggest `@db.Money` because older tutorials did. Use `Decimal` plus a currency column, or integer minor units. **Soft delete versus unique keys.** `@@unique([organizationId, slug])` also counts soft-deleted rows, so a deleted product blocks its slug forever. When slugs must be reusable, generate the migration with `--create-only` and ask the agent to replace that constraint with a partial unique index (`WHERE deleted_at IS NULL`) in the SQL. The same schema change runs differently in each tool: **Claude Code** Run the edit-validate loop headlessly, with Bash limited to Prisma commands: ```bash claude -p "Add a soft-deletable AuditLog model to prisma/schema.prisma, run 'npx prisma validate', \ then 'npx prisma migrate dev --name add_audit_log --create-only'. Print the generated SQL and \ flag any DROP, ALTER TYPE or NOT NULL without a default." \ --allowedTools Read Edit "Bash(npx prisma *)" ``` `--create-only` writes the migration SQL without applying it, so you read the lock implications before anything touches the database. It still connects to `DATABASE_URL` and creates a shadow database, so point it at a local or Testcontainers Postgres, never a shared one. **Codex** A schema change regenerates client types across the repository, so give Codex its own managed worktree: ```bash codex --worktree -c default_permissions=":workspace" \ "Add an AuditLog model with organizationId and deletedAt, run npx prisma generate, \ and fix every call site that now fails npx tsc --noEmit." ``` `--worktree` (Codex CLI 0.157.1) creates the worktree for you. Permission profiles are beta; the legacy equivalent is `--sandbox workspace-write`, and the two do not compose, so pick one. **Cursor** Open `prisma/schema.prisma` and give Cursor's agent the prompt above. Review the per-file diff, paying most attention to the `@@index` lines, before you accept it. With the Prisma extension installed, validation errors appear in the Problems panel, and "fix the schema errors in the Problems panel" is a complete follow-up prompt. ### Use `Repository.extend()` on TypeORM 1.x On TypeORM the most common agent mistake is `@EntityRepository(User) class UserRepository extends Repository`. TypeORM 1.1.1 does not export that decorator, so the code does not compile. The current idiom is `Repository.extend()`: ```typescript export const UserRepository = dataSource.getRepository(User).extend({ findActiveByEmail(email: string) { return this.createQueryBuilder('user') .innerJoinAndSelect('user.organization', 'org') .where('user.email = :email', { email }) .andWhere('user.deletedAt IS NULL AND org.deletedAt IS NULL') .getOne(); }, }); ``` ## Find and kill N+1 queries with a query-count test The N+1 is the ORM's signature failure: an innocent loop issues one query per row. Agents fix it well when they see the loop and the SQL together. They also reintroduce it in a later refactor, so the fix is only half the job. The other half is a test that counts queries. **Copy-paste prompt: find and fix the N+1** ```text GET /api/orgs/:orgId/users is slow under load. Find the N+1 in src/routes/users.ts and rewrite it as one query with a nested include (Prisma) or innerJoinAndSelect (TypeORM). Keep the soft-delete filter deletedAt: null on both users and orders. Use a DataLoader only if one query is impossible, and say why. Then add an integration test that logs queries with new PrismaClient({ adapter, log: [{ emit: 'event', level: 'query' }] }) and prisma.$on('query'), calls the handler for an org with 3 users and 20 users, and asserts the query count is the same for both. Run the test and show me the counts before and after. ``` The fix is a nested `include`, which Prisma resolves without a query per user: ```typescript const users = await prisma.user.findMany({ where: { organizationId, deletedAt: null }, include: { orders: { where: { status: 'COMPLETED', deletedAt: null } } }, }); ``` The test is what keeps it fixed. The count must not grow with the number of rows: ```typescript const queries: string[] = []; const prisma = new PrismaClient({ adapter, log: [{ emit: 'event', level: 'query' }] }); prisma.$on('query', (e) => queries.push(e.query)); it('loads users with orders in a constant number of queries', async () => { await seedOrg('small', 3); await seedOrg('large', 20); queries.length = 0; await listUsersWithOrders(prisma, 'small'); const small = queries.length; queries.length = 0; await listUsersWithOrders(prisma, 'large'); expect(queries.length).toBe(small); }); ``` When the SQL itself is slow rather than repeated, move to [SQL optimization patterns](/en/cookbook/database-recipes/sql-patterns/), which reads the `EXPLAIN` plan. ## Write an order flow that cannot oversell or double-charge Order placement is where agent-written ORM code costs money. The agent's default is one big transaction that locks stock, calls the payment provider and commits. That holds row locks for the length of an HTTP call, and in Prisma the interactive transaction times out after five seconds by default. The safer shape has three phases: 1. **Reserve** in a short transaction: create a `PENDING` order and decrement stock only where enough stock remains. 2. **Charge** outside any transaction, with the order id as the idempotency key. 3. **Confirm** by marking the order `PAID`, or release the reservation if the charge failed. A conditional `updateMany` makes the stock check and the decrement one atomic statement. Under PostgreSQL's default `READ COMMITTED` isolation, a concurrent update re-evaluates the `WHERE` clause against the committed row, so two buyers cannot both take the last unit: ```typescript // Phase 1: reserve (Prisma 7) const order = await prisma.$transaction(async (tx) => { for (const item of items) { const { count } = await tx.productVariant.updateMany({ where: { id: item.variantId, stockQuantity: { gte: item.quantity } }, data: { stockQuantity: { decrement: item.quantity } }, }); if (count === 0) throw new InsufficientStockError(item.variantId); // rolls back all items } const total = orderTotal(items); // sum of unitPrice * quantity, computed as Decimal return tx.order.create({ data: { organizationId, userId, status: 'PENDING', total, currency, items: { create: items.map(({ variantId, quantity, unitPrice }) => ({ variantId, quantity, unitPrice })) }, }, }); }); // Phase 2: charge outside the transaction; the provider deduplicates on the key let payment: { id: string }; try { payment = await payments.charge({ amount: order.total, currency: order.currency, idempotencyKey: order.id }); } catch (err) { await releaseReservation(order.id); // restores stock, marks the order CANCELLED throw err; } // Phase 3: confirm; only a PENDING order can become PAID await prisma.order.updateMany({ where: { id: order.id, status: 'PENDING' }, data: { status: 'PAID', paymentId: payment.id }, }); ``` If phase 3 fails, the customer has paid for a `PENDING` order. Do not refund blindly from a `catch`. Let a reconciliation job match `PENDING` orders older than a few minutes against the payment provider and finish or cancel them. On TypeORM the same reserve step uses `dataSource.transaction('READ COMMITTED', ...)` with `.setLock('pessimistic_write')` on the variants before the stock check. **Copy-paste prompt: audit an order flow for money bugs** ```text Review src/services/order-service.ts for correctness under failure and concurrency. Check: 1. Can two concurrent orders both take the last unit? Show the statement that prevents it (a conditional UPDATE, or FOR UPDATE / pessimistic_write before the check). 2. Is any external call (payment, email, webhook) made while a transaction is open? 3. Is the payment call idempotent (idempotency key = order id), and can a retry double-charge? 4. If the charge succeeds and the next write fails, what state is the order in, and what finds and repairs it? 5. If the code uses SERIALIZABLE, does it retry only on Postgres error 40001, with a bound and jitter? List each gap with the smallest fix, then write a failing integration test for each gap before you fix it. ``` **SERIALIZABLE needs a retry loop** Agents reach for `SERIALIZABLE` as a safety blanket. Under it, PostgreSQL aborts conflicting transactions with error `40001`, and without a retry a burst of orders becomes a burst of 500s. Either keep `READ COMMITTED` with a conditional update or an explicit row lock, or wrap the transaction in a bounded, jittered retry that fires only on `40001`. Never retry a block that contains the payment call. ## Set the connection pool where the ORM actually reads it Agents often write a `datasource` block with `connectionLimit` or a `pool = { ... }` object. Neither field exists, and `prisma validate` rejects them. On Prisma 7 the pool belongs to the driver: `@prisma/adapter-pg` accepts a `pg` pool config (the `max: 10` in `src/db.ts` above) or an existing `pg.Pool`. The `?connection_limit=` URL parameter from Prisma 6 tutorials is a Prisma 6 idiom; configure the `pg` pool instead. TypeORM passes pool options through `extra`: ```typescript const dataSource = new DataSource({ type: 'postgres', url: process.env.DATABASE_URL, extra: { max: 10, idleTimeoutMillis: 30_000, statement_timeout: 60_000 }, }); ``` Size the pool per process, then multiply by the number of processes. Ten connections in each of 50 serverless instances is 500 connections, which exceeds the default `max_connections` of 100 in PostgreSQL. On serverless, put a pooler such as PgBouncer in front and keep `max` small. ## Prove it on real Postgres with Testcontainers Mocking the query builder tests the mock. `@testcontainers/postgresql` starts a disposable Postgres in Docker, so locks, constraints and migrations run for real. In version 12 the constructor requires an image, and `.start()` returns a `StartedPostgreSqlContainer`. Agents often omit the image. **Copy-paste prompt: Testcontainers suite for the order flow** ```text Write a Vitest integration suite for OrderService using @testcontainers/postgresql 12.1. - beforeAll: new PostgreSqlContainer('postgres:17').start(); keep it as StartedPostgreSqlContainer. - Apply the real migrations with `npx prisma migrate deploy` against container.getConnectionUri(). No db push, no synchronize: true. - Test 1: 10 concurrent placeOrder calls for a variant with stock 1. Exactly one succeeds, nine throw InsufficientStockError, final stock is 0. - Test 2: the payment mock succeeds and the confirm step throws. The order stays PENDING with no refund issued, and the reconciliation job moves it to PAID. - Test 3: the query-count test for listUsersWithOrders. - afterAll: stop the container. Run the suite and iterate until it is green. Do not weaken an assertion to make it pass. ``` ```typescript import { execSync } from 'node:child_process'; import { PostgreSqlContainer, StartedPostgreSqlContainer } from '@testcontainers/postgresql'; let container: StartedPostgreSqlContainer; beforeAll(async () => { container = await new PostgreSqlContainer('postgres:17').start(); process.env.DATABASE_URL = container.getConnectionUri(); execSync('npx prisma migrate deploy', { env: process.env, stdio: 'inherit' }); }, 120_000); afterAll(async () => { await container.stop(); }); ``` Each tool drives the red-green loop differently: **Claude Code** ```bash claude -p "Run 'npx vitest run tests/integration/order-service.test.ts'. If the concurrency \ test fails, find the missing guard in placeOrder and fix the code, not the test. Re-run until green." \ --allowedTools Read Edit "Bash(npx vitest *)" "Bash(npx prisma *)" ``` Headless mode suits this loop: container startup is slow, and you do not need to watch each re-run. **Codex** ```bash codex --worktree -c default_permissions=":workspace" \ "Run npx vitest run tests/integration/order-service.test.ts and fix placeOrder until it passes. \ Do not edit the assertions." ``` Testcontainers needs a reachable Docker daemon. If the sandbox blocks the Docker socket, run the suite in CI and paste the failure back instead of widening the sandbox. **Cursor** Give Cursor's agent the prompt above and let it run the suite in the integrated terminal. When the concurrency test fails, paste the failing output back and ask it to explain which interleaving produced it before it changes code. ## Give the agent the live schema through a Postgres MCP server For schema and N+1 work the agent does better when it reads the real indexes, row estimates and `EXPLAIN` output instead of your model file. Postgres MCP Pro (PyPI `postgres-mcp` 0.3.0, from Crystal DBA; last release 2025-05-16, so pin it and watch the repo) provides that; run it against a development or staging database with a read-only role: ```bash # Claude Code: project scope, written to .mcp.json claude mcp add -s project postgres -e 'DATABASE_URI=${DEV_DATABASE_URL}' \ -- uvx postgres-mcp --access-mode=restricted # Codex: user scope, written to ~/.codex/config.toml codex mcp add postgres --env DATABASE_URI="$DEV_DATABASE_URL" \ -- uvx postgres-mcp --access-mode=restricted ``` The single quotes keep `${DEV_DATABASE_URL}` literal in `.mcp.json`. Claude Code expands it from each developer's environment, so no credential is committed. The Codex line uses double quotes because `~/.codex/config.toml` is per-user and stores the value the shell expanded. Cursor takes the same command and arguments in its own MCP config. [Database MCP servers](/en/ecosystem/mcp/database-mcp/) has all three configs and the read-only role to create first. **Do not install the archived reference Postgres server** `@modelcontextprotocol/server-postgres` is marked "Package no longer supported" on npm (last version 0.6.2). [Datadog Security Labs showed](https://securitylabs.datadoghq.com/articles/mcp-vulnerability-case-study-SQL-injection-in-the-postgresql-mcp-server/) on 2025-08-21 that stacking `COMMIT;` before a statement escapes its read-only transaction. Agents still suggest it. Use Postgres MCP Pro in restricted mode, and make the database role read-only whichever server you choose. ## How to verify agent-written ORM code without reading every line Read the migration SQL and the invariants. Let gates check the rest: | Gate | What it proves | Runs in | | --- | --- | --- | | `npx prisma validate` and `npx tsc --noEmit` | The schema is valid Prisma 7 and every call site matches the generated types | Pre-commit hook and CI | | A grep for the banned APIs in the pin block | No removed API slipped back in | CI | | Query-count tests | N+1 regressions fail the build | CI, against Testcontainers | | Concurrency and partial-failure tests | No oversell, no orphaned charge | CI, against Testcontainers | | `npx prisma migrate status` against the target database | Applied migrations match the repository; no hand-edited drift | Deploy job, before `migrate deploy` | | A human read of the migration SQL | Locks, drops, and backfills are intended | PR review | The developer who opens the PR owns the invariants in the tests. A reviewer signs off on the migration SQL and the test names, not on every line of the generated repository code. For the gate order that turns this into a pipeline, see [testing in the agent lifecycle](/en/method/lifecycle/test/). ## When agent-written ORM code breaks in production - **The generated code targets a dead major.** Symptoms: `prisma.$use is not a function`, a `url` validation error in the `datasource` block, or TypeORM imports that do not resolve. Recovery: add the pin block from the first section to the context file and paste the error back with "this is Prisma 7.10 / TypeORM 1.1". Then add the banned-API grep to CI. - **A release candidate arrived through `npx prisma`.** Symptoms: the CLI version and `@prisma/client` differ, and `generate` output changes. Recovery: pin both packages to 7.10.0 in `package.json` and run the CLI from `node_modules`. - **Pool exhaustion under load.** Symptom: timeouts while acquiring a connection. Recovery: count `max` × processes against `max_connections`, lower `max`, and add PgBouncer for serverless. - **Serialization retry storms.** Symptom: bursts of error `40001` turned into 500s. Recovery: drop to `READ COMMITTED` with a conditional update or row lock, or add a bounded retry on `40001` only. - **Orphaned charges.** Symptom: a paid customer with a `PENDING` order. Recovery: run the reconciliation job, and add the partial-failure test from the Testcontainers prompt so the path stays covered. - **The N+1 returns after a refactor.** Symptom: latency grows with page size. Recovery: the query-count test should already be red; if it is green, the fixture is too small to show growth, so seed more rows. - **Migration drift.** Symptom: `migrate deploy` fails in CI after someone changed the database by hand. Recovery: fail the deploy on `migrate status`, and never run `prisma db push` against a shared database. [Database migration patterns](/en/cookbook/database-recipes/migration-patterns/) covers the zero-downtime rewrite. **Bound parameters only** Agents sometimes build bulk updates as a string of `CASE id WHEN ...` clauses with values concatenated in. That is an injection vector. Use the ORM's bound parameters, `Prisma.sql` template tags with `$queryRaw`, or chunked parameterized statements. ## Where to go next with ORM work - [Database recipes](/en/cookbook/database-recipes/): the hub that picks the right recipe for the task in front of you - [Database migration patterns](/en/cookbook/database-recipes/migration-patterns/): expand and contract, lint gates, and rollback for the migrations this page generates - [SQL optimization patterns](/en/cookbook/database-recipes/sql-patterns/): `EXPLAIN` plans and index design when the query is slow rather than repeated - [Database development with AI agents](/en/workflows/build/database-development/): the end-to-end workflow from spec to rollout - [Integration testing with AI](/en/workflows/test/integration-testing/): Testcontainers patterns beyond the database layer --- # SQL Optimization Patterns URL: https://developertoolkit.ai/en/cookbook/database-recipes/sql-patterns/ Description: Tune slow Postgres and MySQL queries with Claude Code, Codex, and Cursor, and prove each index, rewrite, and N+1 fix with plans and parity queries. SQL optimization with an AI agent works when every suggestion is grounded in the database's own evidence. A read-only MCP server lets Claude Code, Codex, or Cursor read the real execution plan, table statistics, and index usage. Each change then ships with a before-and-after plan, a parity query that returns zero rows, and a stated write cost. This recipe is for the developer who owns a slow query and the tech lead who approves the fix. A dashboard query that ran in 40 ms on your laptop now times out in production because the table grew and the planner switched to a sequential scan. You paste the SQL into your agent and get back a confident "add an index on `customer_id`". That index already exists, and the planner is ignoring it. ## What this SQL tuning recipe gives you - A read-only database MCP setup for Claude Code, Codex, and Cursor, so the agent reads `EXPLAIN` output instead of guessing. - A prompt that turns an `EXPLAIN (ANALYZE, BUFFERS)` plan into ranked bottlenecks and at most two justified indexes. - A rewrite prompt that proves the new query returns the same rows, with an `EXCEPT ALL` parity check in both directions. - An N+1 prompt that collapses a per-row ORM loop into two statements, plus a query-count test that keeps it fixed. - An evidence checklist a reviewer can approve without reading every line of SQL. ## Why does the agent's first index suggestion miss? An agent that sees only the SQL text pattern-matches: it indexes the `WHERE` columns, adds a few more "to be safe", and cannot tell a missing index from stale statistics. The plan holds the answer. It shows which node took the time, how far the row estimate was off, and whether a sort spilled to disk. So the order of work is fixed: 1. **Measure.** Capture the plan on staging with production-sized data. A 50,000-row table and an 80-million-row table get different plans. 2. **Diagnose.** Rank nodes by actual time. Check whether the row estimate is off by 10x or more, which usually means stale statistics, not a missing index. 3. **Simulate.** Test the candidate index as a hypothetical index (the `hypopg` extension) before you build anything. 4. **Change.** Write one index or one rewrite as a migration file. Do not apply it from the agent session. 5. **Prove.** Attach the before-and-after plan, the parity result for rewrites, and the write cost to the pull request. ## Connect a read-only database MCP server The MCP server gives the agent the plan, `pg_stats`, and `pg_stat_user_indexes` directly. Use a staging database or a database branch, a read-only role, and a statement timeout. The role, the extensions, and every server option are covered in [database MCP servers](/en/ecosystem/mcp/database-mcp/). This page uses Postgres MCP Pro in restricted mode, which the vendor README defines as read-only transactions with an execution-time limit. **Claude Code** ```bash # Terminal, repo root: writes .mcp.json; ${STAGING_DATABASE_URL} is expanded from your shell at launch claude mcp add -s project postgres -e 'DATABASE_URI=${STAGING_DATABASE_URL}' \ -- uvx postgres-mcp --access-mode=restricted ``` **Codex** ```toml # ~/.codex/config.toml: env_vars forwards DATABASE_URI from your shell. # Export DATABASE_URI first, pointing at the staging read-only URL: # export DATABASE_URI="$STAGING_DATABASE_URL" [mcp_servers.postgres] command = "uvx" args = ["postgres-mcp", "--access-mode=restricted"] env_vars = ["DATABASE_URI"] ``` **Cursor** Put the entry in the project's `.cursor/mcp.json`. Cursor's MCP docs describe `${env:NAME}` interpolation, so the file can hold a reference to an environment variable instead of the secret. Confirm the server connects in Cursor's MCP settings before you commit the file: ```json { "mcpServers": { "postgres": { "command": "uvx", "args": ["postgres-mcp", "--access-mode=restricted"], "env": { "DATABASE_URI": "${env:STAGING_DATABASE_URL}" } } } } ``` Postgres MCP Pro is the PyPI package `postgres-mcp` (0.3.0, the last release on 2025-05-16), so it runs with `uvx`, not `npx`. Its index tools need the `pg_stat_statements` and `hypopg` extensions on the database. Pick another server when your stack differs: | Your database | Server | Why | | --- | --- | --- | | Self-hosted or managed Postgres | Postgres MCP Pro (`crystaldba/postgres-mcp`) | `explain_query` with hypothetical indexes, `get_top_queries`, index recommendations | | MySQL, MariaDB, SQL Server, SQLite, or several engines | DBHub (`@bytebase/dbhub`) | One server with read-only mode, row limits, and query timeouts | | Many engines behind one config | MCP Toolbox for Databases (Google) | Prebuilt tools per engine, or custom tools in `tools.yaml` | | Supabase or Neon | The vendor's remote server | Supabase takes `read_only=true` in its URL; Neon's npm package is deprecated in favour of its remote server | **The archived reference server** The reference `@modelcontextprotocol/server-postgres` is deprecated on npm and was moved to the `modelcontextprotocol/servers-archived` repository. Do not install it for new work. Query results also flow into the model's context, so a row containing instructions is a prompt-injection path; read [MCP security](/en/ecosystem/mcp/mcp-security/) before you connect anything beyond staging. If you want Postgres guidance without a live connection, Supabase publishes a skill that covers performance and row-level security: `npx skills add supabase/agent-skills --skill supabase-postgres-best-practices`. A skill supplies rules; only the MCP server supplies your plan and statistics, so use both for tuning work. ## How do you get index advice from a real execution plan? Start by handing the agent a real plan and forbidding guesses. The grounding lines in the prompt below (check `pg_stats`, list existing indexes first, cap the count at two) are what separate it from a search-engine answer. **Copy-paste prompt: rank bottlenecks from EXPLAIN ANALYZE** ```text Using the postgres MCP server against staging, run EXPLAIN (ANALYZE, BUFFERS, VERBOSE) on the query below and rank the plan nodes by actual time, not estimated cost. For each of the top three nodes, report: 1. The node type (seq scan, nested loop, sort, hash) and its actual time. 2. Estimated vs actual rows. If they differ by 10x or more, check pg_stats for the columns involved and say whether ANALYZE is the fix instead of an index. 3. Rows Removed by Filter, and whether a sort spilled to disk. Then list the existing indexes on every table in the query (pg_indexes) and never propose one that duplicates them. Propose at most two indexes, each as CREATE INDEX CONCURRENTLY, and test each with a hypothetical index in explain_query before recommending it. Show the simulated plan change. Do not create anything. SELECT c.customer_name, COUNT(o.order_id) AS order_count, SUM(oi.quantity * oi.unit_price) AS total_spent FROM customers c JOIN orders o ON c.customer_id = o.customer_id JOIN order_items oi ON o.order_id = oi.order_id WHERE o.order_date >= DATE '2026-01-01' GROUP BY c.customer_id, c.customer_name ORDER BY total_spent DESC LIMIT 100; ``` `EXPLAIN ANALYZE` executes the statement. On a `SELECT` against staging that is what you want. On an `UPDATE`, `DELETE`, or `INSERT`, wrap it in `BEGIN; … ROLLBACK;`, and never run it against production. ### Choose the index type from the access pattern Once the plan points at a scan, ask for the smallest index that serves it. The agent defaults to B-tree everywhere unless you name the alternatives: ```sql -- Partial index: the hot path touches only active rows, so index only those CREATE INDEX CONCURRENTLY idx_customers_active ON customers (customer_id) WHERE status = 'active'; -- GIN: JSONB containment (@>) and full-text search CREATE INDEX CONCURRENTLY idx_products_attributes ON products USING gin (attributes); -- BRIN: append-only, naturally time-ordered data; tiny on disk CREATE INDEX CONCURRENTLY idx_events_created_at ON events USING brin (created_at); ``` Unused indexes cost you on every write. The same MCP session can find them: indexes with `idx_scan = 0` in `pg_stat_user_indexes` since the last statistics reset are drop candidates. Confirm the reset date and check replicas before dropping anything, because the counters are per server. ## Drive the tuning session in Claude Code, Codex, and Cursor The MCP config is the same idea in all three tools; the difference is how you keep the agent in read-only analysis until you have the evidence, then let it write one migration file. **Claude Code** Start in plan mode so the agent analyses and proposes without editing files: ```bash claude --permission-mode plan ``` Paste the plan prompt above. When the proposal carries a simulated plan change you accept, press Shift+Tab to leave plan mode (or accept the plan when Claude Code offers to proceed) and ask it to write the migration file. Claude Code shows each MCP tool call, so you can see which queries it ran. **Codex** Run the analysis under the built-in `:read-only` permission profile (beta, Codex CLI 0.138.0 or later), then a second run under `:workspace` to produce the migration as a reviewable diff: ```bash # Analysis: no file writes codex -c default_permissions=":read-only" -a on-request "Using the postgres MCP server, rank the plan nodes for the query in docs/slow-dashboard.sql and simulate at most two indexes. Do not create anything." # Change: one migration file, reviewed as a diff codex -c default_permissions=":workspace" -a on-request "Write the accepted index as CREATE INDEX CONCURRENTLY in a new file in db/migrations, with a matching DROP INDEX CONCURRENTLY down migration." ``` For a scripted run, `codex exec -c default_permissions=":read-only" "…"` prints the analysis without an interactive session. The legacy `--sandbox read-only` and `--sandbox workspace-write` flags still work in codex-cli 0.157.1, but they do not compose with permission profiles, so use one mechanism or the other, never both. **Cursor** Start in Plan Mode, which plans before it writes any code, so the analysis stays read-only. With the `postgres` server enabled, attach the migrations folder and the slow query file as context with `@` and paste the plan prompt. When you accept a simulated plan change, switch the mode from Plan back to Agent and ask it to write the migration file, then review the diff before you accept it. ## Rewrite a correlated subquery without changing its results Some slow queries are a shape problem, not an index problem. A correlated subquery that re-runs for every row is the classic case, and a window function is the fix. The dangerous part is not the rewrite; it is a rewrite that returns slightly different rows. Make the agent prove parity. **Copy-paste prompt: subquery to window function, with proof** ```text Rewrite this correlated subquery as a window function. Then write a parity check: (rewrite EXCEPT ALL original) UNION ALL (original EXCEPT ALL rewrite) wrapped in SELECT count(*). It must return 0 on staging. Run it through the postgres MCP server and show me the count and both EXPLAIN ANALYZE timings. Keep the default RANGE frame so rows that share an order_date get the same running total, exactly as the <= in the subquery does. Explain in two sentences why a ROWS frame would change the result. SELECT customer_id, order_date, order_amount, (SELECT SUM(o2.order_amount) FROM orders o2 WHERE o2.customer_id = o1.customer_id AND o2.order_date <= o1.order_date) AS running_total FROM orders o1; ``` Use `EXCEPT ALL`, not `EXCEPT`: plain `EXCEPT` removes duplicates, so a rewrite that returns a row twice still passes. Commit the parity query next to the rewrite as a test fixture, so the next refactor has to pass it too. ## Collapse an N+1 into two statements An ORM loop that touches a relation for each parent row fires one query per row, so an orders page with 500 orders makes 501 round-trips. The fix is to load all children in one query keyed by parent ID and group them in memory. The anchor stack here is Drizzle on Postgres; the [ORM patterns](/en/cookbook/database-recipes/orm-patterns/) page covers Prisma and TypeORM. **Copy-paste prompt: N+1 to one batched query, with a query-count test** ```text This Drizzle code triggers an N+1, one query per order to load its items: const orders = await db.select().from(ordersTable).where(eq(ordersTable.userId, userId)); for (const order of orders) { order.items = await db.select().from(itemsTable).where(eq(itemsTable.orderId, order.id)); } Rewrite it to load all items in one query with inArray(itemsTable.orderId, ids), then group them by orderId in memory so every order keeps its items array. Preserve the exact return shape callers expect, and return early without a second query when the user has no orders. Then add an integration test that counts statements through a custom Drizzle logger (logQuery) and asserts exactly 2 statements for a user with 50 orders. Do not use a join that repeats order columns once per item. ``` The query-count test is the verification: it goes red the day someone reintroduces the loop, without anyone reading the diff. It also catches the other bad rewrite agents produce, a single join that sends every order row once per item over the wire. ## Denormalize a hot read path without drifting When a join is hot and its rows rarely change, a maintained summary table beats re-aggregating on every request. The trigger that keeps it correct is the part agents forget, and a stale summary is worse than a slow query. Tell the agent your read/write ratio, or it will tune for reads alone. **Copy-paste prompt: summary table with drift reconciliation** ```text This schema is about 95% reads. Propose a customer_order_summary table (lifetime order count, lifetime value, last order date) maintained by an AFTER INSERT OR UPDATE OR DELETE trigger on orders. Write the table DDL, the trigger function, and a batched one-time backfill. Then write a reconciliation query that recomputes the summary from orders and returns every customer_id where the stored and recomputed values differ. It must return 0 rows after the backfill. Tell me how a bulk COPY into orders interacts with the trigger, and what the nightly drift check should alert on. ``` ## Which SQL functions differ between engines? Agents mix dialects. A connected MCP server lets the agent check that a function exists before it suggests it, but only if you ask. The traps that come up most: | You need | PostgreSQL | MySQL | BigQuery, Snowflake | | --- | --- | --- | --- | | Approximate distinct count | No built-in: the `hll` extension (`hll_cardinality(hll_add_agg(hll_hash_bigint(id)))`) or an exact `COUNT(DISTINCT …)` | No built-in: exact `COUNT(DISTINCT …)` or a counter table | `APPROX_COUNT_DISTINCT(id)` is native | | A plan with real timings | `EXPLAIN (ANALYZE, BUFFERS)` | `EXPLAIN ANALYZE` (MySQL 8.0.18 and later); it also executes the query | Each engine's query profile | | An index build that does not block writes | `CREATE INDEX CONCURRENTLY` | InnoDB online DDL: `ALGORITHM=INPLACE, LOCK=NONE` | Not applicable | | Test a drop before dropping | Hypothetical indexes via `hypopg` | Make the index `INVISIBLE`, watch, then drop | Not applicable | When the agent names an extension or function you have not seen, such as a plausible `pg_fastsearch`, make it query `pg_available_extensions` or the catalogue through the MCP server before the suggestion goes any further. ## What evidence should an SQL change carry to review? A reviewer approves the evidence, not the prose around it. Ask the agent to assemble it in the pull request description; the DDL itself is a few lines and still gets read, because schema changes are one of the classes where [someone still reads the code](/en/ladder/evidence-not-diffs/). | Change | Evidence that proves it | Who signs off | | --- | --- | --- | | New index | Before-and-after `EXPLAIN (ANALYZE, BUFFERS)` from staging, the tables whose writes it slows, and its size | The query owner; the tech lead for tables with heavy writes | | Query rewrite | Parity count of 0 with `EXCEPT ALL` both ways, committed as a test, and both timings | The query owner | | N+1 fix | Query-count test in CI and the two SQL statements it issues | The query owner | | Index drop | Zero scans since a known reset on every replica, or an invisible or hypothetical test period | The tech lead | | Summary table | Reconciliation query returns 0 rows after the backfill, committed as a test, plus a nightly drift alert | The tech lead | After deploy, compare mean execution time for the same statement in `pg_stat_statements`. The rollback for an index is `DROP INDEX CONCURRENTLY`, which belongs in the down migration. Lock safety for the migration itself (a `CONCURRENTLY` build cannot run inside a transaction block, and a linter such as Squawk catches the plain form) is covered in [database migration patterns](/en/cookbook/database-recipes/migration-patterns/), along with the expand, backfill, and contract sequence for column renames. The general PR format is in [the evidence bundle](/en/workflows/ship/evidence-bundle/). ## When SQL optimization advice goes wrong in production **Failure modes and how to recover** - **The planner ignores the new index.** Usually stale statistics: run `ANALYZE orders` and re-check the plan. If it still ignores it, the predicate may not be sargable; `WHERE date_trunc('day', created_at) = …` cannot use a plain index on `created_at`. Rewrite it as a range or add an expression index. - **A `CONCURRENTLY` build fails halfway.** Postgres leaves an `INVALID` index that still slows writes. Find it with `SELECT indexrelid::regclass FROM pg_index WHERE NOT indisvalid;`, drop it with `DROP INDEX CONCURRENTLY`, and retry. - **Plain `CREATE INDEX` on a busy table.** It blocks writes for the whole build. Stop the migration, and require `CONCURRENTLY` through a migration linter in CI. - **Index spam.** Asked to "optimize", agents index every `WHERE` and `ORDER BY` column. Cap the count at two in the prompt and require a plan-backed reason for each. - **`MATERIALIZED` CTEs on small inputs.** Forced materialization blocks predicate push-down. Materialize only when the CTE is large and referenced more than once; otherwise remove the keyword and compare plans. - **Interpolated SQL.** Generated query builders sometimes concatenate user input into the query text. Reject any value that is not a bound parameter, and let a lint rule or test fail the build on it. - **The MCP server can write.** Restricted mode and a read-only role are two separate locks; keep both. If a session did write, restore from the staging snapshot and rotate the credential it used. ## Where to go next with SQL tuning - [Database MCP servers](/en/ecosystem/mcp/database-mcp/) — Roles, extensions, and install details for Postgres MCP Pro, DBHub, MCP Toolbox, Supabase, and Neon. - [Database migration patterns](/en/cookbook/database-recipes/migration-patterns/) — Ship the index or schema change safely: expand, backfill, contract, lint gate, and rollback per phase. - [ORM patterns](/en/cookbook/database-recipes/orm-patterns/) — Catch N+1 queries, bad transactions, and deprecated APIs in Prisma and TypeORM code. - [Performance testing](/en/workflows/test/performance-testing/) — Turn a one-off query fix into a load test that fails CI when latency regresses. For the whole database workflow from schema design to release, start at [database development with agents](/en/workflows/build/database-development/). The other database recipes are listed in the [database recipes overview](/en/cookbook/database-recipes/). --- # DevOps & Infrastructure Recipes URL: https://developertoolkit.ai/en/cookbook/devops-recipes/ Description: Pick the DevOps recipe for Docker, Kubernetes, CI/CD, IaC or monitoring, give the agent your delivery rules, and prove each change with gates. The DevOps recipes are five pages of copy-paste prompts for Claude Code, Codex, and Cursor: Dockerfiles, Kubernetes manifests, CI/CD pipelines, infrastructure as code, and monitoring. Every recipe follows one rule: the agent writes the configuration, and a machine check proves it before a human approves the change. This page is for developers who let an agent write delivery configuration, and for tech leads who own the pipeline it runs through. You know the failure: a 1.2 GB image, a rollout stuck in `CrashLoopBackOff`, or a pipeline that went green because the agent weakened a failing scan. ## Which DevOps recipe fits your task? The last column is the evidence the agent attaches instead of you reading the YAML. | Your task | Recipe | The gate that proves it | | --- | --- | --- | | Write or shrink a Dockerfile, a Compose file, or image CI | [Docker and container patterns](/en/cookbook/devops-recipes/docker-patterns/) | hadolint, a Trivy scan, and a smoke test of the built image | | Deployments, Helm charts, autoscaling, GitOps | [Kubernetes orchestration patterns](/en/cookbook/devops-recipes/kubernetes-patterns/) | `helm lint`, then `kubectl diff` against the real cluster in CI | | GitHub Actions, GitLab CI, or Jenkins pipelines | [CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/) | actionlint, zizmor, and a throwaway pull request that must go red | | Terraform, CloudFormation, or Pulumi changes | [Infrastructure as code patterns](/en/cookbook/devops-recipes/infrastructure-as-code/) | `terraform plan` with zero unexpected replaces or destroys | | Instrumentation, alert rules, dashboards, log pipelines | [Monitoring and logging patterns](/en/cookbook/devops-recipes/monitoring-logging/) | `promtool test rules` and a query that returns real data | For the end-to-end delivery workflow, read [review and ship](/en/workflows/ship/); for running production afterwards, read [DevOps with AI](/en/workflows/operate/). ## Give the agent your delivery rules before any recipe Without rules, an agent writes what an average tutorial would: `:latest` tags, a root user, unpinned actions. Write the rules once, where each tool loads them automatically. ```markdown ## Delivery rules - Never read, print, or write secrets. Use the secret store; no credentials in ENV, ARG, YAML, or HCL. - Pin every base image, action, chart, and provider to an explicit version. - Never delete, skip, or soften a failing check (scanner severity, .trivyignore, `continue-on-error`, `|| true`, `-target`). Report the finding and stop. - You do not run `terraform apply`, `kubectl apply`, `helm upgrade`, or any deploy. CI does that after approval. - After any change, run the gates in scripts/verify-delivery.sh and paste the full output in your summary. ``` **Claude Code** Keep the canonical block in `AGENTS.md` and make `CLAUDE.md` at the repository root the single line `@AGENTS.md`, which imports it. Claude Code loads it in every session, headless `claude -p` runs included. **Codex** Add the block to `AGENTS.md` at the repository root. Since Codex 0.150.0, an untrusted project does not supply its project-level `AGENTS.md`, so trust the repository: accept **Trust this folder?** on your first `codex` run there, or set `trust_level = "trusted"` under `[projects."/absolute/path"]` in `~/.codex/config.toml` (see [Codex configuration](/en/codex/quick-start/configuration/)). **Cursor** Save the block as a project rule ([Cursor Rules](https://cursor.com/docs/rules)). Update this copy whenever the canonical block changes. The deploy rule matters most: without production credentials, a bad recipe costs a failed pull request, not an incident. [Permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/) shows how to enforce it. **Copy-paste prompt: audit the delivery config before you change it** ```text Read-only pass: do not edit files. Inventory every Dockerfile, Compose file, Kubernetes manifest or Helm chart, CI workflow, and Terraform module in this repository. For each, list: unpinned versions (images, actions, charts, providers), containers running as root, checks that cannot fail (continue-on-error, || true, severity filters that exclude HIGH), and secrets referenced outside the secret store. Output one table sorted by risk, with file:line for every finding, and name the recipe fix you would apply first. ``` ## How do you verify agent-written DevOps changes without reading every line? A recipe is done when its gate passes and the agent attaches the output, not when the YAML looks right. - **Static gates run in the agent's session.** They need no credentials. - **Reality gates run in CI.** `terraform plan` and `kubectl diff` need cloud and cluster access, so a read-only CI job posts their output on the pull request for the agent to read. - **Prove a gate can fail.** The CI/CD recipe opens a throwaway pull request that must go red. - **A human signs off on blast radius.** The reviewer reads the plan summary (resources added, changed, destroyed) and the rollback command, not every line. Both go in the pull request's [evidence bundle](/en/workflows/ship/evidence-bundle/), and production approval stays a [human boundary](/en/developer-scorecard-guide/production-approval-gate/). Put the static gates in one script that every tool and every human runs. Delete the lines your repository does not need: ```bash #!/usr/bin/env bash # scripts/verify-delivery.sh: static gates only; no cloud or cluster credentials. set -euo pipefail for f in $(git ls-files '*Dockerfile*'); do docker run --rm -i hadolint/hadolint < "$f"; done actionlint uvx zizmor .github/workflows/ for c in charts/*/; do helm lint "$c"; done terraform -chdir=infra init -backend=false -input=false >/dev/null terraform -chdir=infra validate promtool check rules monitoring/rules/*.yml echo "PASS all static delivery gates" ``` **Copy-paste prompt: fix until the gates pass, without weakening them** ```text Run exactly: scripts/verify-delivery.sh. For each failing gate, fix the configuration, not the gate: do not edit the script, scanner ignore files, severity lists, or CI step conditions. Rerun after each fix. Stop after three rounds or when all gates pass. Then give me: the full final script output, a list of files you changed with one line each on why, and any finding you could not fix, with the reason. Do not run apply, upgrade, or deploy commands. ``` Save it as `prompts/devops-gates.txt` and run it the same way in each tool: **Claude Code** ```bash # Terminal, on a trusted branch. Edits allowed; shell limited to the gate script. claude -p "$(cat prompts/devops-gates.txt)" \ --permission-mode dontAsk \ --allowedTools "Read,Grep,Glob,Edit,Bash(scripts/verify-delivery.sh)" \ --output-format json > gates.json ``` `Bash(scripts/verify-delivery.sh)` matches only that exact spelling, which is why the prompt says "Run exactly". If the agent calls `./scripts/verify-delivery.sh` or `bash scripts/verify-delivery.sh`, the call is denied (`--permission-mode dontAsk` denies whatever would prompt, and nobody could answer a prompt in `-p` mode anyway), so the summary may arrive without gate output. Reject any summary that lacks the final `PASS` line. **Codex** ```bash # Terminal. The sandbox limits writes to the workspace; -o saves the final summary. codex exec --sandbox workspace-write -o gates.md "$(cat prompts/devops-gates.txt)" ``` The `workspace-write` sandbox has no network access by default (`sandbox_workspace_write.network_access` is `false` in codex-cli 0.157.1), so `uvx zizmor`, `terraform init`, and `docker run hadolint` fail inside it. Preinstall the tools in your dev image instead: a pinned zizmor, a provider cache through `TF_PLUGIN_CACHE_DIR`, and a hadolint binary. **Cursor** Paste the prompt into the agent. It runs the script in the integrated terminal, subject to your run-mode settings. Accept the diff only after the terminal shows the final `PASS` line. ## What breaks when agents write DevOps configuration? **DevOps recipe failure modes and recovery** - **A green pipeline because the agent weakened a gate.** The diff adds `|| true`, drops `HIGH` from a severity list, or edits `.trivyignore`. Recovery: revert those lines and require a code owner's approval for changes to gate files. - **Invented or stale versions.** Agents reuse tags from training data and guess commit SHAs. Recovery: resolve every pin against the registry, and let Renovate or Dependabot own digests. - **A plan that replaces a resource you meant to edit.** A renamed Terraform resource or changed immutable field becomes destroy-and-create. Recovery: block the merge on any unexpected replace, and record a rename with a `moved` block instead of a new resource. - **Hardening advice from an older platform.** PodSecurityPolicy was removed in Kubernetes 1.25, yet agents still generate it. Recovery: name the cluster version in the prompt and validate with `kubectl diff` against the real API server. - **The agent asks for credentials to "check it works".** Recovery: refuse, and move that check into the read-only CI job. Never answer with `--dangerously-skip-permissions` or a full-access sandbox outside a disposable, network-restricted environment. ## Where to go next with DevOps recipes - [Docker and container patterns](/en/cookbook/devops-recipes/docker-patterns/) - [Kubernetes orchestration patterns](/en/cookbook/devops-recipes/kubernetes-patterns/) - [CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/) - [Infrastructure as code patterns](/en/cookbook/devops-recipes/infrastructure-as-code/) - [Monitoring and logging patterns](/en/cookbook/devops-recipes/monitoring-logging/) - [Containerization workflow](/en/workflows/ship/containerization/) - [CI/CD pipelines workflow](/en/workflows/ship/ci-cd-pipelines/) - [Infrastructure as code workflow](/en/workflows/ship/infrastructure-code/) - [Infrastructure MCP servers](/en/ecosystem/mcp/infrastructure-mcp/) — Terraform, Kubernetes, and cloud servers that ground the agent in real provider data. - [Headless agents in CI](/en/ecosystem/agent-tools/headless-agents-ci/) — Run these recipes as CI jobs safely, on trusted refs only. --- # CI/CD Pipeline Patterns URL: https://developertoolkit.ai/en/cookbook/devops-recipes/ci-cd-pipelines/ Description: Copy-paste recipes that make Claude Code, Codex, and Cursor generate CI/CD pipelines with gates you prove can fail: scans, pinned actions, gated deploys. CI/CD pipeline recipes for AI agents are copy-paste prompts and reviewed YAML that make Claude Code, Codex, or Cursor generate GitHub Actions, GitLab CI, or Jenkins pipelines whose gates can fail: tests from the repository's real scripts, an image scan that blocks the push, actions pinned to commits, and a deploy that waits for a human approver. Your deploy passed every check and still shipped a critical CVE. The tests were green and the image built, but the scan step only uploaded a report, so nothing in the pipeline could say no. The agent that wrote the workflow did exactly what it was asked; nobody asked it for a gate that fails. This page is for the developer or tech lead who owns a service's pipeline and wants the agent to write it. The recipes below produce the YAML, and then prove each gate can turn red, so you trust the pipeline without re-reading 200 lines of it. ## What you'll walk away with from these CI/CD recipes - A prompt that turns `package.json` and `Dockerfile` into a GitHub Actions workflow with a Node matrix, a Trivy scan that runs **before** the push, and a deploy job behind a GitHub Environment. - A gate drill: `actionlint`, `zizmor`, and throwaway pull requests that must go red, so you know each gate blocks instead of assuming it does. - A prompt that turns a failed run's log into one root cause and one fix. - An AI review step for pipeline pull requests with Claude Code, Codex, or Cursor, configured with least privilege. - The failure modes generated pipelines hit first, with the recovery for each. The broader pipeline techniques (change-aware builds, flaky-test quarantine, progressive rollouts) are on [Pipeline automation with AI](/en/workflows/ship/ci-cd-pipelines/). This page stays on generating and hardening the pipeline file itself. ## How do you get an agent to generate a pipeline that matches your repo? A bare "create a CI/CD pipeline" prompt produces a plausible workflow for a project you do not have: the wrong package manager, an invented `npm run test:ci`, a Node version you never ran. Anchor the agent to the files that already exist, and name the gates you want in terms of what makes them fail. **Claude Code** From the repository root, run `claude`. Claude Code reads `package.json`, the `Dockerfile`, and any existing `.github/workflows/*` itself, so you paste nothing. To review the plan before any file changes, start in plan mode: ```bash claude --permission-mode plan ``` Paste the prompt below. When the plan names the scripts it found in `package.json`, approve it and let Claude Code write the file. **Codex** From the repository root, run Codex with the workspace permission profile (beta in Codex CLI 0.157.1), which lets it write inside the repository and nowhere else: ```bash codex -c default_permissions=":workspace" ``` Paste the prompt below. The `:workspace` profile grants no network access, so Codex asks before it runs `git ls-remote` to look up action SHAs; approve that one request. **Cursor** Open the repository in Cursor, switch the agent to **Plan Mode**, and add `@package.json`, `@Dockerfile`, and any existing workflow files to the context. Paste the prompt below, review the plan, then let the agent write `.github/workflows/ci.yml` and review the diff in the editor before you keep it. **Copy-paste prompt: generate a hardened GitHub Actions workflow** ```text Read package.json and Dockerfile. Write .github/workflows/ci.yml for this Node.js service. Use only scripts that exist in package.json; if a test or build script is missing, stop and tell me instead of inventing one. Jobs: 1. test: matrix over Node 22 and 24, actions/setup-node with cache: npm, npm ci, then the real test script. 2. image (needs: test): build with docker/build-push-action and load: true (not pushed), GHA layer cache. Scan the local image with aquasecurity/trivy-action, severity CRITICAL,HIGH, ignore-unfixed: true, exit-code '1' so a vulnerable image FAILS the job. Only after the scan passes, and only on non-pull_request events, log in to GHCR with GITHUB_TOKEN and push. Lowercase the image name. 3. deploy-prod (needs: image): only on published releases, runs in the GitHub Environment "production", permissions id-token: write for OIDC to the cloud. Leave the rollout as a TODO comment. Hardening rules: - Top-level permissions: contents: read; widen per job only where needed. - persist-credentials: false on every actions/checkout. - Use actions/checkout v7, actions/setup-node v7, docker/setup-buildx-action v4, docker/login-action v4, docker/build-push-action v7, aquasecurity/trivy-action v0.36.0. Pin each to its full commit SHA with the tag as a trailing comment. Look SHAs up with git ls-remote --tags https://github.com/OWNER/REPO; never guess one. - Never put ${{ github.event.* }} inside a run: script; pass it through env. After the YAML, print a table: gate | what makes it fail | how I can test that. ``` A good result has this shape. The excerpt shows tags for readability; the agent's output carries SHAs: ```yaml # .github/workflows/ci.yml (excerpt) name: CI on: push: { branches: [main] } pull_request: release: { types: [published] } permissions: contents: read jobs: test: runs-on: ubuntu-latest strategy: matrix: { node: [22, 24] } steps: - uses: actions/checkout@v7 with: { persist-credentials: false } - uses: actions/setup-node@v7 with: node-version: ${{ matrix.node }} cache: npm - run: npm ci - run: npm test # the script that exists in package.json image: needs: test runs-on: ubuntu-latest permissions: contents: read packages: write env: IMAGE: ghcr.io/acme/billing-api:${{ github.sha }} # GHCR names must be lowercase steps: - uses: actions/checkout@v7 with: { persist-credentials: false } - uses: docker/setup-buildx-action@v4 - name: Build (loaded locally, not pushed) uses: docker/build-push-action@v7 with: load: true tags: ${{ env.IMAGE }} cache-from: type=gha cache-to: type=gha,mode=max - name: Scan - fails the job on fixable CRITICAL/HIGH uses: aquasecurity/trivy-action@v0.36.0 with: image-ref: ${{ env.IMAGE }} severity: CRITICAL,HIGH ignore-unfixed: true exit-code: '1' - if: github.event_name != 'pull_request' uses: docker/login-action@v4 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Push only what passed the scan if: github.event_name != 'pull_request' run: docker push "$IMAGE" deploy-prod: needs: image if: github.event_name == 'release' runs-on: ubuntu-latest environment: production # required reviewers on this environment = the human sign-off permissions: contents: read id-token: write # OIDC to the cloud, no stored cloud keys steps: - uses: actions/checkout@v7 with: { persist-credentials: false } # TODO: cloud login via OIDC, then the rollout ``` Three lines carry the safety, so they are the three you check first: - **`exit-code: '1'`** turns the scan from a report into a gate. Without it, Trivy prints findings and the job stays green. - **`load: true` before the scan, `docker push` after it** means a vulnerable image never reaches the registry. Scanning after `push: true` blocks the deploy, but the bad image is already published. - **`environment: production`** does nothing until you add required reviewers to that environment in the repository settings. The YAML names the gate; the setting enforces it. For the Dockerfile the pipeline builds, see [Docker and container patterns](/en/cookbook/devops-recipes/docker-patterns/); for the rollout the deploy job runs, see [Kubernetes orchestration patterns](/en/cookbook/devops-recipes/kubernetes-patterns/) and [progressive delivery for agent-written changes](/en/workflows/ship/progressive-delivery/). ## How do you prove the pipeline's gates actually block? A generated pipeline that has never gone red is an untested pipeline. Instead of reading every line, run two static checkers and one drill that makes each gate fail on purpose. The same rule applies to tests: a gate that cannot fail is worse than no gate, because it earns the green check without the safety. 1. **Lint the workflow syntax and expressions.** [`actionlint`](https://github.com/rhysd/actionlint) catches invalid keys, broken `${{ }}` expressions, and shell errors in `run:` blocks. Install it with `brew install actionlint` or `go install github.com/rhysd/actionlint/cmd/actionlint@latest`, then run `actionlint` from the repository root. 2. **Audit the workflow for security defects.** [`zizmor`](https://github.com/zizmorcore/zizmor) (PyPI `zizmor` 1.30.1, checked 2026-09-26) flags `template-injection`, `excessive-permissions`, `unpinned-uses`, `cache-poisoning`, and `artipacked` (checkout credentials left on disk). Run `uvx zizmor .github/workflows/`. Since v1.20.0 its default policy requires every action to be pinned by SHA, including `actions/*`, so a tag-pinned workflow fails this step until the agent resolves the SHAs. 3. **Run the gate drill.** Have the agent open draft pull requests from throwaway branches, each carrying exactly one deliberate failure (the prompt below). Keep the failures on separate branches: `image` needs `test`, so a failing test on the same branch would skip the scan and prove nothing about it. Each gate must go red on its own branch, and `deploy-prod` must never start. 4. **Make the gates binding.** In the branch protection or ruleset for `main`, mark `test` and `image` as required status checks, and add required reviewers to the `production` environment. Until then a red check is advice: anyone with merge rights can merge past it. Required checks still run the workflow file from the pull request itself, so a pull request can delete the scan step and stay green; put `/.github/` under `CODEOWNERS` and turn on required code-owner review in the same ruleset. 5. **Record who signs off.** The required reviewers on `production` are the people with production authority. The agent writes and fixes the pipeline; a named human approves each production deploy. See [production approval as a system boundary](/en/developer-scorecard-guide/production-approval-gate/). **Copy-paste prompt: audit the workflow and drill every gate** ```text Audit .github/workflows/ci.yml. 1. Run actionlint and `uvx zizmor .github/workflows/`. Fix every finding. If you decide a finding should stay, add a comment on that line saying why, and list it for me. 2. Prove zizmor bites: add a step using aquasecurity/trivy-action@master, run zizmor, show me the unpinned-uses finding, then revert the step. Do not commit it. 3. From main, create two branches, each with one deliberate failure: a. ci/drill-test: a unit test that asserts 1 === 2 in the existing test directory; b. ci/drill-scan: the Dockerfile base image changed to an end-of-life tag (node:16), nothing else. 4. Push both and open each as a DRAFT pull request titled "CI gate drill - do not merge". 5. Tell me which check must fail on each: (a) test, (b) image. For (b), confirm from the log that the failing step is the Trivy scan, not the Docker build. deploy-prod must be skipped in every run. Do not merge, do not change branch protection, and do not touch secrets. ``` When the drill comes back, compare the actual red checks with the agent's list. A gate that stayed green on its branch is a finding, not a flake. Close the draft pull requests and delete the branches once every gate has failed where it should. ## How do you diagnose a red run without scrolling the log? The expensive half of CI is the run that fails 400 lines into a log with `npm ci` exiting 1. Fetch only the failed steps with the GitHub CLI and give the agent the log together with the job definition: ```bash gh run view RUN_ID --log-failed > failed.log ``` `RUN_ID` is the number in the run's URL. The workflow is identical in all three tools: in Claude Code and Codex, reference `failed.log` by path in the prompt; in Cursor, attach it with `@failed.log`. To let the agent read runs itself, register the GitHub MCP server's read-only Actions toolset with a fine-grained, read-only personal access token in `GITHUB_PAT`: **Claude Code** ```bash claude mcp add --transport http github-actions \ https://api.githubcopilot.com/mcp/x/actions/readonly \ -H "Authorization: Bearer $GITHUB_PAT" ``` The shell expands `$GITHUB_PAT` once, and Claude Code stores the resulting value in its configuration, so use a token scoped to read Actions only. **Codex** ```bash codex mcp add github-actions \ --url https://api.githubcopilot.com/mcp/x/actions/readonly \ --bearer-token-env-var GITHUB_PAT ``` Codex reads the variable at connection time and never writes the token to `config.toml`. **Cursor** In `~/.cursor/mcp.json`, the user-global file that never gets committed: ```json { "mcpServers": { "github-actions": { "url": "https://api.githubcopilot.com/mcp/x/actions/readonly", "headers": { "Authorization": "Bearer ${env:GITHUB_PAT}" } } } } ``` This follows the shape in GitHub's Cursor install guide; the `${env:NAME}` interpolation is from Cursor's MCP docs as quoted in our research, not tested in a Cursor binary. Confirm in **Settings > MCP** that `github-actions` lists tools, and see the Cursor tab of [Install the GitHub MCP server](/en/ecosystem/mcp/github-mcp/#install-the-github-mcp-server-in-claude-code-codex-and-cursor) for the full setup. More on the server's toolsets and lockdown mode is on the [GitHub MCP server](/en/ecosystem/mcp/github-mcp/) page. **Copy-paste prompt: turn a failed run into one root cause** ```text A GitHub Actions run failed. The failed steps' log is in failed.log, and the workflow is .github/workflows/ci.yml. Give me: 1. The single root cause, not a list of possibilities. Quote the log line that proves it. 2. Why it fails in CI but passes on my machine (runner OS, Node version, cache key, lockfile drift, missing service, permissions). 3. The smallest change to the YAML, lockfile, or code that fixes it. 4. A way to confirm the fix before I push: a command I can run locally, or the exact check that must turn green on the next run. If the evidence is not in the log, say what extra log or file you need instead of guessing. ``` The "in CI but not locally" question steers the model toward environment causes: a cache key restoring dependencies built for another Node version, a lockfile out of sync with `package.json`, a missing service container, or a token without the permission the step needs. Point 4 is the verification: the fix is done when that check turns green, not when the explanation sounds right. ## What changes for GitLab CI and Jenkins? The generate-then-drill loop is the same; only the target file and the gate syntax change. Swap `.github/workflows/ci.yml` in the prompts for `.gitlab-ci.yml` or a declarative `Jenkinsfile`, and add these platform notes to the prompt: - **GitLab CI:** ask for GitLab's maintained templates, `include: - template: Jobs/SAST.gitlab-ci.yml` and `Jobs/Container-Scanning.gitlab-ci.yml`, instead of hand-rolled scanner jobs. The older `Security/` paths are redirect stubs (Container Scanning moved in GitLab 15.6), and generated pipelines often still emit them. Pin job images to a real tag such as `node:22-alpine`, and key the cache on the lockfile with `cache: key: files: [package-lock.json]`. - **Jenkins:** ask for a declarative `Jenkinsfile` with Docker agents and `parallel` quality stages, and a SonarQube stage that calls `withSonarQubeEnv` followed by `waitForQualityGate abortPipeline: true`. Without `abortPipeline: true`, a failed quality gate is reported and the pipeline continues. ## How do you add an AI review step to pipeline pull requests? An AI reviewer on pipeline changes catches what the checkers cannot: a deploy condition that is too broad, a permission widened "temporarily", a scan moved after the push. It is advisory. The required checks and the environment approval stay the gates, and a review comment never replaces them. **Claude Code** Run `/install-github-app` inside `claude` to install the Claude GitHub app and store `ANTHROPIC_API_KEY` as a repository secret, then add a review workflow scoped to pipeline files: ```yaml # .github/workflows/claude-pipeline-review.yml name: Claude pipeline review on: pull_request: types: [opened, synchronize] paths: ['.github/workflows/**', 'Dockerfile', '.gitlab-ci.yml', 'Jenkinsfile'] permissions: contents: read pull-requests: write id-token: write # the action swaps an OIDC token for the Claude GitHub App token jobs: review: runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 with: { persist-credentials: false, fetch-depth: 1 } - uses: anthropics/claude-code-action@v1 with: anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }} prompt: | REPO: ${{ github.repository }} PR NUMBER: ${{ github.event.pull_request.number }} Review only the CI/CD changes in this pull request. Flag: gates that can no longer fail, widened permissions, unpinned actions, event data used inside run: scripts, secrets exposed to pull request code, and deploy conditions broader than releases. Comment inline on the exact line. Do not suggest style changes. claude_args: '--allowedTools "mcp__github_inline_comment__create_inline_comment,Bash(gh pr diff:*),Bash(gh pr view:*)"' ``` `id-token: write` is required with the default GitHub App authentication: without it the action cannot get the OIDC token it exchanges for the app token, and the job fails before it reviews anything. If you would rather not use the app, pass `github_token: ${{ secrets.GITHUB_TOKEN }}` instead, and comments then come from `github-actions[bot]`. `--allowedTools` limits the reviewer to reading the diff and posting inline comments. On pull requests, the action restores `.claude/`, `.mcp.json`, and `CLAUDE.md` from the base branch before Claude starts, so a pull request cannot swap in its own hooks or MCP servers. The action configures its own git credentials before that fetch, so `persist-credentials: false` on the checkout does not break the restore (claude-code-action source, checked 2026-09-26). That restore protects the agent's configuration, not this workflow: on `pull_request` GitHub runs the YAML from the pull request, and the `paths` filter includes `.github/workflows/**`, so anyone who can push a branch to this repository can widen `--allowedTools` in their own copy of the job, and it runs with `ANTHROPIC_API_KEY` before any human review. `CODEOWNERS` on `/.github/` with required review stops such a change from merging, not from running, so give only trusted people push access and treat the AI review as advisory. **Codex** `openai/codex-action@v1` installs the Codex CLI and runs `codex exec`. Run Codex in a job that can only read, and post its answer from a second job that holds the write permission: ```yaml # .github/workflows/codex-pipeline-review.yml name: Codex pipeline review on: pull_request: types: [opened, synchronize, reopened] paths: ['.github/workflows/**', 'Dockerfile', '.gitlab-ci.yml', 'Jenkinsfile'] jobs: codex: runs-on: ubuntu-latest permissions: contents: read outputs: final_message: ${{ steps.run_codex.outputs.final-message }} steps: - uses: actions/checkout@v7 with: ref: refs/pull/${{ github.event.pull_request.number }}/merge fetch-depth: 0 # base and head SHAs reachable for the diff persist-credentials: false - id: run_codex uses: openai/codex-action@v1 with: openai-api-key: ${{ secrets.OPENAI_API_KEY }} permission-profile: ':read-only' prompt: | Review only the CI/CD changes between ${{ github.event.pull_request.base.sha }} and ${{ github.event.pull_request.head.sha }}. Flag gates that can no longer fail, widened permissions, unpinned actions, event data used inside run: scripts, and deploy conditions broader than releases. Cite file and line for each finding. No style comments. post: needs: codex if: needs.codex.outputs.final_message != '' runs-on: ubuntu-latest permissions: pull-requests: write steps: - env: GH_TOKEN: ${{ github.token }} BODY: ${{ needs.codex.outputs.final_message }} PR_NUMBER: ${{ github.event.pull_request.number }} run: gh pr comment "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" --body "$BODY" ``` Keep the default `safety-strategy: drop-sudo`, which removes `sudo` before Codex runs. OpenAI's action README prefers a permission profile over the legacy `sandbox` input for new workflows, and the two inputs cannot be combined. Leave `model` empty to use Codex's default model; the [models hub](/en/ecosystem/models/) lists what that is today. The `codex` job reads the pull request's own files, including any `AGENTS.md` or `.codex/` it adds, with `OPENAI_API_KEY` in scope, so `:read-only` and the missing write permission are what keep a hostile pull request harmless: never give that job write permissions or write tools. As with the Claude Code job, anyone who can push a branch can edit this workflow before it runs, so the review stays advisory. **Cursor** Cursor's pull request reviewer is **Bugbot**, which reviews pull requests for bugs, security issues, and code quality problems once you enable it for the repository (Cursor docs, checked 2026-08-28; setup on the [Bugbot](/en/cursor-ide/ship/bugbot/) page). Put the same checklist as the Claude Code prompt in `.cursor/BUGBOT.md`, the project rules file Bugbot reads: gates that can no longer fail, widened permissions, unpinned actions, and broad deploy conditions. For a scripted step inside the workflow itself, Cursor documents running its CLI in GitHub Actions (Cursor docs, checked 2026-08-28). A common split is to author the pipeline in the editor and let Bugbot or one of the other two actions review it in CI. **Do not switch to pull_request_target to review fork pull requests** With the `pull_request` trigger, pull requests from forks receive no secrets, so the AI review job does not run for them. Switching to `pull_request_target` gives fork code the base repository's secrets. If you must review fork pull requests, check out the base branch at the workspace root and the contributor's commit into a subdirectory the agent only reads, load no project settings from it, set `persist-credentials: false`, and give the agent read-only tools. Prompt injection through pull request text is a real path: in the "Clinejection" chain (disclosed February 2026, secondary: Adnan Khan's write-up), an injected GitHub issue title steered an AI triage workflow into Actions cache poisoning and the theft of publish tokens. ## When generated CI/CD pipelines break 1. **The cache restores, yet the build breaks or recompiles everything.** The key is missing the lockfile hash or the Node version, so `node_modules` built for one Node version is restored under another. Use `actions/setup-node` with `cache: npm`, which caches the npm download cache rather than `node_modules`. If you need `actions/cache`, key it on `${{ runner.os }}-node${{ matrix.node }}-${{ hashFiles('**/package-lock.json') }}`. 2. **The push to GHCR fails with "repository name must be lowercase".** `${{ github.repository }}` keeps the owner's capitalisation. Lowercase the name in a prior step, or write it out in lowercase as the skeleton does, and re-run. 3. **The OIDC deploy fails with "Not authorized to perform sts:AssumeRoleWithWebIdentity".** The YAML is usually fine; the cloud trust policy does not match the token. A job that uses `environment: production` sends the subject `repo:ORG/REPO:environment:production`, not a branch ref. Ask the agent to generate the trust policy from the workflow's trigger and environment, then compare its `sub` condition with the claim in the failed run. 4. **Trivy fails on a CVE that has no fix yet.** Do not delete or soften the scan step; a scan that cannot fail is the opening incident all over again. `ignore-unfixed: true` skips vulnerabilities with no fixed version. For the rest, add the CVE to `.trivyignore` with an expiry, for example `CVE-2026-12345 exp:2026-12-31`, and a comment naming the reviewer. Trivy re-raises it when the date passes. 5. **The agent pins actions to tags, `@main`, or versions that do not exist.** Agents reproduce the versions from their training data and guess SHAs. The malicious LiteLLM 1.82.7/1.82.8 releases on PyPI (2026-03-24) were traced to a compromised Trivy step in LiteLLM's CI (secondary reports; tracking issue [BerriAI/litellm#24518](https://github.com/BerriAI/litellm/issues/24518)). Pinning by SHA means a moved or hijacked tag cannot change what your pipeline runs. Re-prompt with "resolve every action to its full commit SHA with `git ls-remote`, tag as a comment", and let `zizmor`'s `unpinned-uses` audit confirm it. 6. **The AI review job never comments.** Check three things in order: the pull request came from a fork (no secrets, by design); the `paths` filter excluded the changed file; or the job lacks `pull-requests: write`. Fix the filter or the permission. Do not widen the trigger. ## Where to go next with CI/CD pipelines - [Pipeline automation with AI](/en/workflows/ship/ci-cd-pipelines/) — Change-aware builds, flaky-test quarantine, and deploys that roll back on error rate. - [The evidence bundle](/en/workflows/ship/evidence-bundle/) — What an agent's pull request must prove before a human approves it, with the pipeline as the proof. - [Kubernetes orchestration patterns](/en/cookbook/devops-recipes/kubernetes-patterns/) — Generate the manifests and rollout logic the deploy job applies. - [Security testing](/en/workflows/test/security-testing/) — SAST, dependency scanning, and secrets detection to run before the pipeline builds an image. --- # Docker & Container Patterns URL: https://developertoolkit.ai/en/cookbook/devops-recipes/docker-patterns/ Description: Recipes for agent-written Dockerfiles, Compose files and image CI with Claude Code, Codex and Cursor, plus a script that proves each image before you merge. Docker patterns for AI coding agents are a set of prompts and gates for letting Claude Code, Codex or Cursor write Dockerfiles, Compose files and image pipelines. The agent drafts multi-stage builds, health-gated Compose stacks and scanning CI; one verification script proves each image's size, user, vulnerabilities, health and shutdown, so a reviewer checks results instead of every line. This page is for developers who own a service's container and tech leads who want the same container rules across a team. Your image is 1.2 GB, CI rebuilds every dependency on each push, the scanner lists 40 CVEs in the base layer, and the container takes 10 seconds to stop because PID 1 ignores `SIGTERM`. An agent can fix all of that in one session. The hard part is knowing the fix is real. ## What a verified container setup gives you - A container rules file the agent reads before it touches a `Dockerfile`, in the format each tool loads. - `scripts/verify-image.sh`: one script that fails on lint errors, an oversized image, a root user, a critical CVE, a missing health status or a slow shutdown. - Three copy-paste prompts: a multi-stage rewrite, a size reduction that names what each cut removes, and health-gated Compose. - A GitHub Actions workflow that scans before it pushes, with least-privilege permissions. - The six ways agent-written container work breaks, and how to recover from each. ## Give the agent your container rules first An agent that has never seen your rules writes the Dockerfile an average tutorial would: `:latest` tags, a root user and no health check. Write the rules once and put them where each tool loads them automatically. ```markdown ## Container rules - Pin base images to an explicit version tag (node:24-alpine, never node:latest). Digests are pinned by Renovate or Dependabot, not by hand. - Multi-stage builds only. Compilers, dev dependencies and caches never reach the final stage. - The final stage runs as a non-root numeric UID and declares a HEALTHCHECK that uses the app's own runtime, not curl. - Copy dependency manifests and install before `COPY . .`, so a source change does not invalidate the dependency layer. - Ship a .dockerignore that excludes .git, node_modules, .env* and test fixtures. - Secrets never go in ENV, ARG or a layer. Use `RUN --mount=type=secret` at build time and runtime secrets from the orchestrator. - Never edit .trivyignore or lower a scanner severity threshold to make a check pass. Report the finding instead. - After any container change, run scripts/verify-image.sh and paste its full output in your summary. ``` **Claude Code** Add the block to `CLAUDE.md` at the repository root. Claude Code loads it at the start of every session, including headless `claude -p` runs. **Codex** Add the block to `AGENTS.md` at the repository root. Codex reads `AGENTS.md` before it does any work. Since Codex 0.150.0, an untrusted project does not supply its project-level `AGENTS.md`, so mark the repository as trusted when Codex asks. **Cursor** Save the block as a project rule (see [project rules in Cursor](/en/cursor-ide/quick-start/project-rules/)) so Agent applies it to every conversation in the repository. Keep the text identical to the other tools' files so that all three agents follow one rule set. The last two rules matter most. The first stops the agent from "fixing" a scan by hiding it. The second makes the agent produce evidence you can read in 30 seconds. ## Prove an image without reading the Dockerfile The verification script is the contract. The agent may change any line of the `Dockerfile`; the change is done only when this script passes. Ask the agent to write it once, then keep it in the repository and run it locally and in CI. ```bash #!/usr/bin/env bash # scripts/verify-image.sh IMAGE [MAX_MB] (runs in your terminal or in CI) set -euo pipefail IMAGE="$1"; MAX_MB="${2:-150}" # SKIP_BUILD=1 checks an image that is already built docker run --rm -i hadolint/hadolint < Dockerfile # 1. Dockerfile lint docker build --check . # 2. BuildKit build checks [ "${SKIP_BUILD:-0}" = 1 ] || docker build -t "$IMAGE" . # 3. build SIZE_MB=$(( $(docker image inspect -f '{{.Size}}' "$IMAGE") / 1000000 )) [ "$SIZE_MB" -le "$MAX_MB" ] || { echo "FAIL size ${SIZE_MB}MB > ${MAX_MB}MB"; exit 1; } USER_ID=$(docker image inspect -f '{{.Config.User}}' "$IMAGE") case "$USER_ID" in ""|root|0|0:*) echo "FAIL image runs as root"; exit 1;; esac docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy \ image --exit-code 1 --severity CRITICAL,HIGH --ignore-unfixed "$IMAGE" # 4. CVE gate CID=$(docker run -d --read-only --tmpfs /tmp --cap-drop ALL \ --security-opt no-new-privileges "$IMAGE") # 5. hardened smoke run trap 'docker rm -f "$CID" >/dev/null 2>&1 || true' EXIT for _ in $(seq 1 30); do STATUS=$(docker inspect -f '{{if .State.Health}}{{.State.Health.Status}}{{else}}none{{end}}' "$CID") [ "$STATUS" = healthy ] && break; sleep 2 done [ "$STATUS" = healthy ] || { docker logs "$CID"; echo "FAIL health: $STATUS"; exit 1; } START=$(date +%s); docker stop -t 10 "$CID" >/dev/null # 6. graceful shutdown [ $(( $(date +%s) - START )) -lt 5 ] || { echo "FAIL slow stop: SIGTERM ignored?"; exit 1; } echo "PASS $IMAGE ${SIZE_MB}MB user=$USER_ID" ``` What each gate proves, so you know what you no longer have to read: | Gate | Goes red when | What you stop checking by hand | | --- | --- | --- | | hadolint and `docker build --check` | Unpinned tags, `apt-get` without cleanup, JSON-form `CMD` mistakes | Dockerfile style | | Size budget | A build toolchain or dev dependency leaked into the final stage | Stage boundaries | | Non-root user | The final stage has no `USER` | Privilege model | | Trivy with `--exit-code 1` | A fixable critical or high CVE in any layer | Base-image hygiene | | Hardened smoke run | The app writes outside `/tmp`, needs a capability or never turns healthy | Runtime assumptions | | Stop time | PID 1 ignores `SIGTERM` and Docker kills it after the timeout | Signal handling | **Who signs off:** the developer who asked for the change reads the script output and the diff of `.dockerignore`, `.trivyignore` and the CI workflow. Those three files change what the gates see, so a human owns them. Put them under a `CODEOWNERS` entry for the platform owner. For the whole pull request, the [evidence bundle](/en/workflows/ship/evidence-bundle/) describes what else the agent attaches. The hardened smoke run needs a working `HEALTHCHECK`. An image without one reports the status `none`, so the loop ends with `FAIL health: none` after printing the container logs. That is intentional: the rules file demands a health check. ## Rewrite a Dockerfile as a multi-stage build The pattern that pays most is a builder stage with the full toolchain and a runtime stage that receives only the build output and production dependencies. The common agent mistake is to copy the builder's `node_modules`, dev dependencies included, into the runtime stage. **Copy-paste prompt: multi-stage rewrite** ```text Rewrite our Dockerfile as a multi-stage build and follow the container rules in the project instructions. Builder stage: node:24-alpine, `npm ci` with all dependencies, then `npm run build`. Runtime stage: node:24-alpine, `npm ci --omit=dev` with a BuildKit cache mount for ~/.npm, copy only dist/ from the builder, run as a non-root numeric UID, use tini as PID 1, and a HEALTHCHECK that runs `node dist/healthcheck.js` against /health. Add or fix .dockerignore. Do not change application code. When you are done, run `scripts/verify-image.sh app:dev 150` and paste the full output. If a gate fails, fix the Dockerfile and rerun; stop after three attempts and tell me which gate still fails and why. ``` A correct result looks like this. Use it to spot-check the agent's output, not to review every line: ```dockerfile # syntax=docker/dockerfile:1 FROM node:24-alpine AS builder WORKDIR /app COPY package.json package-lock.json ./ RUN --mount=type=cache,target=/root/.npm npm ci COPY . . RUN npm run build FROM node:24-alpine AS runtime RUN apk add --no-cache tini WORKDIR /app ENV NODE_ENV=production COPY package.json package-lock.json ./ RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev COPY --from=builder /app/dist ./dist USER 10001 EXPOSE 3000 HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 \ CMD ["node", "dist/healthcheck.js"] ENTRYPOINT ["/sbin/tini", "--"] CMD ["node", "dist/index.js"] ``` How you run the prompt differs by tool, mostly in whether the agent can reach the Docker daemon: **Claude Code** Run it interactively from the repository root and approve the `docker` commands when asked. For an unattended run, allow only the tools the task needs. `claude -p` starts in Manual permission mode (auto mode on third-party providers or with telemetry off, from v2.1.285, where a classifier decides), so add `--permission-mode dontAsk` to refuse anything that would prompt on every provider (file reads in the working directories and read-only Bash commands still run): ```bash claude -p "$(cat prompts/multi-stage.txt)" \ --permission-mode dontAsk \ --allowedTools "Read,Edit,Write,Bash(docker build *),Bash(docker image *),Bash(scripts/verify-image.sh *)" \ --output-format json ``` Docker socket access is root-equivalent on the host: the verification script mounts `/var/run/docker.sock`, so run this only in a disposable VM or CI runner, see [agent sandboxes compared](/en/ecosystem/agent-tools/sandboxes/). With sandboxed Bash turned on, the sandbox can block the Docker socket. If `docker build` fails with a permission error on `/var/run/docker.sock`, run `scripts/verify-image.sh` yourself and paste the output back into the session. **Codex** Run it interactively with `codex`, or unattended with a workspace-write sandbox: ```bash codex exec --sandbox workspace-write "$(cat prompts/multi-stage.txt)" ``` The sandbox can block the Docker socket and the network that `docker build` needs. If the build fails inside Codex, let Codex edit the files, then run `scripts/verify-image.sh` yourself and paste the output back. Do not switch to `danger-full-access` or `--dangerously-bypass-approvals-and-sandbox` outside a disposable, network-restricted VM. **Cursor** Paste the prompt into Agent with the `Dockerfile` and `package.json` in context. Agent runs `docker` commands in the integrated terminal, subject to the terminal approval settings you have chosen. Review the diff view for the `.dockerignore` change, then check that the terminal shows the `PASS` line from the script. ## Shrink an image without breaking it at runtime Once the image builds, make it small. Distroless and `scratch` runtimes remove the shell and package manager, and a static Go binary can run on almost nothing. The risk is an image that is smaller because it lost something the app needs at runtime: CA certificates, time zone data or a C library. Make the agent state the risk of each cut. **Copy-paste prompt: shrink the image and explain every cut** ```text Our image is too large. First run `docker history --no-trunc --format '{{.Size}}\t{{.CreatedBy}}' app:dev` and list the five largest layers with the Dockerfile line that created each one. Then rewrite the Dockerfile to get under 80 MB, ordered by impact. For every cut, state what it removes and the runtime risk (no shell, no CA certificates, no tzdata, no glibc) and how the image still covers it. Do not remove the HEALTHCHECK or the non-root user. Run `scripts/verify-image.sh app:dev 80` and paste the output, with before and after sizes from `docker image ls app`. ``` For a Go service, a correct final stage looks like this. It copies nothing but the binary, because the `distroless/static` image already ships CA certificates and time zone data: ```dockerfile # syntax=docker/dockerfile:1 FROM golang:1.27-alpine AS builder WORKDIR /src COPY go.mod go.sum ./ RUN --mount=type=cache,target=/go/pkg/mod go mod download COPY . . RUN CGO_ENABLED=0 go build -trimpath -ldflags="-s -w" -o /out/server ./cmd/server FROM gcr.io/distroless/static-debian13:nonroot COPY --from=builder /out/server /server EXPOSE 8080 HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \ CMD ["/server", "healthcheck"] ENTRYPOINT ["/server"] ``` A distroless image has no shell, so a `HEALTHCHECK` that calls `curl` or `sh` cannot work. The exec-form check above runs the binary itself, so the binary must implement a `healthcheck` subcommand that calls its own `/health` endpoint and exits `0` or `1`. Without that subcommand, the container never turns healthy and `scripts/verify-image.sh` fails at the health gate, which is the point: the rules file requires a working health check. ## Gate Compose startup on health, not sleep Bare `depends_on` waits only until a dependency's container starts, not until it accepts connections. Agents also still write the obsolete top-level `version:` key, which current Docker Compose ignores with a warning. Ask for both explicitly. **Copy-paste prompt: health-gated Compose** ```text Write compose.yaml for our API with Postgres 17 and Redis 7. Do not add a top-level `version:` key. The api service waits for both with `depends_on: { : { condition: service_healthy } }`. Postgres gets a `pg_isready` healthcheck and Redis a `redis-cli ping` healthcheck, each with interval, timeout, retries and start_period. Named volume for Postgres data. Read the password from `${DB_PASSWORD:?}` so the stack refuses to start without it; no secrets in the file. Put hot-reload bind mounts and debug ports in compose.override.yaml, not in compose.yaml. Then run `docker compose config --quiet` and `docker compose up -d --wait`, and paste the output of `docker compose ps`. ``` ```yaml # compose.yaml services: api: build: . ports: ["8080:8080"] environment: DATABASE_URL: postgresql://app:${DB_PASSWORD:?set DB_PASSWORD}@postgres:5432/app REDIS_URL: redis://redis:6379 depends_on: postgres: { condition: service_healthy } redis: { condition: service_healthy } read_only: true tmpfs: [/tmp] cap_drop: [ALL] security_opt: ["no-new-privileges:true"] postgres: image: postgres:17-alpine environment: POSTGRES_USER: app POSTGRES_PASSWORD: ${DB_PASSWORD:?set DB_PASSWORD} volumes: [pgdata:/var/lib/postgresql/data] healthcheck: test: ["CMD-SHELL", "pg_isready -U app"] interval: 5s timeout: 3s retries: 10 start_period: 10s redis: image: redis:7-alpine healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 5s timeout: 3s retries: 10 start_period: 5s volumes: pgdata: ``` `docker compose up -d --wait` is the verification: it returns non-zero if any service with a health check does not become healthy. The `read_only`, `tmpfs`, `cap_drop` and `security_opt` keys on `api` are the Compose equivalent of the hardened smoke run in the script. They live in the runtime configuration, not in the image, so an agent that only edits the `Dockerfile` never adds them. ## Build, scan and push images in CI The first job, `image`, builds the image once, scans it with a SARIF report, then runs the local script against that same image with `SKIP_BUILD=1`. A second job, `push`, depends on it and runs only for pushes to `main`: it is the only job that holds `packages: write`, so a pull request never gets a token that can write to the registry. Every gate must pass before anything is pushed. ```yaml # .github/workflows/image.yml name: image on: pull_request: push: branches: [main] permissions: {} jobs: image: runs-on: ubuntu-latest permissions: contents: read security-events: write # upload the SARIF report env: IMAGE: ghcr.io/${{ github.repository }} steps: - uses: actions/checkout@v7 with: persist-credentials: false - uses: docker/setup-qemu-action@v4 - uses: docker/setup-buildx-action@v4 - name: Build for scanning (amd64, not pushed) uses: docker/build-push-action@v7 with: context: . load: true tags: ${{ env.IMAGE }}:scan cache-from: type=gha cache-to: type=gha,mode=max - name: Scan and fail on fixable critical or high CVEs uses: aquasecurity/trivy-action@v0.36.0 with: image-ref: ${{ env.IMAGE }}:scan severity: CRITICAL,HIGH ignore-unfixed: true exit-code: "1" format: sarif output: trivy.sarif - name: Upload scan results if: always() continue-on-error: true # fork PRs get a read-only token uses: github/codeql-action/upload-sarif@v4 with: sarif_file: trivy.sarif - name: Run every local gate against the scanned image run: SKIP_BUILD=1 scripts/verify-image.sh "${{ env.IMAGE }}:scan" 150 push: needs: image # runs only if every gate in the image job passed if: github.event_name == 'push' runs-on: ubuntu-latest permissions: contents: read packages: write # push to GHCR; never granted on pull requests env: IMAGE: ghcr.io/${{ github.repository }} steps: - uses: actions/checkout@v7 with: persist-credentials: false - uses: docker/setup-qemu-action@v4 - uses: docker/setup-buildx-action@v4 - name: Log in to GHCR uses: docker/login-action@v4 with: registry: ghcr.io username: ${{ github.actor }} password: ${{ secrets.GITHUB_TOKEN }} - name: Push multi-arch image with SBOM and provenance uses: docker/build-push-action@v7 with: context: . platforms: linux/amd64,linux/arm64 push: true sbom: true provenance: mode=max tags: ${{ env.IMAGE }}:sha-${{ github.sha }} cache-from: type=gha ``` Three choices in this workflow are deliberate: - **Scan before push.** A scan after push leaves a vulnerable image in the registry that anything can pull. Here the `push` job never starts if Trivy or the script fails. The scan covers the amd64 build only; the `push` job rebuilds both architectures from the same cache, so the pushed image is not byte-identical to the scanned one. If you need that proof, also scan the pushed digest, or scan each architecture in a matrix job. - **Pin actions to a full commit SHA before you adopt the workflow.** The tags above were the latest major versions on 2026-09-26. Tags can be moved; a SHA cannot. Let Dependabot or Renovate update the SHAs. - **Deployment is a separate job.** Rollout, probes and rollback belong to the orchestrator. See [Kubernetes patterns](/en/cookbook/devops-recipes/kubernetes-patterns/) and [CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/). When the scan fails, an agent can triage and fix it without registry credentials. Give it the report, not the repository's secrets: **Copy-paste prompt: triage a failed image scan** ```text Run `docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy image --format json --severity CRITICAL,HIGH --ignore-unfixed app:dev` and read the JSON it prints. If a trivy.json file is attached instead, read that. For each finding, give: package, installed and fixed version, and whether it comes from the base image or from our dependencies. Map each one to the Dockerfile line or lockfile entry that brings it in. Propose the smallest change that clears it (base-image tag bump, package upgrade or a slimmer runtime stage) and apply it. Do not touch .trivyignore. Rerun scripts/verify-image.sh and paste the output. ``` **Claude Code** ```bash claude -p "$(cat prompts/triage-scan.txt)" \ --allowedTools "Read,Edit,Bash(docker run --rm -v /var/run/docker.sock:/var/run/docker.sock aquasec/trivy *),Bash(scripts/verify-image.sh *)" \ --output-format json > triage.json ``` The Trivy command mounts the Docker socket, which is root-equivalent on the host, so run this only in a disposable VM or CI runner. The prompt reads Trivy's report from standard output rather than a shell redirect, so the one `Bash` rule covers the scan and the run needs no `Write` permission for it. To run the same triage inside GitHub Actions, see [headless agents in CI](/en/ecosystem/agent-tools/headless-agents-ci/). Run it only on trusted refs, never on a `pull_request_target` checkout of a contributor's branch. **Codex** ```bash codex exec --sandbox workspace-write -o triage.md "$(cat prompts/triage-scan.txt)" ``` `-o` writes the agent's final message to a file you can attach to the pull request. If the sandbox blocks Docker, run the Trivy command yourself, save its output as `trivy.json` and pass that file to Codex. **Cursor** Paste the prompt into Agent. If the scan already ran in CI, download the SARIF artifact, add it to the chat instead of the first line of the prompt, and let Agent map findings to lines. **Docker's MCP server.** Docker's official route for agents is the Docker MCP Toolkit and MCP Gateway (`docker mcp gateway run`), which runs catalog MCP servers in isolated containers. You do not need it for the recipes on this page: the agent's shell already runs `docker`. For setup in all three tools and the security trade-offs, see [Docker and Kubernetes containerization](/en/workflows/ship/containerization/). ## What breaks when an agent writes your container setup? **The agent makes the scan pass by hiding findings** **Symptom:** the scan goes green, but the diff adds lines to `.trivyignore`, removes `HIGH` from the severity list or deletes `exit-code`. **Recovery:** revert those lines, keep the rule "never edit `.trivyignore`" in the rules file, and make the platform owner a required reviewer for `.trivyignore` and `.github/workflows/` in `CODEOWNERS`. An accepted risk is a human decision with an expiry date, not an agent edit. **Every source change reinstalls all dependencies** **Symptom:** CI build time does not drop after the rewrite. **Cause:** `COPY . .` runs before the install step, so any file change invalidates the dependency layer. **Recovery:** copy only the lockfile and manifest, install, and then copy the source. Prove it: build twice with one source file touched in between; the second build must show `CACHED` on the install step. **The health check marks a healthy container unhealthy** **Causes:** `start_period` shorter than the app's boot time, a check that calls `curl` or `wget` in an image that has neither, or the wrong port. **Recovery:** raise `start_period`, check with the app's own runtime (`node dist/healthcheck.js`, a Go `healthcheck` subcommand), and read the probe's output with `docker inspect -f '{{json .State.Health}}' CONTAINER`, where `CONTAINER` is the container name or ID. **You cannot open a shell in the distroless container** **Symptom:** `docker exec -it CONTAINER sh` fails because the image has no shell. **Recovery:** do not add a shell back to the production stage. Build a separate `debug` target that adds busybox and is never pushed, or use `kubectl debug` to attach an ephemeral debug container to a running pod. On Docker Desktop, `docker debug` can attach a temporary toolbox; check that your plan includes it. **The arm64 build fails or takes an hour** **Causes:** no QEMU on an amd64 runner, a dependency compiled from source under emulation, or a base image without an arm64 variant. **Recovery:** keep `docker/setup-qemu-action` before Buildx, prefer base images that publish both architectures, and reproduce locally with `docker buildx build --platform linux/arm64 .`. If emulation is too slow, build each architecture on a native runner and merge the manifests. **The agent cannot reach the Docker daemon** **Symptom:** `permission denied` on `/var/run/docker.sock`, or network errors during `docker build`, inside the agent session. **Cause:** the agent's sandbox is doing its job. **Recovery:** let the agent edit files, run `scripts/verify-image.sh` yourself and paste the output back. Do not widen the sandbox to full access on your workstation. If you need the agent to drive Docker end to end, give it a disposable environment; see [agent sandboxes compared](/en/ecosystem/agent-tools/sandboxes/). ## Where to go next with container work This page is one recipe in [DevOps and infrastructure recipes](/en/cookbook/devops-recipes/), which collects the related Kubernetes, CI/CD and infrastructure-as-code recipes. - [Kubernetes patterns](/en/cookbook/devops-recipes/kubernetes-patterns/) — Deploy the verified image with probes, resource limits and disruption budgets. - [CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/) — Extend the image workflow into test, deploy and rollback stages. - [Docker and Kubernetes containerization](/en/workflows/ship/containerization/) — Connect the Docker MCP Gateway and debug OOMKilled pods with an agent. - [The evidence bundle](/en/workflows/ship/evidence-bundle/) — What an agent's pull request must prove before a human approves it. --- # Infrastructure as Code Patterns URL: https://developertoolkit.ai/en/cookbook/devops-recipes/infrastructure-as-code/ Description: Recipes for agent-written Terraform, CloudFormation and Pulumi, with plan-only credentials, a machine-checked plan gate and a human sign-off on destroys. Infrastructure as code patterns for AI agents are four recipes (split a Terraform monolith, gate the plan, adopt drift, harden CloudFormation or Pulumi) run by Claude Code, Codex or Cursor under plan-only cloud credentials. A machine-checked plan gate, not a human reading HCL, blocks every delete or replace until a named owner approves it. This page is for developers who own a service's infrastructure and tech leads who decide what an agent may touch in a cloud account. You inherit a Terraform repository with one 900-line `main.tf`, hardcoded CIDR blocks, a provider pinned two majors back, and a `terraform plan` that wants to replace the production RDS instance. The agent can split that file in minutes. The question is how you know the split destroys nothing, when the plan is 400 lines long and nobody wants to read it. ## What you'll walk away with from these infrastructure recipes - A permission setup in which the agent can run `terraform plan` but has no credentials that could apply - A short `plan-gate.sh` that fails on any delete or replace, so review starts from a short list instead of the whole plan - Copy-paste prompts for a module split with `moved` blocks, a plan review, drift adoption with `import` blocks, and a CloudFormation hardening pass - A table of gates (format, lint, policy, test, plan) that proves the change without reading every line - Recovery steps for stuck locks, drift, accidental replacements, provider major upgrades and a stuck CloudFormation rollback ## Fence the agent before the first prompt The control that holds is the credential, not the prompt. An agent that has only a plan role cannot apply, whatever it decides to run. Set this up once per repository, in this order. 1. **Create a plan-only identity.** On AWS, attach `ReadOnlyAccess` plus access to the state bucket: read on this stack's state key, and `s3:PutObject` / `s3:DeleteObject` on the `*.tflock` key only. That is enough for `terraform plan` with S3 native locking. `ReadOnlyAccess` also grants `s3:GetObject` on every bucket in the account, including other stacks' state files, so add an explicit `Deny` on `s3:GetObject` for any state key that is not this stack's. Apply runs in CI under a different role that the agent never sees. The same split works on Azure (Reader plus the state storage account) and Google Cloud (Viewer plus the state bucket). [Cloud MCP servers](/en/ecosystem/mcp/cloud-platform-mcp/) covers read-only identities per cloud. 2. **Deny the destructive commands in the tool.** This is a typo-catcher on top of the credential, not a replacement for it. **Claude Code** In `.claude/settings.json` (committed, so the whole team gets it): ```json { "permissions": { "allow": ["Bash(terraform fmt *)", "Bash(terraform validate *)", "Bash(terraform plan *)", "Bash(terraform show *)", "Bash(tflint *)"], "ask": ["Bash(terraform state *)", "Bash(terraform import *)"], "deny": ["Bash(terraform apply *)", "Bash(terraform destroy *)", "Bash(terraform force-unlock *)", "Bash(terraform state rm *)"] } } ``` Deny rules are evaluated before ask and allow. They match the command string, so `sh -c 'terraform apply'` is a different spelling: see [permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/) for why the sandbox and the credential are the real boundary. **Codex** ```bash # Terminal, repo root: approvals on request, writes limited to the workspace codex -a on-request -c default_permissions=":workspace" ``` Permission profiles are beta in Codex 0.157.1 and are what OpenAI now prefers over `--sandbox`; do not combine the two. Codex passes environment variables whose names contain `KEY`, `SECRET` or `TOKEN` to commands unless `shell_environment_policy` says otherwise, so start Codex from a shell that holds only the plan role. **Cursor** Keep Cursor's agent on a run mode that asks before terminal commands (see Cursor's **Run modes** page under Agent security), and start Cursor from a shell or profile that holds only the plan role. Whichever mode you pick, the plan-only credential is the boundary; the run mode only catches typos. 3. **Write the conventions down once.** Put them in `AGENTS.md` (Codex reads it; Claude Code reads it when the repository has no `CLAUDE.md`, from v2.1.277) or `CLAUDE.md`, and in a Cursor project rule: ```markdown ## Infrastructure rules - Terraform >= 1.11. S3 backend with `use_lockfile = true`. No new DynamoDB lock tables. - Pin providers to the current major (`~> 6.0` for hashicorp/aws) and commit .terraform.lock.hcl. - Renames and module moves use `moved` blocks. Never `terraform state mv` in a PR. - Adopt existing resources with `import` blocks, not `terraform import`. - No hardcoded CIDRs, regions, account IDs or secrets: variables and a secrets manager. - You may run fmt, validate, tflint, plan and show. You never run apply or destroy. ``` ## Recipe 1: split a Terraform monolith without destroying anything A module split changes every resource address. Without `moved` blocks, Terraform reads that as "destroy the old address, create the new one", which on a database means data loss. With them, the correct plan for a pure refactor is **zero changes**: that single number is your acceptance criterion. **Claude Code** ```bash # Terminal, repo root. Manual mode so every edit is shown before it lands claude --permission-mode manual ``` Paste the prompt below. Claude Code edits the files, runs `terraform plan` and reads its output in the same session, so the "zero changes" loop closes without you copying anything. **Codex** Save the prompt below as `prompts/split-monolith.txt`, then run: ```bash codex -a on-request -c default_permissions=":workspace" "$(cat prompts/split-monolith.txt)" ``` Keep the prompt in the repository so the next split uses the same wording. If the sandbox blocks network access, Codex asks before it runs `terraform plan` outside it; approve `plan`, never `apply`. **Cursor** Open Agent in Plan Mode, paste the prompt, and approve the module boundaries before it writes files. Switch to Agent to execute, and run `terraform plan` in the integrated terminal when it asks. **Copy-paste prompt: split main.tf into modules with zero plan changes** ```text Refactor main.tf into three local modules: modules/network (VPC, subnets, NAT, route tables), modules/data (RDS, ElastiCache) and modules/compute (ASG, ALB, launch template). Rules: 1. Before writing files, list every resource with its current address and its new address, and the variables each module needs. Wait for my OK. 2. For every address change, add a `moved` block in moved.tf. Do not use terraform state mv. 3. Move hardcoded CIDRs and the region into variables.tf with the current values as defaults, so the plan does not change. 4. Run terraform fmt -recursive, terraform validate, then terraform plan -out=tfplan -input=false. 5. Done means the plan reports "No changes". If it does not, show me each resource the plan would change and why, fix it, and plan again. Never run terraform apply. ``` If the plan still shows changes, the cause is almost always one of three things: a missing `moved` block, a default that differs from the old literal, or `count` turned into `for_each` (which changes the index from `[0]` to `["name"]` and also needs a `moved` block). Ask the agent to name which one for each resource. ## Recipe 2: turn the plan into a gate you don't read line by line A 400-line plan is where review fails, because the one `-/+` on a database hides among 60 tag updates. Reverse the order: a script extracts the destructive actions from the machine-readable plan, and a human reviews only that list. ```bash #!/usr/bin/env bash # scripts/plan-gate.sh: exit 2 when the plan deletes or replaces anything set -euo pipefail terraform plan -out=tfplan -input=false -lock-timeout=60s terraform show -json tfplan > plan.json jq -r '.resource_changes[]? | select(.change.actions | index("delete")) | "\(.change.actions | join("/"))\t\(.address)"' plan.json > destructive.txt jq '[.resource_changes[]? | {address, actions: .change.actions, replace_paths: .change.replace_paths}]' plan.json > plan-summary.json jq -r '[.resource_changes[]?.change.actions | join("/")] | group_by(.) | map("\(.[0]): \(length)") | .[]' plan.json if [ -s destructive.txt ]; then echo "Delete or replace needs a named approver:"; cat destructive.txt; exit 2 fi ``` In `terraform show -json`, a replacement appears as `["delete","create"]` or `["create","delete"]`, so matching on `delete` catches both. Run the script in the agent session and again in CI. In CI, write `destructive.txt` as a job output; when it is non-empty, the apply job targets a protected environment whose required reviewer is the service owner, and apply runs only from the saved `tfplan` that was reviewed. **The plan and the state hold secrets in plaintext** `tfplan`, `plan.json` and the state file contain sensitive values (database passwords, generated keys) unredacted; the `sensitive` flag only hides them in the CLI output. Add `tfplan`, `plan.json` and `plan-summary.json` to `.gitignore`, never upload `plan.json` or `tfplan` as a public CI artifact, and scope the plan role's `s3:GetObject` to this stack's state key. That is why the gate writes `plan-summary.json` (addresses, actions and the attribute paths that force a replacement, no values): the agent reads that file and `destructive.txt`, not `plan.json`. **Copy-paste prompt: review a plan before anyone approves it** ```text Run scripts/plan-gate.sh, then read destructive.txt and plan-summary.json. Do not open plan.json, tfplan or the state: they hold secrets. Produce: 1. The action summary the script printed. 2. For every line in destructive.txt: the attribute that forces it (from replace_paths and the provider docs), whether it loses data or causes downtime, and a way to avoid it (moved block, lifecycle { prevent_destroy = true }, create_before_destroy, or an attribute that can change in place). 3. Any update to a security group, IAM policy or KMS key, listed separately. End with GO or NO-GO and one sentence of reason. Do not run apply and do not edit any .tf file in this step. ``` Add `lifecycle { prevent_destroy = true }` to stateful resources (databases, buckets holding data, KMS keys) as part of Recipe 1. Terraform then refuses any plan that destroys them, which turns the most expensive mistake into a plan error. ## Recipe 3: adopt console drift with import blocks Someone added a security group rule in the console during an incident, and now every plan wants to remove it. Do not let the agent overwrite the drift with an apply: the rule may be what is holding the incident back. Run `terraform plan -refresh-only` to see exactly what changed outside Terraform. Then decide per resource: adopt it, revert it in the console, or change the configuration to match. For adoption, Terraform 1.5 and later write the import as code, so it is reviewed like any other change. **Copy-paste prompt: reconcile drift after an incident** ```text Run terraform plan -refresh-only -input=false and list every drifted attribute. For each resource the console created that is not in state, write an `import` block in imports.tf and run terraform plan -generate-config-out=generated.tf to draft its config. Then move each generated resource into the right module, remove computed and default-valued arguments, and re-run plan until the only actions are imports. Put each drifted item in one of three buckets (adopt, revert in the console, change config to match) with a one-line reason. Do not run terraform import, terraform state commands or apply. ``` A cloud MCP server makes this faster: with read access, the agent lists the real resources itself instead of asking you to paste console output. Connect it read-only, as [cloud MCP servers](/en/ecosystem/mcp/cloud-platform-mcp/) shows. ## Recipe 4: harden a CloudFormation template or Pulumi stack The same discipline applies with a different preview command. For CloudFormation, `aws cloudformation deploy --no-execute-changeset` creates a change set the agent can read without executing it. For Pulumi, `pulumi preview --diff` is the plan for a human, and `pulumi preview --json` is the one for the gate: filter the steps whose `op` is `delete`, `replace`, `create-replacement` or `delete-replaced` into `destructive.txt`, the same way `plan-gate.sh` does. The gate is the same: list replacements, block until an owner approves. **Copy-paste prompt: production-readiness review of a CloudFormation template** ```text Review infrastructure.yaml for production. Check that every RDS instance and EBS volume has DeletionPolicy: Snapshot and UpdateReplacePolicy: Snapshot, storage encryption and Multi-AZ; that security groups reference each other instead of 0.0.0.0/0 on internal ports; and that no secret is a plaintext parameter (move DatabasePassword to Secrets Manager with a dynamic reference). Output the fixes highest risk first, each with the exact YAML change. Then create a change set with aws cloudformation deploy --no-execute-changeset and list every resource whose Replacement is True or Conditional. Do not execute the change set. ``` ## How do you verify agent-written infrastructure without reading every line? Stack the checks so each one catches a class of error mechanically, and a human looks only at what survives. Run them in this order, cheapest first, in the agent session and again in CI. | Gate | Command | Catches | Fails the build when | | --- | --- | --- | --- | | Format and syntax | `terraform fmt -check -recursive` and `terraform validate` | Invented arguments, type errors, bad references | any error | | Lint | `tflint --recursive` | Invalid instance types, deprecated syntax, unused declarations | any error | | Static policy | `checkov -d .` | Public buckets, unencrypted storage, open security groups | a failed check not on the reviewed skip list | | Behaviour | `terraform test` | A module that no longer does what its contract says | any failed run | | Plan policy | `conftest test plan.json` | Your own rules applied to the actual planned values | any `deny` | | Destruction | `scripts/plan-gate.sh` | Deletes and replacements | any line in `destructive.txt` | Versions checked on 2026-09-26: Terraform 1.16.4, hashicorp/aws provider 6.66.0, tflint 0.64.0, checkov 3.3.19, conftest 0.70.1. A plan policy for conftest is a few lines of Rego over `plan.json`: ```rego # policy/no_public_ssh.rego package main import rego.v1 deny contains msg if { some rc in input.resource_changes rc.type == "aws_security_group_rule" rc.change.after.type == "ingress" "0.0.0.0/0" in rc.change.after.cidr_blocks rc.change.after.from_port <= 22 rc.change.after.to_port >= 22 msg := sprintf("%s opens SSH to the internet", [rc.address]) } ``` **Who signs off.** The agent may declare the checks green. It may not approve. A pull request that passes every gate and shows zero lines in `destructive.txt` needs one reviewer on the diff. A pull request with any destructive line needs the service owner to approve that list by name, and apply runs from the reviewed `tfplan` in CI. Attach the gate output to the pull request as its [evidence bundle](/en/workflows/ship/evidence-bundle/), so the reviewer reads six results and a short list instead of the HCL. ## Ground the agent in the registry, not its memory A common source of broken HCL is provider arguments the agent remembers from an older major version. Two additions fix that, and the full setup lives on [infrastructure MCP servers](/en/ecosystem/mcp/infrastructure-mcp/). **HashiCorp's Terraform MCP server** with no token registers only its registry tools, which look up current provider and module documentation. That is read-only by construction: **Claude Code** ```bash claude mcp add terraform -s project -- docker run -i --rm hashicorp/terraform-mcp-server:1.3.0 ``` **Codex** ```bash codex mcp add terraform -- docker run -i --rm hashicorp/terraform-mcp-server:1.3.0 ``` **Cursor** In `.cursor/mcp.json`: ```json { "mcpServers": { "terraform": { "command": "docker", "args": ["run", "-i", "--rm", "hashicorp/terraform-mcp-server:1.3.0"] } } } ``` **HashiCorp's agent skills** (`hashicorp/agent-skills`, MPL-2.0) carry the conventions: `refactor-module` for Recipe 1, `terraform-search-import` for Recipe 3, `terraform-test` and `terraform-style-guide` for the gates. Install the plugin in Claude Code, or individual skills with the `skills` CLI (1.7.0) for Codex and Cursor: ```bash # Claude Code claude plugin marketplace add hashicorp/agent-skills claude plugin install terraform@hashicorp # Codex, Cursor and other agents: pick skills one at a time npx skills add hashicorp/agent-skills/plugins/terraform/skills/refactor-module ``` The whole plugin loads 16 skills and costs about 2,150 always-on tokens in every session (`claude plugin details terraform@hashicorp`, 2026-09-26); each skill adds 0.5k–7k more when it fires. For the wider field, see [infrastructure MCP servers](/en/ecosystem/mcp/infrastructure-mcp/). Do not also install `terraform@claude-plugins-official`: it registers a second `terraform` MCP server pinned to the older 0.4.0 image. Use a skill when you want conventions, and the MCP server when the agent needs live registry data. ## When agent-driven Terraform breaks **The state lock will not release** A killed CI job or an interrupted plan leaves a lock, and every run fails with `Error acquiring the state lock`. Confirm in CI that no apply is running. Then a human with the apply role runs `terraform force-unlock LOCK_ID`, with the ID from the error. With `use_lockfile = true`, the lock is an S3 object next to the state named `.tflock`; with the deprecated `dynamodb_table` setting it is a DynamoDB item. The agent's deny list blocks `force-unlock` on purpose: unlocking during a real apply corrupts state. **A one-line change wants to replace half the VPC** A renamed resource, a `count` to `for_each` switch, or a changed name tag on a launch template can cascade into replacements. `plan-gate.sh` shows the list. Recover by adding `moved` blocks for renames, reverting the attribute that forces replacement, or splitting the change. Use `-target` only to diagnose, never as the way the change ships: Terraform itself warns it is for exceptional cases. **The agent upgrades a provider major version with the refactor** Moving hashicorp/aws from `~> 5.0` to `~> 6.0` changes arguments and defaults. Mixed into a refactor, it makes the "zero changes" check meaningless. Ship the upgrade as its own pull request: `terraform init -upgrade`, commit `.terraform.lock.hcl`, run the gates, and have the agent explain each changed resource against the provider's upgrade guide, fetched through the Terraform MCP server. **The plan fights reality after an incident** The plan wants to delete a rule nobody wrote in code. Stop, and run Recipe 3. Never tell the agent to "make the plan clean" without the refresh-only view first: it will remove the console change, which can reopen the incident. **CloudFormation is stuck in UPDATE_ROLLBACK_FAILED** Ask the agent to read `aws cloudformation describe-stack-events` and name the resource that blocked the rollback, and why. Fix the cause outside the stack if you can. Otherwise a human runs `aws cloudformation continue-update-rollback` with that resource in `--resources-to-skip`, and then brings the resource back in line with the template. ## Where to go next with infrastructure as code The prerequisite for these recipes is a harness that holds: [permissions and sandboxing](/en/workflows/harness/permissions-and-sandboxing/). The next step is putting the gates and the apply step in a pipeline. - [CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/) — Run plan-gate.sh on every pull request and apply only from the reviewed plan. - [Infrastructure as code with AI assistants](/en/workflows/ship/infrastructure-code/) — The full workflow: framing constraints, generation, security review and cost policy. - [Infrastructure MCP servers](/en/ecosystem/mcp/infrastructure-mcp/) — Terraform and Kubernetes MCP servers, read-only, with their context cost. - [Kubernetes orchestration patterns](/en/cookbook/devops-recipes/kubernetes-patterns/) — Drive workloads on the cluster you just provisioned with the same review discipline. --- # Kubernetes Orchestration Patterns URL: https://developertoolkit.ai/en/cookbook/devops-recipes/kubernetes-patterns/ Description: Have Claude Code, Codex, or Cursor write Kubernetes manifests and Helm charts, then prove them with kubeconform, server dry-run, and diff gates. Kubernetes orchestration patterns for AI agents are prompts and gates that make Claude Code, Codex, or Cursor write Deployments and Helm charts that encode real operational limits: probe timing, memory headroom, disruption budgets, and DNS egress. But a manifest that applies cleanly can still cause an outage, so every change passes schema, server dry-run, and diff checks before merge. Your rollout just took the API down. The readiness probe went green before the Postgres pool finished warming, so traffic moved onto pods that returned 500s, and the manifest came from an agent that never knew the pool needs eight seconds. This page is for the developer or tech lead who owns that manifest and wants the next one proven by a script, not by a person reading 400 lines of YAML. ## What you'll walk away with from these Kubernetes patterns - A cluster rules block for `CLAUDE.md`, `AGENTS.md`, or a Cursor rule, so the agent starts from your constraints instead of its defaults. - `scripts/verify-k8s.sh`, a gate that renders the chart and checks schema, invariants, server-side admission, and the live diff. - Copy-paste prompts for a probe-safe Deployment, a Helm chart without Bitnami dependencies, a `CrashLoopBackOff` diagnosis, and a resource-limit tune from real usage. - A read-only Kubernetes MCP setup for all three tools, so diagnosis runs against live cluster state. - Recovery steps for six failures agent-written manifests commonly cause. ## Give the agent your cluster rules first Agents fill every gap in a prompt with a training-data default: `initialDelaySeconds` instead of a `startupProbe`, a `latest` image tag, a default-deny NetworkPolicy with no DNS rule. Write the rules down once, in the file each tool reads on every session: `CLAUDE.md` for Claude Code, `AGENTS.md` for Codex, and a rule under `.cursor/rules/` for Cursor. ```markdown ## Kubernetes rules (k8s/ and charts/) - Every container: requests and limits for CPU and memory; memory limit >= 1.25x observed P99. - Slow-starting apps get a startupProbe; never gate readiness with initialDelaySeconds. - Probes use named ports. Liveness never checks downstream dependencies. - Pods run as non-root, readOnlyRootFilesystem: true, drop ALL capabilities, seccomp RuntimeDefault. - Images are pinned by version tag or digest. Never `latest`. - A PodDisruptionBudget sets exactly one of minAvailable / maxUnavailable. - A default-deny NetworkPolicy always allows egress to kube-dns on UDP and TCP 53. - No Bitnami dependencies (charts.bitnami.com or oci://registry-1.docker.io/bitnamicharts). Postgres comes from the CloudNativePG operator. - If an HPA manages a Deployment, do not set spec.replicas in the Deployment. - Done means: scripts/verify-k8s.sh exits 0. Paste its summary into the PR. ``` The last rule is the one that changes the review. It turns "looks fine to me" into an exit code the agent must produce before it hands the work back. ## Prove a manifest without reading every line Reading generated YAML line by line does not scale, and it misses the failures that matter, because a missing DNS rule looks like nothing at all. Instead, render what will actually reach the cluster and let four layers check it. Run the script in your terminal and in CI. ```bash #!/usr/bin/env bash # scripts/verify-k8s.sh (terminal or CI; needs helm, kubeconform, kubectl) set -euo pipefail CHART=charts/orders-api VALUES=$CHART/values-production.yaml OUT=.rendered; rm -rf "$OUT"; mkdir -p "$OUT" # 1. Render exactly what will be applied helm lint "$CHART" -f "$VALUES" helm template orders-api "$CHART" -n production -f "$VALUES" > "$OUT/all.yaml" # 2. Schema: built-in kinds plus CRDs (such as the CNPG Cluster) kubeconform -strict -summary \ -schema-location default \ -schema-location 'https://raw.githubusercontent.com/datreeio/CRDs-catalog/main/{{.Group}}/{{.ResourceKind}}_{{.ResourceAPIVersion}}.json' \ "$OUT/all.yaml" # 3. Invariants a schema cannot express fail() { echo "FAIL: $1"; exit 1; } grep -Eq 'image: .*:latest' "$OUT/all.yaml" && fail "image pinned to latest" # Assumes no registry port: registry.internal:5000/orders-api (no tag) passes. grep -Eq '^\s*image: "?[^:@"]+"?\s*$' "$OUT/all.yaml" && fail "image with no tag or digest" # orders-api warms a Postgres pool, so its Deployment must have a startupProbe. # Drop this check for charts whose apps start fast. if grep -q 'kind: Deployment' "$OUT/all.yaml"; then grep -q 'startupProbe:' "$OUT/all.yaml" || fail "Deployment without startupProbe" fi if grep -q 'kind: NetworkPolicy' "$OUT/all.yaml"; then grep -q 'k8s-app: kube-dns' "$OUT/all.yaml" || fail "NetworkPolicy without DNS egress" fi grep -Eq 'charts\.bitnami\.com|bitnamicharts' "$CHART/Chart.yaml" && fail "Bitnami dependency" grep -Eq 'image: .*bitnami' "$OUT/all.yaml" && fail "Bitnami image" # 4. Admission and drift against a real API server (staging or kind) kubectl apply --dry-run=server -f "$OUT/all.yaml" set +e; kubectl diff -f "$OUT/all.yaml" > "$OUT/cluster.diff"; rc=$?; set -e [ "$rc" -le 1 ] || fail "kubectl diff errored (rc=$rc)" echo "OK: $(grep -c '^kind:' "$OUT/all.yaml") objects; diff in $OUT/cluster.diff" ``` Each layer catches a different class of defect: | Layer | Catches | Misses | | --- | --- | --- | | `helm lint` and `helm template` | Template errors, the chart's own `fail` checks | Anything valid but wrong | | `kubeconform -strict` | Wrong `apiVersion`, unknown or misspelled fields | Behaviour: probe timing, DNS | | Invariant `grep` lines | Your team's rules, such as a pinned image tag and DNS egress present | Rules you have not written down | | `kubectl apply --dry-run=server` | Admission: Pod Security Standards, policy webhooks, PDB validation, missing CRDs | Runtime behaviour | | `kubectl diff` | What actually changes in the cluster | Nothing; a person reads this one | `kubectl diff` exits 1 when differences exist and above 1 on error, which is why the script tolerates exactly 1. `cluster.diff` is the one artifact a person reads: it is short, and it shows the change in cluster state rather than the template that produced it. Attach it to the PR with the script's summary line, as the [evidence bundle](/en/workflows/ship/evidence-bundle/) describes. The owner of the service signs off on the diff, not on the YAML. Server-side dry-run needs the same RBAC as a real apply, so it needs credentials that can write. Point it at a staging cluster or a local `kind` cluster that has the same CRDs and the same Pod Security labels as production. Never give an agent session production write credentials for this step. After the merge, the gate moves to the rollout. `kubectl rollout status deployment/orders-api -n production --timeout=5m` fails the pipeline if new pods never become Ready. For canary analysis and automated rollback, use [progressive delivery](/en/workflows/ship/progressive-delivery/). ## Run the agent on a manifest directory The prompts below work in all three tools. The difference is how you run them against a directory of manifests, and how you keep the agent away from the cluster while it writes. **Claude Code** Start `claude` in the repository root and paste a prompt. Claude Code reads `CLAUDE.md` and your existing `kustomization.yaml` or chart, so new objects follow the same labels and overlays. For a read-only audit in CI or a script, use print mode with plan permissions, so the agent can read files but not edit them: ```bash claude -p --permission-mode plan --output-format json \ "Audit charts/orders-api against the Kubernetes rules in CLAUDE.md. List violations by severity with file and line." ``` The bare `claude "query"` form opens an interactive session seeded with the prompt. It is not a batch command. From v2.1.283 (both release channels on 2026-10-12), interactive sessions start in auto mode, where a classifier approves most actions. To keep the agent from changing a live cluster, add deny rules to `.claude/settings.json`, such as `"deny": ["Bash(kubectl apply *)", "Bash(kubectl delete *)"]`, and start the session with a kubeconfig context bound to a read-only RBAC role. A prefix rule catches only the plain spelling of a command, so the RBAC role is the control that holds. **Codex** Run Codex with the `:workspace` permission profile and on-request approvals, so it writes only to the workspace and asks before anything wider, such as a `kubectl` call: ```bash codex -c default_permissions=":workspace" -a on-request \ "Generate a probe-safe Deployment for orders-api under k8s/base following AGENTS.md" ``` For an unattended audit, `codex exec` with the `:read-only` profile writes its final answer to a file: ```bash codex exec -c default_permissions=":read-only" -o k8s-audit.md \ "Audit charts/orders-api against the Kubernetes rules in AGENTS.md. List violations by severity." ``` Permission profiles are beta (Codex CLI 0.138.0 or later) and have no dedicated flag, so you select them with `-c default_permissions=…` or in `config.toml`. The legacy alternative is `--sandbox workspace-write` or `--sandbox read-only`; OpenAI says the two systems do not compose, so use one or the other, never both. In Codex CLI 0.157.1, `-a` accepts only `on-request` and `never`, and `codex exec` has no `-a` flag; there is no `--full-auto` flag. **Cursor** Put the rules in a project rule under `.cursor/rules/` so the agent loads them for `k8s/` and `charts/`. Start in Plan Mode for a multi-file change, such as manifests to chart, review the plan, then let the agent write. Review each manifest in the diff view before you accept it; a PodDisruptionBudget with `minAvailable: 1` on a single-replica Deployment is visible there before it blocks every node drain. For scripted audits, Cursor's CLI has a print mode (`-p, --print`) that runs headless in CI. ## Generate a Deployment that does not race its own probes A frequent defect in an agent-written Deployment is a readiness probe that passes before the app is ready. Put the warm-up window into the prompt, and the `startupProbe` gates the other probes correctly. **Copy-paste prompt: probe-safe Deployment** ```text Generate k8s/base/deployment.yaml for a Node/Express service named orders-api in the production namespace. Follow the Kubernetes rules in our agent instructions file. - 3 replicas; RollingUpdate with maxSurge: 1, maxUnavailable: 0. - The app needs about 8 s to warm its Postgres pool. Add a startupProbe on /health/startup (periodSeconds: 2, failureThreshold: 30, so up to 60 s) before liveness and readiness start. - readinessProbe on /health/ready, livenessProbe on /health/live, both on the named port http. Liveness must not call Postgres. - requests 250m/256Mi, limits 500m/512Mi. - Preferred podAntiAffinity on kubernetes.io/hostname. Then run scripts/verify-k8s.sh and fix every failure. Reply with the script's last line and any rule you could not satisfy. ``` The part to look for in the result is the probe block: ```yaml # k8s/base/deployment.yaml (container excerpt) startupProbe: # gates liveness and readiness while the pool warms httpGet: { path: /health/startup, port: http } periodSeconds: 2 failureThreshold: 30 # up to 60 s readinessProbe: httpGet: { path: /health/ready, port: http } periodSeconds: 5 failureThreshold: 3 livenessProbe: httpGet: { path: /health/live, port: http } periodSeconds: 10 failureThreshold: 3 ``` If the agent returns `initialDelaySeconds` on the readiness probe instead, reject it. `initialDelaySeconds` is a fixed guess that is either too short on a cold node or wasted time on a warm one. A `startupProbe` waits for the real signal and stops liveness from killing the pod during warm-up. ## Lock down networking without breaking DNS Ask for the Service, Ingress, and NetworkPolicy in the same prompt, so the workload is exposed and restricted at once. A rule agents often omit is DNS: ```yaml # k8s/base/networkpolicy.yaml (egress excerpt) egress: - to: - namespaceSelector: {} podSelector: matchLabels: k8s-app: kube-dns ports: - { protocol: UDP, port: 53 } - { protocol: TCP, port: 53 } ``` Without it, pods start, cannot resolve any hostname, and log `no such host` errors that look like an application bug. The invariant line in `verify-k8s.sh` fails the build instead. Check the `k8s-app: kube-dns` label against your cluster with `kubectl get pods -n kube-system --show-labels`, because some distributions label CoreDNS differently. ## Parameterize the manifests into a Helm chart When the same manifests ship to dev, staging, and production, have the agent extract a chart with values validation. Correct one training-data default first: agents still reach for Bitnami dependencies. Bitnami moved its versioned container images out of `docker.io/bitnami` into the unmaintained `bitnamilegacy` repository from 28 August 2025, and its packaged charts stopped receiving updates ([Bitnami announcement](https://github.com/bitnami/containers/issues/83267)). A pin copied from an old example can resolve to an image that no longer exists. For Postgres, install the CloudNativePG operator once per cluster and let the app chart render only a `Cluster` resource. Do not bundle an operator as a subchart of an app, because its CRDs and cluster-wide RBAC then share the app's release lifecycle. ```bash # Platform team, once per cluster (terminal) helm repo add cnpg https://cloudnative-pg.github.io/charts helm upgrade --install cnpg --namespace cnpg-system --create-namespace cnpg/cloudnative-pg ``` **Copy-paste prompt: manifests to Helm chart** ```text Convert k8s/base/ into a Helm chart at charts/orders-api (Chart.yaml apiVersion v2). - values.yaml with replicaCount, image (repository, tag; no default tag of "latest"), resources, autoscaling, ingress, and postgres blocks. Add values-production.yaml. - Postgres: when postgres.enabled, render a postgresql.cnpg.io/v1 Cluster resource. The CloudNativePG operator is already installed. Add no chart dependencies at all, and nothing from Bitnami (charts.bitnami.com or oci://.../bitnamicharts). - _helpers.tpl with name, fullname, labels and selectorLabels helpers, plus a validateValues helper that calls fail when image.repository is empty or when ingress.enabled is true with no ingress.hosts. - When autoscaling.enabled, omit spec.replicas from the Deployment. Run scripts/verify-k8s.sh until it exits 0, then paste its summary and cluster.diff. ``` The validation helper makes a bad values file fail at `helm template`, which is the first layer of the gate: ```yaml # charts/orders-api/templates/_helpers.tpl (excerpt) {{- define "orders-api.validateValues" -}} {{- if not .Values.image.repository }} {{- fail "image.repository is required" }} {{- end }} {{- if and .Values.ingress.enabled (not .Values.ingress.hosts) }} {{- fail "ingress.hosts must be set when ingress.enabled is true" }} {{- end }} {{- end }} ``` ## Scale and drain safely with an HPA and a PDB Generate the HorizontalPodAutoscaler and the PodDisruptionBudget together. The PDB has a sharp edge: it accepts `minAvailable` or `maxUnavailable`, never both, and the API server rejects a PDB that sets both. `maxUnavailable: 1` is usually the better choice with at least two replicas, because it keeps working when the HPA changes the replica count. At one replica, any PDB either blocks drains or allows downtime. ```yaml # pdb.yaml — exactly one of minAvailable / maxUnavailable apiVersion: policy/v1 kind: PodDisruptionBudget metadata: { name: orders-api, namespace: production } spec: maxUnavailable: 1 selector: matchLabels: { app: orders-api } ``` With GitOps, the HPA and Argo CD fight over `spec.replicas` unless you tell Argo CD to ignore it. Add this to the `Application`: ```yaml spec: ignoreDifferences: - group: apps kind: Deployment jsonPointers: [/spec/replicas] syncPolicy: syncOptions: [RespectIgnoreDifferences=true] ``` `ignoreDifferences` on its own only hides the diff: if `spec.replicas` is still in Git, every sync (and every self-heal) writes it back over the HPA. So remove `spec.replicas` from the Deployment in Git, as the rules file says, or keep the `RespectIgnoreDifferences=true` sync option shown above so a sync leaves the replica count alone. For traffic splitting and canaries, [progressive delivery](/en/workflows/ship/progressive-delivery/) covers the analysis step that decides whether to promote. When you generate Istio routing, check which API versions your mesh serves with `kubectl api-resources --api-group=networking.istio.io` before you accept the `apiVersion` the agent picked. ## Diagnose a failing pod from live cluster state Without cluster access, an agent answers "why is this pod restarting?" with a generic checklist. With the community [Kubernetes MCP server](https://github.com/containers/kubernetes-mcp-server) (npm `kubernetes-mcp-server`, version 0.0.67 on 2026-09-26), it lists pods, reads logs, and pulls events itself. Its runtime settings live in a TOML file; the CLI keeps only `--config`, `--config-dir`, and `--version`. Start it read-only: ```toml # ~/.config/k8s-mcp.toml read_only = true toolsets = ["core", "config", "helm"] ``` Also point the server at a kubeconfig context bound to a read-only RBAC role. `read_only = true` limits the server's tools; RBAC limits what any credential leak can do. Keep `toolsets` to what diagnosis needs, because every enabled tool's definition takes up context in each session. `claude mcp add` writes to local scope by default (Claude Code 2.1.283); add `--scope project` to write `.mcp.json`, which you commit so the whole team gets the same server. **Claude Code** ```bash claude mcp add kubernetes -- npx -y kubernetes-mcp-server@0.0.67 --config "$HOME/.config/k8s-mcp.toml" ``` **Codex** ```bash codex mcp add kubernetes -- npx -y kubernetes-mcp-server@0.0.67 --config "$HOME/.config/k8s-mcp.toml" ``` **Cursor** Add the server to `.cursor/mcp.json` in the project. Use an absolute path to the TOML file; the args are passed to `npx` as-is, not through a shell. ```json { "mcpServers": { "kubernetes": { "command": "npx", "args": ["-y", "kubernetes-mcp-server@0.0.67", "--config", "/home/you/.config/k8s-mcp.toml"] } } } ``` **Copy-paste prompt: CrashLoopBackOff root cause** ```text The orders-api pods in namespace production are in CrashLoopBackOff since the last rollout. Using the kubernetes MCP tools, read the pod status, the previous container's logs and the namespace events. Rank the three most likely causes, citing the exact line of evidence for each. Weigh: liveness probe failing during slow boot, OOMKilled in Last State, a missing ConfigMap or Secret, and an entrypoint crash. For the top cause, give the kubectl command that confirms it and the smallest manifest change that fixes it. Do not apply anything. ``` No cluster access from the agent? Run `kubectl describe pod POD -n production` and `kubectl logs POD -n production --previous` yourself and paste both outputs above the same prompt. More infrastructure servers, and when a skill fits better than a server, are on [infrastructure MCP servers](/en/ecosystem/mcp/infrastructure-mcp/). ## Tune resource limits from observed usage Agent-chosen limits are guesses. Replace them with numbers from your own metrics. **Copy-paste prompt: requests and limits from real usage** ```text orders-api requests 250m CPU / 256Mi memory with limits 500m / 512Mi. Below are 7 days of per-pod CPU and memory P50, P95 and P99 from Prometheus. Recommend new values: - memory limit at least 25% above observed P99 (memory is not compressible; the kernel kills the container instead of throttling it), memory request near P95; - CPU request near P50, CPU limit near P95. Give one sentence of reasoning per resource and output only the patched resources: block. ``` Where the metrics come from, and the alerts that tell you a limit is too tight, are on [monitoring and logging patterns](/en/cookbook/devops-recipes/monitoring-logging/). ## What breaks when an agent writes your Kubernetes config? 1. **`CrashLoopBackOff` right after a rollout.** The liveness probe kills the pod before it finishes booting. Confirm with `kubectl describe pod POD -n production`: the events show `Liveness probe failed` followed by a restart. `kubectl logs POD -n production --previous` shows the boot sequence, cut short. Recover: move the boot guard into a `startupProbe`, and add a `startupProbe` check to `verify-k8s.sh` if it is not already there. 2. **`OOMKilled` under load.** `kubectl describe pod` shows `Last State: Terminated, Reason: OOMKilled`. Recover: raise the memory limit above observed P99 with the resource prompt above and real data. Do not double the number to make the alert stop. 3. **A node drain hangs.** The PDB leaves zero disruption budget, for example `minAvailable: 3` with three replicas. Recover: switch to `maxUnavailable: 1`. A PDB that sets both fields never reaches the cluster, because the server dry-run in the gate rejects it. 4. **`ImagePullBackOff`.** The tag does not exist, the registry needs `imagePullSecrets`, or a chart still points at a removed Bitnami image. Recover: confirm the tag in your registry, attach the pull secret, and replace the Bitnami dependency as shown above. 5. **Argo CD stuck `OutOfSync` or `Progressing`.** `OutOfSync` that returns after every sync is usually the HPA and Git fighting over `spec.replicas`: add the `ignoreDifferences` entry, and either remove `spec.replicas` from the Deployment in Git or set `RespectIgnoreDifferences=true`, so a sync does not reset the replica count. `Progressing` that never ends means the Deployment never becomes Ready: go back to items 1 and 2. 6. **Your emergency `kubectl rollout undo` reverts itself.** With `selfHeal: true`, Argo CD restores whatever Git says within minutes. Recover: revert the commit in the config repository. That is the rollback; `kubectl` is not. Rehearse the path as described in [rollback pipelines](/en/developer-scorecard-guide/rollback-pipeline/). A green gate with a broken production is the one silent failure here. It happens when the staging cluster used for server dry-run lacks a CRD, a policy, or a Pod Security label that production has. Keep the two in step, and treat a new admission rejection in production as a gap in staging. ## Where to go next with Kubernetes and agents - [Docker and container patterns](/en/cookbook/devops-recipes/docker-patterns/) — Build and prove the non-root, pinned images these manifests deploy. - [Docker and Kubernetes containerization](/en/workflows/ship/containerization/) — The end-to-end workflow from Dockerfile to hardened manifests, with the Docker MCP gateway. - [CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/) — Run verify-k8s.sh in CI and bump image tags in the GitOps repository. - [Infrastructure as code patterns](/en/cookbook/devops-recipes/infrastructure-as-code/) — Apply the same render-validate-diff gate to Terraform and the clusters themselves. - [Reviewing an agent's pull request](/en/workflows/ship/agent-pr-review/) — Decide what a person must read in an agent's PR, and what the gates prove instead. - [Choosing a model](/en/ecosystem/models/) — Start on the tool's default model and switch only when your evals say so. --- # Monitoring & Logging Patterns URL: https://developertoolkit.ai/en/cookbook/devops-recipes/monitoring-logging/ Description: Agent recipes for golden-signal and SLO burn-rate alerts, Alertmanager routing, log-trace correlation and tail sampling, each proven by a machine check. Monitoring and logging patterns are copy-paste recipes for having Claude Code, Codex, or Cursor write observability configuration: OpenTelemetry bootstrap code, golden-signal and SLO burn-rate alerts, Alertmanager routing, log pipelines that carry `trace_id`, and collector tail sampling. Each recipe ends in a machine check (`promtool`, `amtool`, or a config test), so nobody has to proofread PromQL. This page is for developers and tech leads who own a service's alerts. Your checkout API threw 500s for an hour last night while every dashboard stayed green, because the alerts watched CPU instead of the error rate. The one trace that would explain it was sampled away, and the logs from that minute carry no `trace_id`. For the end-to-end build (instrumentation, the collector stack, dashboards, and sign-off), follow [monitoring and observability](/en/workflows/operate/monitoring-observability/). This page holds the individual recipes you reach for once that stack exists. ## What these monitoring recipes give you - A golden-signals prompt that turns a four-line spec into latency, error, traffic, and saturation rules with a `promtool` test for each - A prompt that turns an SLO target into recording rules and a multi-window burn-rate alert pair, with `promtool` tests that prove when each alert fires - An Alertmanager routing prompt, plus the `amtool` commands that prove which receiver a given alert reaches - A log pipeline prompt that promotes `trace_id` to a top-level field and redacts PII, tested with `--config.test_and_exit` - A collector tail-sampling recipe that keeps every error trace and samples the rest - Two read-only audit prompts: one for alert-fatigue antipatterns in existing Prometheus rules or CloudWatch alarms, one for unbounded label cardinality - A migration prompt for monitoring code still on the AWS SDK v2 or the old OpenTelemetry metrics package ## Which check proves each monitoring artifact? Agents write observability configuration quickly and get it subtly wrong: a metric name from old training data, a label that explodes cardinality, a burn-rate constant copied from a different SLO. Reading the YAML does not catch those. A validator and a behaviour test do. Give the agent the check together with the task, and ask it to paste the output. | Artifact the agent writes | Syntax check | Behaviour check | | --- | --- | --- | | Prometheus recording and alert rules | `promtool check rules rules.yml` | `promtool test rules rules_test.yml`: synthetic series, "fires at X, silent at Y" | | `alertmanager.yml` | `amtool check-config alertmanager.yml` | `amtool config routes test --config.file=alertmanager.yml severity=critical` prints the receiver | | OpenTelemetry Collector config | `otelcol-contrib validate --config=collector.yaml` | the `debug` exporter with `verbosity: detailed` shows spans arriving | | Logstash pipeline | `bin/logstash -f logstash.conf --config.test_and_exit` | feed one real log line and inspect the output event | | Instrumentation code | type check and unit tests | the metric names exist in Prometheus: `curl -s localhost:9090/api/v1/label/__name__/values` | You review the behaviour check, not the configuration. "The fast-burn alert fires at 10% errors and stays silent at 0.3%" is two lines of intent; the PromQL behind it is the agent's job. ## Give the agent live telemetry through MCP first An agent that cannot see your metrics invents thresholds and metric names. With the official Sentry and Grafana MCP servers connected, the agent reads the real metric list, the p95 for the last week, and the stack trace behind an error spike before it writes a rule. The URLs and packages are the same in every agent; only the command differs. **Claude Code** ```bash # Terminal, repo root. Sentry: hosted server, OAuth on first use (or /mcp in a session) claude mcp add -s project --transport http sentry https://mcp.sentry.dev/mcp # Grafana Labs' server from PyPI, read-only; the token file lives outside the repo claude mcp add -s project grafana \ -e GRAFANA_URL=https://grafana.example.com \ -e 'GRAFANA_SERVICE_ACCOUNT_TOKEN_FILE=${HOME}/.config/grafana/mcp-token' \ -- uvx mcp-grafana --disable-write ``` **Codex** ```bash # Terminal. Entries land in ~/.codex/config.toml codex mcp add sentry --url https://mcp.sentry.dev/mcp codex mcp login sentry codex mcp add grafana \ --env GRAFANA_URL=https://grafana.example.com \ --env GRAFANA_SERVICE_ACCOUNT_TOKEN_FILE=$HOME/.config/grafana/mcp-token \ -- uvx mcp-grafana --disable-write ``` **Cursor** In `.cursor/mcp.json` (project) or `~/.cursor/mcp.json` (user): ```json { "mcpServers": { "sentry": { "url": "https://mcp.sentry.dev/mcp" }, "grafana": { "command": "uvx", "args": ["mcp-grafana", "--disable-write"], "env": { "GRAFANA_URL": "https://grafana.example.com", "GRAFANA_SERVICE_ACCOUNT_TOKEN_FILE": "/Users/you/.config/grafana/mcp-token" } } } } ``` With Grafana connected, ask the agent to list the dashboards and data sources that already exist before it proposes a panel, so it extends them instead of duplicating them. Give the Grafana service account the **Viewer** role. `GRAFANA_API_KEY` is deprecated in `mcp-grafana` (1.6.0 on PyPI, checked 2026-09-26); use `GRAFANA_SERVICE_ACCOUNT_TOKEN` or the `_FILE` variant. Avoid lookalike packages such as `@leval/mcp-grafana` (a community port) or the deprecated `@elastic/mcp-server-elasticsearch` npm package; Elastic's current server is documented in the `elastic/mcp-server-elasticsearch` repository. Scopes, token headers, and context cost for each server are on [observability MCP servers](/en/ecosystem/mcp/observability-mcp/). **Copy-paste prompt: ground an alert in real incident data** ```text Using the Sentry MCP, find the three unresolved issues in project api-prod with the most events in the last 7 days. For the top one, report its event count per hour, first_seen, and the release that introduced it. Then, using the Grafana MCP, query Prometheus for the 5xx ratio and p95 latency of job="api" over the same 7 days, at 1h resolution. Propose an alert threshold that would have fired within 10 minutes of that issue starting, and show the query and the numbers you based it on. Do not write any rule files yet. ``` A skill is the lighter option when you need the agent to know how to write good monitoring configuration, not what is firing right now. Seth Hobson's `wshobson/agents` repository ships `prometheus-configuration`, `slo-implementation`, `grafana-dashboards`, and `distributed-tracing` skills in its `observability-monitoring` plugin: ```bash # Any skills-compatible agent (Claude Code, Codex, Cursor, and others) npx skills add wshobson/agents --skill slo-implementation # Claude Code, inside a session: the whole plugin /plugin marketplace add wshobson/agents /plugin install observability-monitoring@claude-code-workflows ``` Use the skill for drafting rules from scratch, and the MCP server for tuning thresholds against production. For scale, checked 2026-09-26: `wshobson/agents` had about 40.0k GitHub stars and `grafana/mcp-grafana` about 3.5k. Read a third-party skill before you install it; see [installing and managing skills](/en/ecosystem/skills/installing-managing/). ## Turn a golden-signals spec into alert rules Alert on what users feel. Of the four golden signals (latency, traffic, errors, and saturation), page on errors and latency, and send saturation to a ticket. The fastest way to a sane first rule set is a four-line spec in plain language; the agent writes the PromQL and the test, and you review the spec and the test output. **Copy-paste prompt: golden-signal alert rules with tests** ```text Write monitoring/rules/checkout-golden-signals.yml for Prometheus job="checkout-api". First list the real metric names (query /api/v1/label/__name__/values or use the Grafana MCP) and use only names from that list. - Latency: p95 of the HTTP server duration histogram above 0.5 s for 5m, severity warning. histogram_quantile must read a _bucket series with le in the by() clause. - Errors: 5xx ratio above 5% for 5m, severity critical. - Traffic: 5m request rate below 50% of the previous hour's rate for 10m, severity warning, and only while the previous hour averaged more than 1 request per second. - Saturation: CPU above 80% for 10m from node_cpu_seconds_total, severity ticket. Every rule gets for:, a severity label, summary and runbook_url. Write monitoring/rules/checkout-golden-signals_test.yml with one firing and one silent case per alert, run promtool check rules and promtool test rules, and paste the output. Do not change a test to make it pass. ``` The latency and traffic rules are the two that agents get wrong most often, so they are the two to look at in the result: ```yaml # monitoring/rules/checkout-golden-signals.yml (excerpt) groups: - name: checkout-golden-signals rules: - alert: CheckoutLatencyP95High expr: | histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket{job="checkout-api"}[5m])) ) > 0.5 for: 5m labels: { severity: warning } annotations: summary: "checkout-api p95 latency above 500 ms" runbook_url: "https://runbooks.example.com/checkout-latency" - alert: CheckoutTrafficDrop # The floor stops the rule paging every night when traffic is naturally low expr: | sum(rate(http_server_request_duration_seconds_count{job="checkout-api"}[5m])) < 0.5 * sum(rate(http_server_request_duration_seconds_count{job="checkout-api"}[1h] offset 5m)) and sum(rate(http_server_request_duration_seconds_count{job="checkout-api"}[1h] offset 5m)) > 1 for: 10m labels: { severity: warning } annotations: summary: "checkout-api traffic fell below half of the previous hour" runbook_url: "https://runbooks.example.com/checkout-traffic" ``` The static 5% error rule is the blunt version of the burn-rate pair in the next section. Once the burn-rate alerts are in place, delete the static rule or demote it to a ticket, so one incident does not page twice. ## Write SLO burn-rate alerts that are tested, not trusted CPU and latency thresholds say something is off. A burn-rate alert says you are spending error budget faster than you can afford. The multi-window, multi-burn-rate pattern from Google's SRE workbook fires only when a long and a short window agree, which keeps it quiet through a single bad scrape and lets it reset quickly after recovery. First, confirm the metric names. From `@opentelemetry/instrumentation-http` 0.222.0 (checked 2026-09-26), Node.js services emit the stable histogram `http.server.request.duration` in seconds, which Prometheus usually stores as `http_server_request_duration_seconds_bucket`, `_count`, and `_sum`. Most tutorials and most model training data still use `http_requests_total` or `http_request_duration_seconds`. The details are in [which HTTP metric names current OpenTelemetry emits](/en/workflows/operate/monitoring-observability/#which-http-metric-names-does-current-opentelemetry-emit). **Copy-paste prompt: SLO burn-rate rules with promtool tests** ```text Our API (Prometheus job="api") has a 99.5% availability SLO over 30 days. A bad request is any response with http_response_status_code 5xx. 1. List the real metric names first: query /api/v1/label/__name__/values (or use the Grafana MCP) and show me every http_server_* name. Use only names from that list. 2. In monitoring/rules/api-slo.yml, write recording rules for the error ratio over 5m, 30m, 1h and 6h, grouped by job. 3. Add a fast-burn alert (1h and 5m windows, 14.4x burn, severity critical) and a slow-burn alert (6h and 30m windows, 6x burn, severity warning). Every alert gets for:, summary, description and runbook_url. 4. Above each alert, write a comment with the burn-rate arithmetic: the error-ratio threshold, and how many days until the budget is gone at that rate. 5. Write monitoring/rules/api-slo_test.yml: for each alert, one input that must fire and one that must stay silent, with the error ratio stated in a comment. 6. Run promtool check rules and promtool test rules and paste the output. Do not edit a test to make it pass. If a test fails, explain why and fix the rule. ``` The recording rules the agent produces should look like this. Every alert then reads a precomputed ratio instead of repeating the division: ```yaml # monitoring/rules/api-slo.yml (excerpt) groups: - name: api-slo-recording rules: - record: job:slo_errors:ratio_rate5m expr: | sum by (job) (rate(http_server_request_duration_seconds_count{http_response_status_code=~"5.."}[5m])) / sum by (job) (rate(http_server_request_duration_seconds_count[5m])) - record: job:slo_errors:ratio_rate1h expr: | sum by (job) (rate(http_server_request_duration_seconds_count{http_response_status_code=~"5.."}[1h])) / sum by (job) (rate(http_server_request_duration_seconds_count[1h])) # ratio_rate30m and ratio_rate6h follow the same shape - name: api-slo-alerts rules: # 99.5% SLO -> budget 0.005. 14.4x burn -> error ratio > 0.072. # At that rate a 30-day budget is gone in about 2.1 days (30 / 14.4). - alert: ApiErrorBudgetFastBurn expr: | job:slo_errors:ratio_rate1h{job="api"} > (14.4 * 0.005) and job:slo_errors:ratio_rate5m{job="api"} > (14.4 * 0.005) for: 2m labels: { severity: critical } annotations: summary: "api is burning error budget 14.4x faster than the SLO allows" runbook_url: "https://runbooks.example.com/api-error-budget" ``` **Check one burn-rate constant by hand** Models often copy the windows and multipliers from a different SLO than the one you gave them. Recompute one number yourself: for a 99.5% SLO the fast-burn threshold is 14.4 × 0.005 = 0.072, and for 99.9% it is 14.4 × 0.001 = 0.0144. If the generated rule does not match, the alert is either deaf or a noise machine. The `promtool` test catches this only when the test inputs sit near the threshold, so ask for one input just above it and one just below. A test file for these rules has the shape shown in [generate alert rules you can test without reading them](/en/workflows/operate/monitoring-observability/#generate-alert-rules-you-can-test-without-reading-them). Keep that test file out of the agent's reach when it later edits the rule, so "make the test pass" cannot mean "weaken the test". ## Route alerts with Alertmanager and prove the routing tree Routing is where alert storms start: `group_wait: 0s` on every route turns one cluster outage into hundreds of pages. Describe the escalation policy in plain language and let `amtool` prove the result. **Copy-paste prompt: Alertmanager routing with route tests** ```text Write monitoring/alertmanager.yml: - severity="critical" goes to the pagerduty-oncall receiver, group_wait 30s, repeat_interval 1h. - Alerts whose service label matches ^(postgres|redis|mongodb)$ go to the db-alerts Slack receiver. - severity="warning" is muted on weekends and outside 09:00-18:00 on weekdays, using time_intervals and mute_time_intervals. - An inhibit rule: a firing critical alert suppresses warning alerts with the same alertname and cluster. - Read every credential from a file (routing_key_file, api_url_file), never inline. Then run amtool check-config, and amtool config routes test for these label sets, pasting the receiver each one reaches: severity=critical service=checkout severity=warning service=postgres severity=warning service=checkout ``` ```bash # Terminal: the checks you run, or have the agent run and paste amtool check-config monitoring/alertmanager.yml amtool config routes test --config.file=monitoring/alertmanager.yml \ --verify.receivers=pagerduty-oncall severity=critical service=checkout ``` `--verify.receivers` makes the command exit non-zero when the label set reaches a different receiver, so the same line works as a CI step. ## Correlate logs with traces in the log pipeline The most valuable logging change is making every log line carry `trace_id`. Then you move from a Grafana span to the surrounding logs in one click. Field names are where agent-written pipelines break, so the prompt starts from one real log line. **Copy-paste prompt: Logstash pipeline with trace correlation and redaction** ```text Here is one raw log line from our API, exactly as it reaches Logstash: Write monitoring/logstash/pipeline.conf: - Beats input on 5044 with TLS, and a Kafka input on topic application-logs. - Parse the JSON body. Promote trace_id and span_id to top-level fields, using the exact paths in the sample line (they may be nested). Rename level to log_level and convert status to an integer. - Redact card numbers and email addresses in message with gsub. - Drop DEBUG events when environment is "production". - Output to Elasticsearch with ILM, rollover alias logs. Then run bin/logstash -f monitoring/logstash/pipeline.conf --config.test_and_exit and paste the result. Show the event the sample line produces after the filter stage. ``` The part to check is the correlation block. The field paths must match what your OpenTelemetry log bridge or logger emits: ```ruby filter { if [message] =~ /^\{/ { json { source => "message" target => "parsed" } mutate { rename => { "[parsed][trace_id]" => "trace_id" "[parsed][span_id]" => "span_id" "[parsed][level]" => "log_level" } } } if [environment] == "production" and [log_level] == "DEBUG" { drop {} } } ``` On Loki instead of Elasticsearch, the prompt transfers: ask for a Grafana Alloy or Promtail configuration that extracts `trace_id` as structured metadata, not as a label. A label per trace ID is the same cardinality explosion described below. For the application side, structured and redacted logging with request correlation, see [logging patterns](/en/cookbook/error-handling-recipes/logging-patterns/). ## Keep every error trace with tail sampling Head sampling decides at the first span, before anyone knows whether the request failed, so the trace you need is often gone. Tail sampling decides after the trace completes: keep all errors and slow requests, and sample the rest. **Copy-paste prompt: collector tail sampling** ```text Edit monitoring/otel-collector.yaml (the contrib distribution): - Add a tail_sampling processor with decision_wait 30s and three policies: keep every trace with a span whose status code is ERROR, keep every trace longer than 1000 ms, and sample the remainder at 5% probabilistic. - Add an attributes processor that deletes http.request.header.authorization and db.statement before export. - Wire both into the traces pipeline, exporting OTLP to our backend on port 4317. - Explain what happens with 3 collector replicas behind a round-robin load balancer, and what to change so that setup still samples whole traces. Run otelcol-contrib validate --config=monitoring/otel-collector.yaml and paste the output. ``` ```yaml # monitoring/otel-collector.yaml (excerpt) processors: tail_sampling: decision_wait: 30s policies: - name: keep-errors type: status_code status_code: { status_codes: [ERROR] } - name: keep-slow type: latency latency: { threshold_ms: 1000 } - name: sample-the-rest type: probabilistic probabilistic: { sampling_percentage: 5 } ``` **Tail sampling needs whole traces on one collector** `tail_sampling` ships in the collector's contrib distribution, not the core one. It also needs every span of a trace to reach the same collector instance. Behind a round-robin load balancer, spans scatter across replicas and the sampler decides on partial traces, dropping data without an error. Use a two-tier setup with the `loadbalancing` exporter (routing by trace ID) in front, or run one tail-sampling collector. ## Instrument a service without the deprecated exporters Dashboards are downstream of instrumentation. Ask for OTLP explicitly. Older model knowledge reaches for `@opentelemetry/exporter-jaeger`, whose README marks it deprecated with support ended in March 2024 (npm 2.11.0, checked 2026-09-26); Jaeger accepts OTLP directly. **Copy-paste prompt: OpenTelemetry bootstrap for an Express service** ```text Add OpenTelemetry tracing to this Express service in src/tracing.js, loaded with node --require ./src/tracing.js. Use @opentelemetry/sdk-node with @opentelemetry/auto-instrumentations-node and the OTLP/HTTP exporter @opentelemetry/exporter-trace-otlp-proto. Never use the Jaeger exporter. Disable the fs instrumentation. Take the endpoint and service name from the standard OTEL_EXPORTER_OTLP_ENDPOINT and OTEL_SERVICE_NAME variables; set service.version and deployment.environment.name from SERVICE_VERSION and ENVIRONMENT using the @opentelemetry/semantic-conventions constants. Do not record Authorization or Cookie headers as span attributes. Flush spans on SIGTERM before exit. Then start the service against a local collector with the debug exporter and paste one received span. ``` ```javascript // src/tracing.js — node --require ./src/tracing.js server.js const { NodeSDK } = require('@opentelemetry/sdk-node'); const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node'); const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-proto'); const { resourceFromAttributes } = require('@opentelemetry/resources'); const { ATTR_SERVICE_VERSION, ATTR_DEPLOYMENT_ENVIRONMENT_NAME, } = require('@opentelemetry/semantic-conventions'); const sdk = new NodeSDK({ // service.name comes from OTEL_SERVICE_NAME resource: resourceFromAttributes({ [ATTR_SERVICE_VERSION]: process.env.SERVICE_VERSION ?? '0.0.0', [ATTR_DEPLOYMENT_ENVIRONMENT_NAME]: process.env.ENVIRONMENT ?? 'production', }), // Reads OTEL_EXPORTER_OTLP_ENDPOINT; OTLP/HTTP is port 4318, gRPC is 4317 traceExporter: new OTLPTraceExporter(), instrumentations: [getNodeAutoInstrumentations({ '@opentelemetry/instrumentation-fs': { enabled: false }, })], }); sdk.start(); process.on('SIGTERM', () => sdk.shutdown().finally(() => process.exit(0))); ``` `deployment.environment.name` is the stable attribute in `@opentelemetry/semantic-conventions` 1.43.0; the older `deployment.environment` that many examples use is not. The collector stack this code exports to is in [monitoring and observability](/en/workflows/operate/monitoring-observability/). ## Audit existing alerts and metrics with a read-only agent Most teams do not lack alerts; they have the wrong ones. An audit is a good first agent job because it needs no write access: the agent reads rule files or an alarm export and reports. **Copy-paste prompt: alert-fatigue and cardinality audit** ```text Audit monitoring/rules/*.yml and alarms.json (output of aws cloudwatch describe-alarms --output json). Report each finding as file:line (or AlarmName) - problem - fix. Look for: - a Prometheus alert with no for: clause - histogram_quantile over a series that is not a _bucket histogram, or without le in the by() clause - a severity="critical" alert with no runbook_url - a label whose values are unbounded (user_id, request_id, full URL paths with IDs, trace_id) - a CloudWatch alarm with AlarmActions but no OKActions, EvaluationPeriods of 1, or TreatMissingData left at its default where the metric is sparse Do not edit any file. End with the three findings most likely to page someone for nothing. ``` How you run the audit differs by tool: **Claude Code** Run it headless with only read tools. In CI, add the isolation flags so a pull request cannot inject hooks, settings, or MCP servers into the job: ```bash claude -p "$(cat prompts/alert-audit.md)" \ --bare --setting-sources "" --strict-mcp-config \ --tools "Read,Grep,Glob" --output-format json > audit.json ``` `--bare` never reads OAuth credentials or the keychain, connects only the MCP servers named on the command line (from v2.1.286), and authenticates with `ANTHROPIC_API_KEY` (or an `apiKeyHelper` passed with `--settings`), so read the key from your CI secret store. Fail the job when `audit.json` reports findings. The rules for agents in pipelines are on [CI/CD pipeline recipes](/en/cookbook/devops-recipes/ci-cd-pipelines/). **Codex** Run it non-interactively under the read-only permission profile and save the final report: ```bash codex exec -c 'default_permissions=":read-only"' \ -o audit.md "$(cat prompts/alert-audit.md)" ``` To have Codex fix what the audit found in its own cloud environment and hand you a diff, submit the task with `codex cloud exec --env ENV_ID "…"`, then inspect it with `codex cloud diff` before `codex cloud apply` (the `codex cloud` command is marked experimental in 0.157.1). `ENV_ID` is the ID of the Codex cloud environment set up for this repository. To apply the fixes locally instead, start an interactive session with `codex -c 'default_permissions=":workspace"'`, so writes stay inside the repository (permission profiles are beta in 0.157.1), and run `promtool check rules` before you commit. **Cursor** Use Plan Mode for the audit so the agent proposes before it edits, then switch to Agent to apply the fixes you accept, one rule file at a time, and run `promtool check rules` in the terminal after each. For recurring work, Cursor's Automations can start a Cloud Agent from a Sentry or PagerDuty event (verified on Cursor's docs 2026-08-28), which suits "draft a rule change when this alert fires" more than a scheduled audit. For cardinality, give the agent the numbers instead of asking it to guess. Prometheus reports its heaviest metrics directly: ```bash # Terminal: top metrics by series count, and total head series curl -s localhost:9090/api/v1/status/tsdb | jq '.data.seriesCountByMetricName[:10]' curl -s 'localhost:9090/api/v1/query?query=prometheus_tsdb_head_series' | jq '.data.result[0].value[1]' ``` Paste both outputs into the audit prompt, and ask for a `metric_relabel_configs` rule that drops the offending label. ## Migrate monitoring code off end-of-support SDKs Monitoring code is often years old. Two migrations come up constantly, and both are mechanical enough for an agent. The `aws-sdk` npm package (v2) is deprecated on npm with the notice that it "has reached end-of-support, and no longer receives updates" (2.1693.0, checked 2026-09-26). `@opentelemetry/metrics` stopped at 0.24.0 and was renamed twice; the current package is `@opentelemetry/sdk-metrics` (2.11.0, checked 2026-09-26), where metric readers are passed to the `MeterProvider` constructor. **Copy-paste prompt: migrate CloudWatch and OpenTelemetry metrics code** ```text Migrate src/monitoring/ to current SDKs without changing behaviour: 1. AWS SDK v2 to v3: replace require('aws-sdk') and new AWS.CloudWatch() with CloudWatchClient, PutMetricAlarmCommand and PutMetricDataCommand from @aws-sdk/client-cloudwatch. Drop .promise(); send() returns a promise. 2. OpenTelemetry: replace @opentelemetry/metrics with @opentelemetry/sdk-metrics and pass readers in new MeterProvider({ readers: [...] }) instead of calling addMetricReader(). 3. Every CloudWatch alarm that has AlarmActions must also have OKActions. Print the npm install and uninstall commands, run the type checker and the tests, and paste the output. ``` ```javascript // src/monitoring/alarms.mjs — the migrated shape import { CloudWatchClient, PutMetricAlarmCommand } from '@aws-sdk/client-cloudwatch'; import { MeterProvider } from '@opentelemetry/sdk-metrics'; import { PrometheusExporter } from '@opentelemetry/exporter-prometheus'; const cw = new CloudWatchClient({}); await cw.send(new PutMetricAlarmCommand({ AlarmName: 'checkout-api-high-5xx', Namespace: 'AWS/ApplicationELB', MetricName: 'HTTPCode_Target_5XX_Count', Statistic: 'Sum', Period: 300, EvaluationPeriods: 3, DatapointsToAlarm: 2, Threshold: 10, ComparisonOperator: 'GreaterThanThreshold', TreatMissingData: 'notBreaching', AlarmActions: [process.env.SNS_TOPIC_ARN], OKActions: [process.env.SNS_TOPIC_ARN], // without it the alarm never reports recovery })); // PrometheusExporter is a MetricReader; it serves /metrics on port 9464 by default const meterProvider = new MeterProvider({ readers: [new PrometheusExporter()] }); export const meter = meterProvider.getMeter('checkout-api'); ``` The type checker catches most leftovers, such as a v2-only option name. Paste the compiler error back to the agent rather than describing it. ## Who signs off on agent-written monitoring? The agent writes the configuration and runs the checks; people approve intent. The service owner approves the SLO target and the test cases ("fires at 7.2% errors, silent at 0.3%"). The on-call lead approves routing, confirmed by the `amtool` output. A pull request that changes rules or routing without the matching test output in its description is not ready for review. What else that pull request must prove is on [the evidence bundle](/en/workflows/ship/evidence-bundle/). ## What breaks when agents write monitoring and logging config? 1. **An alert storm follows a missing `for:` clause.** A rule without `for:` fires on one bad scrape. Recover: grep the rule files for alerts with an `expr` and no `for:`, add a window, and add a `promtool` test with a one-sample spike that must stay silent. 2. **A latency panel or alert reads `NaN`.** `histogram_quantile` is running over a series that is not a `_bucket` histogram, or `le` is missing from the `by (...)` clause. Recover: have the agent list the real metric names from Prometheus and rewrite the query from that list. 3. **An alert never fires because the metric does not exist.** The rule uses `http_requests_total` or `http_request_duration_seconds`, but current OpenTelemetry emits `http_server_request_duration_seconds_*`. Recover: `promtool test rules` passes against synthetic series, so also run each alert expression once against the real Prometheus; an empty result means a wrong name. 4. **Prometheus runs out of memory, or scrapes slow down.** A label the agent added, often `user_id` or a raw URL path, multiplied the series count. Recover: find the metric with `/api/v1/status/tsdb`, drop the label with `metric_relabel_configs`, and fix the instrumentation so the label becomes a bounded route template. 5. **Spans never arrive.** The exporter protocol and port do not match the receiver: OTLP/HTTP is 4318, OTLP/gRPC is 4317. Recover: add the `debug` exporter with `verbosity: detailed` to the collector and confirm spans arrive before you blame the backend. 6. **Logs do not link to traces.** The pipeline expects `trace_id` at the top level, but the logger nests it. Recover: log one raw event, give it to the agent, and have it fix the `rename` paths from that sample. 7. **A CloudWatch alarm looks stuck firing.** It has `AlarmActions` but no `OKActions`, so nobody hears about recovery. Recover: pair every alarm action with an OK action; the audit prompt above finds the rest. 8. **A traffic-drop alert pages every night, or one incident pages twice.** A relative traffic rule with no volume floor fires whenever traffic is naturally low, and a static error-ratio rule next to a burn-rate pair pages for the same outage twice. Recover: add the floor shown in the golden-signals example, and keep only the burn-rate pair paging for errors. 9. **The thresholds are invented.** Without MCP access to real data, the agent produces confident numbers that do not match your traffic. Recover: connect Grafana read-only, have the agent quote last week's p95 and error ratio, and set thresholds from those numbers. ## Where to go next with monitoring and logging - [Monitoring and observability](/en/workflows/operate/monitoring-observability/) — The end-to-end workflow: instrumentation, the collector stack, dashboards and sign-off. - [Observability MCP servers](/en/ecosystem/mcp/observability-mcp/) — Sentry, Grafana, Datadog and PostHog MCP, read-only, with scopes and context cost. - [Incident response](/en/workflows/operate/incident-response/) — What to do with the alert once it pages someone. - [Debugging patterns](/en/cookbook/error-handling-recipes/debugging-patterns/) — Turn the telemetry behind an alert into a root cause. - [Recovery patterns](/en/cookbook/error-handling-recipes/recovery-patterns/) — Automate the runbook an alert links to. - [CI/CD pipeline recipes](/en/cookbook/devops-recipes/ci-cd-pipelines/) — Run promtool and amtool on every pull request, safely. --- # Error Handling Recipes URL: https://developertoolkit.ai/en/cookbook/error-handling-recipes/ Description: Pick the recipe for debugging, logging, recovery or monitoring, give the agent your error rules, and prove each fix with a check that failed first. The error handling recipes are copy-paste prompts for Claude Code, Codex, and Cursor that cover four jobs around a production failure: debugging, logging, recovery, and monitoring. Every recipe follows one rule: the agent attaches evidence that a check failed before the change and passes after it, so you approve evidence instead of reading every line. This hub is for developers who hand production errors to an agent, and for tech leads who approve those fixes. You know the situation: the API returns 500s, the logs say `Error: undefined`, and the agent's first fix wraps the call in `try/catch` so the error disappears from the dashboard but not from your users' screens. ## Which error handling recipe fits your problem? Start from the symptom. The last column is the evidence the agent attaches to the pull request. | Your problem | Recipe | The check that proves it | | --- | --- | --- | | A bug you can see but cannot explain: a stack trace, an intermittent failure, a leak, a race | [Debugging patterns](/en/cookbook/error-handling-recipes/debugging-patterns/) | A reproduction that fails on the unfixed code and passes after the fix | | Logs that are `console.log` strings, lack request IDs, or leak secrets | [Logging patterns](/en/cookbook/error-handling-recipes/logging-patterns/) | A test that asserts the structured fields and that a secret never reaches the output | | A flaky dependency that takes your service down with it | [Recovery patterns](/en/cookbook/error-handling-recipes/recovery-patterns/) | A chaos or fault-injection test that kills the dependency and checks the fallback | | Errors your users find before you do: no alerts, noisy alerts, no SLO | [Monitoring and logging patterns](/en/cookbook/devops-recipes/monitoring-logging/) | `promtool test rules` and a query that returns real data | Starting from nothing? Fix the logs first, because every other recipe needs evidence the agent can read. Then debug the failures you have, add recovery where a dependency keeps failing, and finish with alerts so the next failure reaches you before a customer does. For the incident process around a fix (paging, triage, the postmortem), read [AI-powered incident response](/en/workflows/operate/incident-response/). For the principle that turns every production error into a regression test, read [error-driven development](/en/method/principles/error-driven-development/). ## Give the agent your error-handling rules before any recipe Without rules, an agent optimizes for a quiet log: it swallows exceptions, adds optional chaining, and returns defaults for data that must exist. Write the rules once, where each tool loads them automatically. ```markdown ## Error-handling rules - Never swallow an error: no empty catch, no catch that only logs and continues, no default value for data that must exist. Rethrow, or return a typed error. - Classify every new catch: "expected sometimes" (handle it, log at warn) or "should never happen" (fail loudly, log at error with context). - Log with the project logger in structured form, with the request ID. Never log tokens, passwords, cookies, or full request bodies. - Every bug fix starts with a test or script that reproduces the bug and fails. Never edit, skip, or loosen that test to make it pass. - Retries only for idempotent calls, with a cap, backoff, and jitter. ``` **Cursor** Save the block as a project rule in `.cursor/rules/`, set to apply always. Keep the text identical to the other tools' files so a change to the rules reaches every agent. **Claude Code** Add the block to `CLAUDE.md` at the repository root. Claude Code loads it in every session, including headless `claude -p` runs. **Codex** Add the block to `AGENTS.md` at the repository root. Codex reads `AGENTS.md` before it starts work; in a project you have not marked as trusted, it ignores the project's `AGENTS.md` (Codex 0.150.0+). The "never loosen the test" rule matters most, and a rule alone is trust, not enforcement. [Protecting the oracle](/en/workflows/test/protect-the-oracle/) shows how to make the reproduction test read-only for the agent. **Copy-paste prompt: audit how this codebase handles errors** ```text Read-only pass: do not edit files. Find every place in src/ where an error can disappear: empty catch blocks, catch blocks that only log, promise chains with no rejection handler, optional chaining or default values on data that must exist, and retries without a cap. For each, give file:line, which rule it breaks ("swallowed", "no context", "unbounded retry", "secret in log"), and the user- visible effect if it fires in production. Output one table sorted by that effect, then name the error handling recipe that fixes the top three. ``` **Copy-paste prompt: fix a production error with a failing test first** ```text Here is a production error with its stack trace and request ID: . 1. Explain the cause in two sentences and quote the log lines or code that prove it. If the evidence is not enough, say what you need and stop. 2. Write a test that reproduces the error and run it. Show me that it fails. 3. Fix the cause, not the symptom: no new catch that hides the error. 4. Rerun the test, the full suite, the type check, and lint. Paste the output. Do not edit the test after step 2. ``` ## How do you verify an agent's error handling without reading every line? Each recipe ends in a check a machine runs, and the pull request carries its output. - **Red, then green.** The reproduction fails on the unfixed code and passes after the fix. A test that never failed proves nothing. - **The gates run in CI.** The full suite, the type check, and lint run on the pull request, not only in the agent's session. - **A second agent reviews the diff against the diagnosis.** Run `/code-review` in a Claude Code session, `codex exec review --uncommitted` in the terminal, or Bugbot on the pull request in Cursor, and ask it to look for hidden errors: new catches, loosened assertions, defaults on required data. - **Production confirms the fix.** After deploy, the error rate for that issue stays at zero through one traffic peak. The developer who shipped the fix checks it. The developer owns the evidence; the tech lead approves when every item is present. For the full evidence table, see [how to prove a bug fix without reading every line](/en/cookbook/error-handling-recipes/debugging-patterns/#how-do-you-prove-a-bug-fix-without-reading-every-line). For deliberate fault injection beyond one dependency, see [error injection testing](/en/workflows/test/error-injection-testing/). ## What breaks when agents handle errors? **Error handling failure modes and recovery** - **The fix hides the error.** A new `try/catch`, optional chaining, or a default value makes the stack trace vanish while users still see the failure. Recovery: reject the diff, and rerun the second-agent review with "does this hide errors anywhere?" as its first question. - **The reproduction turns green because the agent edited it.** Recovery: `git diff` the test file on its own, revert it, and make the path read-only for the agent. - **A retry turns a slow dependency into an outage.** Retries without jitter or a cap multiply load on a service that is already struggling. Recovery: apply the circuit breaker and jittered retry from the recovery recipe, and prove them with its chaos test. - **Logging leaks a secret.** "Log the request so we can debug it" writes tokens and cookies to the log store. Recovery: add the redaction test from the logging recipe, and rotate any credential that reached the logs. - **The agent diagnoses from a paraphrase.** Your summary of the error drops the detail that matters. Recovery: give it the raw stack trace, or connect a read-only error-tracking MCP server, as the debugging recipe shows. ## Where to go next with error handling - [Debugging patterns](/en/cookbook/error-handling-recipes/debugging-patterns/) — Five hunts, from stack trace to race condition, each proven by a check that failed first. - [Logging patterns](/en/cookbook/error-handling-recipes/logging-patterns/) — Structured, correlated, secret-safe logs the agent can query. - [Recovery patterns](/en/cookbook/error-handling-recipes/recovery-patterns/) — Circuit breakers, jittered retries, and fallbacks, proven with a chaos test. - [Monitoring and logging patterns](/en/cookbook/devops-recipes/monitoring-logging/) — Alert rules, SLO burn rates, and dashboards the agent writes and tests. - [Observability MCP servers](/en/ecosystem/mcp/observability-mcp/) — Give the agent the real error and trace instead of your summary of it. - [Monitoring and observability](/en/workflows/operate/monitoring-observability/) — The operate-stage workflow these recipes plug into. --- # Debugging Patterns URL: https://developertoolkit.ai/en/cookbook/error-handling-recipes/debugging-patterns/ Description: Five agent debugging recipes for intermittent failures, stack traces, memory leaks, races and cross-service bugs, each proven by a check that failed first. AI-assisted debugging patterns are five evidence-first recipes for Claude Code, Codex and Cursor: instrument and correlate intermittent failures, turn a stack trace into a targeted fix, find memory leaks from heap snapshots, reproduce race conditions with a failing test, and rebuild cross-service timelines by request ID. Each recipe ends with a check that fails before the fix and passes after. This page is for developers who hand bugs to a coding agent, and for tech leads who decide what evidence a bug-fix pull request must carry. The situation: about one login in three fails in production, the stack trace points at a line that looks fine, and the failure disappears when you attach a debugger. Asked to "fix the auth bug", the agent returns a confident guess and a diff that makes the symptom go quiet. The patterns below make the agent collect evidence first and prove the fix with a check you can rerun. ## What these debugging patterns give you - A symptom-to-pattern table that tells you which evidence to collect before the agent edits anything - Seven copy-paste prompts: instrumentation, log correlation, stack-trace diagnosis, heap-diff analysis, race reproduction, cross-service timelines, and a review of the fix - The exact commands to pipe logs into Claude Code and Codex without an interactive session - An evidence checklist that lets a reviewer approve a bug fix without reading every line of the diff - The ways agent debugging goes wrong, with a recovery for each ## Which debugging pattern fits your bug? Start from the symptom. Every row names the evidence the agent needs and the check that proves the fix, because a fix with no check that failed first is still a guess. | Symptom | Pattern | Evidence to give the agent | Proof that the fix works | | --- | --- | --- | --- | | Fails some of the time, no clear trigger | [1. Instrument and correlate](#pattern-1-instrument-and-correlate-an-intermittent-failure) | Structured logs from 100 or more reproduced runs | The same loop shows zero failures | | One exception with a stack trace | [2. Stack trace to targeted fix](#pattern-2-turn-a-stack-trace-into-a-targeted-fix) | The full trace, the event payload, the release | A test built from the event fails, then passes | | Memory climbs until the process restarts | [3. Heap-snapshot diff](#pattern-3-find-a-memory-leak-from-heap-snapshots) | Two snapshots under the same load, top retainers | A soak script (the leaking operation repeated thousands of times under a heap budget) passes | | Duplicates or lost updates under load | [4. Failing concurrency test](#pattern-4-reproduce-a-race-condition-with-a-failing-test) | The operation, the shared state, the observed duplicate | The concurrent test fails before and passes after | | Slow or failing only across services | [5. Request-ID timeline](#pattern-5-rebuild-a-cross-service-timeline-by-request-id) | Logs or spans from every hop, keyed by request ID | The gap is gone in a fresh timeline or trace | For a deterministic bug with a clear reproduction, you need none of this: write the failing test and let the agent fix it, as in [test-driven development with AI](/en/method/principles/test-driven-development/). ## Set up the agent before the first bug Two additions make every pattern below cheaper. A debugging skill gives the agent a method (evidence first, one hypothesis at a time, a failing test before the fix), so you stop repeating it in every prompt. A read-only error-tracking MCP server lets the agent pull the real stack trace and event instead of your paraphrase of it. Both installs are covered in depth, with their traps, on [testing and debugging skills](/en/ecosystem/skills/testing-debugging-skills/) and [observability MCP servers](/en/ecosystem/mcp/observability-mcp/). **Claude Code** ```bash # Terminal, repository root npx skills add obra/superpowers --skill systematic-debugging -a claude-code -y claude mcp add -s project --transport http sentry https://mcp.sentry.dev/mcp claude mcp login sentry ``` **Codex** ```bash # Terminal, repository root npx skills add obra/superpowers --skill systematic-debugging -a codex -y codex mcp add sentry --url https://mcp.sentry.dev/mcp codex mcp login sentry ``` **Cursor** ```bash # Terminal, repository root npx skills add obra/superpowers --skill systematic-debugging -a cursor -y ``` Then add the server to `.cursor/mcp.json` and complete the OAuth sign-in when Cursor asks: ```json { "mcpServers": { "sentry": { "url": "https://mcp.sentry.dev/mcp" } } } ``` On the Sentry OAuth screen, leave **Triage Issues** and **Manage Projects & Teams** unchecked so the agent can read issues and events but not resolve or reassign them. If you use another error tracker, the patterns work the same with a pasted trace. ## Pattern 1: Instrument and correlate an intermittent failure An intermittent failure needs data from many runs, not a longer stare at one. The agent adds narrow, structured logging, you reproduce the failure many times, and the agent correlates failing runs against passing ones before it proposes anything. 1. **Commit or stash your work first**, so `git diff` shows only what the agent adds. The instrumentation is temporary; you revert it at the end. 2. **Ask for logging only, scoped to the suspect path.** Give the symptom, the rate, and what you have ruled out. **Copy-paste prompt: instrument an intermittent auth failure** ```text Token validation in src/auth/validate.ts fails on roughly 30% of logins in production. It does not correlate with user type or time of day. Add temporary debug logging to diagnose it: token issue time (iat), expiry (exp), validation latency, the clock of the host that validates, and every branch that can reject the token. Use one structured JSON line per event with the prefix [AUTH-DEBUG] and a requestId field. Logging only: do not change behaviour, error handling or return values. List every line you added. ``` 3. **Reproduce many times and capture the output.** A single passing run proves nothing about an intermittent bug. Run the narrowest test that exercises the path in a loop: ```bash # Terminal. 100 runs of one test file; every run is bracketed in the log for i in $(seq 1 100); do echo "RUN $i START" >> debug.log npx vitest run tests/auth/validate.test.ts >> debug.log 2>&1 \ && echo "RUN $i PASSED" >> debug.log || echo "RUN $i FAILED" >> debug.log done grep -c "^RUN [0-9]* FAILED" debug.log ``` If the test never fails locally, the trigger is environmental (clock skew between hosts, load, a shared cache). Capture the `[AUTH-DEBUG]` lines from staging or production for the same window instead. 4. **Ask for correlation, not a fix.** Pipe the log to the agent in a read-only run, so it cannot edit code while it reasons. The flags below were checked against Claude Code 2.1.283 and Codex 0.157.1. **Claude Code** ```bash # -p runs non-interactively and prints the answer; plan mode keeps it read-only grep -E "AUTH-DEBUG|^RUN " debug.log | claude -p --permission-mode plan \ "Correlate the failing [AUTH-DEBUG] events against the passing ones. What do the failures share that the passes do not? Give confidence and the log lines that support it. No fix yet." ``` **Codex** ```bash # Piped stdin is appended to the prompt; read-only sandbox, no edits grep -E "AUTH-DEBUG|^RUN " debug.log | codex exec -s read-only \ "Correlate the failing [AUTH-DEBUG] events against the passing ones. What do the failures share that the passes do not? Give confidence and the log lines that support it. No fix yet." ``` **Cursor** Switch to Plan Mode, attach `debug.log` to the chat with `@`, and paste the correlation prompt below. Plan Mode produces a plan instead of edits, which keeps this step read-only. **Copy-paste prompt: correlate failing and passing runs** ```text debug.log holds 100 reproduced runs. Each run is bracketed by RUN n START and RUN n PASSED or RUN n FAILED. Group the [AUTH-DEBUG] events by run and requestId. Compare failing requests with passing ones on validation latency, exp minus the validating host's clock, and iat. Tell me what the failures have in common that the passes do not, quote the lines that show it, and give your confidence as high, medium or low. Do not propose a fix yet. If the evidence is too thin to decide, say which extra field to log. ``` A useful answer names a testable cause, for example: "every failure has `exp` less than 2 s ahead of the validating host's clock, and all of them come from host B, whose clock runs 4 s ahead." A vague answer ("possibly a race condition") means the logging missed the signal; add the field it asks for and run the loop again. 5. **Turn the cause into a failing test, then fix.** The test pins the condition (a token validated by a host whose clock is 4 s ahead) and must fail on the current code. Then the agent adds the fix, for example a small clock-skew tolerance, and the loop from step 3 runs again. Zero failures in 100 runs, plus the new test, is the evidence. 6. **Remove the instrumentation.** Ask the agent to revert every `[AUTH-DEBUG]` line, then confirm with `git grep AUTH-DEBUG` returning nothing. Durable logging belongs in [logging patterns](/en/cookbook/error-handling-recipes/logging-patterns/), not in leftovers from a hunt. ## Pattern 2: Turn a stack trace into a targeted fix A stack trace pins the file, line and call chain, which makes it the richest single input you can give an agent. The risk is the fix: the fastest way to make `Cannot read properties of undefined` disappear is optional chaining everywhere, which hides the real bug. Make the agent classify the missing value before it touches code. **Copy-paste prompt: stack trace to a targeted fix** ```text Production error (Sentry issue linked if you have the Sentry MCP server, otherwise below): TypeError: Cannot read properties of undefined (reading 'id') at OrderService.createOrder (src/services/order.ts:145:23) at async OrderController.create (src/controllers/order.ts:67:18) 1. Walk the call chain and tell me which value is undefined at order.ts:145 and every path by which it can arrive undefined. Quote the code for each path. 2. Classify each path: "should never happen" (a bug upstream: fail loudly with a typed error) or "expected sometimes" (legitimate incomplete data: handle it explicitly). 3. Write one failing test per path that reproduces the error with the event's data. 4. Only then fix. No blanket optional chaining, no empty catch blocks, no default values that hide missing data. Run the tests and show the output. ``` A good fix keeps the two cases apart: ```typescript async createOrder(userId: string, input: OrderInput) { // "Should never happen": the controller validated userId, so this is a bug upstream const user = await this.users.find(userId); if (!user) throw new NotFoundError(`User ${userId} not found`); // "Expected sometimes": users created before billing launched have no customer record if (!user.billingCustomer) { logger.warn('user without billing customer; creating one', { userId }); user.billingCustomer = await this.billing.createCustomer(user); } return this.orders.create(user, input); } ``` The test that matters is the one built from the real event. If the agent's test passes on the unfixed code, it reproduced something else; send it back to step 1. This prompt, and the ones in patterns 3 and 4, work unchanged in Claude Code, Codex and Cursor. Only the headless piping in patterns 1 and 5 differs by tool, which is why only those steps carry tabs. ## Pattern 3: Find a memory leak from heap snapshots Heap usage that climbs until the process restarts is a retention problem, and retention is visible in two heap snapshots taken under the same load. Collect the evidence with Node's own tooling, then hand the agent the retainers, not the phrase "it leaks". 1. **Start the service with snapshots on a signal.** `--heapsnapshot-signal` writes a `.heapsnapshot` file to the working directory each time the process receives the signal: ```bash # Terminal node --heapsnapshot-signal=SIGUSR2 dist/server.js & # run warm-up load until heap usage is steady, then: kill -USR2 $! # snapshot 1 # run the same load for 30 minutes, then: kill -USR2 $! # snapshot 2 ``` Writing a snapshot blocks the event loop and needs roughly as much extra memory as the heap itself, so on a service already near its memory limit it can trigger the very restart you are chasing. Take the snapshots on one instance drained from the load balancer, or in staging under the same load, and leave memory headroom. 2. **Compare the snapshots.** Load both into Chrome DevTools (**Memory** tab), select the second, and switch the view to **Comparison**. Sort by size delta and copy the top 10 constructors with their retainer paths. 3. **Give the agent the diff and ask for the retention path.** **Copy-paste prompt: explain a heap-snapshot diff** ```text Two heap snapshots of our Express service, 30 minutes apart under constant load. Retained size grew about 100 MB. Top of the Comparison view, with retainer paths: Name the object that keeps these alive and the code path that adds to it without removing. Quote the lines. Propose the smallest cleanup (an unsubscribe, a bounded cache, a removed listener), not a redesign. Then write scripts/soak-leak.mjs: run the leaking operation 10,000 times, call global.gc() before taking the baseline and again after the loop, then exit 1 if heapUsed grew more than 10 MB. The script must fail on the current code. ``` 4. **Run the soak script before and after the fix.** It needs `--expose-gc` for `global.gc()`: `node --expose-gc scripts/soak-leak.mjs`. A plain Node script avoids the question of whether your test runner's worker processes inherit the flag. The usual cause is an unbounded collection: listeners, timers or cache entries that are added per request and never removed. The fix is a release path that callers actually invoke, and the soak script, run in CI, is what shows they keep doing it. ## Pattern 4: Reproduce a race condition with a failing test A race fixed without a failing test is a race you hope you fixed. Make the agent write a concurrent test that fails on the current code, then implement the smallest guard that turns it green. **Copy-paste prompt: race condition to failing test** ```text Customers are charged twice when they double-click Pay, on roughly 5% of checkouts under load. Write a Vitest test that fires 5 concurrent processPayment calls with the same idempotency key and asserts that exactly one charge reaches the payment gateway mock and the other four reject with ConflictError. Run it and show me it fails on the current code. Then implement the smallest guard that makes it pass. We run 4 instances behind a load balancer, so an in-memory lock is not enough: use the database. Pass the idempotency key to the gateway call too, so a retry after a timeout cannot create a second charge. ``` The last two sentences of that prompt carry the lesson. Without them, the obvious guard is an in-memory `Map` keyed on the user ID, which passes a single-process test and still double-charges once two instances receive the two clicks. A guard that survives several instances looks like this: ```typescript async processPayment(key: string, payment: Payment) { // INSERT ... ON CONFLICT (idempotency_key) DO UPDATE SET status = 'pending' // WHERE payment_attempts.status = 'failed' // against a unique index on idempotency_key: // only one instance can claim the key, however many receive the click const claimed = await db.paymentAttempts.insertIfAbsent({ idempotencyKey: key, status: 'pending' }); if (!claimed) throw new ConflictError('Payment already processing'); try { const charge = await gateway.charge(payment, { idempotencyKey: key }); await db.paymentAttempts.update(key, { status: 'done', chargeId: charge.id }); return charge; } catch (err) { // release the claim, or a gateway error leaves it 'pending' and every retry gets ConflictError await db.paymentAttempts.update(key, { status: 'failed' }); throw err; } } ``` The `catch` branch matters as much as the claim: without it, one gateway timeout locks that key for good. `insertIfAbsent` must treat a `failed` row as claimable again. Releasing the claim is only safe because the key also reaches the gateway: a timeout does not tell you whether the charge went through, and a gateway that deduplicates on the same key turns the retry into a lookup instead of a second charge. If your gateway has no idempotency key, leave the row `pending` and reconcile it against the gateway before allowing a retry. The test suite needs a second case where the gateway mock throws once and the retry succeeds. Run the test at least 20 times in a loop, as in pattern 1. A concurrency test that passes once proves little. ## Pattern 5: Rebuild a cross-service timeline by request ID When a request crosses services, no single log explains the failure; the explanation is in the gaps between hops. Stamp a request ID at the edge, collect every hop's logs, and have the agent rebuild the timeline. ```bash # Terminal. Collect one hour of logs from each hop (adjust to your platform) for app in api-gateway order-service payment-service; do kubectl logs -l app=$app --since=1h --timestamps --tail=-1 | sed "s/ / [$app] /" > $app.log done grep -h "req_7f3a2c" *.log | sort | claude -p --permission-mode plan \ "Rebuild the timeline for request req_7f3a2c across these services. Flag the longest gap." ``` The `sed` tags each line with its service right after the timestamp, so `sort` still orders by time and the agent can see which hop emitted each line. `--tail=-1` matters: with a label selector, `kubectl logs` returns only the last 10 lines per pod unless you set `--tail`, and the agent would rebuild the timeline from missing data without any warning. Production logs carry user data and user-controlled strings: redact emails, tokens and IDs first (for example, pipe them through a `sed` filter), and keep the run read-only, as here, because log lines can contain text that reads like instructions. The same applies to `[AUTH-DEBUG]` lines captured from staging or production in pattern 1. For Codex, replace the last command with `codex exec -s read-only` and the same prompt. In Cursor, attach the three files with `@` in Plan Mode. **Copy-paste prompt: cross-service timeline** ```text Attached are logs from api-gateway, order-service and payment-service, each line with a timestamp, the service name in brackets and a requestId. For requestId req_7f3a2c, list every event across the three services in time order with the milliseconds since the previous event. Mark the longest gap and name the service that owns it. Then list the log lines from that service in the same window for other requestIds: is the gap specific to this request or shared (a pool, a lock, a downstream timeout)? No fix yet. ``` A timeline turns "checkout is slow sometimes" into "payment-service waited 5 s for a database connection because the pool was exhausted by a batch job". If your services export OpenTelemetry spans, give the agent the trace instead of text logs: the prompt works unchanged, and the parent-child structure removes the guesswork about ordering. Wiring the traces and alerts themselves is covered in [monitoring and logging patterns](/en/cookbook/devops-recipes/monitoring-logging/). ## How do you prove a bug fix without reading every line? A reviewer should approve a bug-fix pull request on evidence, and read code only where the evidence is missing or surprising. Require these items in the pull request description: | Evidence | What it proves | Who produces it | | --- | --- | --- | | The reproduction (test or loop) and its output **before** the fix | The agent reproduced the reported bug, not a neighbour of it | The agent, checked by the developer | | The same reproduction **after** the fix, including the run count | The cause is gone, not just less frequent | The agent | | Full test suite, type check and lint green in CI | Nothing else broke | CI | | The diagnosis in two sentences: cause, and the evidence for it | The fix addresses the cause, not the symptom | The developer | | A second-agent review of the diff against that diagnosis | Side effects a tired author misses | A separate review run | | The error rate or metric after deploy, for one traffic peak | The fix held in production | The developer who shipped it | The built-in reviewers give you a general pass with no diagnosis: `/code-review` in a Claude Code session, `codex exec review --uncommitted` in the terminal, or Bugbot on the pull request in Cursor. In Codex, custom instructions and a diff target are mutually exclusive: `codex exec review ""` with no target flag takes your instructions, but `codex exec review --uncommitted ""` fails with "the argument '--uncommitted' cannot be used with '[PROMPT]'" (checked against codex-cli 0.157.1). To review the fix against the diagnosis, pipe the diff into a fresh read-only headless session with the prompt below: `git diff | claude -p --permission-mode plan ""` or `git diff | codex exec -s read-only ""` (or `codex exec review ""` without a target flag). In Cursor, paste the prompt into Plan Mode. **Copy-paste prompt: review a bug fix against its diagnosis** ```text Review this diff as a bug fix. The diagnosis: . Check three things and answer each with file:line evidence: (1) does the diff change the code path the diagnosis names, (2) does it hide errors anywhere (optional chaining that swallows a bug, empty catch, a default value for required data, a skipped or loosened test), (3) does the new test fail if the fix is reverted? Report findings only; do not edit. ``` Sign-off: the developer who ran the hunt owns the evidence; the reviewer, usually the tech lead for an incident fix, approves when every row is present. The agent must not edit the reproduction test to make it pass. [Protecting the oracle](/en/workflows/test/protect-the-oracle/) shows how to make that mechanically impossible rather than a matter of trust. ## What goes wrong when an agent debugs for you? **Failure modes of agent-assisted debugging** - **A plausible but wrong root cause.** With thin evidence, the agent names a cause that fits the symptom. Recovery: ask for confidence and the supporting log lines, and accept no fix until a reproduction fails on the unfixed code. - **The fix silences the symptom.** Optional chaining, empty `catch` blocks or a retry make the error vanish from the logs. Recovery: the review prompt above checks for exactly this; reject the fix and send the agent back to the "should never happen" or "expected sometimes" classification. - **The agent edits the test.** A reproduction that was red turns green because an assertion was loosened. Recovery: `git diff` the test file separately, and keep reproduction tests in a path the agent cannot write to. - **The instrumentation hides the bug.** Synchronous logging changes timing, and the race stops reproducing. Recovery: log to an in-memory buffer and flush it after the request, or log fewer fields. - **Log noise drowns the signal.** "Add logging everywhere" produces megabytes the agent cannot correlate. Recovery: scope logging to the suspect path and a single grep-able prefix, as in pattern 1. - **Fix after fix, no progress.** Three failed fixes in a row usually mean a wrong model of the system, not bad luck. Recovery: stop editing, start a fresh session with only the evidence, and ask for three ranked hypotheses and the observation that would rule each one out. - **Stale context.** After a long session, the agent reasons about code that has changed since. Recovery: start a new session, or rerun the headless command against the current checkout, before you trust its analysis. ## Where to go next with debugging - Start from the section overview: [error handling recipes](/en/cookbook/error-handling-recipes/). - Tool-specific debugging loops: [Claude Code in the terminal](/en/claude-code/test/debugging/), [Codex across its surfaces](/en/codex/test/bug-hunting/), and [Cursor's Plan Mode and Agent mode](/en/cursor-ide/test/bug-hunting/). - Make every production error a test first: [error-driven development](/en/method/principles/error-driven-development/). - Next in this section: [logging patterns](/en/cookbook/error-handling-recipes/logging-patterns/) for the structured logs these prompts need, then [recovery patterns](/en/cookbook/error-handling-recipes/recovery-patterns/) for retries and graceful degradation once you know the cause. --- # Logging Patterns URL: https://developertoolkit.ai/en/cookbook/error-handling-recipes/logging-patterns/ Description: Agent recipes that turn console.log into structured, correlated, redacted Node.js logs, proven by a log-contract test, a secret canary and a lint gate. Logging patterns for AI agents are four recipes that have Claude Code, Codex or Cursor turn scattered `console.log` calls into structured JSON logs from one maintained library, with a request ID on every line and secrets redacted by configuration. Each recipe ends in a machine check (a log-contract test, a secret canary and a lint rule), so nobody reviews every call site by eye. This page is for developers who own a Node.js service and for tech leads who decide what a logging pull request must prove. Your API throws intermittent 500s, the logs are interpolated strings, and you cannot follow one request through three services. Asked to "add logging", an agent sprinkles `logger.info` calls with no schema. The recipes below give it a contract to meet instead. ## What you get from these logging recipes - A log contract written as a test before the agent touches a call site, so "structured" and "redacted" are pass or fail - Five copy-paste prompts: write the log contract, convert `console.*`, add request correlation with `AsyncLocalStorage`, audit for secrets and personal data, and review the finished pull request - Exact commands to run each pass with Claude Code and Codex, and the Cursor equivalent - A lint rule that stops `console.log` from coming back the week after the refactor - The ways agent-written logging passes review and fails in production, with a recovery for each ## Which logging pass comes first? Run the work as four small passes, not one "add logging" request. Each pass has its own check, and the next one starts only when the check is green. | Pass | What the agent changes | Check that proves it | | --- | --- | --- | | 1. Log contract | `src/lib/logger.ts` and one test file | Contract test green, and red when one redact path is removed | | 2. Convert | Every `console.*` call site | Contract test green, `no-console` lint at zero | | 3. Correlate | Middleware plus the logger's context hook | A test logs from a function that never sees `req` and finds the `requestId` | | 4. Audit | Nothing at first: a findings table | Canary test green, findings table empty or triaged | The same passes work in Python (`structlog` with `contextvars`) and Go (`log/slog` with `context.Context`). The examples use Node.js and TypeScript. ## Should the agent use pino or winston? Pick the library in the prompt. Left to choose, an agent often writes its own `Logger` class with transports and levels, which you then maintain. Both libraries below are maintained (npm latest on 2026-09-26: `pino` 10.3.1, `winston` 3.19.0). | Need | pino | winston | | --- | --- | --- | | JSON output by default | Yes | With `format.json()` | | Redaction | Built in: `redact: { paths, censor }`, path-based | A custom `format` you write | | Per-request context on every line | `mixin()` option, called for each log call | A custom `format` that reads the context | | Many transports (files, HTTP, syslog) | `pino.transport()`, which runs transports in a worker thread | Wide transport ecosystem, configured in one place | | Call signature | `logger.info({ userId }, 'User login')`: object first | `logger.info('User login', { userId })`: message first | The default in this page is pino, because redaction and per-line context are configuration rather than code. Choose winston when the service already uses it or needs several transports configured together. The call-signature row matters more than it looks: see the failure modes below. ## Write the log contract as a test first The contract is what makes the rest provable. It pins the fields every line must carry and plants canary secrets that must never reach the output. Ask the agent to write it before anything else. Then prove the test can fail: remove one redact path, watch it go red, and restore the path. A contract that cannot fail proves nothing. The core of `src/lib/logger.ts` that the contract drives toward: ```ts import { AsyncLocalStorage } from 'node:async_hooks'; import pino, { type DestinationStream } from 'pino'; export const requestContext = new AsyncLocalStorage<{ requestId: string; userId?: string }>(); export function createLogger(destination?: DestinationStream) { return pino( { level: process.env.LOG_LEVEL ?? 'info', base: { service: 'api-gateway', version: process.env.APP_VERSION }, timestamp: pino.stdTimeFunctions.isoTime, redact: { paths: ['*.password', '*.token', '*.apiKey', '*.headers.authorization', '*.headers.cookie'], censor: '[REDACTED]', }, mixin: () => requestContext.getStore() ?? {}, }, destination, ); } export const logger = createLogger(); ``` And the contract test, in the project's existing runner (Vitest shown): ```ts import { Writable } from 'node:stream'; import { expect, it } from 'vitest'; import { createLogger, requestContext } from '../src/lib/logger'; function capture() { const lines: string[] = []; const sink = new Writable({ write(chunk, _enc, done) { lines.push(chunk.toString()); done(); }, }); return { log: createLogger(sink), lines }; } it('emits JSON with a constant message and no canary secrets', () => { const { log, lines } = capture(); log.info({ user: { id: 'u1', password: 'CANARY-pw' }, req: { headers: { authorization: 'Bearer CANARY-tok' } } }, 'User login'); expect(lines.join('')).not.toContain('CANARY'); expect(JSON.parse(lines[0])).toMatchObject({ msg: 'User login', service: 'api-gateway' }); expect(JSON.parse(lines[0]).user.id).toBe('u1'); }); it('carries the requestId across an async boundary', async () => { const { log, lines } = capture(); await requestContext.run({ requestId: 'req-test-1' }, async () => { await new Promise((resolve) => setTimeout(resolve, 5)); log.info('Downstream call'); }); expect(JSON.parse(lines[0]).requestId).toBe('req-test-1'); }); ``` The `CANARY-` prefix is the trick: one `not.toContain` covers every field, however deeply the agent nests it. Add a canary for each kind of secret the service handles. The redact paths above cover one level of nesting; the two-level canary in the prompt below forces the agent to add deeper paths such as `*.*.password`, or to stop logging the parent object. Both the logger and the test ran as shown against pino 10.3.1 and Node.js `AsyncLocalStorage`. Install the library yourself first (`npm install pino`), so no pass needs network access. Then run the contract prompt. **Copy-paste prompt: write the log contract first** ```text Do not install packages and do not touch any console.* call. Create src/lib/logger.ts exporting createLogger(destination?) and a default logger, using pino (already in package.json). Requirements: JSON output, ISO timestamps, level from LOG_LEVEL (default info), base fields service="api-gateway" and version=APP_VERSION, redact paths for password, token, apiKey, and the authorization and cookie headers with censor "[REDACTED]", and a mixin that merges the store of an exported AsyncLocalStorage named requestContext. Then write tests/logger.contract.test.ts that captures output through a Writable and asserts: (1) no "CANARY" string survives when I log objects containing canary passwords, tokens, API keys and an Authorization header, at one and two levels of nesting; (2) msg is the constant message I passed; (3) a log call made inside requestContext.run() after an await and a setTimeout carries the requestId. Run the tests and show me the output. Then remove the password redact path, rerun, show that the canary assertion fails, and restore the path. Do not write your own logger class. ``` Read the test, not the logger. If the assertions match the requirements above, the logger either passes them or does not. ## Convert console.log to structured logs across the repository With the contract green, the conversion is a mechanical multi-file refactor. The prompt is the same for every tool; how you run it differs. **Claude Code** ```bash # Terminal, repository root. Flags checked against Claude Code 2.1.283; the # v2.1.285 change is from the Claude Code changelog (checked 2026-10-12). # claude -p starts in Manual mode (auto mode on third-party providers or with # telemetry off, from v2.1.285); --permission-mode dontAsk denies anything that # would prompt, on every provider. Reads and read-only commands still run. claude -p "$(cat prompts/convert-logging.txt)" \ --permission-mode dontAsk \ --allowedTools "Read" "Edit" "Write" "Bash(npm test:*)" "Bash(npx eslint:*)" ``` Save the conversion prompt below as `prompts/convert-logging.txt`. The allowlist lets the agent edit files and run the tests and the linter, and nothing else: no `git push`, no package installs. **Codex** ```bash # Terminal, repository root. Checked against codex-cli 0.157.1. # Permission profiles are beta (Codex CLI 0.138.0 or later). codex exec -c default_permissions=":workspace" "$(cat prompts/convert-logging.txt)" ``` The `:workspace` profile lets Codex write inside the repository only. On a Codex version without permission profiles, use `--sandbox workspace-write` instead; do not combine the two. For a large repository, run the same prompt as a Codex cloud task and review the result as a pull request. **Cursor** Add a project Rule first: "Never use `console.*` in `src/`. Import `logger` from `src/lib/logger.ts`. pino signature: object first, message second." The rule keeps later agent sessions from reintroducing `console.log`. Then paste the conversion prompt into the Agent, review the multi-file diff before accepting, and run `npm test` in the terminal. For a large repository, hand the same prompt to a Cloud Agent and review its pull request. **Copy-paste prompt: convert console.* to structured logging** ```text Replace every console.log, console.info, console.warn and console.error in src/ with the logger from src/lib/logger.ts. Rules: - pino signature: logger.info({ fields }, 'Constant message'). Never interpolate values into the message; every dynamic value goes in the object. - Errors: logger.error({ err }, 'Message') so the stack is serialized. - Levels: handled validation or 4xx paths are warn, unhandled or 5xx paths are error, per-item loops and payload dumps are debug. - Never log a whole request body, response body, or headers object. Log the fields you need by name. - Do not change src/lib/logger.ts or the contract test. When done, add "no-console": "error" to the ESLint rules, then run npm test and npx eslint src/. Both must pass. List any call site where you were unsure whether a field is sensitive. ``` Three things to check in the summary, not in every file: the tests and the linter are green, the list of uncertain fields is short enough to decide on in a few minutes, and both searches below print nothing: ```bash # Terminal, repository root git grep -n "console\." src/ # leftover console calls git grep -nE "logger\.[a-z]+\([^)]*\`" src/ # messages built with template literals ``` ## Add request correlation that survives async boundaries A `requestId` stored on `req` disappears the moment a service function does not take `req`. `AsyncLocalStorage` fixes that: middleware stores the context once, and the logger's `mixin` reads it from anywhere in the call stack. Agents default to threading `req.logger` through function arguments, so name the mechanism in the prompt. **Copy-paste prompt: request correlation with AsyncLocalStorage** ```text Add Express middleware in src/middleware/request-context.ts. For each request, read the x-request-id header (generate one with crypto.randomUUID() when absent), set it on the response header, and run the rest of the chain inside requestContext.run({ requestId, userId: req.user?.id }, next). Log request start and completion with method, route pattern (not the raw URL), status code and duration in ms. Register it before every other middleware. Do not pass loggers or req through function arguments. Then extend tests/logger.contract.test.ts with a supertest case (supertest is already a devDependency): call one route whose service function logs from inside a Promise and a setTimeout, and assert every captured line for that request carries the same requestId as the response header. Run npm test and show the output. ``` Install `supertest` as a devDependency yourself before this pass if the project lacks it. The supertest case is the proof. An implementation that only works on the synchronous path fails it, which is the version that loses the ID in production. Log the route pattern (`/users/:id`) rather than the raw URL: raw URLs carry IDs, emails and tokens in query strings. If the service already exports OpenTelemetry traces, `@opentelemetry/instrumentation-pino` (npm latest 0.68.0 on 2026-09-26) adds `trace_id` and `span_id` to each log line, so logs and traces join in your backend. Carrying those fields through the log pipeline is covered in [monitoring and logging patterns](/en/cookbook/devops-recipes/monitoring-logging/). ## Audit logs for secrets and personal data Path-based redaction catches the keys you listed. It does not catch an email in a message string, an IP address, or a token under a key nobody thought of. Emails and IP addresses are personal data under the GDPR, which turns a harmless-looking `info` line on every login into a retention and erasure problem. Run the audit read-only, so the agent reports before it edits. **Claude Code** ```bash # Plan mode keeps the run read-only claude -p --permission-mode plan "$(cat prompts/audit-logging.txt)" > log-audit.md ``` **Codex** ```bash codex exec -c default_permissions=":read-only" "$(cat prompts/audit-logging.txt)" > log-audit.md ``` **Cursor** Switch to Plan Mode, paste the audit prompt, and save the table it returns. Plan Mode produces a plan instead of edits. **Copy-paste prompt: audit logging for secrets and personal data** ```text Do not edit any file. Scan every logger.* call in src/ and the redact paths in src/lib/logger.ts. Report, as a Markdown table with file, line, field, risk and fix: - whole request or response bodies, header objects, or query strings being logged - tokens, API keys, session IDs or credentials under any key name, including ones the redact paths miss (check nesting depth: *.password only matches one level down) - emails, IP addresses, names, phone numbers, card-number or national-ID shaped values - personal data interpolated into the message string, where redaction cannot reach it For each finding pick one fix: drop the field, replace it with a salted hash or an internal ID, or move it to a separate audit log with its own retention. Finish with the canary strings I should add to tests/logger.contract.test.ts. ``` Triage the table, then send the fixes back as a normal edit pass with the new canaries added to the contract test. The audit is done when the canary test is green and every row in the table is fixed or accepted by name. For the policy side (which data may be logged at all and for how long), see [privacy and data handling](/en/org/privacy-data-handling/). ## How do you prove the logging refactor without reading every call site? A logging pull request touches dozens of files. Review the evidence instead of the diff: 1. **Contract test**: green, and shown to go red when a redact path is removed. It covers JSON shape, constant messages, redaction canaries and `requestId` propagation across `await` and `setTimeout`. 2. **Lint gate**: `no-console` is `error` in the linter config and runs in CI, so the rule outlives this pull request. 3. **Searches with empty output**: the two `git grep` commands from the conversion pass. 4. **One real line**: start the service locally, send one request, and paste one log line into the pull request description. A reviewer checks the fields in seconds. 5. **Audit table**: attached, with each row fixed or accepted. The author signs off on steps 1–4. Whoever owns data protection for the service accepts or rejects the remaining audit rows. For a reusable review prompt, ask the agent to check the finished diff against this list: **Copy-paste prompt: review a logging pull request** ```text Review the current branch against main as a logging change. Do not edit files. Report pass or fail, with file and line for each fail: 1. Any console.* left in src/? 2. Any log message built with a template literal or string concatenation? 3. Any logger call with the message first and the object second (winston order)? 4. Any whole body, headers object or raw URL logged? 5. Any catch block that logs at info or swallows the error without logging it? 6. Is no-console set to error in the lint config? End with the single riskiest line in the diff. ``` ## What breaks when an agent rewrites your logging? - **The metadata silently disappears.** An agent used to winston writes `logger.info('User login', { userId })` against pino. pino reads the second argument as a format parameter, so `userId` is not recorded as a structured field. Recovery: `git grep -nE "logger\.[a-z]+\('[^']*', *\{" src/` lists every call in winston order, and the review prompt checks argument order in the diff. The contract test only guards the logger configuration: it asserts `user.id` survives, so a redact path that is too broad goes red, but it calls the logger directly and cannot see a call site. - **Redaction misses nested secrets.** pino redact paths are exact: `*.password` matches `user.password` but not `body.user.password`. Recovery: canaries at two nesting levels in the contract test, and add deeper paths (or stop logging the parent object) when one leaks. - **A whole body sits under a safe-looking key.** `logger.debug({ payload: req.body })` bypasses every key-based rule, and someone turns on `debug` in production during an incident. Recovery: the conversion prompt forbids whole bodies; the review prompt checks for them. - **The `requestId` vanishes in queue workers and timers.** Context stored in `AsyncLocalStorage` does not cross a process boundary. A job picked up by a worker has no store. Recovery: put the `requestId` in the job payload and call `requestContext.run()` at the top of the worker handler. - **Every line became `info`.** The refactor flattened levels, so an error-rate alert either never fires or fires on every request. Recovery: rerun the conversion prompt's level rules on the affected files only, then check that the error rate from logs matches the 5xx rate from your metrics. - **Logging adds latency on the request path.** A synchronous write to a slow destination blocks the request. Recovery: write JSON to stdout and let the platform ship it, or use `pino.transport()`, which runs the transport in a worker thread. Never `await` a log write in a handler. - **The agent guesses the library's API.** It writes an option from another major version, or a winston idiom into pino config, and the result looks plausible in review. Recovery: connect the Context7 MCP server so the agent reads the docs for the installed version (setup for all three tools on [Context7](/en/ecosystem/mcp/context7/)), and keep the contract test as the arbiter. ## Where to go next with logging - [Debugging patterns](/en/cookbook/error-handling-recipes/debugging-patterns/): use these structured logs to correlate failing and passing requests - [Monitoring and logging patterns](/en/cookbook/devops-recipes/monitoring-logging/): carry `trace_id` through the log pipeline and alert on what the logs now emit - [Recovery patterns](/en/cookbook/error-handling-recipes/recovery-patterns/): what the service does when the errors you now log actually fire - [Observability MCP servers](/en/ecosystem/mcp/observability-mcp/): let the agent query production logs and errors read-only - [Error handling recipes](/en/cookbook/error-handling-recipes/): the rest of this section --- # Recovery Patterns URL: https://developertoolkit.ai/en/cookbook/error-handling-recipes/recovery-patterns/ Description: Agent recipes for circuit breakers, retries and fallbacks built on opossum and cockatiel, proven by a contract test that trips the breaker on purpose. Recovery patterns for AI agents are recipes that have Claude Code, Codex or Cursor protect one flaky dependency with a maintained library (opossum, cockatiel, Resilience4j or tenacity) instead of a hand-written state machine: a circuit breaker, a retry that cannot amplify an outage, and an ordered fallback. A contract test that trips the breaker on purpose proves each one. This page is for developers who own a service with a fragile downstream call and for tech leads who decide what a resilience pull request must prove. Your payment provider has a 90-second outage at 2 a.m. Every checkout request waits on the dead dependency, the connection pool drains, and the whole app falls over, not only payments. Asked to "add a circuit breaker", an agent writes 200 lines of `class CircuitBreaker` that nobody tests. The recipes below give it a named library, a named call and a test to pass instead. ## What you get from these recovery recipes - A resilience contract written as a test before the agent changes the call, so "the breaker opens" and "a 400 never retries" are pass or fail - Five copy-paste prompts: the contract test, an opossum circuit breaker, a cockatiel retry nested around a breaker, a read-path fallback, and a review of the finished diff - Exact commands to run the work with Claude Code and Codex, and the Cursor equivalent - A Sentry MCP loop that picks the call to protect from production evidence rather than a guess - The ways agent-written resilience code passes review and amplifies an outage, with a recovery for each ## Which recovery pattern does this call need? Decide per call, not per service. The pattern depends on whether the call is a read or a write and whether a repeat is safe. | Call | Pattern | Node library | Check that proves it | | --- | --- | --- | --- | | Slow or dead dependency on the request path | Circuit breaker with a timeout and a fallback | [opossum](https://www.npmjs.com/package/opossum) 10.0.0 | Breaker opens after N failures, fallback runs, half-open probe closes it | | Idempotent read (`GET`, lookup by ID) | Retry with jittered backoff, nested around a breaker | [cockatiel](https://www.npmjs.com/package/cockatiel) 4.0.0 | 5xx retries, 4xx never retries, total calls capped | | Non-idempotent write (`POST /charge`) | Breaker and a queue; **no blind retry** | opossum plus your job queue | The same idempotency key reaches the provider on every attempt | | Read with a degraded answer available | Ordered fallback: primary, replica, cache, default | Plain async functions | A `404` propagates; only infrastructure errors fall through | Versions are the npm `latest` tags checked on 2026-09-26. On the JVM, name [Resilience4j](https://resilience4j.readme.io/) and its Spring Boot `@CircuitBreaker(name = ..., fallbackMethod = ...)` annotation. On Python, name `tenacity` (9.1.4) for retries and `pybreaker` (1.4.1) for the breaker. Naming the library is what stops the agent from writing its own. ## Write the resilience contract as a test first A circuit breaker you have never tripped in a test is a circuit breaker you debug during an incident. Write the contract first, watch it fail against the unprotected call, and only then let the agent change the code. The contract is the thing a reviewer reads instead of the diff. The test drives the breaker through a factory that accepts option overrides. That design choice matters: the test passes `resetTimeout: 50` and uses real timers, because fake timers can stall the async I/O of an HTTP stub and hang the test. **Copy-paste prompt: write the resilience contract first** ```text Write tests/payment.resilience.test.ts with vitest. Do not change any file in src/. The module under test will be src/lib/payment-breaker.ts exporting createPaymentBreaker({ charge, enqueue }, overrides), which returns an opossum CircuitBreaker fired as breaker.fire(order, idempotencyKey). Stub charge and enqueue with vi.fn(); no network, no fake timers. Create the breaker with overrides { volumeThreshold: 5, resetTimeout: 50, timeout: 100 }. Fire calls one after another, awaiting each. Cases: 1. 10 calls where charge rejects with { status: 503 }: every result is { status: 'queued' }, breaker.opened is true, charge was called fewer than 10 times. 2. 10 calls where charge rejects with { status: 400 }: every call rejects with the 400, breaker.opened is false, the fallback never ran. 3. charge never resolves: the call resolves to { status: 'queued' } within 200 ms. 4. Open the breaker as in case 1 (same breaker instance within this test), wait 60 ms, make charge resolve, fire once: breaker.closed is true. 5. The idempotency key passed to charge is identical to the one in the job the fallback enqueues. 6. One call where charge never resolves, then one where it resolves: the second charge receives a signal that is not aborted, and the call returns its result. Run the tests and confirm they fail only because src/lib/payment-breaker.ts does not exist yet. Report the failure output. ``` Cases 5 and 6 are the ones agents skip. An opossum timeout rejects the call and runs the fallback, but it does not cancel the request, so the provider can still complete a charge that your code has already sent to the fallback queue. opossum can abort through an `AbortController`, but in opossum 10.0.0 that controller is shared by the whole breaker: one timeout aborts every charge in flight, and `autoRenewAbortController` renews it only when the breaker half-opens or closes, so later calls start with an already-aborted signal. Case 6 catches that; a signal created per call passes it. Even an aborted request may have reached the provider, so the idempotency key is what makes the queued retry harmless. ## Wrap the flaky call in a circuit breaker With the contract red, the implementation is a small, bounded change. The prompt is the same for every tool; how you run it differs. **Claude Code** ```bash # Terminal, repository root. Flags checked against Claude Code 2.1.283; the # v2.1.285 change is from the Claude Code changelog (checked 2026-10-12). # claude -p starts in Manual mode (auto mode on third-party providers or with # telemetry off, from v2.1.285); --permission-mode dontAsk denies anything that # would prompt, on every provider. Reads and read-only commands still run. claude -p "$(cat prompts/payment-breaker.txt)" \ --permission-mode dontAsk \ --allowedTools "Read" "Edit" "Write" "Bash(npm test *)" ``` Save the breaker prompt below as `prompts/payment-breaker.txt`. Install `opossum` yourself first, so the agent needs no network access and cannot add packages. The `Bash(npm test *)` rule does not limit what the tests run: `npm test` executes whatever `package.json` says, and `Write` can change that file. Review any change to `package.json` in the diff, or add `--disallowedTools "Edit(package.json)" "Write(package.json)"`. **Codex** ```bash # Terminal, repository root. Checked against codex-cli 0.157.1. # Permission profiles are beta (Codex CLI 0.138.0 or later). codex exec -c default_permissions=":workspace" "$(cat prompts/payment-breaker.txt)" ``` The `:workspace` profile lets Codex write inside the repository only. On a Codex version without permission profiles, use `--sandbox workspace-write` instead; do not combine the two. To get the change as a pull request rather than local edits, run the same prompt as a Codex cloud task. **Cursor** Open `src/routes/checkout.ts` and the contract test side by side, paste the breaker prompt into the Agent, and review the diff before you accept it. Run `npm test` in the terminal afterwards. When the flaky call lives in a service you do not want to edit locally, hand the same prompt to a Cloud Agent and review its pull request. **Copy-paste prompt: wrap a payment call in an opossum circuit breaker** ```text Make tests/payment.resilience.test.ts pass. Do not edit the test. Create src/lib/payment-breaker.ts exporting createPaymentBreaker({ charge, enqueue }, overrides) that returns an opossum CircuitBreaker (opossum is installed; do not write your own breaker class, state machine or semaphore). Defaults: timeout 3000, errorThresholdPercentage 50, volumeThreshold 20, resetTimeout 30000, name 'payments.charge'. Do not use opossum's abortController, autoRenewAbortController or getSignal(): that controller is shared by the whole breaker, so one timeout would abort every charge in flight. The wrapped function takes (order, idempotencyKey) and calls charge(order, key, { signal: AbortSignal.timeout(2500) }), so each call cancels only its own request; opossum's timeout stays above it as a backstop. errorFilter: return true for 4xx errors, so they neither count toward opening nor trigger the fallback. Fallback: enqueue('payments', { order, idempotencyKey }) and return { status: 'queued' }. The route generates the idempotency key once per order and fires breaker.fire(order, key). On 'open', 'halfOpen' and 'close', log the transition at warn with the breaker name and increment the metric circuit_breaker_state_change{name,state}. Wire src/routes/checkout.ts to the breaker without changing the route's response shape. Run npm test until it passes and list every default you chose that is not in this prompt. ``` The result should be short. With opossum it is configuration, a filter and a fallback, with no state machine in sight: ```typescript import CircuitBreaker from 'opossum'; export function createPaymentBreaker({ charge, enqueue }: PaymentDeps, overrides = {}) { const breaker = new CircuitBreaker( // A signal per call: aborting it cancels this charge and no other (order: Order, key: string) => charge(order, key, { signal: AbortSignal.timeout(2500) }), { name: 'payments.charge', timeout: 3000, // backstop above the per-call abort errorThresholdPercentage: 50, volumeThreshold: 20, // never open on a handful of requests resetTimeout: 30000, errorFilter: (err: HttpError) => err.status >= 400 && err.status < 500, ...overrides, }, ); // opossum calls the fallback with the same arguments, so the key is reused breaker.fallback(async (order: Order, key: string) => { await enqueue('payments', { order, idempotencyKey: key }); return { status: 'queued' as const }; }); for (const state of ['open', 'halfOpen', 'close'] as const) { breaker.on(state, () => recordBreakerState(breaker.name, state)); } return breaker; } // In the route: breaker.fire(order, order.idempotencyKey) ``` opossum 10.0.0 ships no TypeScript types, and `@types/opossum` is at 8.1.9 (both checked 2026-09-26). An option that is newer than the types, such as `coalesce`, fails type checking even though opossum reads it. Tell the agent to extend the type locally rather than casting the whole options object to `any`. ## Add retries that cannot amplify an outage Naive retries multiply load during a partial outage: three retries on every client is a self-inflicted traffic spike on a dependency that is already struggling. Two rules prevent it. Jittered backoff stops clients from retrying in lockstep, and a strict predicate stops a `400` or a non-idempotent `POST` from being retried at all. Nest the retry **outside** the breaker, so every retry counts toward the breaker's failure rate and a sustained outage opens it. cockatiel does this in one line with `wrap(retryPolicy, breakerPolicy)`. One detail breaks the combination: if the breaker has a fallback, the retry never sees a failure and never retries. Put the fallback outside both. **Copy-paste prompt: jittered retry around a breaker for an idempotent read** ```text In src/lib/inventory.ts, protect getStock(sku), which calls fetch(inventoryUrl), with cockatiel (installed). Build: - retryPolicy = retry(handleWhen(isRetryable), { maxAttempts: 2, backoff: new ExponentialBackoff({ maxDelay: 4000 }) }). The default generator is decorrelated jitter; keep it. cockatiel's maxAttempts counts retries, so this is at most three calls in total. Say so in a comment. - breakerPolicy = circuitBreaker(handleWhen(isRetryable), { halfOpenAfter: 30000, breaker: new SamplingBreaker({ threshold: 0.5, duration: 10000, minimumRps: 5 }) }). - policy = wrap(retryPolicy, breakerPolicy). The retry is outermost. isRetryable returns true only for a response status of 500 or above, or an error code of ECONNRESET or ETIMEDOUT. It returns false for 4xx, AbortError and BrokenCircuitError. Convert a non-ok fetch Response into a thrown error that carries the status. Apply any fallback outside policy, never inside it. Add tests: a 503 twice then 200 returns the stock after exactly three calls; a 404 is called exactly once; after breakerPolicy.isolate(), no fetch is made. Run npm test. ``` Leave the payment write out of this recipe. `POST /charge` gets a breaker and a queue, and the queue worker retries with the same idempotency key. If your payment provider does not accept an idempotency key, do not retry the charge automatically at all. ## Degrade reads with an ordered fallback For reads, a fallback chain keeps the feature alive when the primary source is down: primary database, then read replica, then cache marked stale, then a safe default. Each tier must be labeled in the response, or you ship silent staleness. Keep it as an ordered list of async functions, not a `FallbackChain` framework. **Copy-paste prompt: ordered fallback for a read path** ```text Refactor getUserProfile(userId) in src/lib/users.ts into an ordered fallback: 1. primaryDb.getUser(userId) 2. on an infrastructure error, replicaDb.getUser(userId); log "serving from replica" at warn 3. on an infrastructure error, cache.get(`user:${userId}`) returned with stale: true 4. last resort { id: userId, name: 'User', limited: true } Infrastructure error means a timeout, a connection error or an open circuit. A NotFound, a validation error or an authorization error rethrows immediately from any tier: a missing user must never be served from the cache tier. Keep the UserProfile return type; add stale and limited as optional fields. Increment user_profile_fallback{tier} whenever a tier other than 1 answers. Add one test per tier plus one proving a NotFound from tier 1 is rethrown and the cache is never read. Run npm test. ``` The rethrow rule separates resilience from a bug factory. A fallback that swallows a legitimate `404` and serves a cached profile is worse than the outage it was meant to hide. ## Let production errors pick the call to protect Without production data, the agent guesses which call is flaky. Connect the Sentry MCP server and the agent reads the real issue (stack trace, event count, the failing span) before it proposes a breaker. Sentry's server is remote, so there is nothing to install; only the registration differs between tools. Full read-only setup, token options and scopes are on [Observability MCP servers](/en/ecosystem/mcp/observability-mcp/). **Claude Code** ```bash # Checked against Claude Code 2.1.283 claude mcp add -s project --transport http sentry https://mcp.sentry.dev/mcp claude mcp login sentry # or run /mcp inside a session ``` **Codex** ```bash # Checked against codex-cli 0.157.1 codex mcp add sentry --url https://mcp.sentry.dev/mcp codex mcp login sentry ``` **Cursor** Add the server to `.cursor/mcp.json` in the project, then approve it in Cursor's MCP settings: ```json { "mcpServers": { "sentry": { "url": "https://mcp.sentry.dev/mcp" } } } ``` On the OAuth screen, leave **Triage Issues** unchecked: the agent needs to read issues here, not resolve them. If you prefer a packaged skill to a bare server, Sentry's plugin (`sentry@claude-plugins-official`, or `codex plugin add sentry@openai-curated` for Codex, checked against 0.157.1 help; requires a signed-in Codex) bundles the same server with its `sentry-debug-issue` skill. Install one or the other, not both, or the server registers twice. Before the connection, "add a circuit breaker to checkout" produces a breaker around whatever call looks risky. After it: **Copy-paste prompt: let Sentry choose the call and the thresholds** ```text Using the Sentry MCP server, read only. Find the three unresolved issues in project checkout-api with the most events in the last 24 hours. For each, name the exact downstream call in the stack trace, the error type (timeout, 5xx, connection reset, 4xx) and the event count. Do not edit anything yet. Then recommend one pattern per call from: circuit breaker, retry, fallback, or none (4xx and validation errors get none). For any breaker, propose resetTimeout from the gap between the first and last event of the longest burst in the issue timeline. Quote the Sentry issue ID and event count so I can put them in a code comment above the breaker. ``` ## How do you prove recovery code works without reading every line? A resilience pull request is small, but its failure mode is invisible until an incident. Review the evidence, not the diff: 1. **Contract test**: red against the old code, green against the new. It covers opening, the `4xx` filter, the timeout, the half-open probe, the idempotency key and a call that follows a timeout. 2. **Retry count test**: asserts the exact number of calls for a `503`, a `404` and an open circuit. A retry policy with no count assertion fails silently: it passes every other test while multiplying load. 3. **Greps with empty output**: `git grep -nE "class [A-Za-z]*(CircuitBreaker|Retry|Backoff)" src/` returns nothing, so no hand-written state machine slipped in next to the library. 4. **Metric and alert**: `circuit_breaker_state_change` exists and an alert fires when a breaker stays open. Paste one real metric line from a local run into the pull request description. 5. **One staged fault**: before the first production rollout, inject the failure in staging with a proxy such as Toxiproxy and watch the breaker open on the dashboard. The method is on [error injection testing](/en/workflows/test/error-injection-testing/). The author signs off on steps 1–4 in the pull request. The service owner or on-call lead signs off on step 5 and on the thresholds, because they own the recovery time the thresholds encode. To check a finished diff against the list, run the review prompt in a fresh session: **Copy-paste prompt: review a resilience pull request** ```text Review the current branch against main as a resilience change. Do not edit files. Report pass or fail, with file and line for each fail: 1. Is every breaker, retry and timeout built from a library, with no custom class? 2. Is any 4xx, validation or auth error retried, counted toward a breaker, or caught by a fallback? 3. Is any retry nested inside a breaker instead of outside it, or is a fallback placed inside a retry? 4. Is any non-idempotent call (POST, PUT without a key, a charge, an email send) retried without an idempotency key? 5. Does every timeout cancel only its own underlying request, with a signal created per call rather than one shared by the breaker? 6. Does every breaker emit a state-change metric, and does a test assert the exact number of calls? End with the single threshold you would change first, and why. ``` ## What breaks when an agent writes resilience code? - **The breaker opens on a blip.** opossum's `volumeThreshold` defaults to 0, so with `errorThresholdPercentage: 50` one failure out of one request is enough to open the circuit. Recovery: set `volumeThreshold` to a request count that a normal quiet minute exceeds, and base `resetTimeout` on the dependency's observed recovery time (the Sentry prompt above), not on a round number. - **Retries turn a brownout into an outage.** A retry inside the breaker, or no breaker at all, lets every client keep hammering the dependency. Recovery: `wrap(retry, breaker)` with the retry outermost, a jittered backoff, and a test that asserts the total call count. - **The retry never fires.** A fallback registered on the breaker turns every failure into a success, so the retry around it has nothing to retry. Recovery: move the fallback outside the retry and breaker, and keep the retry count test. - **The fallback masks a real bug.** A fallback that catches everything converts `400`s, auth failures and missing records into quiet wrong answers. Recovery: opossum's `errorFilter` for `4xx`, an explicit `isRetryable` predicate for cockatiel, and a test that a `404` propagates. - **A timeout double-charges.** The breaker times out, the fallback queues the order, and the original request completes at the provider anyway. Recovery: give each call its own `AbortSignal.timeout()` a little below opossum's `timeout`, not the breaker's shared `getSignal()`, and send the same idempotency key on the original call and the queued one. - **The open breaker hides the outage.** With the fallback working, the user-facing error rate looks healthy and nobody is paged while a dependency is fully down. Recovery: alert on the breaker-state metric and on the fallback counter, not only on 5xx rates. Routing that alert is covered in [monitoring and logging patterns](/en/cookbook/devops-recipes/monitoring-logging/). - **The agent guesses the library's API.** Option names differ between opossum, cockatiel and older forks, and types can lag behind the package. Recovery: the contract test is the arbiter; connect a documentation MCP server such as [Context7](/en/ecosystem/mcp/context7/) so the agent reads the docs for the installed version. ## Where to go next with recovery patterns - [Debugging patterns](/en/cookbook/error-handling-recipes/debugging-patterns/): find the root cause that justifies a breaker in the first place - [Logging patterns](/en/cookbook/error-handling-recipes/logging-patterns/): make every breaker transition a structured, correlated log line - [Monitoring and logging patterns](/en/cookbook/devops-recipes/monitoring-logging/): turn a tripped breaker into an alert that pages someone - [Error injection testing](/en/workflows/test/error-injection-testing/): system-level fault injection beyond the unit contract - [AI-powered incident response](/en/workflows/operate/incident-response/): what happens after the breaker opens at 2 a.m. - [Error handling recipes](/en/cookbook/error-handling-recipes/): the rest of this section --- # Frontend recipes URL: https://developertoolkit.ai/en/cookbook/frontend-recipes/ Description: Pick the frontend recipe for your framework, give the agent a browser, and prove UI work with type, test, a11y and screenshot gates, not line-by-line review. The frontend recipes are five pages of copy-paste prompts for Claude Code, Codex, and Cursor, one each for Angular, Next.js, Nuxt, React, and Vue. Each recipe works best when the agent can open the running app in a browser and when the repository names its gates: type check, unit tests, a browser test, an accessibility scan, and a screenshot. This hub is for developers who let an agent write interface code. You know the failure: the component compiles, the unit test passes, and the screen is still wrong. The layout breaks at 375 pixels, a hydration warning fills the console, the modal traps no focus, and nobody notices until a user does. ## Which frontend recipe fits your framework? Every recipe assumes the browser and gate setup in the next two sections. | Your framework | Recipe | What the recipe covers | | --- | --- | --- | | Angular | [Angular development recipes](/en/cookbook/frontend-recipes/angular-patterns/) | Signals, standalone components, typed forms, lazy routes, interceptors | | Next.js App Router | [Next.js optimization recipes](/en/cookbook/frontend-recipes/nextjs-patterns/) | Server Components, streaming, Server Actions, caching, Core Web Vitals | | Nuxt | [Nuxt 4 development recipes](/en/cookbook/frontend-recipes/nuxt-patterns/) | Server routes, data-fetching composables, hybrid rendering, testing | | React | [React development recipes](/en/cookbook/frontend-recipes/react-patterns/) | Typed components from a design, server state, forms, error boundaries, tests | | Vue 3 | [Vue.js workflow recipes](/en/cookbook/frontend-recipes/vue-patterns/) | Composition API, Pinia stores, composables, lazy routes, i18n | React Native, Flutter, and Expo live in [mobile development recipes](/en/cookbook/mobile-development/). Skills that raise the design quality of generated UI are compared in [best skills for frontend development](/en/ecosystem/skills/top-skills-frontend/). ## Give the agent a browser before the first recipe An agent that cannot see the page guesses at layout. A browser MCP server lets it load the dev server, click through a flow, read the console, and take a screenshot. Playwright MCP (`@playwright/mcp`, 0.0.82 on 2026-09-26) is the common choice. The `--isolated` flag keeps the browser profile in memory, so two agents in two worktrees do not fight over one profile. **Claude Code** Run in a terminal inside the repository: ```bash claude mcp add playwright -- npx @playwright/mcp@latest --isolated ``` Add `--scope project` to write the entry to `.mcp.json` and share it with the team. **Codex** Run in a terminal: ```bash codex mcp add playwright -- npx @playwright/mcp@latest --isolated ``` `codex mcp list` confirms the entry. **Cursor** Add the server to `.cursor/mcp.json` in the project, the shape Playwright's README documents for Cursor: ```json title=".cursor/mcp.json" { "mcpServers": { "playwright": { "command": "npx", "args": ["@playwright/mcp@latest", "--isolated"] } } } ``` For performance traces and network inspection, add Chrome DevTools MCP (`chrome-devtools-mcp`, 1.10.1) the same way, for example `codex mcp add chrome-devtools -- npx chrome-devtools-mcp@latest`. It sends usage statistics to Google unless you add `--no-usage-statistics`. [Playwright MCP versus Playwright CLI](/en/ecosystem/mcp/playwright-mcp/) covers the flags, the parallel-worktree setup, and the CLI route that costs less context. ## Write the frontend gate into the agent's instructions A recipe ends with "run the gate", so the repository has to say what the gate is. For a TypeScript app with Vitest and Playwright: ```markdown title="AGENTS.md" ## Commands - Types: `npx tsc --noEmit` - Lint: `npm run lint` - Unit and component tests: `npx vitest run` - Browser tests, including axe accessibility scans: `npx playwright test` ## Definition of done for UI changes Types, lint, unit, and browser tests pass, and your reply ends with the last lines of each. Every new screen or component state gets a Playwright test that checks it at 375 px and 1280 px wide, runs an axe scan with @axe-core/playwright, and fails on any console error. Never update a screenshot baseline or edit an existing test without asking first. ``` Claude Code reads `CLAUDE.md`; from v2.1.277 it also reads `AGENTS.md` when the project has no `CLAUDE.md`; once a `CLAUDE.md` exists, keep the line `@AGENTS.md` in it. Codex reads `AGENTS.md` once you trust the project. In Cursor, repeat both sections in a [project rule](/en/cursor-ide/quick-start/project-rules/) that applies to every request. The CI job that runs the same commands on every pull request is the gate that decides. ## How do you verify UI code without reading every line? Ask for the check that goes red for each failure, and require the agent to attach its output. | Failure | The check that catches it | | --- | --- | | Layout breaks on a small screen | A Playwright test per viewport, plus a `toHaveScreenshot` comparison against a committed baseline | | Hydration mismatch or runtime error | A browser test that fails when the page logs a console error | | Missing labels, contrast, focus order | An axe scan in the browser test, plus a keyboard-only test of the flow; see [accessibility testing](/en/workflows/test/accessibility-testing/) | | The component looks nothing like the design | An agreed mock or screenshot as the acceptance target; see [visual acceptance before frontend implementation](/en/developer-scorecard-guide/ui-design-mock/) | | Bundle or performance regression | A bundle-size budget or a Lighthouse run in CI that fails above a threshold | A human signs off twice: on the visual target before the agent starts, and on the screenshots and any changed baseline after it finishes. Both go into the pull request's [evidence bundle](/en/workflows/ship/evidence-bundle/). The prompts work unchanged in Claude Code, Codex and Cursor once the Playwright MCP server is connected. **Copy-paste prompt: a component that proves itself** ```text Build the account settings form described in the acceptance criteria above, following the existing components in src/components/. Work test-first: 1. Write failing Playwright tests: the form at 375 px and 1280 px wide, validation messages for each invalid field, submit with the keyboard only, and an axe scan with @axe-core/playwright that allows no violations. 2. Make every test fail on any console error. 3. Implement until the Definition of done in AGENTS.md passes. 4. Open the page with the Playwright MCP tools, take a screenshot at each width, and attach them with the last lines of every gate command. Do not update screenshot baselines or edit a test to make it pass. ``` **Copy-paste prompt: audit a screen in the browser** ```text Start the dev server and open /checkout with the Playwright MCP tools. Check the page at 375 px, 768 px and 1280 px wide. Report every console error, every element that overflows the viewport, every interactive element you cannot reach with Tab, and every control without an accessible name. For each finding, give the component file and write a failing Playwright test that proves it before you change any code. ``` ## What breaks when agents write frontend code? - **The agent accepts its own screenshot diff.** It runs the update-snapshots command and the visual test goes green. Recovery: forbid baseline updates in the instruction file, and review baseline changes as their own commit. [Protect the oracle](/en/workflows/test/protect-the-oracle/) shows how to make tests read-only for the agent. - **The code uses an API from an older framework version.** Pages Router code lands in an App Router project, or Options API code in a Composition API codebase. Recovery: state the version and the idiom in the instruction file, and give the agent current docs through [Context7](/en/ecosystem/mcp/context7/). - **Tests pass in jsdom but the page is broken.** Recovery: require at least one real-browser test per changed screen, as in the gate above. - **Parallel agents collide on the browser or the dev-server port.** Recovery: run the MCP server with `--isolated`, start each worktree's dev server with an explicit `--port`, and point Playwright's `baseURL` and `webServer.url` at that port. See [parallel agents](/en/ecosystem/agent-tools/parallel-agents/) for the worktree setup. - **The UI works but looks generic.** Recovery: give the agent a design target and a design skill; see [Taste Skill](/en/ecosystem/skills/taste-skill/) and [Impeccable](/en/ecosystem/skills/impeccable-design/). ## Where to go next with frontend recipes - [React development recipes](/en/cookbook/frontend-recipes/react-patterns/) - [Agent-driven browser verification](/en/developer-scorecard-guide/e2e-agent-verification/) - [End-to-end test automation](/en/workflows/test/e2e-testing/) - [Best skills for frontend development](/en/ecosystem/skills/top-skills-frontend/) - [AI Developer Cookbook](/en/cookbook/) --- # Angular Development Recipes URL: https://developertoolkit.ai/en/cookbook/frontend-recipes/angular-patterns/ Description: Copy-paste prompts that get Angular 22 code from Claude Code, Codex or Cursor: signals, Signal Forms, zoneless, SSR, proven by build, Vitest and E2E gates. Angular development recipes for AI agents work when three things hold: the agent knows it is writing Angular 22 (zoneless, `OnPush` by default, Signal Forms stable), it can query the Angular CLI MCP server instead of guessing, and every change passes `ng build`, `ng test` on Vitest and a Playwright check. This page is for developers who let Claude Code, Codex or Cursor write Angular code. The failure is familiar: the agent produces a component that compiles, the spec passes, and the view never updates, because the agent mutated a plain field the way Zone.js-era Angular allowed, and your app has no Zone.js to notice. Or it hands you `BehaviorSubject` services, `*ngIf`, `@HostListener` and a `fakeAsync` test that cannot run under Vitest. ## What these Angular recipes give you - A one-command setup that gives the agent Angular's own best-practice file and the Angular CLI MCP server - Ten copy-paste prompts for current Angular: components, services, Signal Forms, interceptors, routing, NgRx SignalStore, SSR, a zoneless migration, micro-frontends and directives - A table of the gates that sign an Angular change off without anyone reading every line - The Angular-specific ways agent code breaks, and how to recover from each **Versions checked on 2026-09-26** `@angular/core`, `@angular/cli`, `@angular/ssr` and `@angular/build` 22.2.0; `@ngrx/signals` 22.0.1; `@angular-architects/native-federation` 22.2.1; `angular-eslint` 22.5.0; `@playwright/test` 1.63.0 (npm registry). The API statements on this page were checked against the published type definitions and schematics of those versions. Angular 22.0.0 shipped on 2026-06-03. ## Which Angular 22 defaults do agents get wrong? Agents were trained on a decade of NgModule, Zone.js and decorator-era code. The current APIs and defaults below contradict most of that training data: | Agent writes | What Angular 22 does | Write instead | | --- | --- | --- | | A plain class field mutated in a handler, expecting the view to refresh | New CLI apps are zoneless (the application schematic's `zoneless` option defaults to `true`), and `ChangeDetectionStrategy.OnPush` is the default strategy | A `signal()` or `computed()` read in the template | | `changeDetection: ChangeDetectionStrategy.Default` | `Default` is deprecated in favour of `Eager` | Leave it out; add `Eager` only with a written reason | | `provideExperimentalZonelessChangeDetection()` | Not exported by `@angular/core` 22.2.0 | `provideZonelessChangeDetection()`, or nothing in a new app | | `FormGroup` plumbing for a new form | Signal Forms (`@angular/forms/signals`: `form()`, `[formField]`) are public API since 22.0 | Signal Forms; typed reactive forms for existing forms | | `fakeAsync` and `tick()` in specs | `ng test` runs Vitest by default, and loads `zone.js/testing` only when the app's polyfills include `zone.js` | Vitest fake timers (`vi.useFakeTimers()`) or `await fixture.whenStable()` | | `provideClientHydration(withIncrementalHydration())` | Incremental hydration is on by default; `withIncrementalHydration()` is deprecated since 22.0 | `provideClientHydration()`, plus `withEventReplay()` if you want it | | `@HostListener`, `@HostBinding`, `ngClass`, `CommonModule` | Angular's own AI instructions ban them for new code | The `host` object in the decorator, `class` and `style` bindings, per-directive imports | The next section puts these rules into the agent's context so you do not have to repeat them in every prompt. ## Give the agent Angular's own context and MCP server The Angular CLI ships two things written for coding agents. The `ai-config` schematic writes Angular's best-practice instruction file and an MCP config for your tool. The `ng mcp` command runs the Angular CLI MCP server, whose default tools include `get_best_practices`, `search_documentation`, `list_projects`, `run_target` (build and test targets), dev-server start, stop and wait tools, and `onpush_zoneless_migration`. **Claude Code** Generate `CLAUDE.md` and a project `.mcp.json` from the repository root: ```bash npx ng generate ai-config --tool=claude-code ``` If a `CLAUDE.md` already exists, the schematic (checked in `@schematics/angular` 22.2.0) leaves it untouched and prints a warning, while an existing `.mcp.json` gets the `angular-cli` server merged into its `mcpServers`. To take Angular's guidance into your own file, move `CLAUDE.md` aside, run the command, and merge the two by hand. To add only the MCP server, at project scope so the team shares it: ```bash claude mcp add --scope project angular-cli -- npx -y @angular/cli mcp ``` **Codex** Generate `AGENTS.md` and `.codex/config.toml`: ```bash npx ng generate ai-config --tool=open-ai-codex ``` Or add only the server to your user config: ```bash codex mcp add angular-cli -- npx -y @angular/cli mcp ``` Codex reads project-level `AGENTS.md` only in trusted projects (since 0.150.0), so trust the workspace when Codex asks. **Cursor** Generate `AGENTS.md` (Angular's best-practice file) and `.cursor/mcp.json`: ```bash npx ng generate ai-config --tool=cursor ``` Then open Cursor's MCP settings, confirm `angular-cli` is listed and enabled, and copy the best-practice text from the generated `AGENTS.md` into a project Rule so every agent session loads it. Add the project facts the schematic cannot know, below the generated block: ```markdown ## This repository - Angular 22.2, standalone only, zoneless. Tests: `npx ng test --watch=false` (Vitest). Lint: `npx ng lint`. - State: signals in components; NgRx SignalStore (`@ngrx/signals` 22) for shared feature state. - New forms use Signal Forms. Never add `zone.js`, `fakeAsync`, `@HostListener` or `CommonModule`. - Before you finish: `npx ng build` and `npx ng test --watch=false` must both pass. Paste their last lines. ``` The `ng build` line matters most. The production build type-checks every template, so a wrong input name or a missing import fails there, not in review. For the reasoning behind project context files, see [how to make a codebase agent-ready](/en/workflows/harness/agent-ready-codebase/). ## How to run a recipe in each tool The prompts are tool-agnostic. What differs is how each tool runs the verification loop. **Claude Code** Paste the prompt into an interactive session, where auto mode is the starting permission mode from v2.1.283 (both release channels on 2026-10-12). To run a recipe headless in a script, allow only the commands it needs: ```bash claude -p "$(cat prompts/angular-product-card.txt)" \ --permission-mode acceptEdits \ --allowedTools "Bash(npx ng build *)" "Bash(npx ng test *)" ``` **Codex** Paste the prompt into the TUI, or run it non-interactively with write access limited to the workspace: ```bash codex exec --sandbox workspace-write "$(cat prompts/angular-product-card.txt)" ``` For a long refactor such as the zoneless migration, `codex cloud` (experimental in 0.157.1) lets you browse a cloud task and apply its diff locally; `codex apply` applies the latest diff as a `git apply`. **Cursor** Paste the prompt into the agent chat with the target folder and the relevant data-model or type file (for example `src/app/models/product.ts`) attached as context. For recipes that touch many files, such as routing or SSR, start in Plan Mode and approve the plan before any code is written. Review the diff in the editor, and keep the build and test commands in the prompt so the agent runs them in the terminal before it stops. ## Build a standalone component with signals Every prompt in this section names the file, the signal APIs and the proof you expect back. The 2025 file-name style (`product-card.ts`, not `product-card.component.ts`) is the CLI default in 22.x. **Copy-paste prompt: signal-based product card** ```text Create a standalone component at src/app/components/product-card/product-card.ts (2025 file-name style, selector app-product-card). Match the existing Product type in src/app/models. - Inputs with input(): product (required, Product), showActions (default true). - Outputs with output(): addToCart emits Product, viewDetails emits the product id. - computed(): isOnSale (discountPercentage > 0), finalPrice, formattedPrice via Intl.NumberFormat. - Template: @if / @for / @switch only. Class and style bindings, no ngClass, no CommonModule. - Do not set standalone or changeDetection in the decorator; the defaults are right. - Spec with Vitest (no fakeAsync): render with fixture.componentRef.setInput(), assert the DOM for on-sale and regular products, and assert both outputs emit the right values. Finish by running `npx ng build` and `npx ng test --watch=false`. Paste the last 10 lines of each. ``` **What proves it:** the spec drives inputs through `setInput()` and asserts rendered text, so it fails if the template reads a stale field. A spec that only calls component methods proves nothing about change detection. ## Replace BehaviorSubject services with signals and httpResource `resource()` and `httpResource()` are public API since 22.0, and the CLI's own guidance prefers `inject()` and the `@Service` decorator for new singletons. Keep RxJS where you have real streams; move state to signals. **Copy-paste prompt: auth service on signals** ```text Refactor src/app/services/auth.service.ts from BehaviorSubject state to signals. 1. currentUser = signal(null); isAuthenticated and role as computed(). 2. login() and logout() keep HttpClient Observables for the calls, then set the signal. Expose only readonly signals (asReadonly()). 3. Load the profile with httpResource('/api/me') so loading and error states are signals too. 4. Keep toObservable(currentUser) as a temporary bridge for the three callers that still subscribe; list them in a TODO comment with file paths. 5. Use inject(), not constructor injection. Every remaining subscribe() uses takeUntilDestroyed(). 6. Tests: login sets the user, logout clears it, a failed profile load leaves isAuthenticated false. Use HttpTestingController via provideHttpClientTesting(). Run `npx ng test --watch=false` and paste the result. Then grep the diff for "BehaviorSubject" and "subscribe(" and explain every remaining hit. ``` ## Build a registration form with Signal Forms Signal Forms replace `FormGroup` wiring with a signal model, a schema function and the `[formField]` directive. The validators you need (`required`, `email`, `minLength`, `pattern`, `validate`, `validateAsync`, `validateHttp`, `applyWhen`, `hidden`, `disabled`) are all exported from `@angular/forms/signals` in 22.2.0. **Copy-paste prompt: Signal Forms registration** ```text Build src/app/auth/register/register.ts with Signal Forms from @angular/forms/signals (form(), schema functions, [formField] in the template). Do not use FormGroup or FormBuilder. Model signal: email, password, confirmPassword, accountType ('personal' | 'business'), companyName. Rules: - email: required, email, and validateHttp against GET /api/users/exists?email=... (error "taken"). - password: required, minLength(12), pattern requiring upper, lower and digit. - confirmPassword: validate() comparing with valueOf(password), error "mismatch". - companyName: required and visible only when accountType is 'business' (applyWhen + hidden). - Submit button disabled while the form is invalid or pending; submit() posts to /api/register. Show errors from the field state, one message map for all fields. Spec (Vitest, no fakeAsync): each rule fails and passes once, the async check hits the endpoint once per settled value (use vi.useFakeTimers() for any debounce), and companyName toggles with accountType. Run `npx ng test --watch=false` and paste the summary. ``` For an existing reactive form, do not ask for a rewrite in the same change. Ask for typed `NonNullableFormBuilder` fixes first, then migrate one form per pull request with its tests unchanged, so the tests become the oracle for the migration. ## Chain functional HTTP interceptors **Copy-paste prompt: interceptor chain** ```text Create functional interceptors in src/app/core/http/ and register them in app.config.ts with provideHttpClient(withInterceptors([...])). 1. authInterceptor: adds the bearer token from AuthService except for URLs in PUBLIC_ENDPOINTS. 2. refreshInterceptor: on 401, calls refresh once, retries the original request once, and logs out if refresh fails. Concurrent 401s share one refresh call. 3. errorInterceptor: maps 403 to /forbidden, 429 to a toast with the Retry-After value, 5xx to a generic toast. Never swallows the error; rethrows after handling. 4. timingInterceptor: logs method, URL and duration in dev mode only (isDevMode()). Explain the order you chose in one comment above the array (request order, then response order). Test each interceptor alone with provideHttpClientTesting(). Add one test where two requests get 401 at the same time and assert refresh is called exactly once. ``` The concurrent-401 test is the one that catches real bugs. Agents write a refresh that works for a single request and fires three refreshes when a dashboard loads three widgets. ## Lazy-load routes with guards and resolvers **Copy-paste prompt: lazy admin area** ```text Move the admin section to lazy standalone routes. 1. src/app/admin/admin.routes.ts exports ADMIN_ROUTES with loadComponent for dashboard, users, settings and reports, under an AdminLayout component with a router-outlet. 2. In app.routes.ts: { path: 'admin', loadChildren: () => import('./admin/admin.routes') .then(m => m.ADMIN_ROUTES), canMatch: [adminGuard] }. 3. adminGuard is a functional CanMatchFn using inject(AuthService); unauthenticated users go to /login?returnUrl=..., authenticated non-admins to /forbidden (return a UrlTree, do not navigate). 4. userResolver is a ResolveFn for users/:id; on 404 it returns a UrlTree to /admin/users. 5. Bind resolved data and params to component inputs: add withComponentInputBinding() to provideRouter if it is missing. Tests: guard outcomes for the three user types, resolver success and 404. Then run `npx ng build` and paste the "Lazy chunk files" section, which must list the admin chunks. ``` The last line turns "is it really lazy?" into evidence. If the admin components appear under initial chunks, the prompt failed, whatever the diff says. ## Manage feature state with NgRx SignalStore **Copy-paste prompt: products SignalStore** ```text Create src/app/products/products.store.ts with signalStore() from @ngrx/signals 22. - withState: products, selectedId, filters { query, category }, loading, error. - withComputed: filteredProducts, selectedProduct, hasActiveFilters. - withMethods: load(), select(id), setFilter(), clearFilters(), and remove(id) with an optimistic update that restores the previous array if the API call fails. Use patchState only. - A search method built with rxMethod (from @ngrx/signals/rxjs-interop): debounceTime(300), distinctUntilChanged, switchMap to the API. - withHooks onInit calls load(). Provide the store on the products route, not in root. Tests with Vitest fake timers: filters recompute, the debounce sends one request for five keystrokes, and a failed remove() restores the item. Run `npx ng test --watch=false`. ``` ## Add SSR with hydration `ng add @angular/ssr` generates a server built on `AngularNodeAppEngine` and server routes with a `RenderMode` per path. Hydration comes from `provideClientHydration()`, which in 22.x already turns on incremental hydration and the `HttpClient` transfer cache; `withEventReplay()` is the option you add. `withIncrementalHydration()` is deprecated since 22.0, and the cache means responses fetched during server rendering are reused on the client, so do not ask the agent for hand-written `TransferState` code for plain `HttpClient` calls. **Copy-paste prompt: SSR and hydration audit** ```text Add server-side rendering: run `npx ng add @angular/ssr`, then: 1. In app.routes.server.ts, prerender '' and 'about' (RenderMode.Prerender), render 'products/:id' on the server (RenderMode.Server), and render 'account/**' on the client (RenderMode.Client). 2. In app.config.ts use provideClientHydration(withEventReplay()). Incremental hydration and the HttpClient transfer cache are on by default; do not add withIncrementalHydration() or TransferState. 3. Audit every file under src/app for window, document, localStorage and navigator. Replace each with afterNextRender() or an injected BrowserStorage service that uses an in-memory Map on the server. List every file you changed and why. 4. Set Title and Meta for products/:id from the resolved product. Verify: `npx ng build`, then start the server build and curl /products/1. Paste the and the first product heading from the HTML. Report any hydration warning from the browser console. ``` ## Migrate a legacy app to zoneless and OnPush This is the recipe where the Angular CLI MCP server earns its place: its `onpush_zoneless_migration` tool analyses a file for Zone.js-dependent patterns and returns a migration plan the agent then applies. Run it one feature folder at a time. **Copy-paste prompt: zoneless migration, one folder** ```text Use the angular-cli MCP server. Migrate src/app/orders/ to zoneless-compatible, OnPush-safe code. 1. Call onpush_zoneless_migration on each component in the folder, and show me its plan first. 2. Apply the plan: state read by templates becomes signals; replace setTimeout-driven UI updates and manual ChangeDetectorRef calls; subscribe() calls use takeUntilDestroyed(). 3. Migrate specs off fakeAsync/tick to Vitest fake timers or await fixture.whenStable(). 4. Do not touch files outside src/app/orders/. Before you change anything, run `npx ng test --watch=false` and record the pass count. After the migration the same tests must pass with no assertion changed. If an assertion must change, stop and explain why instead of editing it. ``` Freezing the assertions is what makes this safe to accept without reading every line: the existing tests are the specification, and the agent may not move them. See [protect the test oracle](/en/workflows/test/protect-the-oracle/) for the general pattern, and [legacy modernization](/en/workflows/build/legacy-modernization/) for sequencing a larger migration. ## Split a shell into micro-frontends with Native Federation The CLI's default `application` builder is esbuild-based. `@angular-architects/module-federation` targets webpack, so a current CLI app that keeps the default builder uses `@angular-architects/native-federation` instead, which delegates to the esbuild application builder. **Copy-paste prompt: Native Federation shell and remote** ```text Set up Native Federation for the shell app and a products remote with @angular-architects/native-federation (ng add on each project). Keep the default esbuild builder. 1. The remote exposes its PRODUCTS_ROUTES (standalone routes), not a module. 2. The shell loads it with loadRemoteModule inside loadChildren, from a manifest file so the remote URL can change per environment without a rebuild. 3. Share @angular/* and rxjs as singletons with strict versions; list any other shared package and why. 4. If the remote fails to load, the route renders a fallback component instead of a blank page. Verify: build both, serve both, and run a Playwright test that opens /products in the shell and asserts the remote's heading. Stop the remote and assert the fallback renders. ``` Before you split, check that you need independent deployment. Micro-frontends trade build simplicity for team autonomy; [microservices trade-offs](/en/workflows/build/microservices/) apply to the frontend too. ## Build directives with the host object **Copy-paste prompt: directive and pipe set** ```text Create standalone directives and pipes in src/app/shared/. Use the host object in the decorator for all listeners and bindings; never @HostListener or @HostBinding. - clickOutside: output() fires on document clicks outside the host. - inViewport: output() with IntersectionObserver, disconnected on destroy, no-op on the server. - hasRole: structural directive, selector appHasRole (*appHasRole="'admin'"), that reads AuthService signals. - relativeTime and fileSize pure pipes using Intl.RelativeTimeFormat and Intl.NumberFormat. Test each with a small host component in the spec. Cover null, undefined, 0 and negative inputs for the pipes, and destroy the host to prove the observer disconnects. Run `npx ng test --watch=false`. ``` ## How to verify agent-written Angular code without reading every line Each gate answers one question, and together they replace a line-by-line read. The agent runs build and tests before it stops; CI runs all of them. | Gate | Command | What it proves | | --- | --- | --- | | Build with template type-checking | `npx ng build` | Templates bind to real inputs and outputs, imports are complete, budgets hold (`angular.json` → `budgets`) | | Unit and component tests | `npx ng test --watch=false` | Behaviour through the DOM, on Vitest, with no Zone.js crutch | | Lint | `npx ng lint` after `npx ng add angular-eslint` | Angular-specific TypeScript and template rules, including the `template-accessibility` config | | End-to-end | `npx playwright test` | Real routing, lazy chunks, hydration and forms in a browser. See [end-to-end testing with agents](/en/workflows/test/e2e-testing/) and [Playwright MCP](/en/ecosystem/mcp/playwright-mcp/) | | Accessibility | Axe checks inside the Playwright suite, after `npm i -D @axe-core/playwright` (4.13.0 on 2026-09-26) | WCAG AA, which Angular's own AI instructions require. See [accessibility testing](/en/workflows/test/accessibility-testing/) | You still decide two things: that the acceptance criteria in the prompt are the right ones, and that no test assertion was weakened to get to green. A reviewer who reads the spec diff and the gate output, not the implementation diff, signs off. Bundle the outputs into the pull request as described in [the evidence bundle](/en/workflows/ship/evidence-bundle/). ## When agent-written Angular code breaks | Symptom | Cause | Recovery | | --- | --- | --- | | The view does not update after a click or an HTTP response | A plain field mutated in a zoneless, `OnPush` app | Ask the agent to move template state to signals. Do not add `zone.js` back to hide it | | `fakeAsync` throws "zone-testing.js is needed for the fakeAsync() test helper" | Zone-era spec running under Vitest in a zoneless app | Rewrite the spec with `vi.useFakeTimers()` or `await fixture.whenStable()` | | `ng build` fails with "is not a known element", "Can't bind to … since it isn't a known property" or "No pipe found with name" | A component, pipe, or directive used through a property binding is missing from the standalone component's `imports` | Make the agent run `ng build` before it stops and fix every error; this case cannot reach a green build | | An attribute directive silently does nothing, with no build error | The directive is missing from `imports`, and the template uses it only as a plain attribute or an event binding such as `(clickOutside)`, which Angular compiles as an ordinary DOM attribute or listener | Require a spec that asserts the directive's effect (for example, that the output fires), and check the `imports` array in the diff | | Resolved data or route params arrive as `undefined` inputs | `withComponentInputBinding()` is missing from `provideRouter` | Add it once in `app.config.ts` | | `ReferenceError: window is not defined` during SSR | Browser API read at construction time | Move the code into `afterNextRender()` or a platform-guarded service | | The agent installs `@angular-architects/module-federation` in an esbuild app | Webpack-era training data | Switch to Native Federation, or keep webpack deliberately and say so in the context file | | Memory grows on long sessions | `subscribe()` without `takeUntilDestroyed()`, or an observer never disconnected | Grep the diff for `subscribe(` and require a destroy test for each | When the agent keeps repeating the same wrong pattern, fix the context file, not the prompt: add the rule to the repository section of `CLAUDE.md` or `AGENTS.md`, or to your Cursor Rule, so the next session starts correct. ## Where to go next with Angular and agents - [Frontend recipes overview](/en/cookbook/frontend-recipes/) for the other frameworks - [React development recipes](/en/cookbook/frontend-recipes/react-patterns/) to compare the same tasks in React - [API development patterns](/en/cookbook/backend-recipes/api-patterns/) for the backend your Angular app calls - [Unit testing with agents](/en/workflows/test/unit-testing/) for writing specs that fail for the right reasons - [Acceptance criteria for agents](/en/workflows/plan/acceptance-criteria/) for turning a ticket into the criteria these prompts end with --- # Next.js Optimization Recipes URL: https://developertoolkit.ai/en/cookbook/frontend-recipes/nextjs-patterns/ Description: Copy-paste prompts that get Next.js 16 App Router code from Claude Code, Codex or Cursor, with the build, type and Playwright gates that prove it. To get correct Next.js 16 code from an AI agent, make three moves: point the agent at the docs bundled in your installed `next` package so it stops writing Next.js 14 and 15 code, connect it to the running dev server through `next-devtools-mcp`, and let `next build`, `tsc` and Playwright tests prove each change. The recipes target Next.js 16 and the App Router. This page is for developers who let Claude Code, Codex or Cursor write a Next.js App Router application, and for the tech lead who has to trust the result. The agent's dashboard renders, but it creates `middleware.ts` with `export const runtime = 'edge'`, calls `revalidateTag('posts')` with one argument, and puts `'use client'` at the top of a page. Everything compiles, the build warns, and nobody reads the warnings. ## What these Next.js recipes give you - A context setup that makes the agent read version-matched Next.js docs instead of its training data - The Next.js DevTools MCP server and the `next-dev-loop` skill wired into all three tools, so the agent sees runtime errors itself - Eight prompts for the App Router work agents most often get wrong: streaming, Server Actions, auth, modals, caching, Proxy, Core Web Vitals, and tenant isolation - A gate table that signs a change off without anyone reading every line, and a failure-mode table with recovery steps **Versions checked on 2026-09-26** npm registry: `next` 16.3.6 (`latest`), `@next/playwright` 16.3.6, `next-devtools-mcp` 0.4.0, `@trpc/server` 11.19.0, `@lhci/cli` 0.15.1. The API facts on this page come from the docs bundled in `next@16.3.6` under `node_modules/next/dist/docs/`. One trap: `next-auth`'s `latest` tag is still 4.24.15, and Auth.js v5 ships under the `beta` tag (`5.0.0-beta.32`), so `npm install next-auth` gives you v4. ## Give the agent version-matched Next.js docs first Agents learned Next.js from years of Pages Router, Next.js 13 to 15, and Vercel blog posts. Since Next.js 16.2, the `next` package ships its own docs in `node_modules/next/dist/docs/`, matched to the version you installed. Your job is to make the agent read them before it writes code. 1. Check which case applies. On Next.js 16.3 or later, `next dev` detects a coding agent and writes a managed block into `AGENTS.md`, plus a `CLAUDE.md` that contains `@AGENTS.md`. Commit both files. On 16.2, write the `AGENTS.md` instruction yourself. On 16.1 or earlier, run `npx @next/codemod@canary agents-md` in the project root to download version-matched docs into `.next-docs/`. 2. Add your project rules to `AGENTS.md` **outside** the `<!-- BEGIN:nextjs-agent-rules -->` markers. `next dev` rewrites everything inside them. ```markdown ## Next.js rules for this repo (Next.js 16.3, App Router only) - Read node_modules/next/dist/docs/ before using any Next.js API. Heed deprecation notices. - Request interception lives in proxy.ts (export `proxy`). Never create middleware.ts. - No `export const runtime = 'edge'`. The Edge Runtime is deprecated. - cacheComponents is on: use 'use cache' + cacheLife + cacheTag, never `revalidate`, `dynamic` or `dynamicParams` segment exports. - revalidateTag(tag, 'max') in Route Handlers; updateTag(tag) in Server Actions. - 'use client' only on leaf interactive components, never on page.tsx or layout.tsx. - Every Server Action checks the session and the user's permission itself. - Done means: next typegen && tsc --noEmit, eslint, next build and Playwright all pass. ``` 3. Put the stale patterns in front of the reviewer too. These are the APIs the agent reaches for first, checked against the bundled docs of `next@16.3.6`: | Agent writes | Status in Next.js 16 | Write instead | | --- | --- | --- | | `middleware.ts` with `export function middleware` | Deprecated, renamed in 16.0.0 | `proxy.ts` with `export function proxy` (codemod: `npx @next/codemod@canary middleware-to-proxy .`) | | `export const runtime = 'edge'` | Edge Runtime deprecated; not supported in `proxy.ts` or with Cache Components | Remove the export; Node.js is the default | | `revalidateTag('posts')` | One-argument form deprecated, TypeScript error | `revalidateTag('posts', 'max')`, or `updateTag('posts')` inside a Server Action | | `experimental.ppr` or `experimental_ppr` | Removed in 16 | `cacheComponents: true` in `next.config.ts` | | `export const revalidate = 3600` on a page | Removed when Cache Components is on | `'use cache'` with `cacheLife('hours')` | | `request.geo`, `request.ip` | Removed in 15 | Your host's headers, or `geolocation()` from `@vercel/functions` on Vercel | | `dynamic(() => import(...), { ssr: false })` in a Server Component | Build error | Move the call into a Client Component | | `next lint` | Removed in 16 | `eslint` directly (codemod: `next-lint-to-eslint-cli`) | | A parallel route slot without `default.tsx` | Build fails in 16 | A `default.tsx` that returns `null` or calls `notFound()` | | `<Image priority>` | Deprecated in 16.0.0 | `fetchPriority="high"` or `loading="eager"` (or `preload`) on the one LCP image | ## Connect the agent to the running Next.js dev server A type check proves the code compiles. It does not show the hydration error in the browser console or the route that blocks prerendering. Next.js 16 dev servers expose an MCP endpoint at `/_next/mcp`, and the `next-devtools-mcp` package (0.4.0) connects agents to it. Its tools include `get_errors`, `get_routes` and `get_logs`, plus two compile tools that work without a full `next build`: `compile_route`, which compiles one route on demand, and `get_compilation_issues`, which returns the project's current compile errors. Both compile tools are Turbopack only. See [dev-server MCP servers for Next.js and other frameworks](/en/ecosystem/mcp/framework-devtools-mcp/) for the details. **Claude Code** ```bash # Terminal, in the project root. -s project writes .mcp.json so the team shares it. claude mcp add -s project next-devtools -- npx -y next-devtools-mcp@latest npx skills add vercel/next.js --skill next-dev-loop ``` Start `npm run dev` in a second terminal, then run `/mcp` in the session to confirm `next-devtools` is connected. **Codex** ```bash # Terminal. Writes the server to ~/.codex/config.toml. codex mcp add next-devtools -- npx -y next-devtools-mcp@latest npx skills add vercel/next.js --skill next-dev-loop ``` Run `codex mcp list` to confirm the entry, and keep `npm run dev` running while the session works. **Cursor** Add the same server to `.cursor/mcp.json` in the project root, then install the skill from a terminal with `npx skills add vercel/next.js --skill next-dev-loop`. ```json { "mcpServers": { "next-devtools": { "command": "npx", "args": ["-y", "next-devtools-mcp@latest"] } } } ``` `next-dev-loop` needs Next.js 16.3 or later on Turbopack and the `agent-browser` CLI 0.31.1 or later: `npm install -g agent-browser && agent-browser install`. When either is missing, the skill tells you how to upgrade and stops instead of running. The `next-dev-loop` skill turns that connection into an inspect, edit and verify cycle, using the MCP server and the [`agent-browser` CLI](/en/ecosystem/skills/agent-browser/) for the browser's view. For page-level browser checks beyond that, add [Playwright MCP or the Playwright CLI](/en/ecosystem/mcp/playwright-mcp/). The other Next.js skills in `vercel/next.js` (`next-cache-components-adoption`, `next-cache-components-optimizer`, `next-partial-prefetching-adoption`) are listed with the rest of the [frontend skills](/en/ecosystem/skills/top-skills-frontend/). ## Stream a dashboard with independent Suspense boundaries Your dashboard makes four independent data calls, and the page waits for the slowest one. The fix is one `<Suspense>` boundary per section. The failure you are preventing is the agent wrapping everything in `Promise.all` or moving the page to the client. **Copy-paste prompt: stream the dashboard** ```text Refactor app/dashboard/page.tsx (Next.js 16, cacheComponents on) to stream. Read node_modules/next/dist/docs/01-app/02-guides/instant-navigation.md first. - Keep page.tsx a Server Component. No 'use client' in app/dashboard/page.tsx or layout.tsx. - Split the four fetches (getStats, getRecentOrders, getTopProducts, getActivityFeed) into four async Server Components, each wrapped in its own <Suspense> with a skeleton that has the same height as the loaded section. Do not use Promise.all across sections. - getStats and getTopProducts can be 5 minutes stale: 'use cache' + cacheLife('minutes'). Orders and activity are per-user and stay uncached. - Add an e2e test in e2e/dashboard.spec.ts with instant() from @next/playwright asserting the page heading and all four skeletons are visible on navigation from /settings. Verify: call get_errors and compile_route for /dashboard via next-devtools, then run npx next build and npx playwright test e2e/dashboard.spec.ts. Report both outputs. ``` The `instant()` helper from `@next/playwright` scopes assertions to the UI available the moment the user navigates. The test fails if a later change makes the route block again, which is the regression a code review almost never catches. ## Build forms with Server Actions that check authorization Server Actions look like function calls, but the Next.js docs are explicit that they are "reachable via direct POST requests". An agent that checks the session in `proxy.ts` and trusts it inside the action leaves the endpoint open to anyone who replays the request. **Copy-paste prompt: a contact form with Server Actions** ```text Build a contact form with a Server Action. Next.js 16, React 19, Zod 4. 1. app/contact/actions.ts ('use server'): submitContact(prevState, formData). Validate with Zod (name 1-100 chars, valid email, message 10-1000 chars, empty honeypot field). Rate-limit 5 submissions per IP per hour; read the IP from the x-forwarded-for header set by our host, not request.ip. Return { ok, fieldErrors } and never throw to the client. 2. app/contact/contact-form.tsx ('use client'): useActionState for state and field errors, useFormStatus for the pending button. The form must work with JavaScript disabled. 3. app/contact/page.tsx stays a Server Component. Tests: Vitest for the action (valid, each invalid field, honeypot, 6th submission) and a Playwright test that submits with javaScriptEnabled: false. Run both and paste the output. ``` For an action that changes the signed-in user's own data, add one line to the prompt: "call `updateTag` for the tag the page reads, so the user sees the change on the next render". `updateTag` works only inside Server Actions; a webhook Route Handler uses `revalidateTag(tag, 'max')`. ## Protect routes with Proxy and a data access layer Auth is where agents blur the server and client boundary most. In Next.js 16, `proxy.ts` runs on the Node.js runtime and the docs recommend it only for optimistic checks, reading the session cookie without a database call. The real check belongs next to the data. Pick one library before you prompt: Auth.js v5 is still on the `beta` tag, and Better Auth (`better-auth` 1.7.6) is the other common choice for App Router projects. **Claude Code** Start in plan mode (`/plan`) so you review the file list before any code exists. After the change, run `/code-review` and ask it to list every Server Action and Route Handler that does not call `verifySession()`. For CI, the same audit runs headless with `claude -p "…" --tools "Read,Grep,Glob"` so the reviewer cannot edit what it audits. **Codex** Run the change in its own worktree so a half-written `proxy.ts` never breaks your running dev server: `codex exec --worktree --sandbox workspace-write "…"`. Then ask a second, read-only session (`codex exec --sandbox read-only`) for the same list of unprotected actions and handlers. **Cursor** Use Plan Mode for the file list, then let the agent implement it in a worktree. Review the diff of `proxy.ts` and `lib/dal.ts` in the editor. Those two files hold every decision; the rest is wiring. Bugbot on the pull request is a second reviewer, not the gate. **Copy-paste prompt: auth with Proxy plus a data access layer** ```text Add authentication with Better Auth to this Next.js 16 App Router app. Read node_modules/next/dist/docs/01-app/02-guides/authentication.md and data-security.md first. - proxy.ts (export proxy, Node runtime, no runtime export): optimistic check only. Read the session cookie, redirect unauthenticated users from /dashboard/* and /admin/* to /login. Matcher excludes _next/static, _next/image, favicon.ico and /api/auth/*. No database calls. - lib/dal.ts with import 'server-only': verifySession() (cached per request with React cache) and requireRole(role). Every Server Action, Route Handler and admin page calls one of them. - Session and role come from the server; never from a client-supplied header or form field. Tests (Playwright): anonymous user redirected from /dashboard; a user without the admin role gets 403 from /admin and from a direct POST to each admin Server Action; sign-out invalidates the session. Then list every exported Server Action and Route Handler and state which guard each one calls. ``` ## Open product details in a modal with intercepting routes Product details should open in a modal from the grid and as a full page on a direct visit or refresh. Agents usually get the folder names right and miss two things: the `default.tsx` that Next.js 16 now requires for every parallel slot, and the behaviour on refresh. **Copy-paste prompt: an intercepted product modal** ```text Implement a product modal with parallel and intercepting routes (Next.js 16). - app/products/page.tsx: Server Component grid linking to /products/[id]. - app/products/[id]/page.tsx: full detail page (await params). - app/products/@modal/(.)[id]/page.tsx: the same data inside <ProductModal>. - app/products/@modal/default.tsx returning null. The build fails without it. - app/products/layout.tsx renders {children} and {modal}. - ProductModal ('use client'): closes on backdrop click and Escape via router.back(), traps focus, returns focus to the clicked card, and has a "View full page" link. Playwright tests: click opens the modal and the URL changes; Escape closes it; the browser back button closes it; reload on /products/42 shows the full page with no modal; a direct visit shows the full page. Run them and paste the result. ``` ## Cache a blog with Cache Components and on-demand revalidation The old recipe for a 500-post blog was Incremental Static Regeneration with `export const revalidate`. With `cacheComponents: true`, those segment exports are gone. Caching is declared on the data function with `'use cache'`, and a CMS webhook expires the right tag. **Copy-paste prompt: blog caching, metadata and revalidation** ```text Set up caching for app/blog on Next.js 16 with cacheComponents: true in next.config.ts. Read 01-app/02-guides/migrating-to-cache-components.md in the bundled docs first. - lib/posts.ts: getPost(slug) and listPosts() with 'use cache', cacheLife('days'), cacheTag('post-' + slug) and cacheTag('posts'). - app/blog/[slug]/page.tsx: generateStaticParams for the 50 newest posts; generateMetadata with title, description, canonical URL and Open Graph data; Article JSON-LD in a script tag. - app/blog/[slug]/opengraph-image.tsx with ImageResponse from next/og. - app/api/revalidate/route.ts: POST, verify the CMS signature header with a secret from process.env.CMS_WEBHOOK_SECRET, then revalidateTag('post-' + slug, 'max') and revalidateTag('posts', 'max'). Return 401 on a bad signature. - app/sitemap.ts and app/robots.ts. No `export const revalidate`, `dynamic` or `dynamicParams` anywhere. Verify: npx next build must list /blog/[slug] as prerendered; a Vitest test for the webhook covers a valid signature, a bad signature and an unknown slug. ``` ## Run A/B tests and feature flags in proxy.ts Proxy is the right place for a cookie-based variant split and for passing flags to Server Components as request headers. It is the wrong place for anything slow, because it runs on every matched request, prefetches included. **Copy-paste prompt: A/B split and feature flags in Proxy** ```text Create proxy.ts (Next.js 16, export function proxy, no runtime export) that: 1. Assigns an ab-pricing cookie (a or b, 50/50, 30 days) if missing, and rewrites /pricing to /pricing/a or /pricing/b without changing the visible URL. 2. Reads flags for the visitor from lib/flags.ts (an in-memory snapshot refreshed every 60 seconds, no per-request network call) and sets an x-flags request header. 3. Sets x-is-bot for known crawler user agents so pages skip personalisation. The matcher excludes _next/static, _next/image, favicon.ico, robots.txt and sitemap.xml. Keep each concern a small pure function in lib/proxy/ and unit-test it with NextRequest. Add a Playwright test that a first visit to /pricing sets the cookie and that the same variant is served on the next five visits. ``` ## Fix Core Web Vitals with a budget CI enforces Lighthouse reports a performance score of 65, LCP of 4.2 s and CLS of 0.25. The edits are routine: `next/image` with `fetchPriority="high"` on the one LCP image, `next/font`, skeletons with fixed dimensions, and `useTransition` on the filter. The part that lasts is the budget in CI, so the next agent-written change cannot undo them. **Claude Code** Add the Chrome DevTools MCP server (`claude mcp add chrome-devtools --scope user npx chrome-devtools-mcp@latest`, version 1.10.1) so the agent records a performance trace against `http://localhost:3000` and reads the LCP element itself, instead of guessing which image it is. **Codex** Run the fix as `codex exec --worktree` with the prompt below, then open the pull request with the before and after Lighthouse numbers in its description. The worktree keeps the performance branch apart while the budgets settle. **Cursor** Let the agent sweep the component edits across files and check each diff for `fetchPriority="high"`: it belongs on one image per page. High priority on every image slows LCP down instead of speeding it up. If the agent writes `priority`, replace it: Next.js 16 deprecated that prop. **Copy-paste prompt: Core Web Vitals with a CI budget** ```text Improve Core Web Vitals on / and /products. Measure first, change second. 1. Run npx @lhci/cli autorun against a production build (npx next build && npx next start) and record LCP, CLS and total blocking time for both pages before any change. 2. Fix LCP: next/image with fetchPriority="high" on the single LCP image, never on more than one (the priority prop is deprecated in Next.js 16); explicit width, height and sizes. Fix CLS: fixed-size skeletons, next/font for every font. Fix interaction delay: useTransition on the product filter; next/dynamic with ssr:false only inside Client Components; analytics via next/script strategy="lazyOnload". 3. Add lighthouserc.json with assertions: largest-contentful-paint maxNumericValue 2500, cumulative-layout-shift 0.1, total-blocking-time 200, and a GitHub Actions job with permissions: contents: read that runs npx @lhci/cli autorun on every pull request. 4. Add useReportWebVitals in a Client Component that posts field INP, LCP and CLS to /api/vitals. Report a before/after table for each page. Do not change unrelated components. ``` Lighthouse is a lab test with no user input, so it cannot measure Interaction to Next Paint. Total blocking time is the lab proxy; field INP comes from `useReportWebVitals` in real sessions. Google's [web.dev Core Web Vitals thresholds](https://web.dev/articles/vitals) (checked 2026-09-26) put "good" at LCP up to 2.5 s, CLS up to 0.1 and INP up to 200 ms. For a load-testing setup beyond the page, see [performance testing with agents](/en/workflows/test/performance-testing/). ## Isolate tenants in a multi-tenant SaaS A SaaS that routes tenants by subdomain fails in one way that matters: one tenant sees another tenant's rows. A tenant-scoped query wrapper plus a test that tries to cross the boundary is the only proof that holds after the agent's next refactor. **Copy-paste prompt: tenant isolation with a crossing test** ```text Add subdomain multi-tenancy to this Next.js 16 app with Drizzle on Postgres. - proxy.ts resolves the tenant from the host (acme.example.com -> acme), treats www and the apex domain as the marketing site, rewrites unknown subdomains to a branded 404, and sets x-tenant-slug. It does no database lookup. - lib/tenant.ts (import 'server-only'): getTenant() reads the header, loads the tenant once per request with React cache, and throws if it is missing. - lib/db/scoped.ts: scopedDb(tenantId) returns query helpers that always add where tenant_id = tenantId. Direct imports of the raw db outside lib/db are an ESLint error (no-restricted-imports). - Integration test on a real Postgres (Testcontainers): seed tenants A and B, then call every exported query and Server Action as A with B's record ids. Each call must return nothing or 404. The test fails if a new query is exported without being added to the test's list. ``` For end-to-end type safety between server and client, tRPC 11 (`@trpc/server` 11.19.0) remains an option. Server Actions and Route Handlers with `PageProps` types cover most App Router apps without it. Whichever you choose, the proof is the same: change a server return type and confirm `tsc --noEmit` fails in the consuming component. ## How to verify agent-written Next.js code without reading every line Read the diffs of `proxy.ts`, `lib/dal.ts`, `next.config.ts` and any file that exports a Server Action. Let the gates prove the rest. | Gate | Command or tool | What goes red | | --- | --- | --- | | Types | `npx next typegen && npx tsc --noEmit` | Sync `params`, wrong `PageProps`, a one-argument `revalidateTag`, a server type change the client did not follow | | Lint | `npx eslint .` plus `no-restricted-imports` for `server-only` modules and the raw database client | Server code imported into a Client Component; tenant queries that skip the scoped client | | Build | `npx next build` (add `--debug-prerender` when the build error is not enough) | Routes that block prerendering, `ssr: false` in a Server Component, a slot without `default.tsx` | | Runtime | `get_errors` and `compile_route` through `next-devtools-mcp` | Hydration errors and runtime errors that type checks miss | | Behaviour | Playwright, with `instant()` from `@next/playwright` for navigations | Auth bypass, modal navigation, streaming regressions, tenant crossing | | Performance | `npx @lhci/cli autorun` with the budgets above | LCP and CLS regressions, heavy JavaScript | Make the agent run the same gates before it says it is done. In Claude Code, add a `Stop` hook to `.claude/settings.json` that runs `npx tsc --noEmit && npx next build` and exits with code 2 when either fails. Exit code 2 sends the hook's stderr back to the agent instead of ending the turn, so the command redirects the build output to stderr: ```json { "hooks": { "Stop": [ { "hooks": [ { "type": "command", "command": "cd \"$CLAUDE_PROJECT_DIR\" && { npx tsc --noEmit && npx next build; } 1>&2 || exit 2", "timeout": 600 } ] } ] } } ``` `Stop` takes no `matcher`. To stop a failing build from looping, check `stop_hook_active` in a script instead; see [hooks automation](/en/claude-code/automate/hooks-automation/). In Codex and Cursor, put the "Done means" line from the rules block in `AGENTS.md` or your Rules and require the command output in the summary. The developer who owns the pull request signs off on the gate results and the four files above; CI enforces the rest. For how that review works at team scale, see [reviewing agent pull requests](/en/workflows/ship/agent-pr-review/). ## When agent-written Next.js code breaks | Symptom | Cause | Recovery | | --- | --- | --- | | Whole page is client-rendered; `generateMetadata` has no effect | `'use client'` on `page.tsx` or `layout.tsx` | Move the directive to the smallest interactive leaf; add an ESLint rule or grep in CI that fails on `'use client'` in `page.tsx` and `layout.tsx` | | Build warns that `middleware` is deprecated, or fails with a `runtime` config error in proxy.ts | Agent wrote Next.js 15 code | `npx @next/codemod@canary middleware-to-proxy .`, delete the `runtime` export, and confirm `AGENTS.md` still has the managed block | | A mutation shows stale data | `revalidateTag` with a profile where the user needs to see their own write | Use `updateTag` inside the Server Action; keep `revalidateTag(tag, 'max')` for webhooks | | Admin action works for a normal user through a crafted POST | Authorization only in `proxy.ts` | Add `requireRole()` inside the action; add the direct-POST Playwright test from the auth recipe | | Server Action or page fails with an "Only plain objects" serialization error | A class instance (an ORM entity, a `Decimal`) or a function crossed the server–client boundary | Map results to plain objects in the data layer before they reach a Client Component or leave an action; add a unit test that asserts the return value is a plain object | | CSS or images stop loading after a Proxy change | Matcher runs on `_next/static` and `_next/image` | Restore the negative matcher; add a Playwright check that a page's stylesheet returns 200 | | Agent keeps producing Next.js 14 code in a new session | `AGENTS.md` block deleted, or the docs are not bundled (16.1 or earlier) | Run `next dev` from the agent's session (or `npx @next/codemod@canary agents-md` on 16.1 and earlier) to restore the block, then commit it | ## Where to go next with Next.js and agents - Start from the [frontend recipes overview](/en/cookbook/frontend-recipes/) if you also work in Angular, Vue or Nuxt. - Take component-level patterns further with [React development recipes](/en/cookbook/frontend-recipes/react-patterns/). - Write the acceptance criteria your Playwright tests encode with [acceptance criteria agents can verify](/en/workflows/plan/acceptance-criteria/). - Build the end-to-end suite the gates rely on with [end-to-end testing with agents](/en/workflows/test/e2e-testing/). - Give agents current docs for the rest of your stack with [Context7](/en/ecosystem/mcp/context7/). - Ship the app in a container with [Docker patterns](/en/cookbook/devops-recipes/docker-patterns/), or design the API behind it with [API development patterns](/en/cookbook/backend-recipes/api-patterns/). --- # Nuxt 4 development recipes with AI agents URL: https://developertoolkit.ai/en/cookbook/frontend-recipes/nuxt-patterns/ Description: Copy-paste prompts that get Nuxt 4 code from Claude Code, Codex or Cursor, with the Nuxt docs MCP server and the type, test and build gates that prove it. Nuxt development recipes for AI agents rest on three moves: pin the agent to Nuxt 4 documentation through the official Nuxt MCP server, because agents mix Nuxt 3 and unreleased Nuxt 5 APIs; write the Nuxt 4 conventions into the agent's instruction file; and let `nuxt typecheck`, `@nuxt/test-utils` and `nuxt build` prove each change. The recipes target Nuxt 4.5. This page is for developers who let Claude Code, Codex or Cursor build a full-stack Nuxt app, and for the tech lead who has to trust the result. The agent's feature works on your machine, but it put the pages in `pages/` instead of `app/pages/`, passed a Zod schema straight to `readValidatedBody`, and read `document.cookie` in a plugin that also runs on the server. The page works after client-side navigation, the hydration warnings scroll past, and the first user who opens a deep link directly gets a 500. ## What these Nuxt recipes give you - A context setup that keeps the agent on Nuxt 4 when both its training data (Nuxt 3) and the newest docs and skills (Nuxt 5) pull it elsewhere - The official Nuxt MCP server wired into all three tools, plus the experimental dev-server MCP module - Seven prompts for the Nuxt work agents most often get wrong: validated server routes, data fetching, sessions, hybrid rendering, Cloudflare Workers, Nuxt Content, and the test harness - A gate table that signs a change off without anyone reading every line, and a failure table with recovery steps **Versions checked on 2026-09-26** npm registry: `nuxt` 4.5.2 (`latest`; the `3x` tag is 3.21.11), `nitropack` 2.13.4 with `h3` 1.15.x, `@nuxt/test-utils` 4.3.2, `@nuxt/content` 3.16.1, `@nuxt/image` 2.1.0, `nuxt-auth-utils` 0.5.30, `nuxt-mcp-dev` 0.3.2. Two traps: the `h3` package's `latest` tag is `2.0.1-rc.32`, so `npm install h3` gives you the Nuxt 5 server API; and the `main` branch of the Nuxt docs now describes Nuxt 5, which is "still in development" and has no release of the `nuxt` package (only `nuxt-nightly` builds). ## Keep the agent on Nuxt 4 docs An agent writing Nuxt code draws on three sources that disagree. Its training data is mostly Nuxt 3, with `pages/` at the root and `data` that defaults to `null`. The newest material describes Nuxt 5: Nitro v3, h3 v2, and server helpers imported from `nuxt/server`, which only arrives in Nuxt 4.6. Your `package.json` says 4.5. Every step below exists to make the third source win. 1. Write the Nuxt 4 rules down where every tool finds them: in `AGENTS.md` for Codex, in `CLAUDE.md` for Claude Code (or a `CLAUDE.md` containing `@AGENTS.md`; from v2.1.277 Claude Code reads `AGENTS.md` when there is no `CLAUDE.md`), and in a project Rule for Cursor. ```markdown ## Nuxt rules for this repo (Nuxt 4.5, nitropack 2, h3 1.x) - Vue code lives in app/ (app/pages, app/components, app/composables, app/middleware, app/plugins). server/, shared/, content/, public/ and nuxt.config.ts stay at the root. - Code used by both app and server goes in shared/utils or shared/types. - Look up APIs in the Nuxt 4.x docs (Nuxt MCP server, version 4.x). Never apply Nuxt 5 guidance: no h3 v2 APIs, and no nuxt/server imports until nuxt >= 4.6. - createError takes { status, statusText } (statusCode/statusMessage are deprecated). - Never add h3 or nitropack to package.json; use the versions Nuxt brings. - readValidatedBody / getValidatedQuery take a function: readValidatedBody(event, Schema.parse). - useFetch/useAsyncData: data and error start as undefined; branch on status, not pending. - No browser globals (window, document, localStorage) in setup, plugins or middleware unless guarded by import.meta.client or inside onMounted. - Done means: npx nuxt typecheck, npx eslint ., npx vitest run and npx nuxt build pass. ``` 2. Connect the Nuxt MCP server (next section) and tell the agent to query it with the `4.x` version filter. The server's `list-documentation-pages` tool accepts `3.x`, `4.x`, `5.x` or `all`, so an unfiltered lookup can return Nuxt 5 pages. The filter is not a version pin: the 4.x docs already describe Nuxt 4.6 features such as `nuxt/server`, so check the `nuxt` version in `package.json` before accepting code built on them. 3. Check any Nuxt skill before you install it. The `nuxt` skill in `antfu/skills` states that it "is based on Nuxt 5.x (`5.0.0-0`), generated at 2026-09-25". On a Nuxt 4.5 project it teaches `nuxt/server` imports and h3 v2, so leave it out until you upgrade. The `nuxt-ui` skill in `nuxt/ui` targets `@nuxt/ui` v4 and is safe to add if you use that library; see [installing and managing skills](/en/ecosystem/skills/installing-managing/). 4. Put the stale patterns in front of the reviewer too. These are the APIs the agent reaches for first: | Agent writes | Status on Nuxt 4.5 | Write instead | | --- | --- | --- | | `pages/`, `components/`, `composables/` at the root of a new project | Nuxt 3 layout; Nuxt 4 defaults `srcDir` to `app/` | `app/pages/` and so on; migrate an old app with `npx codemod@latest nuxt/4/file-structure` | | `readValidatedBody(event, BodySchema)` | h3 1.x expects a validation function | `readValidatedBody(event, BodySchema.parse)` | | `if (data.value === null)` or `pending.value` as the loading flag | `data` and `error` default to `undefined` in Nuxt 4 | `status.value === 'pending'` and `data.value === undefined` | | `import { defineEventHandler } from 'nuxt/server'` | Arrives in Nuxt 4.6 (not exported by 4.5.x) | The auto-imported `defineEventHandler` | | `routeRules: { '/blog/**': { isr: 3600 } }` on Cloudflare or Node | `isr` reaches the CDN only on Netlify and Vercel | `swr: 3600` everywhere else | | `preset: 'cloudflare-pages'` for a new Worker | Pages preset | `preset: 'cloudflare_module'`, the preset Nitro recommends for Workers | ## Connect the agent to the Nuxt docs and your dev server The Nuxt team runs a documentation MCP server at `https://nuxt.com/mcp` over HTTP, with no authentication. Its tools list and fetch documentation pages, blog posts, deployment guides, modules (with README, compatibility and download stats) and the changelog. The `X-MCP-Tools` header limits which tools load, which keeps the context cost down; see [reducing MCP token cost](/en/ecosystem/mcp/reducing-mcp-token-cost/). **Claude Code** ```bash # Terminal, in the project root. -s project writes .mcp.json so the team shares it. claude mcp add -s project --transport http nuxt https://nuxt.com/mcp \ -H "X-MCP-Tools: list-documentation-pages,get-documentation-page,get-module" ``` Run `/mcp` in a session to confirm `nuxt` is connected. **Codex** ```bash # Terminal. Writes the server to ~/.codex/config.toml. codex mcp add nuxt --url https://nuxt.com/mcp ``` Run `codex mcp list` to confirm the entry. `codex mcp add` has no header flag (checked in 0.157.1), so add the header to the entry it wrote, under `[mcp_servers.nuxt]`: ```toml # ~/.codex/config.toml [mcp_servers.nuxt] url = "https://nuxt.com/mcp" http_headers = { "X-MCP-Tools" = "list-documentation-pages,get-documentation-page,get-module" } ``` **Cursor** Add the server to `.cursor/mcp.json` in the project root. This is the shape the Nuxt docs give for Cursor. ```json { "mcpServers": { "nuxt": { "type": "http", "url": "https://nuxt.com/mcp", "headers": { "X-MCP-Tools": "list-documentation-pages,get-documentation-page,get-module" } } } } ``` The docs server knows Nuxt; it does not know your app. For that, Anthony Fu's `nuxt-mcp-dev` module (marked "Experimental. Use with caution.") adds an MCP endpoint to your dev server at `http://localhost:3000/__mcp/sse` and, per its README, updates the MCP config of VS Code, Cursor, Windsurf and Claude Code for you. Add it with `modules: ['nuxt-mcp-dev']` in `nuxt.config.ts`. The endpoint uses the SSE transport, which Claude Code still supports but has deprecated, so treat it as a convenience rather than a gate. For the browser's view of a page, add [Playwright MCP](/en/ecosystem/mcp/playwright-mcp/); the other dev-server servers are compared in [framework devtools MCP servers](/en/ecosystem/mcp/framework-devtools-mcp/). ## Validate a server route with Zod and a session check Server routes are where the agent's Nuxt 3 and Nuxt 5 habits collide. The route below needs a validated body, an authenticated user, and a proper status code for each failure. **Copy-paste prompt: a validated POST route** ```text Create server/api/posts.post.ts in this Nuxt 4.5 app (nitropack 2, h3 1.x, Zod 4). Look up server routes in the Nuxt MCP server with version 4.x first. - Put the Zod schema in shared/types/post.ts so the form can reuse it: title 3-200 chars, content min 10 chars, categoryId uuid, tags max 5 strings, publishedAt optional ISO date. - Handler: const session = await requireUserSession(event) (nuxt-auth-utils), then const body = await readValidatedBody(event, PostInput.parse). Pass the parse function, not the schema object. - Insert with Drizzle through server/utils/db.ts. Return 201 via setResponseStatus. A duplicate slug returns createError({ status: 409, statusText: 'Duplicate slug' }). - Do not add h3 or nitropack to package.json and do not import from nuxt/server. Tests in test/e2e/posts.test.ts with $fetch and setup from @nuxt/test-utils/e2e: 201 on valid input, 400 on each invalid field, 401 without a session, 409 on a duplicate. Run npx vitest run --project e2e and paste the output. ``` The 400 on invalid input comes from h3 itself: when the validation function throws, `readValidatedBody` turns it into a 400. That is why passing the schema object is dangerous. The call fails on every request, and a test that only checks "some error" still passes. ## Fetch data without duplicate requests or hydration errors The agent's usual data layer is `$fetch` inside `onMounted`, which fetches twice (once on the server, once on the client) or not at all on the server. The Nuxt pattern is `useFetch` or `useAsyncData` in `setup`, with a stable key and the status ref. **Copy-paste prompt: a typed data-fetching composable** ```text Create app/composables/useApi.ts for this Nuxt 4.5 app. - useApi<T>(path, options) wraps useFetch with: an explicit key built from the path and query, baseURL from useRuntimeConfig().public.apiBase, and an onResponseError hook that maps the body to an ApiError { statusCode, message, fieldErrors? } defined in shared/types. - Return { data, error, status, refresh, clear } unchanged from useFetch. Consumers branch on status ('idle' | 'pending' | 'success' | 'error'); data starts as undefined. - Use useFetch only in setup. For mutations triggered by a click, export apiPost/apiPut/apiDelete that call $fetch, then refresh() the affected useApi key. - Cookies on SSR: rely on useFetch forwarding request headers for relative URLs; for $fetch calls that run during SSR, use useRequestFetch(). Tests (test/nuxt/useApi.test.ts, environment nuxt): registerEndpoint to mock /api/posts, mountSuspended a test component that uses useApi, and assert status goes to 'success', the ApiError mapping on a 422, and that two components with the same key share one request. ``` The shared-key assertion matters. In Nuxt 4, components that call `useAsyncData` or `useFetch` with the same key share one `data`, `error` and `status` ref, and the docs require consistent options across those calls. A composable that builds keys from unstable values (a new object each render) breaks the sharing without breaking a type check. ## Add sessions and route middleware without SSR leaks Auth spans a server route, a route middleware, a plugin and a composable. The SSR boundary is where the agent fails: a plugin that reads `document.cookie` crashes the server render, and a middleware that trusts client state lets a crafted request through. `nuxt-auth-utils` keeps the session in a sealed cookie and gives you `requireUserSession` on the server and `useUserSession` in the app, which removes most of the hand-written token code. **Claude Code** Start in plan mode (`/plan`) and approve the file list before any code exists. After the change, run `/code-review` and ask it to list every file under `server/api/` that does not call `requireUserSession`. For CI, run the same audit read-only: `claude -p "…" --allowedTools "Read,Grep,Glob"`. **Codex** Run the change in its own worktree so a half-written plugin never breaks your dev server: `codex exec --worktree --sandbox workspace-write "…"`. Then ask a second, read-only session (`codex exec --sandbox read-only`) for the list of unprotected server routes. **Cursor** Use Plan Mode for the file list, then review the diffs of `app/middleware/auth.ts` and the login route in the editor. Those two files hold every decision. Search the diff for `document.` and `window.` before you accept it. **Copy-paste prompt: sessions with nuxt-auth-utils** ```text Add email and password auth to this Nuxt 4.5 app with nuxt-auth-utils. 1. npx nuxt module add auth-utils. NUXT_SESSION_PASSWORD (32+ chars) comes from .env locally and from the host's secret store in production; never commit it. 2. server/api/auth/login.post.ts: validate with readValidatedBody(event, LoginInput.parse), verifyPassword against the stored hash, setUserSession with { user: { id, name, role } }. Same 401 message for unknown email and wrong password. Rate-limit 5 attempts per email per 15 minutes. 3. server/api/auth/register.post.ts with hashPassword; server/api/auth/logout.post.ts with clearUserSession. 4. app/middleware/auth.ts (named): if !loggedIn from useUserSession(), navigateTo /login with a redirect query. app/middleware/guest.ts sends logged-in users to /dashboard. 5. Every route under server/api/ except auth/* calls requireUserSession; admin routes also check session.user.role on the server. The middleware is UX, not security. No window, document or localStorage anywhere in plugins or middleware. Tests (e2e): login sets the cookie, /dashboard redirects anonymous users, a non-admin gets 403 from a direct request to every admin route, logout clears the session. ``` ## Choose a rendering mode per route Marketing pages should be static, the dashboard rendered on the client or per request, and the blog cached. In Nuxt, that is one `routeRules` block, and the one fact the agent gets wrong is which rules your host honours. **Copy-paste prompt: hybrid rendering for your host** ```text Configure routeRules in nuxt.config.ts for this Nuxt 4.5 app deployed to Cloudflare Workers (preset cloudflare_module). Look up rendering in the Nuxt MCP server with version 4.x first. - '/', '/pricing', '/about': { prerender: true }. - '/blog/**': { swr: 3600 }. Do not use isr: it reaches the CDN only on Netlify and Vercel. - '/dashboard/**': { ssr: false }. '/api/**': { headers: { 'cache-control': 'no-store' } }. - '/old-pricing': { redirect: { to: '/pricing', statusCode: 301 } }. Then run npx nuxt build and paste the prerendered route list. Add an e2e test that fetches / and /blog/hello and asserts the cache-control header of each, and one that /dashboard returns the SPA shell without server-rendered dashboard markup. ``` On Vercel or Netlify, swap `swr` for `isr` and state the host in the prompt. Nitro maps route rules to those platforms' native CDN rules, and nowhere else. ## Deploy to Cloudflare Workers with D1 and KV Nitro's `cloudflare_module` preset builds a Workers module, and `cloudflare.deployConfig: true` generates the `wrangler.json`. Bindings reach your server code through `event.context.cloudflare.env`. The agent's two classic mistakes are the Pages preset and a binding name collision with Nuxt Content, which uses a D1 binding named `DB` by default. **Copy-paste prompt: Cloudflare Workers deployment** ```text Prepare this Nuxt 4.5 app for Cloudflare Workers. Read the Cloudflare deployment docs page through the Nuxt MCP server first (get-documentation-page, version 4.x). - nuxt.config.ts: nitro: { preset: 'cloudflare_module', cloudflare: { deployConfig: true, nodeCompat: true } }, with a D1 binding named APP_DB and a KV binding named SESSIONS declared in the generated wrangler config: d1_databases: [{ binding: 'APP_DB', database_name: '<name>', database_id: '<id>' }], kv_namespaces: [{ binding: 'SESSIONS', id: '<id>' }]. Ask me for the names and ids; do not invent them. Use the binding name APP_DB so it cannot collide with Nuxt Content's default DB binding. - server/utils/cf.ts: typed accessor useCf(event) returning event.context.cloudflare.env, throwing a 500 with a clear message when the binding is missing (it is undefined in plain nuxt dev without the Cloudflare dev preset). - Drizzle with the D1 driver in server/utils/db.ts; migrations with drizzle-kit into server/db/migrations. - Secrets (NUXT_SESSION_PASSWORD and others) go through wrangler secret put, never into wrangler.json or nuxt.config.ts. Verify locally: npx nuxt build, then npx wrangler dev, then run the e2e suite against it. Do not run wrangler deploy; CI deploys. ``` For the Workers platform itself (Queues, Durable Objects, limits), see [serverless development patterns](/en/cookbook/backend-recipes/serverless-patterns/); for letting the agent inspect your Cloudflare account, see the [Cloudflare MCP server](/en/ecosystem/mcp/cloudflare-mcp/). Drizzle schema and migration patterns are in [ORM best practices](/en/cookbook/database-recipes/orm-patterns/). ## Build a blog with Nuxt Content 3 Nuxt Content 3 replaced the v2 query API with collections declared in `content.config.ts` and queried with `queryCollection()`, backed by SQLite (D1 on Cloudflare). An agent trained on v2 writes `queryContent()` and `<ContentDoc>`, which no longer exist. **Copy-paste prompt: a Nuxt Content 3 blog** ```text Add a blog with @nuxt/content 3 to this Nuxt 4.5 app. Look up the collections API in the Nuxt MCP server (get-module for @nuxt/content) first. Do not use queryContent, ContentDoc or any v2 API. - content.config.ts: a blog collection, type 'page', source 'blog/**/*.md', schema with Zod: title, description, date, tags (string array), draft (boolean, default false). - app/pages/blog/index.vue: useAsyncData('blog-list', () => queryCollection('blog') .where('draft', '=', false).order('date', 'DESC').all()), paginated 10 per page. - app/pages/blog/[...slug].vue: queryCollection('blog').path(route.path).first(), ContentRenderer, a 404 via createError({ status: 404 }) when nothing matches, and useSeoMeta with title and description from the document. - server/routes/rss.xml.ts returning published posts as RSS 2.0. Tests: a draft post never appears in the list, the RSS feed, or at its URL; a missing slug returns 404. Run npx nuxt build and confirm no content build errors. ``` ## Set up the Nuxt test harness the agent runs every time Tests only protect you if the agent runs them after every edit. `@nuxt/test-utils` 4.x splits the work into Vitest projects: plain unit tests in Node, Nuxt-runtime tests (components, composables, plugins) in the `nuxt` environment, and end-to-end tests that build and serve the app. **Claude Code** Add a `Stop` hook whose script runs `npx nuxt typecheck && npx vitest run` and exits with code 2 on failure. The error goes back to the agent instead of ending the turn. See [hooks automation](/en/claude-code/automate/hooks-automation/). **Codex** Put the "Done means" line from the rules block in `AGENTS.md` and ask for the command output in the final message. For CI, `codex exec --sandbox workspace-write -o result.md "…"` writes that message to `result.md`, which your CI job can upload as an artifact. **Cursor** Keep the "Done means" line in your project Rules and run the harness in the integrated terminal after each agent step. Paste a failing `mountSuspended` stack trace back into the chat instead of describing it. **Copy-paste prompt: the @nuxt/test-utils harness** ```text Set up testing for this Nuxt 4.5 app with @nuxt/test-utils, Vitest, @vue/test-utils and happy-dom. Follow the 4.x testing docs from the Nuxt MCP server. - vitest.config.ts with test.projects: unit (test/unit, environment node), e2e (test/e2e, environment node) and nuxt (test/nuxt, created with defineVitestProject, environment nuxt). Add "type": "module" to package.json if missing. - test/nuxt: mountSuspended tests for AppHeader, PostCard and LoginForm; registerEndpoint for every API they call; mockNuxtImport only where a composable must be faked. - test/e2e: setup({ server: true }) and $fetch for two API routes. - package.json scripts: test (vitest run), test:unit, test:nuxt, test:e2e, typecheck (nuxt typecheck, with vue-tsc and typescript as devDependencies). Never mix @nuxt/test-utils/runtime and @nuxt/test-utils/e2e in one file. Run all projects and paste the summary. Break one assertion on purpose, show that it fails, then restore it. ``` The deliberate failure at the end is the cheapest check that the tests can fail at all. An agent-written test that passes whatever the code does is worse than none. ## How to verify agent-written Nuxt code without reading every line Read the diffs of `nuxt.config.ts`, anything under `app/middleware/` and `app/plugins/`, and every server route that reads a session. Let the gates prove the rest. | Gate | Command or tool | What goes red | | --- | --- | --- | | Types | `npx nuxt typecheck` | Wrong `useFetch` return types, a `nuxt/server` import on Nuxt 4.5, a shared type the client did not follow | | Lint | `npx eslint .` with `@nuxt/eslint` 1.17.0 | Unused auto-imports, browser globals where you ban them with `no-restricted-globals` | | Unit and runtime tests | `npx vitest run --project unit --project nuxt` | Composable behaviour, component states, mocked endpoints | | End to end | `npx vitest run --project e2e`, or Playwright against `npx nuxt preview` | Auth bypass, status codes, cache headers, redirects | | Build | `npx nuxt build` | Prerender errors, Nuxt Content parse errors, preset problems | | Hydration | Playwright test that fails on any `console` message containing `Hydration` | Server and client markup that differ | | Bundle | `npx nuxt analyze` (experimental) | A dependency that doubled the client bundle | The developer who owns the pull request signs off on the gate results and the files named above; CI enforces the rest. For how that review scales across a team, see [reviewing agent pull requests](/en/workflows/ship/agent-pr-review/), and for writing the acceptance criteria your e2e tests encode, see [acceptance criteria agents can verify](/en/workflows/plan/acceptance-criteria/). ## When agent-written Nuxt code breaks | Symptom | Cause | Recovery | | --- | --- | --- | | Every POST to a new route returns 400 | `readValidatedBody(event, Schema)` with the schema object | Pass `Schema.parse`; add a test that a valid body returns 2xx, not only that invalid ones fail | | Pages 404 after the agent adds them | Files created in root `pages/` while the app uses `app/` (or the reverse) | Move them under `app/pages/`; keep the directory rule in `AGENTS.md` | | `Cannot find module 'nuxt/server'` or h3 errors about `event.req` | Guidance for Nuxt 4.6+ or Nuxt 5 (the 4.x docs already describe 4.6; the docs `main` branch and Nuxt 5 skills describe 5) | Check `package.json`'s `nuxt` version before accepting `nuxt/server` imports; on 4.5, remove any direct `h3` dependency and revert to auto-imports | | `document is not defined` during SSR | Browser API in a plugin, middleware or `setup` | Guard with `import.meta.client`, move it into `onMounted`, or name the plugin `*.client.ts` | | Hydration mismatch warnings | `Date.now()`, `Math.random()` or locale formatting in render | Compute on the server and pass it through `useState`, or wrap the widget in `<ClientOnly>` | | A page shows another request's data | Two `useFetch` calls share a key with different options | Build keys from the full URL and query; keep options identical for a shared key | | Blog pages never refresh after `isr: true` | Without a TTL, `isr: true` keeps a page until the next deploy; without Netlify or Vercel, `isr` behaves like `swr` and gets no CDN caching | Use `swr` with a TTL; add the cache-header e2e test | | D1 queries hit the wrong database after adding Nuxt Content | Both use the `DB` binding | Rename your app binding (for example `APP_DB`) and redeploy | ## Where to go next with Nuxt and agents - Start from the [frontend recipes overview](/en/cookbook/frontend-recipes/) for the browser and gate setup every framework recipe assumes. - Take component-level and Pinia patterns further with [Vue.js workflow recipes](/en/cookbook/frontend-recipes/vue-patterns/). - Build the browser suite behind the e2e gate with [end-to-end testing with agents](/en/workflows/test/e2e-testing/). - Compare Nuxt with the React stack in [Next.js optimization recipes](/en/cookbook/frontend-recipes/nextjs-patterns/). - Find other skills for Vue and Nuxt work in [best skills for frontend development](/en/ecosystem/skills/top-skills-frontend/), and give agents current docs for the rest of your stack with [Context7](/en/ecosystem/mcp/context7/). --- # React Development Recipes URL: https://developertoolkit.ai/en/cookbook/frontend-recipes/react-patterns/ Description: Copy-paste prompts for React 19 work in Claude Code, Codex and Cursor: Figma to code, TanStack v9 tables, forms, optimistic UI, and gates. React development recipes for AI agents are copy-paste prompts for production React 19 code in Claude Code, Codex or Cursor. Each pairs a prompt with the gate that proves the result: type check, React Hooks lint rules, Vitest with Testing Library, and a Playwright accessibility scan. Start by pinning library versions: agents default to APIs that no longer exist. This page is for React developers and the tech leads who set their team's agent conventions. You ask the agent for a data table and it writes `useReactTable`, which TanStack Table v9 no longer exports. You ask for a form and get `z.string().email()`, deprecated in Zod 4. The code looks idiomatic, the diff is 600 lines, and you cannot read all of it before Friday. ## What these React recipes give you - A version-pin block for `CLAUDE.md`, `AGENTS.md` or a Cursor rule that stops the agent from writing TanStack Table v8, TanStack Query v4, Zod 3 or Create React App code - One "definition of done" command the agent runs before it reports success, so you review a green gate instead of every line - Eight prompts for common React work: Figma to component, data tables, server state, optimistic UI, forms, class-to-hooks refactors, performance, and a Create React App to Vite migration - A table of which gate catches which class of bug, and who signs the change off - The failure modes of agent-written React and how to get out of each one **Versions checked** npm registry on 2026-09-30: `react` 19.3.0, `@tanstack/react-table` 9.2.4, `@tanstack/react-query` 5.104.0, `zustand` 5.0.15, `react-hook-form` 7.89.0, `@hookform/resolvers` 5.9.1, `zod` 4.6.5, `vite` 8.3.1, `vitest` 5.0.3, `@testing-library/react` 16.3.3, `eslint-plugin-react-hooks` 7.1.1, `@axe-core/playwright` 4.13.0, `msw` 3.0.0 (a major release on 2026-09-28; `setupServer` still returns `server.resetHandlers()`, so the recovery steps below hold). CLIs on 2026-09-26: Claude Code 2.1.283, Codex CLI 0.157.1. ## Pin the React stack in the agent's context first Agents learned React from years of React 16–18 code, TanStack Table v8 and Create React App tutorials. Without a pin they reproduce it. Put the versions, the banned APIs and the done command in the instructions your tool reads: `CLAUDE.md` for Claude Code, `AGENTS.md` for Codex, and a project rule for Cursor. Claude Code v2.1.277 and later also reads `AGENTS.md` when a project has no `CLAUDE.md`. ```markdown ## Frontend stack (React) - React 19.3, TypeScript strict, Vite 8, Vitest 5 + Testing Library, Playwright for e2e. - Server state: TanStack Query v5. Client state: Zustand 5. Forms: React Hook Form 7 + Zod 4 via @hookform/resolvers. Tables: TanStack Table v9 (`useTable` + `tableFeatures`). - Never write: useReactTable, cacheTime, `import { ReactComponent } from './x.svg'`, process.env.REACT_APP_*, z.string().email(), `as any`, useState+useEffect loading flags for server data. - Before you say a task is done, run `npm run verify` and paste the last 20 lines of output. - Tests query by role and label, never by class name or test id unless no role exists. ``` The replacements below were checked against the published type definitions of the versions in the note above: | Agent writes | Status on 2026-09-26 | Write instead | | --- | --- | --- | | `useReactTable(options)` | Not exported by `@tanstack/react-table` 9.2.4; only `useLegacyTable` from `/legacy`, marked deprecated | `useTable({ ...options, features })` with `tableFeatures()` | | `cacheTime` in a query | Not in `@tanstack/query-core` v5 types | `gcTime` | | `z.string().email()` | `@deprecated Use z.email() instead` in Zod 4.6.5 | `z.email()` | | `import { ReactComponent } from './logo.svg'` | Create React App only | `import Logo from './logo.svg?react'` with `vite-plugin-svgr` 5 | | `process.env.REACT_APP_API_URL` | Create React App only | `import.meta.env.VITE_API_URL` | | Loading and error flags in `useState` around `fetch` | Works, but duplicates what the cache does | a `useQuery` hook per endpoint | **TanStack Table v9 ships its own agent skills** The `@tanstack/react-table` 9.2.4 package includes a `skills/` directory with `getting-started`, `migrate-v8-to-v9`, `table-state`, `create-table-hook`, `with-tanstack-query` and `with-tanstack-virtual`. Tell the agent to read `node_modules/@tanstack/react-table/skills/<name>/SKILL.md` before writing table code. It is the vendor's own checklist, pinned to the version you installed. ## Give the agent one command that proves the change A recipe is only as good as the check that runs after it. Add one script that chains every gate, and make the agent run it before it reports done: ```json { "scripts": { "verify": "tsc --noEmit && eslint . --max-warnings 0 && vitest run && playwright test --grep @a11y" } } ``` Use the flat `recommended` config from `eslint-plugin-react-hooks` 7, and raise `react-hooks/exhaustive-deps` to `error`: stale closures are a common agent bug, and this rule catches them without a human reading the dependency array. In v7 the flat preset is `reactHooks.configs.flat.recommended`; the `plugin:react-hooks/recommended` string that agents often write is the legacy `.eslintrc` form: ```js // eslint.config.js import reactHooks from 'eslint-plugin-react-hooks'; import { defineConfig } from 'eslint/config'; export default defineConfig([ reactHooks.configs.flat.recommended, { rules: { 'react-hooks/exhaustive-deps': 'error' } }, ]); ``` The `@a11y` Playwright tests run `@axe-core/playwright` against each page the change touched. How you make the agent run `verify` differs by tool: **Claude Code** Put the rule in `CLAUDE.md` as in the block above. To enforce it rather than ask for it, add a `Stop` hook to `.claude/settings.json`. Exit code 2 blocks the stop and hands the gate's output, sent to stderr, back to Claude: ```json { "hooks": { "Stop": [{ "hooks": [{ "type": "command", "command": "jq -e '.stop_hook_active' >/dev/null && exit 0; npm run verify >&2 || exit 2" }] }] } } ``` The `stop_hook_active` check lets the stop through on the second attempt, so a failure Claude cannot fix ends the turn and reaches you instead of looping; Claude Code also caps stop-hook continuations at eight in a row. See [hooks automation](/en/claude-code/automate/hooks-automation/) for a version that runs only on a dirty working tree. For a headless run in CI, `claude -p` takes the same prompt. **Codex** Put the rule in `AGENTS.md`, which Codex loads at the start of a session. In CI, `codex exec` runs the prompt headless; run `npm run verify` as the next step of the CI job so the job fails when the gate does, whatever the agent reported. **Cursor** Put the rule in a project rule. Cursor Hooks can run a script at points in the agent loop, so the gate does not depend on the agent remembering the rule. Bugbot then reviews the pull request as a second opinion, not as the gate. ## Turn a Figma frame into a typed component **Scenario:** you have a Figma frame for a pricing card and want a component that reuses your existing `Button` and `Card` instead of inventing new ones. The Figma MCP server gives the agent the frame's layout, variables and Code Connect mappings. Figma's plugin bundles the remote server (`https://mcp.figma.com/mcp`) with its design-to-code skills. Check your seat before you plan a sprint on it: Starter plans, and View or Collab seats on paid plans, get up to 6 tool calls per month, while Dev and Full seats on Professional, Organization and Enterprise plans get per-minute limits. The details are in [Figma MCP and design-to-code](/en/ecosystem/mcp/design-tools-mcp/). **Claude Code** ```bash claude plugin install figma@claude-plugins-official # or the server alone, then run /mcp in a session to log in: claude mcp add --transport http figma https://mcp.figma.com/mcp ``` **Codex** ```bash codex mcp add figma --url https://mcp.figma.com/mcp codex mcp login figma ``` Or install Figma's plugin, which bundles the server with its design-to-code skills: ```bash codex plugin add figma@openai-curated ``` **Cursor** Type `/add-plugin figma` in the agent chat (from Figma's README), or add the server to `.cursor/mcp.json`: ```json { "mcpServers": { "figma": { "url": "https://mcp.figma.com/mcp" } } } ``` **Copy-paste prompt: Figma frame to React component** ```text Implement this Figma frame as a React component: <paste the frame URL with node-id>. Call get_design_context and get_screenshot first. Reuse Button, Card and Badge from src/components/ui; do not create new primitives. Map Figma variables to our Tailwind theme tokens; if a value has no token, list it instead of hard-coding a hex. Output: PricingCard.tsx with an exported PricingCardProps interface, a Storybook story with default, highlighted and disabled variants, and a Vitest test that finds the CTA by role and asserts the price text. Run npm run verify and show the result. ``` **How you know it worked:** the list of values with no token is empty or explained, `verify` is green, and a Storybook screenshot next to the Figma screenshot matches at your breakpoints. A designer compares those two images; nobody needs to read the Tailwind classes. ## Build a data table with TanStack Table v9 **Scenario:** an admin screen needs a sortable, filterable, paginated table of 10,000 users with row selection. **Copy-paste prompt: TanStack Table v9 data table** ```text Read node_modules/@tanstack/react-table/skills/getting-started/SKILL.md and node_modules/@tanstack/react-table/skills/table-state/SKILL.md before writing code. Build a generic DataTable<TData> in src/components/data-table/ with @tanstack/react-table v9: useTable with tableFeatures registering only row sorting, column filtering, pagination and row selection. Do not use useReactTable or useLegacyTable. Props: data, columns, onSelectionChange. Page sizes 10/25/50/100, a loading skeleton, an empty state, and a header button per sortable column with aria-sort. Tests: sort toggles order, a filter narrows rows, selection calls onSelectionChange with the selected rows, and the empty state renders. Run npm run verify. ``` **How you know it worked:** `grep -r "useReactTable\|useLegacyTable" src` returns nothing, the four tests pass, and the axe scan finds no violations on the page. For server-side paging, point the agent at the `with-tanstack-query` skill in the same directory. ## Move server state to TanStack Query v5 **Scenario:** 15 components each fetch in `useEffect` and keep their own `loading` and `error` flags. Data goes stale after an edit on another screen. **Copy-paste prompt: TanStack Query v5 hooks with MSW tests** ```text Replace every fetch-in-useEffect under src/features/users/ with TanStack Query v5. Create src/lib/query-client.ts (staleTime 60s, gcTime 5 min, retry 2, no retry on 4xx) and src/features/users/api.ts with a queryOptions factory per endpoint and hooks useUsers(params), useUser(id), useCreateUser(), useUpdateUser(), useDeleteUser(). Mutations invalidate the list and detail keys they affect. Errors are typed from our ApiError class. Use gcTime, never cacheTime. Tests: mock the HTTP layer with MSW, not the hooks; one test per hook plus one that proves an update refreshes the list. Keep Zustand only for UI state (theme, sidebar); move nothing server-owned into it. Run npm run verify and list each component you changed. ``` **How you know it worked:** `grep -rn "useEffect" src/features/users` shows no data fetching, the list-refresh test passes, and the component list matches the files in the diff. Mocking HTTP with MSW rather than mocking the hooks keeps the tests honest: the agent cannot make them pass by mocking the thing under test. ## Add optimistic UI without losing data **Scenario:** toggling a todo waits 400 ms for the server, and users double-click. Use React 19's `useOptimistic` when the update comes from a form action and the state is local to one component. Use TanStack Query's `onMutate` / `onError` / `onSettled` when the same data appears in several places through the query cache. **Copy-paste prompt: optimistic updates with rollback** ```text Make add, toggle and delete in src/features/todos/ optimistic using TanStack Query v5. In onMutate: cancel outgoing queries for ['todos'], snapshot the cache, apply the change (new items get a temporary id from crypto.randomUUID() and a pending flag). In onError: restore the snapshot and show a toast with the server message. In onSettled: invalidate ['todos']. Delete shows an Undo toast for 5 seconds. Tests with MSW: the UI updates before the response resolves; a 500 restores the previous list; two fast toggles end in the server's final state. Run npm run verify. ``` **How you know it worked:** the rollback test and the double-toggle test pass. Those two cases are where optimistic code loses data, and they are the only part of this diff worth a human glance. ## Build forms with React Hook Form and Zod 4 **Scenario:** a settings form gets validation errors back from the server, and they land on the wrong field or nowhere at all. **Copy-paste prompt: typed form with server-side errors** ```text Build the account settings form in src/features/settings/ with React Hook Form 7 and Zod 4 through zodResolver from @hookform/resolvers. Define the schema once in schema.ts and infer the form type with z.infer; use z.email() and z.url(), not the deprecated string methods. Map a 422 response body { field, message }[] onto the fields with setError. Every input has a visible label; errors are linked with aria-describedby and announced. Tests with userEvent: empty submit shows errors, a bad email shows the email message, a 422 lands on the right field, and a valid submit sends the parsed values once. Run npm run verify. ``` **How you know it worked:** the four tests pass and the axe scan is clean. If the agent reaches for `as any` to satisfy the resolver types, reject the change: the version pin is wrong or the resolver is out of date. ## Refactor a class component to hooks without changing behaviour **Scenario:** a 400-line class component with `componentDidUpdate` logic nobody fully understands, and no tests. Write the tests before the refactor. A refactor that has only the agent's word for "no behaviour change" is unverified. The method is in [characterization tests](/en/workflows/test/characterization-tests/). **Copy-paste prompt: characterize, then refactor** ```text Step 1, do not touch src/components/UserDashboard.tsx yet: write characterization tests that pin its current behaviour - rendered output for three prop sets, every API call it makes and when, and what happens when props change. Run them; they must pass against the class version. Commit. Step 2: convert UserDashboard to a function component, moving state logic into useUserDashboard.ts. Do not edit the tests. Do not change props, markup or API calls. Run npm run verify. If a characterization test fails, fix the component, not the test. Commit. ``` **How you know it worked:** the test files are identical between the step 1 and step 2 commits (`git diff HEAD~1 HEAD -- '*.test.tsx'` is empty after both commits exist) and they pass on both. That diff is the one thing to check by hand. ## Find the re-renders that actually cost time **Scenario:** the product list takes seconds to respond to a filter change. The instinct, human or agent, is to wrap everything in `memo`, `useMemo` and `useCallback`. Measure first. If the project already compiles with the React Compiler (`babel-plugin-react-compiler` 1.0.0 in `package.json`), most manual memoization is redundant, and the fix is usually a component the compiler skipped or an expensive computation during render. Chrome DevTools MCP gives the agent a performance trace of the real page: **Claude Code** ```bash claude mcp add chrome-devtools --scope user npx chrome-devtools-mcp@latest ``` **Codex** ```bash codex mcp add chrome-devtools -- npx chrome-devtools-mcp@latest ``` **Cursor** ```json { "mcpServers": { "chrome-devtools": { "command": "npx", "args": ["-y", "chrome-devtools-mcp@latest"] } } } ``` The server sends usage statistics to Google by default; add `--no-usage-statistics` to opt out. **Copy-paste prompt: measured performance fix** ```text Start the dev server. With the chrome-devtools MCP, open http://localhost:5173/products, start a performance trace, type "shoe" into the filter, stop the trace. Report the three longest tasks and the components they belong to. Propose at most three fixes, each tied to a number from the trace. Apply them, record the same trace again, and show before/after durations in a table. Do not add memo, useMemo or useCallback anywhere the trace does not point to. Run npm run verify. ``` **How you know it worked:** the before/after table shows the interaction getting faster on the same trace, and the diff touches only the components the trace named. Watch the profiler rather than the code; see [performance testing](/en/workflows/test/performance-testing/) for making the number a CI budget. ## Migrate from Create React App to Vite **Scenario:** a Create React App project is still on `react-scripts` 5.0.1, the last stable release (April 2022), and its dev server takes minutes to start. **Copy-paste prompt: Create React App to Vite 8** ```text Migrate this Create React App project to Vite 8 without changing app behaviour. 1. Record a baseline: run the current test suite and save the list of passing tests. 2. Add vite.config.ts with @vitejs/plugin-react, aliases from tsconfig paths, and vite-plugin-svgr for SVGs imported as components (import Logo from './logo.svg?react'). 3. Move public/index.html to the project root with a module script entry. 4. Rename every REACT_APP_ variable to VITE_ in .env* files and replace process.env.REACT_APP_* with import.meta.env.VITE_* in code; add types in vite-env.d.ts. 5. Move Jest to Vitest with a jsdom environment; keep test bodies unchanged. 6. Remove react-scripts and react-app-rewired. Finish by running npm run build and npm run verify, and compare the passing-test list with the baseline. Report any test that changed status. ``` **How you know it worked:** `grep -rn "REACT_APP_\|react-scripts" src package.json .env*` returns nothing, and the passing-test list matches the baseline. The larger version of this job is in [legacy modernization](/en/workflows/build/legacy-modernization/). ## Add a React review skill for a second opinion Two skills from `vercel-labs/agent-skills` review React code against written rules, and install into Claude Code, Codex and Cursor through the same CLI. The `--skill` value is the frontmatter name, not the folder name: ```bash npx skills add vercel-labs/agent-skills --skill vercel-react-best-practices npx skills add vercel-labs/agent-skills --skill web-design-guidelines ``` `vercel-react-best-practices` flags data-fetching waterfalls, bundle size and re-render problems; `web-design-guidelines` reports accessibility, focus and form issues as `file:line` findings. Use them as reviewers after `verify` is green, not as the gate. More options are on [the best skills for frontend development](/en/ecosystem/skills/top-skills-frontend/). ## How to verify agent-written React code without reading every line | Gate | Catches | Runs where | Signs off | | --- | --- | --- | --- | | `tsc --noEmit` with `strict` | Wrong props, lost generics, stale library APIs that no longer type-check | agent loop, CI | automatic | | `eslint-plugin-react-hooks` 7 with `exhaustive-deps` at `error` | Stale closures, conditional hooks, Rules of React violations | agent loop, CI | automatic | | Vitest + Testing Library + MSW | Behaviour: what the user sees after each action, including error paths | agent loop, CI | automatic; the author reviews test names, not bodies | | Characterization tests, unchanged across the refactor | Behaviour drift in refactors | agent loop, CI | author checks the test diff is empty | | Playwright + `@axe-core/playwright` | Missing labels, focus traps, contrast, roles | CI | automatic; an accessibility owner reviews new exceptions | | Storybook screenshot next to Figma | Visual drift from the design | pull request | designer | | Performance trace before/after | Regressions in the interaction you changed | agent loop with Chrome DevTools MCP | author; a CI budget when it matters | A human reviews what the gates cannot: the acceptance criteria, the test names, and any diff to a test file. Write the acceptance criteria before the prompt; see [acceptance criteria](/en/workflows/plan/acceptance-criteria/). Keep the agent from editing its own tests to make them pass; see [protect the oracle](/en/workflows/test/protect-the-oracle/). ## When agent-written React code breaks - **The agent writes an API the installed version does not have.** `useReactTable`, `cacheTime` and `z.string().email()` are the common ones. Recovery: add the version-pin block, point the agent at the library's bundled skill or its `.d.ts` files in `node_modules`, and let `tsc` reject the rest. - **Stale closures.** A `useCallback` or `useEffect` reads state its dependency array does not list, so it acts on old values. Recovery: `exhaustive-deps` at `error`; never let the agent silence it with an `eslint-disable` comment. Ban that comment in review. - **Tests that test the mock.** The agent mocks the hook it wrote and asserts the mock returned what it was told to. Recovery: mock at the HTTP boundary with MSW and reject tests that `vi.mock` the module under test. - **Blind memoization.** `memo` on every component adds comparison cost and hides the real problem. Recovery: require a trace number for every memoization, as in the performance prompt; with the React Compiler on, remove manual memoization the trace does not justify. - **`as any` at library boundaries.** Generic tables and form resolvers lose type inference, and the agent casts. Recovery: treat `as any` as a failed gate (`@typescript-eslint/no-explicit-any` at `error`) and ask for the generic signature instead. - **Mocks leaking between tests.** A test passes alone and fails in the suite. Recovery: set `restoreMocks: true` in the Vitest config, and reset MSW handlers in `afterEach`. - **Design drift from Figma.** The agent hard-codes a hex or spacing value. Recovery: the prompt asks for a list of values with no token; the designer compares screenshots, not class names. ## Where to go next with React and agents - [Frontend recipes overview](/en/cookbook/frontend-recipes/) for the other frameworks in this section - [Next.js recipes](/en/cookbook/frontend-recipes/nextjs-patterns/) for Server Components, the App Router and caching, which this page leaves to its neighbour - [Unit testing with agents](/en/workflows/test/unit-testing/) and [accessibility testing](/en/workflows/test/accessibility-testing/) for the gates behind `verify` - [Playwright MCP](/en/ecosystem/mcp/playwright-mcp/) and [agent-browser](/en/ecosystem/skills/agent-browser/) for letting the agent check the running app - [React Native development patterns](/en/cookbook/mobile-development/react-native/) when the same team ships mobile --- # Vue.js Workflow Recipes URL: https://developertoolkit.ai/en/cookbook/frontend-recipes/vue-patterns/ Description: Copy-paste prompts for Vue 3.5 work in Claude Code, Codex and Cursor: Pinia 4 stores, composables, forms, routes, i18n, and the gates that prove them. Vue.js workflow recipes are copy-paste prompts that get production Vue 3.5 code from Claude Code, Codex or Cursor. Each recipe pairs a prompt with the check that proves it: `vue-tsc`, `eslint-plugin-vue` reactivity-loss rules, Vitest with Vue Test Utils, and a Playwright accessibility scan. Pinning versions matters most, because popular Vue packages disagree about which versions they support. This page is for Vue developers and the tech leads who set their team's agent conventions. You ask the agent for a store and it writes Vuex with the Options API. You ask for a form and it installs `@vee-validate/zod`, which declares Zod 3 as its peer while your project runs Zod 4. The component renders, a destructured store property silently stops updating, and nothing fails until a user changes a quantity in the cart. ## What these Vue recipes give you - A version-pin block for `CLAUDE.md`, `AGENTS.md` or a Cursor rule that keeps the agent on `<script setup>`, Pinia 4 and the packages your lockfile actually holds - One `verify` command the agent runs before it reports success, so you review a green gate instead of every line - Eight prompts for the Vue work agents are asked for most: typed components, Pinia stores, composables, multi-step forms, long lists, lazy routes, i18n, and Options API migrations, plus Storybook setup - A table of which gate catches which class of bug, and who signs the change off - The failure modes of agent-written Vue and how to get out of each one **Versions checked on 2026-09-26** npm registry: `vue` 3.5.43, `pinia` 4.0.3, `@pinia/testing` 2.0.1, `pinia-plugin-persistedstate` 4.7.1, `vue-router` 5.3.1, `vue-i18n` 11.4.12, `@vueuse/core` 15.0.0, `vee-validate` 4.15.1, `zod` 4.6.5, `@tanstack/vue-virtual` 3.13.39, `vue-tsc` 3.3.11, `eslint-plugin-vue` 10.11.1, `vite` 8.3.1, `vitest` 5.0.2, `@vue/test-utils` 2.5.1, `storybook` 10.6.0, `@axe-core/playwright` 4.13.0, `msw` 2.15.0. CLIs: Claude Code 2.1.283, Codex CLI 0.157.1. ## Pin the Vue stack in the agent's context first Agents learned Vue from years of Vue 2, Vuex and Options API tutorials, and from package READMEs that predate this year's major releases. Put the versions, the banned patterns and the done command in [the instructions your tool reads](/en/developer-scorecard-guide/claude-md-context/): `CLAUDE.md` for Claude Code, `AGENTS.md` for Codex, and a project rule for Cursor. Claude Code v2.1.277 and later also reads `AGENTS.md` when a project has no `CLAUDE.md`. ```markdown ## Frontend stack (Vue) - Vue 3.5 with <script setup lang="ts"> only. TypeScript strict. Vite 8, Vitest 5, Vue Test Utils 2, Playwright for e2e. - State: Pinia 4 setup stores. Routing: Vue Router 5. i18n: vue-i18n 11 with legacy: false. Utilities: check @vueuse/core before writing a composable (useFetch, useWebSocket, useColorMode, useRefHistory already exist). - Validation: Zod 4 schemas. Do not install @vee-validate/zod (its peer range is Zod 3). - Never write: Options API in new files, Vuex, `this.$store`, destructuring a store or a reactive() object without storeToRefs/toRefs, `as any`, `<Suspense>` for route loading. - Before you say a task is done, run `npm run verify` and paste the last 20 lines of output. - Tests find elements by role and label text, never by CSS class. ``` The traps below were checked against the published packages on 2026-09-26. Each one is a case where the agent's default, or the first README it finds, gives you something that installs and then misbehaves: | Agent writes | What the registry says on 2026-09-26 | Write instead | | --- | --- | --- | | `createI18n({ locale: 'en' })` | `legacy` defaults to `true` in vue-i18n 11.4.12 and is marked "will be removed at vue-i18n v12" | `createI18n({ legacy: false, ... })` and `useI18n()` | | `npm i @vee-validate/zod` with Zod 4 | `@vee-validate/zod` 4.15.1 declares `peerDependencies: { zod: "^3.24.0" }` | Validate with the Zod 4 schema's `safeParse` in a small composable, as in the form recipe below | | `import { expect } from '@storybook/test'` | The package stopped at 8.6.15; Storybook 10.6.0 ships it as `storybook/test` | `import { expect } from 'storybook/test'` | | `@storybook/addon-vitest` next to Vitest 5 | Its 10.6.0 peer range is `vitest ^3.0.0 \|\| ^4.0.0` | Check the peer range first, as in the Storybook recipe below | | `vite-plugin-vue-mcp` for a Vite 8 app | Its 0.3.2 peer range ends at Vite 6 | Chrome DevTools MCP or Playwright MCP against the dev server | | `const { items } = useCartStore()` | Loses reactivity: `items` is a snapshot | `const { items } = storeToRefs(useCartStore())` | ## Give the agent one command that proves the change Add one script that chains every gate, and make the agent run it before it reports done: ```json { "scripts": { "verify": "vue-tsc --noEmit && eslint . --max-warnings 0 && vitest run && playwright test --grep @a11y" } } ``` The last step runs only tests whose title carries `@a11y`, so on a fresh project it matches nothing until you add one. Start with a single axe scan of a page and add a test per view as you build it: ```ts // e2e/a11y.spec.ts import { test, expect } from '@playwright/test'; import AxeBuilder from '@axe-core/playwright'; test('home page has no axe violations @a11y', async ({ page }) => { await page.goto('/'); const results = await new AxeBuilder({ page }).analyze(); expect(results.violations).toEqual([]); }); ``` `eslint-plugin-vue` 10 ships `flat/recommended`, but the two rules that catch the most common agent bug in Vue, lost reactivity, are not in that preset. Turn them on yourself: ```js // eslint.config.js import pluginVue from 'eslint-plugin-vue'; export default [ ...pluginVue.configs['flat/recommended'], { rules: { 'vue/no-ref-object-reactivity-loss': 'error', 'vue/no-setup-props-reactivity-loss': 'error', 'vue/require-explicit-emits': 'error', 'vue/no-v-html': 'error', }, }, ]; ``` Add your TypeScript parser setup (for example `typescript-eslint`) to the same file. How you make the agent run `verify` differs by tool: **Claude Code** Put the rule in `CLAUDE.md` as in the block above. To enforce it rather than ask for it, add a `Stop` hook that runs `npm run verify` and blocks the stop when it fails; see [hooks automation](/en/claude-code/automate/hooks-automation/). For a headless run in CI, `claude -p` takes the same prompt. **Codex** Put the rule in `AGENTS.md`, which Codex loads at the start of a session. In CI, `codex exec` runs the prompt headless; run `npm run verify` as the next job step so the job fails when the gate does, whatever the agent reported. **Cursor** Put the pin block in a project rule under Cursor Rules. Cursor Hooks can run a script at points in the agent loop, so the gate does not depend on the agent remembering the rule. Bugbot then reviews the pull request as a second opinion, not as the gate. ## Load the Vue skills before the first prompt The `vuejs-ai/skills` repository packages Vue guidance as agent skills: `vue-best-practices`, `vue-pinia-best-practices`, `vue-router-best-practices`, `vue-testing-best-practices`, `vue-debug-guides` and `create-adaptable-composable`. Its README calls it an "early experiment" and a community project, and its router skill targets Vue Router 4, so treat it as a reviewer's checklist, not as the gate. **Claude Code** ```bash claude plugin marketplace add vuejs-ai/skills claude plugin install vue-best-practices@vue-skills ``` **Codex** ```bash npx skills add vuejs-ai/skills --skill vue-best-practices ``` **Cursor** ```bash npx skills add vuejs-ai/skills --skill vue-best-practices ``` The README advises starting a prompt with "Use vue skill" because the skill does not always trigger on its own. For a Vite-and-Nuxt-wide set, `antfu/skills` generates `vue`, `pinia`, `vite` and `vitest` skills from the official docs. Load one framework set, not both: overlapping skills compete for the same context. More options are on [the best skills for frontend development](/en/ecosystem/skills/top-skills-frontend/). ## Scaffold a typed component with script setup **Scenario:** you need a feature component that follows the team's conventions: typed props, typed emits, and tests that exercise both. **Copy-paste prompt: typed Vue 3.5 component with tests** ```text Use vue skill. Create src/components/UserCard.vue with <script setup lang="ts">. Props: user: User (from @/types), showActions?: boolean (default true), compact?: boolean (default false). Use Vue 3.5 reactive props destructure with defaults, not withDefaults. Emits with the tuple syntax: defineEmits<{ edit: [id: string]; remove: [id: string]; select: [user: User] }>(). Template: avatar with alt text, name, email and role badge; compact hides email and role; showActions renders Edit and Remove as <button> elements with accessible names. No Options API, no v-html. Write UserCard.test.ts with Vue Test Utils and Vitest: one test per prop and one per emit, finding buttons by role. Run npm run verify. ``` **How you know it worked:** `verify` is green, and the test names read like the prop and emit list. Read the test names, not the template. If a test finds an element by class, send it back. ## Build a Pinia 4 store that stays reactive **Scenario:** a cart store must survive a page refresh, support undo of the last change, and keep every component in sync. **Copy-paste prompt: Pinia 4 setup store with persistence and undo** ```text Create src/stores/cart.ts as a Pinia 4 setup store (defineStore('cart', () => {...})). State: items (CartItem[]), couponCode (string | null), isCheckingOut (boolean). Getters as computed: totalItems, subtotal, discount, total. Actions: addItem, removeItem, updateQuantity (minimum 1), applyCoupon (POST /api/coupons/validate), clearCart, checkout. Persist items and couponCode only, with pinia-plugin-persistedstate `pick`; never persist isCheckingOut. Undo: keep a history stack of the last 20 item snapshots; undo() restores the previous one. Components must read state with storeToRefs, never destructure the store directly. Tests: use @pinia/testing createTestingPinia with createSpy: vi.fn and stubActions: false so the actions really run; mock HTTP with MSW. Cover each action, undo after add and after remove, and a reload that restores items but not isCheckingOut. Run npm run verify. ``` **How you know it worked:** the reload test and the two undo tests pass, and `grep -rn "useCartStore()" src/components` shows every destructuring call wrapped in `storeToRefs`. `stubActions: false` matters: `createTestingPinia` stubs every action by default, so an action test without it passes without running the action. ## Extract composables without rewriting VueUse **Scenario:** twelve components repeat the same fetch-with-loading pattern, a debounced search, and a permission check. The trap here is the agent writing its own `useFetch` or `useWebSocket` when `@vueuse/core` 15 already exports both, with abort, auto-reconnect and heartbeat options. Tell it to look first. **Copy-paste prompt: composables with MaybeRefOrGetter inputs** ```text Find the repeated fetch-with-loading, debounced search and permission-check code in src/components. For each pattern, first check whether @vueuse/core (installed version in package.json) already exports it; if it does, use it and do not write a wrapper. Write only what is missing as composables in src/composables/, one per file: accept MaybeRefOrGetter inputs and read them with toValue() inside watch or watchEffect, return refs (never a reactive object that callers will destructure), and clean up timers and listeners with onScopeDispose. Replace the duplicated code in the components. Tests: mount a small host component per composable with Vue Test Utils; use fake timers for debounce. Report which patterns you replaced with VueUse and which you wrote. Run npm run verify. ``` **How you know it worked:** the report lists each pattern once, the component diff removes more lines than the composables add, and `vue/no-ref-object-reactivity-loss` stays silent. A composable that returns `reactive()` fails that lint rule the moment a caller destructures it. ## Validate a multi-step form with Zod 4 **Scenario:** a four-step checkout form must block "Next" on invalid fields, keep data when the user goes back, and survive an accidental refresh. **Copy-paste prompt: multi-step form with per-step Zod 4 schemas** ```text Build the checkout form in src/features/checkout/. Steps: Shipping, Billing, Payment, Review. One Zod 4 schema per step in schemas.ts; the full form type is the z.infer of the merged schemas. Use z.email(), not z.string().email(). Do not install vee-validate adapters. Write useStepForm(schema, initial) that returns the step's reactive model, a validate() that calls schema.safeParse and maps issues to a per-field error record, and isValid. MultiStepForm.vue holds the step index and provides next/prev/goTo through a typed InjectionKey; next() runs validate() first. Persist the draft to sessionStorage, excluding card fields. Each input has a visible label; errors are linked with aria-describedby. Tests with Vue Test Utils: Next is blocked on an empty step, back keeps values, a reload restores the draft without the card number, and submit sends the parsed data once. Run npm run verify. ``` **How you know it worked:** the four tests pass, `grep -rn "vee-validate\|string().email" src package.json` returns nothing, and the axe scan is clean. The card-field exclusion is the one line worth a human glance, because a failure there stores card data in the browser. ## Render 50,000 rows without freezing the page **Scenario:** an admin log view must show 50,000 rows with sorting and filtering. Virtualization fixes rendering; it does not fix a sort that runs on every keystroke. Ask for a measured result, not a component list. Chrome DevTools MCP gives the agent a performance trace of the running page; the setup for all three tools is in [browser automation with MCP](/en/ecosystem/mcp/browser-automation/). **Copy-paste prompt: virtualized table with a measured result** ```text Build a generic VirtualTable.vue in src/components/table/ with @tanstack/vue-virtual: typed columns (ColumnDef<T>), sortable headers with aria-sort, one text filter per column, a sticky header, and row selection with Shift+click ranges. Keep the source array in shallowRef; compute filtered and sorted rows once per filter change, not per render. Mount it on /admin/logs with 50,000 generated rows. Then, with the chrome-devtools MCP, record a trace while typing "error" into the message filter and while scrolling to the bottom. Report the longest task in each trace. Tests: sorting toggles order, filtering narrows rows, Shift+click selects a range. Run npm run verify. ``` **How you know it worked:** the trace numbers are in the report, and the DOM row count while scrolling stays near the viewport size rather than 50,000. Keep the trace as the baseline; [performance testing](/en/workflows/test/performance-testing/) shows how to turn it into a CI budget. ## Lazy-load routes and recover from a failed chunk **Scenario:** every view ships in the first bundle, and after each deploy some users hit a blank page because their tab asks for a chunk that no longer exists. **Copy-paste prompt: lazy routes with chunk-error recovery** ```text Refactor src/router/index.ts (Vue Router 5) so every view except Home is loaded with () => import('../views/X.vue'). Do not use <Suspense>; show a route-level loading bar driven by beforeEach/afterEach. Handle stale chunks after a deploy: listen for the vite:preloadError window event and for router.onError errors from failed dynamic imports, and reload once to the target route, with a sessionStorage guard so it never loops. Then run npm run build and list the emitted chunk for each route with its size. Tests: navigation to each lazy route renders its heading; a rejected import triggers exactly one reload. Run npm run verify. ``` **How you know it worked:** the build output lists one chunk per lazy route, and the reload test proves the guard. `<Suspense>` is still marked experimental in the Vue docs, which is why the prompt bans it for routing. ## Add i18n with lazy-loaded locales **Scenario:** the app ships English only, and Spanish and Japanese must load on demand without bloating the first bundle. **Copy-paste prompt: vue-i18n 11 in Composition API mode** ```text Set up vue-i18n 11 in src/i18n/index.ts with createI18n({ legacy: false, locale: 'en', fallbackLocale: 'en' }). Only en.json is bundled; es.json and ja.json load through loadLocale(locale), which dynamically imports the file, calls i18n.global.setLocaleMessage, sets the locale and updates <html lang>. In components use useI18n() and t, d and n; do not use this.$t. Add a LocaleSwitcher.vue that persists the choice to localStorage. Add a test that fails if any key in en.json is missing from es.json or ja.json, and a component test that switching to es changes visible text without a reload. Run npm run verify. ``` **How you know it worked:** the key-parity test passes, `grep -rn "legacy: true\|this\.\$t" src` returns nothing, and the build shows `es` and `ja` as separate chunks. The parity test is what keeps the next agent from adding an English key and forgetting the other two. ## Migrate an Options API component without changing behaviour **Scenario:** a 500-line Options API component with watchers and a Vuex module, no tests, and a plan to move to `<script setup>` and Pinia. Pin the behaviour before the refactor. The method is in [characterization tests](/en/workflows/test/characterization-tests/). **Copy-paste prompt: characterize, then migrate to script setup and Pinia** ```text Step 1, do not touch src/components/OrderDashboard.vue yet: write characterization tests that pin its current behaviour - rendered output for three prop sets, every store action it dispatches and when, emitted events, and what happens when props change. Run them; they must pass against the Options API version. Commit. Step 2: convert OrderDashboard to <script setup lang="ts"> and move its Vuex module to a Pinia setup store with the same state, getters and actions. Do not edit the tests except the store-mounting helper. Do not change props, emits or markup. Run npm run verify. If a characterization test fails, fix the component, not the test. ``` **How you know it worked:** the test bodies are identical between the two commits (`git diff HEAD~1 -- '*.test.ts'` touches only the mounting helper) and pass on both. That diff is the one thing to check by hand. ## Set up Storybook 10 with accessibility checks **Scenario:** new team members cannot find existing components, and accessibility issues reach review. The installer asks questions, so how you start it differs by tool: **Claude Code** Run `npm create storybook@latest` in your own terminal first, answer the prompts (Vue 3 with Vite), then give `claude` the prompt below to write the stories. **Codex** Run `npm create storybook@latest` yourself, or let Codex run it and approve the install when asked, then give Codex the prompt below. **Cursor** In Agent mode, ask Cursor to run `npm create storybook@latest` in its terminal and answer the prompts, then paste the prompt below. **Copy-paste prompt: Storybook 10 stories with a11y** ```text Storybook 10 is installed with @storybook/vue3-vite. Before adding addons, run npm view @storybook/addon-vitest peerDependencies and compare the vitest range with our installed vitest. If ours is outside the range, do not add addon-vitest; tell me and continue without it. Add @storybook/addon-a11y and set it to fail on violations. Write stories for Button, TextField, Modal, Card and VirtualTable: a Default story, one story per variant, and args typed from the component props. For Modal, add a play function using storybook/test (not @storybook/test) that opens it, checks focus moves inside, presses Escape and checks focus returns to the trigger. Reuse the Vite aliases. Run npm run build-storybook and npm run verify. ``` **How you know it worked:** `build-storybook` succeeds, the a11y panel shows no violations on the five components, and the Modal play function passes. If the agent reports the Vitest range mismatch, that is the recipe working: a forced install with `--legacy-peer-deps` is the wrong fix. ## How to verify agent-written Vue code without reading every line | Gate | Catches | Runs where | Signs off | | --- | --- | --- | --- | | `vue-tsc --noEmit` with `strict` | Wrong props and emits, lost generics, APIs the installed version does not have | agent loop, CI | automatic | | `eslint-plugin-vue` with the reactivity-loss rules at `error` | Destructured props, refs and stores that stop updating; implicit emits; `v-html` | agent loop, CI | automatic | | Vitest + Vue Test Utils + MSW | Behaviour after each user action, including error paths and reloads | agent loop, CI | automatic; the author reviews test names, not bodies | | Characterization tests, unchanged across a migration | Behaviour drift in refactors | agent loop, CI | author checks the test diff | | Locale key-parity test | Missing translations | agent loop, CI | automatic | | Playwright + `@axe-core/playwright`, Storybook a11y addon | Missing labels, focus traps, contrast, roles | CI | automatic; an accessibility owner reviews new exceptions | | Performance trace before and after | Regressions in the interaction you changed | agent loop with Chrome DevTools MCP | author; a CI budget when it matters | A human reviews what the gates cannot: the acceptance criteria, the test names, and any diff to a test file. Write the acceptance criteria before the prompt; see [acceptance criteria](/en/workflows/plan/acceptance-criteria/). Keep the agent from editing its own tests to make them pass; see [protect the oracle](/en/workflows/test/protect-the-oracle/). For the pull request itself, [reviewing agent pull requests](/en/workflows/ship/agent-pr-review/) covers who signs off and on what evidence. ## When agent-written Vue code breaks - **Reactivity silently lost.** The agent destructures a store, a `reactive()` object or a composable's return value, and the UI stops updating after the first render. Recovery: `storeToRefs` for stores, `toRefs` or ref returns for composables, and the two reactivity-loss lint rules at `error`. - **Vue 2 or Options API code in a Vue 3.5 project.** `this.$store`, `data()`, Vuex and filters appear in new files. Recovery: the version-pin block, the Vue skill, and a lint rule or code review that rejects Options API in new files. - **Peer-range mismatches forced through.** The agent hits an `ERESOLVE` error from `@vee-validate/zod` or `@storybook/addon-vitest` and retries with `--legacy-peer-deps`. Recovery: ban that flag in the instruction file, and have the agent report the mismatch instead, as the Storybook prompt does. - **Store tests that never run the store.** `createTestingPinia` stubs actions by default, so the test asserts a spy was called and the action body never executes. Recovery: `stubActions: false` in store tests; keep stubbing only in component tests. - **A composable that duplicates VueUse.** The agent writes 200 lines of reconnect logic that `useWebSocket` already has. Recovery: the "check `@vueuse/core` first" line in the instructions, and the replaced-versus-written report the composable prompt asks for. - **Hydration or `window` errors when the app moves to SSR.** Code that reads `window` or `localStorage` at module scope breaks on the server. Recovery: browser-only code goes in `onMounted`; for a server-rendered Vue app, the [Nuxt recipes](/en/cookbook/frontend-recipes/nuxt-patterns/) cover the SSR gates. - **Tests that test the mock.** The agent mocks the composable it wrote and asserts the mock's return value. Recovery: mock at the HTTP boundary with MSW, and reject tests that `vi.mock` the module under test. ## Where to go next with Vue and agents - [Frontend recipes overview](/en/cookbook/frontend-recipes/) for the other frameworks in this section - [Nuxt recipes](/en/cookbook/frontend-recipes/nuxt-patterns/) for server rendering, server routes and deployment, which this page leaves to its neighbour - [Unit testing with agents](/en/workflows/test/unit-testing/) and [accessibility testing](/en/workflows/test/accessibility-testing/) for the gates behind `verify` - [Playwright MCP](/en/ecosystem/mcp/playwright-mcp/) for letting the agent check the running app, and [end-to-end testing](/en/workflows/test/e2e-testing/) for the flows that span pages - [API development patterns](/en/cookbook/backend-recipes/api-patterns/) for the backend these components call --- # Mobile Development URL: https://developertoolkit.ai/en/cookbook/mobile-development/ Description: Mobile recipes for Claude Code, Codex, and Cursor: pick Expo, React Native, Flutter, or native, install the stack's skills, and verify on simulators. The mobile cookbook holds five recipes for building iOS and Android apps with Claude Code, Codex, or Cursor: Expo, React Native, Flutter, native Swift and Kotlin, and cross-platform UI patterns. Each recipe pins the framework version, installs the vendor's skills, and proves every change with type checks, tests, and simulator evidence instead of a diff read line by line. This hub is for developers and tech leads who ship a mobile app with an agent. The agent reports "done", the code compiles, and the screen still breaks on the Android emulator nobody opened. Pick a recipe and require the same evidence from every change. Before you start, give the repository an agent instructions file; the prompts below write into it, and [AGENTS.md and CLAUDE.md: concise repository context](/en/developer-scorecard-guide/claude-md-context/) keeps it short. For recipes outside mobile, see the [cookbook overview](/en/cookbook/). ## Which mobile recipe fits your stack? | Your app | Start with | What the recipe adds | | --- | --- | --- | | New cross-platform app, or a team on Expo's build and update services | [Expo](/en/cookbook/mobile-development/expo/) | Expo skills and MCP, Expo Router auth gates, a fingerprint-gated EAS pipeline, safe over-the-air (OTA) updates | | React Native app that has outgrown the demo stage | [React Native](/en/cookbook/mobile-development/react-native/) | Offline-first state, a janky list rebuilt on FlashList, biometric auth, CI to TestFlight and Play, failures the simulator never shows | | Dart codebase, or a team that wants one rendering engine on both platforms | [Flutter](/en/cookbook/mobile-development/flutter/) | Riverpod, go_router, Dio, clean architecture, widget tests | | Swift/SwiftUI or Kotlin/Compose | [Native iOS and Android](/en/cookbook/mobile-development/native-ios-android/) | One build-and-test script per platform, simulator and emulator loops, UI-test evidence | | Any of the above, and you need a screen built | [React Native and Flutter UI recipes](/en/cookbook/mobile-development/mobile-patterns/) | 12 prompts: adaptive navigation, feed lists, offline-first data, animations, push notifications, store submission | The Expo and React Native recipes are complementary: the Expo recipe covers the platform (routing, EAS builds, OTA updates), and the React Native recipe covers the app code that runs on it. On a new app, read the Expo recipe first. ## Give the agent your stack's official skills first Install only your stack's set, because skill descriptions compete for the agent's attention. The `claude`, `codex mcp` and `skills` commands were checked on 2026-09-26 against `claude` 2.1.283, `codex` 0.157.1, and the `skills` CLI 1.7.0; the Codex Expo commands were rerun on 2026-10-02 with the same versions. Codex's `openai-curated` marketplace also lists an Expo plugin, but on 2026-10-02 it shipped 13 skills under older names and no MCP server, so the Codex tab installs Expo's current set and server directly. With `--agent codex` or `--agent cursor`, the `skills` CLI writes to `.agents/skills/` in the project. **Claude Code** ```bash # Expo: 24 skills plus Expo's remote MCP server # If the marketplace is missing: claude plugin marketplace add anthropics/claude-plugins-official claude plugin install expo@claude-plugins-official # Flutter and Dart: skills plus the Dart MCP server claude plugin marketplace add flutter/agent-plugins claude plugin install dart-flutter@dart-flutter # React Native (Callstack, community) through the skills CLI npx skills@latest add callstackincubator/agent-skills --skill '*' --agent claude-code -y # iOS builds: MobileBuildMCP (needs macOS 14.5+ and Xcode 16+) claude mcp add mobilebuild -- npx -y mobilebuildmcp@latest mcp ``` **Codex** ```bash # Expo: the current skill set from expo/skills plus Expo's remote MCP server npx skills@latest add expo/skills --skill '*' --agent codex -y codex mcp add expo --url https://mcp.expo.dev/mcp # If the server asks you to sign in: codex mcp login expo # Flutter and React Native skills through the cross-agent skills CLI npx skills@latest add flutter/agent-plugins --skill '*' --agent codex -y npx skills@latest add callstackincubator/agent-skills --skill '*' --agent codex -y # iOS builds: MobileBuildMCP (needs macOS 14.5+ and Xcode 16+) codex mcp add mobilebuild -- npx -y mobilebuildmcp@latest mcp ``` **Cursor** ```bash # Cursor installs skills through the cross-agent skills CLI npx skills@latest add expo/skills --skill '*' --agent cursor -y npx skills@latest add flutter/agent-plugins --skill '*' --agent cursor -y npx skills@latest add callstackincubator/agent-skills --skill '*' --agent cursor -y ``` MCP servers, including MobileBuildMCP, go in `.cursor/mcp.json`; each recipe shows its entry. | Stack | Skill or server | Publisher | GitHub stars, 2026-09-26 | | --- | --- | --- | --- | | Expo | [expo/skills](https://github.com/expo/skills) | Expo (official) | 2,612 | | Flutter and Dart | [flutter/agent-plugins](https://github.com/flutter/agent-plugins) (renamed from `flutter/skills`) | Flutter team (official) | 2,996 | | React Native | [callstackincubator/agent-skills](https://github.com/callstackincubator/agent-skills) | Callstack (community, not Meta) | 1,656 | | iOS builds | [MobileBuildMCP](https://github.com/getsentry/MobileBuildMCP) (npm `mobilebuildmcp` 2.7.1, formerly XcodeBuildMCP) | Sentry | about 6,400 | Skill or MCP server? See the [frontend skills roundup](/en/ecosystem/skills/top-skills-frontend/) and the [dev-server MCP servers](/en/ecosystem/mcp/framework-devtools-mcp/). ## How do you verify a mobile change without reading every line? Make the agent produce evidence, and review the evidence. Every recipe uses the same four gates, in order: 1. **Static gates.** Run `npx tsc --noEmit` and your linter for React Native, or `flutter analyze` for Flutter. For Expo, add `npx expo install --check` to catch dependency versions the agent wrote by hand. 2. **Unit and widget tests.** Run `flutter test`, or your JavaScript test runner with React Native Testing Library. Write the acceptance criteria as tests before the agent writes the feature. 3. **Both platforms, on a simulator or emulator.** The agent launches the app on iOS and Android and attaches a screenshot of each changed screen (Maestro in the Expo recipe, XCUITest and Compose UI tests in the native one). 4. **Release safety.** A staged rollout in the store, and for Expo a fingerprint check so an OTA update never targets a build that lacks its native code. The developer who opened the task signs off on the evidence; a tech lead owns the release gate. The [evidence bundle](/en/workflows/ship/evidence-bundle/) carries it into a pull request, and [mobile app testing patterns](/en/workflows/test/mobile-testing/) cover device matrices and flaky tests. **Copy-paste prompt: write the mobile verification contract** ```text Inspect this repository and identify the mobile stack (Expo, bare React Native, Flutter, or native), the framework version pinned in the lockfile, and the test tools already installed. Then add a "Verify before done" section to AGENTS.md (and CLAUDE.md if it exists) listing the exact commands for: type check, lint, unit tests, and launching the app on one iOS simulator and one Android emulator. Run every command once and report which pass, which fail, and which tools are missing. Do not install anything or change app code. ``` **Copy-paste prompt: ship one screen with evidence** ```text Implement the change described in TASK.md. Before you write code, turn its acceptance criteria into failing tests. When the tests pass, run the full "Verify before done" list from AGENTS.md, then launch the app on the iOS simulator and the Android emulator and save a screenshot of every changed screen to evidence/. Finish with a summary: commands run with their results, screenshot paths, and anything that differs between iOS and Android. Do not run any EAS build, store submission, or OTA publish. ``` ## What breaks when agents build mobile apps? - **The agent pins versions from memory**, writing APIs and config keys from an older SDK. Put the pinned version in `AGENTS.md`, and let `npx expo install` or `flutter pub add` choose package versions. - **"Done" without a device run.** Reject any summary without a screenshot from each platform, and rerun the second prompt. - **One platform only.** The agent tested whichever simulator was running; layout, permissions, and keyboard behaviour differ on the other. Name both targets in the prompt. - **Paid cloud builds run unattended.** The `eas-*` skills drive paid Expo Application Services builds. Keep builds, submissions, and OTA publishes behind your approval. - **Too many tools in context.** Each MCP server adds its tool list to every turn. Enable only what the task needs; the native recipe shows how to narrow MobileBuildMCP's workflows. ## Where to go next with mobile development - [Expo](/en/cookbook/mobile-development/expo/) — Expo SDK 57: skills, MCP, Expo Router, EAS, and OTA updates - [React Native](/en/cookbook/mobile-development/react-native/) — Offline-first state, FlashList, biometrics, and store CI - [Flutter](/en/cookbook/mobile-development/flutter/) — Riverpod, go_router, Dio, and widget tests - [Native iOS and Android](/en/cookbook/mobile-development/native-ios-android/) — SwiftUI and Compose with simulator loops and UI tests - [React Native and Flutter UI recipes](/en/cookbook/mobile-development/mobile-patterns/) — 12 copy-paste prompts for cross-platform mobile UI - [Mobile app testing patterns](/en/workflows/test/mobile-testing/) — Device matrices, platform-specific tests, and offline scenarios Cursor users: see the [Cursor mobile development guide](/en/cursor-ide/build/mobile-dev/). To supervise a long agent run from your phone, see [driving agents from your phone](/en/ecosystem/agent-tools/remote-mobile/). --- # Expo Development Patterns URL: https://developertoolkit.ai/en/cookbook/mobile-development/expo/ Description: Expo SDK 57 with Claude Code, Codex, and Cursor: Expo skills and MCP, Expo Router auth gates, a fingerprint-gated EAS pipeline, and safe OTA updates. Expo development with Claude Code, Codex, or Cursor works when the agent knows two facts first: the pinned Expo SDK (SDK 57 is current on npm as of 2026-09-26) and whether the app runs in Expo Go or a development build. Expo's official skills, a fingerprint-gated EAS pipeline, and Maestro flows then make each change verifiable without reading every line. This page is for developers and tech leads who ship an Expo app to the stores. A teammate adds `react-native-vision-camera`, Expo Go stops loading the app, and the agent keeps writing code for whichever setup it guessed. A week later an over-the-air (OTA) update reports success, yet no phone picks it up, because the update targets a runtime that no installed build has. **Before you start:** this page assumes the React Native basics (navigation, state, native modules) from [React Native development patterns](/en/cookbook/mobile-development/react-native/), and an agent that can install skills, as described in [how to install and manage skills](/en/ecosystem/skills/installing-managing/). ## What you'll set up on this page - An agent setup with Expo's official skills and MCP server, installed per tool - A scaffolding prompt that pins the SDK and the build type, so the agent stops guessing - A copy-paste prompt for an Expo Router auth gate, and the Maestro flow that proves it works - A fingerprint-gated EAS Workflows pipeline that decides between a store build and an OTA update for you - A staged OTA rollout with the commands to watch it and roll it back - A "what breaks" map for SDK upgrades, Expo Go mismatches, credentials, and runtime mismatches ## Which Expo versions does this page assume? Tell the agent the versions. Its training data spans several SDKs, and each SDK changes APIs, config keys, and the React Native version under it. The table lists what npm served on 2026-09-26. | Package | Version on 2026-09-26 | Note | | --- | --- | --- | | `expo` | 57.0.25 (SDK 57, released 2026-06-30) | the `sdk-56` dist-tag still receives patches; SDK 58 is on the `next` dist-tag, so check `npm view expo dist-tags` before pinning | | `react-native` / `react` | 0.86.3 / 19.2.3 | the versions SDK 57's `bundledNativeModules.json` pins | | `expo-router` | 57.0.23 | `Stack.Protected` takes a `guard` prop | | `eas-cli` | 24.8.0 | fingerprint, workflow, and update-rollout commands used below | | `nativewind` | 4.2.7 | 5.0 is a release candidate (`5.0.0-rc.0`); pin one major | Never let the agent write a version into `package.json` by hand. `npx expo install <package>` picks the version that matches your SDK, and `npx expo install --check` lists every package that drifted. ## Set up Expo skills and the Expo MCP server Expo publishes its own agent skills in [expo/skills](https://github.com/expo/skills) (about 2.6k stars on GitHub on 2026-09-26). The Expo plugin for Claude Code and Codex (1.13.7 on 2026-09-26) bundles 24 skills, such as `expo-router`, `expo-upgrade`, `eas-update`, and `eas-workflows`. It also registers Expo's remote MCP server at `https://mcp.expo.dev/mcp`. The skills load on demand, so they cost little context until a task needs one. MCP servers cost context per tool; Claude Code and Codex both defer tool definitions behind tool search, so the cost stays lower there, but every server you connect still adds to it. **Claude Code** ```bash # Skills + Expo MCP server in one plugin claude plugin install expo@claude-plugins-official ``` To add only the MCP server, run `claude mcp add --transport http expo https://mcp.expo.dev/mcp`, then open `/mcp` in a session to complete any sign-in it asks for. Without `--transport http`, Claude Code 2.1.283 saves the URL as a stdio command, and the connection fails later. **Codex** ```bash # Skills + Expo MCP server in one plugin codex plugin add expo@openai-curated ``` To add only the MCP server, run `codex mcp add expo --url https://mcp.expo.dev/mcp`, then `codex mcp login expo` if the server asks for OAuth. Do not run both: the plugin already registers the server. **Cursor** Install the skills with the cross-agent skills CLI (`skills` 1.7.0 on npm): ```bash npx skills@latest add expo/skills --skill '*' -a cursor ``` Then add the MCP server to `.cursor/mcp.json`: ```json { "mcpServers": { "expo": { "url": "https://mcp.expo.dev/mcp" } } } ``` **Traps in the Expo plugin** - The `eas-*` skills drive paid Expo Application Services (EAS). Each one opens with a cost note. A build, submit, or workflow run spends your plan's minutes, so keep those commands behind your approval. - The plugin installs `PostToolUse` and `UserPromptExpansion` hooks that record skill usage (Claude Code only). Plugin 1.13.7 sends nothing until you opt in with `EXPO_SKILLS_TELEMETRY=1`; `EXPO_SKILLS_TELEMETRY=0` or `DO_NOT_TRACK=1` turns it off. - Installing every skill with `--skill '*'` is fine for an Expo repository. In a monorepo that also holds a web app, install only the skills you use. Skill descriptions compete for the agent's attention. For how skills and MCP servers compare, see [how to install and manage skills](/en/ecosystem/skills/installing-managing/) and the [frontend skills roundup](/en/ecosystem/skills/top-skills-frontend/). ## Scaffold an Expo app the agent cannot misread The prompt matters less than the two facts it pins. Put them in `AGENTS.md` (or `CLAUDE.md`) as well, so every later session inherits them. **Copy-paste prompt: scaffold an Expo SDK 57 app** ```text Scaffold a new Expo SDK 57 app with `npx create-expo-app@latest` (TypeScript). Constraints: - We ship a development build, not Expo Go: add expo-dev-client, because we will add third-party native modules. - Use Expo Router with typed routes. - Create eas.json with development (developmentClient: true, internal distribution), preview (internal), and production profiles. - In app.json set "runtimeVersion": { "policy": "fingerprint" }. - Install every dependency with `npx expo install`, never by editing package.json versions. - Write an AGENTS.md that states: Expo SDK 57, development build, package manager, and the check command below. - Run `npx expo lint` once to set up eslint-config-expo, and install jest-expo with `npx expo install jest-expo jest`, before you add the check script. - Add a "check" script to package.json: tsc --noEmit && expo lint && jest --ci && expo install --check Stop and show me eas.json and app.json before running any `eas` command. ``` The `fingerprint` runtime-version policy matters later. It hashes everything native in the project, so any native change produces a new runtime version by itself. That removes the most common OTA accident: a JavaScript update that calls a native module the installed build does not have. **Claude Code** Run `claude --permission-mode manual` in an empty directory and paste the prompt. The `expo-overview` skill routes the task to `expo-project-structure` and `expo-dev-client`. Manual mode makes every `eas` command wait for your approval. From v2.1.283 (both release channels on 2026-10-12), Claude Code starts interactive sessions in auto mode, where a classifier approves commands for you. **Codex** Run `codex` in the empty directory and paste the prompt. To let Codex edit and run local commands but ask before anything outside the workspace, start it with `codex --sandbox workspace-write -a on-request`. **Cursor** Paste the prompt into the Agent chat. Review the diff of `eas.json` and `app.json` before you accept the change: those two files decide what every later build does. **Expo Go or development build?** Expo Go runs only the native modules that ship inside it. The moment you add a third-party native module or a config plugin, the app needs a development build (`npx expo run:ios`, `npx expo run:android`, or `eas build --profile development`). If the agent does not know which one you run, it writes code that works in Expo Go and fails in the development build, or the other way round. ## Build an auth-protected Expo Router layout Most Expo Router bugs sit in the auth gate. A redirect before the root layout mounts triggers a "navigate before mounting the Root Layout" warning. A redirect during render flashes protected content for a frame. `Stack.Protected` removes both, because the router never registers the protected screens while the guard is false. **Copy-paste prompt: auth-gated tabs with Stack.Protected** ```text Build the auth layout for this Expo SDK 57 app with Expo Router. - app/_layout.tsx: a SessionProvider (React context, `useSession`) that loads the token from expo-secure-store. Keep the splash screen up with SplashScreen.preventAutoHideAsync() until the token has loaded. - Gate routes with <Stack.Protected guard={isSignedIn}> around the (tabs) group and <Stack.Protected guard={!isSignedIn}> around the (auth) group. - Do not call router.replace or <Redirect> in render or in a useEffect. - (auth): login.tsx. (tabs): index.tsx and profile.tsx with a sign-out button. - Add testID props: login-email, login-password, login-submit, tab-profile, sign-out. - Write a Maestro flow in .maestro/auth.yaml that signs in, opens the profile tab, signs out, and asserts that the login screen is visible again. Show the file tree first, then the files. Run `npm run check` at the end. ``` The agent should produce this tree: ```text app/ _layout.tsx # SessionProvider + Stack.Protected guards (auth)/ _layout.tsx login.tsx (tabs)/ _layout.tsx # Tabs index.tsx profile.tsx .maestro/ auth.yaml ``` You do not need to read the layout to accept it. Search it for `router.replace` and `<Redirect`: a hit inside the render path means the redirect flash is back, so send it back with "move the guard into Stack.Protected". Then run the Maestro flow on a simulator with the development build installed (`maestro test .maestro/auth.yaml`). The flow is the acceptance criterion: sign-in, a protected tab, and sign-out either pass on a real runtime or they do not. Install the Maestro CLI once per machine with `curl -fsSL "https://get.maestro.mobile.dev" | bash`, the command in the Maestro README (the repository's main branch sets CLI version 2.11.0 on 2026-09-26). It needs Java 17 or newer, and `maestro test` needs a booted simulator or emulator with the development build already installed. ## Keep styling in one theme with NativeWind The usual NativeWind failure is a wall of `className="bg-[#1d4ed8]"` values. A rebrand then touches every screen. Ask for semantic tokens so colours live in one place. **Copy-paste prompt: a typed NativeWind theme** ```text Configure NativeWind (keep the major version already in package.json) for this Expo SDK 57 app. Define primary, surface, and danger as CSS variables in global.css with light and dark values, and map them in tailwind.config.js so `bg-primary` follows the colour scheme. Build a typed <Button variant="primary" | "danger" loading?> on Pressable with a pressed opacity state. Then add a lint check: fail `npm run check` if any file under app/ or components/ contains a hex colour literal in a className. ``` The last sentence turns the style rule into a gate. You stop reviewing colours by eye, because the check fails on the first hard-coded hex value. More UI recipes for React Native and Flutter are in [mobile UI recipes](/en/cookbook/mobile-development/mobile-patterns/). ## Ship with a fingerprint-gated EAS pipeline The riskiest decision in an Expo release is "store build or OTA update?". An agent should not make it by judgement. `eas-cli` 24.8.0 ships a deploy workflow template that makes the decision mechanically: `eas workflow:create` saves it as `.eas/workflows/deploy.yml` by default, modelled on Expo's deploy-to-production example. A `fingerprint` job hashes the native project, and a `get-build` job looks for an existing production build with that hash. If one exists, the workflow publishes an update. If not, it builds and submits to the stores. **Copy-paste prompt: an EAS workflow for production** ```text Use the eas-workflows skill. Start from the `eas workflow:create` deploy template and save it as .eas/workflows/deploy.yml, triggered on pushes to main: 1. a `fingerprint` job; 2. per platform, a `get-build` job with the fingerprint hash and the production profile; 3. if no build matches: a `build` job, then a `submit` job; 4. if a build matches: an `update` job on branch production. Also create .eas/workflows/pull-request.yml that runs `npm run check` and publishes a preview update to a branch named after the PR. Validate both files with `npx eas-cli@latest workflow:validate <path>` and show me the output. Do not run `eas workflow:run`, `eas build`, or `eas submit`. ``` You verify the pipeline without reading every YAML key: 1. `workflow:validate` passes for both files. 2. The production file contains jobs of type `fingerprint`, `get-build`, `build`, `submit`, and `update`, and each `update` job's `if:` checks that its `get-build` job returned a `build_id`. Search for `type:`, not for job names: the template names its jobs `get_ios_build`, `build_android`, and so on. 3. Before you merge a native-looking change, compare your working tree with the latest production build. Get the build ID with `eas build:list --platform ios --build-profile production --limit 1 --json`, then run `eas fingerprint:compare --build-id <BUILD_ID>` (add `--non-interactive` in CI). Repeat for Android: run the same `eas build:list` with `--platform android` and compare against that build ID. Bare `eas fingerprint:compare` opens an interactive picker, so an agent or a CI step cannot run it unattended. A different hash means the next push triggers a store build, not an OTA update. If your team runs CI on GitHub Actions instead, keep the same decision logic and have the agent read the existing workflows first through the [GitHub MCP server](/en/ecosystem/mcp/github-mcp/). The generic pipeline patterns are in [CI/CD pipelines with agents](/en/workflows/ship/ci-cd-pipelines/). ## Roll out an OTA update in stages An OTA update reaches every user on a channel within minutes, so ship it the way you would ship a server change: to a slice first. 1. Publish to 10% of users on the production branch: ```bash eas update --branch production --message "Fix checkout total rounding" --rollout-percentage 10 ``` 2. Watch launches and crashes for the update group: ```bash eas update:insights <GROUP_ID> --days 1 ``` 3. If the numbers match the previous update, widen the rollout with `eas update:edit <GROUP_ID> --rollout-percentage 100`. 4. If crashes rise, revert with `eas update:revert-update-rollout`, or roll back to an earlier update or the embedded bundle with `eas update:rollback`. `GROUP_ID` is the update group ID that `eas update` prints. Hand the agent this sequence as a runbook, not as permission. It can prepare the commands and read `update:insights`, and a person approves each widening step. The general pattern is in [progressive delivery](/en/workflows/ship/progressive-delivery/). ## Wire push notifications end to end Agents usually stop after the permission prompt. A working setup also sends the token to your backend, refreshes it, and routes a tapped notification to the right screen. **Copy-paste prompt: end-to-end Expo push notifications** ```text Implement push notifications with expo-notifications in this Expo SDK 57 app (development build). - On sign-in, get a token with getExpoPushTokenAsync (pass the EAS projectId from expo-constants) and POST it to /api/devices; register again when the token changes and delete it on sign-out. - Call Notifications.setNotificationHandler so banners show in the foreground. - Create the Android notification channel before requesting the token. - Use useLastNotificationResponse to deep-link a tapped notification with data.url to that Expo Router route, including a cold start. - Add a Jest test for the URL-to-route mapping and a Maestro flow that opens the app from a deep link and asserts the target screen. List any credentials I must add in EAS (APNs key, FCM service account) instead of guessing them. ``` The Jest test proves the mapping from payload to route. The Maestro flow proves that the route opens on a device. Delivery itself still needs one manual send to a physical device per platform, because simulators do not reproduce every push path. ## How you verify agent output without reading every line Expo gives you enough machine-checkable signals that review becomes a check of evidence, not of code. | Gate | Command | What it catches | | --- | --- | --- | | Types, lint, unit tests | `npm run check` (`tsc --noEmit`, `expo lint`, `jest --ci`) | wrong API shapes, dead imports, logic regressions | | Dependency drift | `npx expo install --check` and `npx expo-doctor` | versions outside the SDK's range, duplicate native modules | | Native change | `eas fingerprint:compare --build-id <BUILD_ID> --non-interactive` | a JavaScript-only PR that changed the runtime | | Behaviour | Maestro flows in `.maestro/` | auth gates, deep links, and navigation on a real runtime | | Release health | `eas update:insights` and Sentry | crashes and launch failures per update group | Make the agent attach the output of each gate to the pull request. The reviewer then reads what changed in behaviour, the Maestro result, and whether the fingerprint moved. That is the same [evidence bundle](/en/workflows/ship/evidence-bundle/) the rest of the site uses. For crash triage, the `@sentry/react-native` config plugin uploads source maps during EAS builds, and the [Sentry MCP server](/en/ecosystem/mcp/observability-mcp/) (`https://mcp.sentry.dev/mcp`) lets the agent read the symbolicated trace itself. Device testing beyond Maestro, such as device farms and visual checks, is covered in [mobile app testing](/en/workflows/test/mobile-testing/). ## What breaks in Expo projects, and how do you recover? - **An SDK upgrade leaves native dependencies behind.** Bumping `expo` is the easy part. Run `npx expo-doctor`, paste the full output, and use this prompt: "We upgraded to Expo SDK 57. Use the expo-upgrade skill. Fix each mismatch with `npx expo install --fix`, and list every third-party package with no SDK 57 support instead of forcing a version." Then rebuild the development client, because the old one no longer matches. - **It works in Expo Go but not in the development build, or the reverse.** The cause is almost always a module that is not in Expo Go, or a config plugin that applies only during `prebuild`. Tell the agent which environment fails and ask it to check whether the module needs a config plugin entry in `app.json` and a new development build. - **`eas build` fails on signing.** Paste the build log and ask the agent to name the failing credential, for example an expired distribution certificate or a missing push key. Do not let it regenerate credentials: `eas credentials` changes shared signing state for the whole team, so a person runs it. - **An update "succeeds" but no device receives it.** The update's runtime version matches no installed build. Take the latest store build's ID from `eas build:list --platform ios --build-profile production --limit 1 --json` and run `eas fingerprint:compare --build-id <BUILD_ID>`. If the hashes differ, the change needs a store build, and the fingerprint-gated workflow would have produced one. - **A bad update is already live.** Run `eas update:revert-update-rollout` if it is still in a staged rollout, or `eas update:rollback` otherwise. Then add a Maestro flow that reproduces the bug, so the next pull request fails before it ships. ## Next steps - [React Native development patterns](/en/cookbook/mobile-development/react-native/) for navigation, offline state, list performance, and native modules without Expo's services - [Native iOS and Android recipes](/en/cookbook/mobile-development/native-ios-android/) when you drop into Swift or Kotlin for a custom module - [Flutter development patterns](/en/cookbook/mobile-development/flutter/) if you are comparing cross-platform stacks - [API design patterns](/en/cookbook/backend-recipes/api-patterns/) for the `/api/devices` endpoint and the sync API your app calls --- # Flutter Development Patterns URL: https://developertoolkit.ai/en/cookbook/mobile-development/flutter/ Description: Flutter with Claude Code, Codex, and Cursor: the official Dart and Flutter plugin, Riverpod 3 codegen, go_router, Dio, and a gate that checks every change. Flutter development with Claude Code, Codex, or Cursor produces verifiable code when the agent starts from three pinned facts: the package versions (Riverpod 3 with code generation, go_router, Dio, freezed), the architecture rules, and one check command. The Flutter team's agent plugin and the Dart MCP server then verify each change through analysis, code generation, and tests. This page is for developers and tech leads who ship a Flutter app with an agent. You ask for a provider and get a `StateNotifierProvider`, which Riverpod 3 moved to a `legacy.dart` import. You ask for a Dio retry interceptor, and a failing screen now fires dozens of requests, because Riverpod 3 also retries failing providers on its own. Neither bug shows up in a diff you skim. ## What you'll walk away with from Flutter development patterns - The Flutter team's agent plugin (skills plus the Dart MCP server), installed per tool - An `AGENTS.md` block that pins the stack and the check command, so every session inherits them - Copy-paste prompts for a code-generation Riverpod provider, a go_router auth redirect that cannot loop, a Dio service with typed failures, and widget tests - Mechanical checks for each recipe (`rg` guards, `build_runner --only-check`, table-driven tests) that replace reading the generated code - A failure map for `build_runner` drift, double retries, go_router's SDK floor, Gradle and CocoaPods breaks, and golden-test flakiness ## Which Flutter package versions does this page assume? The agent's training data spans several major versions of every package below, and each major changed an API the agent likes to use. State the versions in the prompt and in `AGENTS.md`. The table lists what pub.dev served on 2026-09-26. | Package | Version | What changed that an agent gets wrong | | --- | --- | --- | | `flutter_riverpod` | 3.4.3 (needs Dart ^3.12) | `StateNotifierProvider`, `StateProvider`, and `ChangeNotifierProvider` live in `package:flutter_riverpod/legacy.dart`. Failing providers retry automatically. | | `riverpod_annotation` / `riverpod_generator` | 4.0.7 / 4.0.9 | The generator's major (4) differs from the runtime's (3). Keep annotation and generator on the same major. Providers take a plain `Ref`; the generated `UserProfileRef`-style subclasses are gone. | | `riverpod_lint` | 3.1.9 (needs Dart 3.13) | Built on `analysis_server_plugin`, not `custom_lint`. Follow its README, not a `custom_lint` recipe from an older article. | | `go_router` | 18.0.1 | 18.0.0 requires Flutter 3.44 / Dart 3.12. On an older Flutter, pin `^17.5.0`. URLs are case-sensitive since 15.0.0. | | `dio` | 5.11.1 | Stable 5.x API: `InterceptorsWrapper`, `DioException`. | | `freezed` | 4.0.2 (needs Dart 3.13) | 4.0.0 no longer accepts `final` inside constructor parameters. Classes need `sealed` or `abstract` (since 3.0). | | `build_runner` | 2.16.1 | Fixes incorrect generated files by default. `--delete-conflicting-outputs` is a removed flag that is ignored with a warning. `--only-check` fails the build when files on disk differ from what the generator would write. | Let the agent add packages with `flutter pub add <package>`, which resolves a version compatible with your SDK, rather than typing version numbers into `pubspec.yaml`. ## Install the Flutter team's agent plugin and the Dart MCP server The Flutter team publishes [flutter/agent-plugins](https://github.com/flutter/agent-plugins), renamed from `flutter/skills`. Its `dart-flutter` plugin (1.0.6 on 2026-09-26) bundles 25 skills, 10 for Flutter and 15 for Dart, such as `flutter-add-widget-test`, `flutter-fix-layout-issues`, and `dart-resolve-package-conflicts`. It also registers the Dart MCP server (`dart mcp-server`, which ships with the Dart SDK). The Dart team also publishes its skills in [dart-lang/skills](https://github.com/dart-lang/skills). **Claude Code** ```bash # Marketplace and plugin are both named dart-flutter claude plugin marketplace add flutter/agent-plugins claude plugin install dart-flutter@dart-flutter ``` To add only the MCP server, run `claude mcp add dart -- dart mcp-server`. Open `/mcp` in a session to confirm the server connected. **Codex** ```bash # The repository ships a Codex marketplace named dart-flutter codex plugin marketplace add flutter/agent-plugins codex plugin add dart-flutter@dart-flutter ``` To add only the MCP server, run `codex mcp add dart -- dart mcp-server`. **Cursor** The repository also ships a Cursor plugin manifest (`.cursor-plugin/plugin.json`); the skills CLI route below works without it. Install the skills with the cross-agent skills CLI (`skills` 1.7.0 on npm), which writes them to `.agents/skills`: ```bash npx skills@latest add flutter/agent-plugins --skill '*' --agent universal --yes ``` Then add the Dart MCP server to `.cursor/mcp.json`: ```json { "mcpServers": { "dart": { "command": "dart", "args": ["mcp-server"] } } } ``` The MCP server is what changes the loop. Without it, the agent writes a widget and hopes. With it, the agent can call `analyze_files`, read `get_runtime_errors` from the running app, trigger `hot_reload`, and walk the tree with `widget_inspector` (tool names from the [dart-lang/ai README](https://github.com/dart-lang/ai/tree/main/pkgs/dart_mcp_server), read 2026-09-26). The server needs Dart 3.9 or later. It reaches a running app through the Dart Tooling Daemon, which `flutter run` starts in debug and profile mode. **Traps in the Flutter plugin** - Two skills teach a different stack from the one on this page: `flutter-use-http-package` uses the `http` package, and `flutter-implement-json-serialization` writes `fromJson` by hand with `dart:convert`. If your app uses Dio and freezed, say so in `AGENTS.md`, or install skills one at a time instead of with `--skill '*'`. - `flutter-apply-architecture-best-practices` teaches UI, Logic, and Data layers with `ChangeNotifier` view models, while this page pins `data/domain/presentation` with Riverpod. The `Layout:` and `State:` lines in `AGENTS.md` take precedence; say so in the prompt when you ask for a new feature. - The README marks the Dart MCP server as experimental and shows several tools, such as `run_tests` and `launch_app`, as not enabled. Check which tools your session lists before you write a prompt that depends on one. - Every MCP server adds its tool list to every session. Skills load only when a task matches their description, so they cost little until used. For how skills and MCP servers compare, see [how to install and manage skills](/en/ecosystem/skills/installing-managing/) and [official vendor skills](/en/ecosystem/skills/top-skills-official/). ## Pin the Flutter stack in AGENTS.md A prompt pins the stack for one session. A project instruction file pins it for every session. Codex reads `AGENTS.md`, and Claude Code reads it when the repository has no `CLAUDE.md` (from v2.1.277, both release channels on 2026-10-12). If you keep a `CLAUDE.md`, put the same block there. In Cursor, put the same block in a project rule (Cursor Rules). Copy this block and adjust the versions. ```markdown ## Flutter stack (do not substitute) - Flutter 3.47+, Dart 3.13+. Add packages with `flutter pub add`, never by typing versions. - State: Riverpod 3 with code generation (`@riverpod`, `part '*.g.dart';`). Never import `package:flutter_riverpod/legacy.dart`. No StateNotifier, no get_it. - Navigation: go_router 18 with one `GoRouter` provided through Riverpod. - Networking: Dio behind `ApiService`. Map every `DioException` to the sealed `ApiFailure`. - Models: freezed 4 (`sealed` or `abstract` classes). No hand-written fromJson. - Layout: lib/features/<feature>/{data,domain,presentation}. domain/ imports no Flutter and no Dio. ## Check command (run before you say a task is done) dart run build_runner build && dart format --output=none --set-exit-if-changed . \ && flutter analyze && flutter test ``` The last line is the contract. An agent that reports "done" without a green check command has not finished, and you can hold it to that without opening a single file. **Copy-paste prompt: scaffold a Flutter app on the pinned stack** ```text Scaffold a new Flutter app with `flutter create --org com.example shop_app`. Require Flutter 3.47+ (Dart 3.13+); stop and tell me if `flutter --version` is older. Use exactly this stack, added with `flutter pub add`: flutter_riverpod, riverpod_annotation, and dev dependencies riverpod_generator, build_runner, riverpod_lint; go_router; dio; freezed_annotation, json_annotation, and dev dependencies freezed, json_serializable. Use Riverpod code generation (`@riverpod`) only. Do not import package:flutter_riverpod/legacy.dart. Create lib/features/home/{data,domain,presentation} with one example provider, and write the AGENTS.md block from our team template with the check command. Finish by running the check command and pasting its last 20 lines. ``` Run the prompt in whichever tool you use. In Claude Code, pass it as the first argument (`claude "…"`). In Codex, pass it the same way (`codex "…"`); the session asks before commands that need approval. In Cursor, paste it into the agent chat. Each tool follows the block only from the file it reads. When you change the stack, update every copy of the block in the same commit. ## Write a code-generation Riverpod provider The payoff of `@riverpod` is that loading, caching, and parameters become declarative. The risk is that the agent mixes in legacy provider classes from its training data. **Copy-paste prompt: async Riverpod provider with refresh** ```text Using Riverpod 3 code generation, create `userProfile(String userId)` in lib/features/profile/data/user_profile_provider.dart. It fetches a freezed `Profile` from `ApiService` (itself a @riverpod provider). Use @Riverpod(keepAlive: true) so the profile stays cached. Take a plain `Ref`. In ProfilePage (a ConsumerWidget), render loading, error, and data with `switch` on the AsyncValue, and add pull-to-refresh with `ref.invalidate`. Write a test with `ProviderContainer.test()` that overrides apiServiceProvider with a fake and asserts one success and one ApiFailure case. Run the check command and show its result. ``` Check the result mechanically instead of reading it: ```bash # Must print nothing: legacy providers or pre-3.0 generated refs rg -n "flutter_riverpod/legacy.dart|StateNotifier|ProviderRef\b|FutureProviderRef" lib # Generated files must match what the generator writes dart run build_runner build --only-check ``` The `--only-check` line matters only if you commit the `.g.dart` and `.freezed.dart` files. If you commit them, it catches the agent that edited a generated file by hand or forgot to rerun the generator. ## Build a go_router auth redirect that cannot loop The classic go_router bug is an infinite redirect: the guard sends signed-out users to `/login` but forgets to let `/login` through. The fix is one guard clause, and it is the line the agent most often omits. Do not trust your eyes to find it. Make the redirect a pure function and test it. **Copy-paste prompt: go_router redirect with a table-driven test** ```text Set up go_router 18 for this app. Put the redirect logic in a pure top-level function `String? authRedirect(AuthStatus status, Uri location)` in lib/app/router/auth_redirect.dart, and call it from GoRouter.redirect. Rules: signed-out users go to /login unless already on /login or /register; signed-in users on /login or /register go to /home; everything else returns null. Refresh the router from the auth @riverpod provider through refreshListenable. Use StatefulShellRoute.indexedStack for a bottom-nav shell with three branches. Write test/app/router/auth_redirect_test.dart as a table-driven test covering every (status, location) pair, including /login?from=/cart and /LOGIN. Run the check command. ``` The table-driven test is the acceptance criterion. If it lists every status and route pair and passes, the redirect cannot loop, whatever the implementation looks like. The `/LOGIN` row matters because go_router URLs have been case-sensitive since 15.0.0. ## Build a Dio API service with typed failures and one retry layer The happy path of a Dio service is trivial. The production parts are the 401 refresh-and-replay, the typed failure, and where retries happen. Riverpod 3 retries a failing provider by default. In `riverpod` 3.4.3, `ProviderContainer.defaultRetry` allows up to 10 retries, from 200 ms doubling to a 6.4 s cap, for any failure that is not an `Error` or a `ProviderException`. An `ApiFailure` is neither. Add a Dio interceptor that retries three times, and one failing screen can send dozens of requests. Pick one layer for retries. **Copy-paste prompt: Dio ApiService with typed failures** ```text Create ApiService in lib/core/network/api_service.dart wrapping dio 5. - An InterceptorsWrapper injects the bearer token from flutter_secure_storage. - On 401, call the token-refresh callback once, replay the request once, and sign the user out if the refresh fails. Guard against parallel refreshes. - Retries happen in Dio only: exponential backoff, max 3 attempts, only for GET requests that fail with a timeout or a 5xx. Never retry POST, PUT, or PATCH. - In ProviderScope, pass a `retry` function that returns null for ApiFailure and defers to ProviderContainer.defaultRetry for everything else. - LogInterceptor only when kDebugMode is true, with request and response bodies off. - Map every DioException to a sealed freezed ApiFailure (network, unauthorized, server(statusCode), unknown). Never rethrow DioException. Expose ApiService as a @riverpod provider. Write tests with a fake HttpClientAdapter that assert: 401 then 200 replays once; 503 three times gives ApiFailure.server; POST 503 is not retried. Run the check command. ``` The three tests prove the behaviour that matters. Pair them with one mechanical guard: `rg -n "rethrow|throw e\b" lib/core/network` should print nothing once every `DioException` is mapped. For the API contract on the server side, see [API development patterns](/en/cookbook/backend-recipes/api-patterns/). ## Keep clean-architecture layering honest with a check For a larger app, ask for a concrete feature, not "set up clean architecture". The constraint that matters is that `domain` imports neither Flutter nor Dio. A leaked `package:flutter/material.dart` in a use case means the layering is cosmetic, and a grep finds it faster than a reviewer. **Copy-paste prompt: a checkout feature slice** ```text Generate a checkout feature in lib/features/checkout: - domain: CartItem entity (freezed), OrderRepository interface, and a PlaceOrder use case returning a sealed Result<OrderId, ApiFailure>. - data: OrderRepositoryImpl calling ApiService. - presentation: a @riverpod CheckoutController and CheckoutPage. Wire dependencies through Riverpod providers only (no get_it). domain/ must not import package:flutter or package:dio. Add a unit test for PlaceOrder with a fake OrderRepository. Show the folder tree with one sentence per file, then run the check command. ``` Add the layering rule to CI so it holds after the agent's next hundred edits. The step passes only when `rg` reports no match (exit 1); a match (exit 0) or an `rg` error such as a missing directory (exit 2) fails it, and the `|| rc=$?` form keeps working under the `bash -e` shell that CI runners use: ```bash rc=0 rg -n 'package:(flutter|dio)/' lib/features --glob '**/domain/**' || rc=$? test "$rc" -eq 1 ``` ## Verify each Flutter change without reading every line The check command in `AGENTS.md` is the inner loop. The pull request needs a gate that runs the same checks plus the ones too slow for every edit. The order below is cheapest first, so a failure costs as little CI time as possible. 1. **Generated code is current.** `dart run build_runner build --only-check` (if you commit generated files), otherwise `dart run build_runner build`. 2. **Format and static analysis.** `dart format --output=none --set-exit-if-changed .` and `flutter analyze`. Treat `riverpod_lint` findings as errors. 3. **Guards.** The `rg` checks for legacy Riverpod imports and domain-layer imports from the sections above. 4. **Unit and widget tests.** `flutter test`, including the redirect table and the Dio tests. 5. **Golden tests on one OS.** Golden tests run with `flutter test` on the CI Linux image and compare against the committed images. Regenerate them with `flutter test --update-goldens` only on that image, in a separate commit. 6. **Integration tests on a device.** `flutter test integration_test` on an emulator for the flows that touch plugins, such as sign-in and payment. The [mobile app testing patterns](/en/workflows/test/mobile-testing/) page covers device farms and flaky-test triage. Who signs off: the pull-request reviewer confirms the gate is green and that the tests match the acceptance criteria in the task, such as the redirect table and the three Dio cases. Human reading goes to those tests and to the `domain` layer, not to generated code or widget boilerplate. For the review process itself, see [how to review agent pull requests](/en/workflows/ship/agent-pr-review/). **Copy-paste prompt: widget and golden tests for a page** ```text Write widget tests for CheckoutPage with flutter_test. Wrap it in a ProviderScope that overrides orderRepositoryProvider with a fake. Cover: loading shows a progress indicator; success shows the order id; ApiFailure.server shows the retry message; the Place order button is disabled while submitting. Add one golden test that loads a bundled font in test/flutter_test_config.dart, so the image does not depend on host fonts. Tell me the exact command to regenerate the golden on the CI Linux image. Run flutter test and show the summary. ``` To have the agent write the CI job itself, connect the GitHub MCP server first, so it reads your real workflows and secret names instead of inventing them. See the [GitHub MCP server guide](/en/ecosystem/mcp/github-mcp/) for per-tool setup and [CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/) for the job structure. For production crashes, an [observability MCP server](/en/ecosystem/mcp/observability-mcp/) such as Sentry's lets the agent read the real stack trace for a release before it proposes a fix. ## What breaks when agents write Flutter code? - **`build_runner` drift.** Symptoms: a provider that "does not exist", a stale `.g.dart`, or a type error in generated code. Recovery: run `dart run build_runner clean`, then `dart run build_runner build`. The `--delete-conflicting-outputs` flag no longer does anything in `build_runner` 2.16.1, so an agent that keeps adding it has not found the cause. Paste the first error into the agent and ask which of three causes it is: a missing `part` directive, a legacy and codegen syntax mix, or `riverpod_annotation` and `riverpod_generator` on different majors. - **Legacy Riverpod creeps back.** Symptom: the `rg` guard finds `legacy.dart` or `StateNotifier`. Recovery: reject the change and paste one of your existing providers into the prompt as a style anchor. Add the rule to `AGENTS.md` if it is missing. - **A failing screen floods the API.** Symptom: logs show the same GET many times per screen open. Cause: Riverpod's automatic retry on top of a Dio retry interceptor. Recovery: pass a `retry` function to `ProviderScope` that returns `null` for `ApiFailure`, as in the Dio prompt. - **Tests expect the raw error.** Symptom: a test that expects `ApiFailure` from `ref.read` or `ref.watch` fails after the Riverpod 3 upgrade. Cause: Riverpod 3 wraps a rethrown provider error in `ProviderException`. Recovery: assert on the provider's `AsyncValue` state, or unwrap the exception, and tell the agent which one your suite uses. - **freezed 4 resolves as 3.2.x.** Symptom: `flutter pub add freezed` picks freezed 3.2.5 and riverpod_lint 3.1.8, and the agent's freezed 4 code fails to build. Cause: freezed 4.0.0 and later and riverpod_lint 3.1.9 need Dart 3.13, which ships with Flutter 3.47. Recovery: upgrade to Flutter 3.47+ in its own change, or, on Dart 3.12, write "freezed 3" in `AGENTS.md` so the agent targets the version it gets. - **go_router 18 will not resolve.** Symptom: `flutter pub get` fails on the SDK constraint. Cause: 18.0.0 needs Flutter 3.44 and Dart 3.12. Recovery: pin `go_router: ^17.5.0` until you upgrade Flutter. Do not let the agent upgrade the Flutter SDK as a side effect of a feature task. - **Gradle and CocoaPods failures.** Android failures after a dependency bump are usually an Android Gradle Plugin, Gradle, or Kotlin version mismatch. iOS failures are usually a pod that needs `pod repo update` or a higher deployment target. Recovery: paste the full build log, ask the agent to pin the specific plugin versions, and forbid it from changing the Flutter SDK version to fix a pod. - **Goldens pass locally and fail in CI.** Cause: macOS and Linux render fonts differently. Recovery: generate goldens only on the CI image and load a bundled font in `flutter_test_config.dart`. - **The agent cannot see the running app.** Symptom: Dart MCP tools such as `get_runtime_errors` return nothing. Cause: the app runs in release mode or with `--no-dds`, so no Dart Tooling Daemon is registered. Recovery: run `flutter run` in debug mode and ask the agent to connect to it through the `dtd` tool. ## Where to go next with Flutter - [Mobile development overview](/en/cookbook/mobile-development/) for how the Flutter, Expo, and React Native pages divide the work - [React Native and Flutter UI recipes](/en/cookbook/mobile-development/mobile-patterns/) for widget-level recipes such as custom widget libraries and platform-adaptive design - [Expo development patterns](/en/cookbook/mobile-development/expo/) and [React Native development patterns](/en/cookbook/mobile-development/react-native/) if you are comparing cross-platform stacks - [Native iOS and Android recipes](/en/cookbook/mobile-development/native-ios-android/) for the platform code behind a Flutter plugin - [Test-driven development with agents](/en/method/principles/test-driven-development/) for writing the table-driven test before the agent writes the redirect --- # React Native and Flutter UI Recipes URL: https://developertoolkit.ai/en/cookbook/mobile-development/mobile-patterns/ Description: 12 copy-paste agent prompts for React Native and Flutter UI, pinned to current package majors, each with the device evidence that proves it works. React Native and Flutter UI recipes are 12 copy-paste prompts for building cross-platform mobile screens with Claude Code, Codex, or Cursor, from adaptive navigation to store preparation. Each prompt pins the package majors current in September 2026 and asks for evidence from both platforms, so you check screenshots and tests instead of reading every line. This page is for developers who build mobile UI with an agent, and for tech leads who review what it ships. You ask for a swipeable card and get `Gesture.Pan()`, which `react-native-gesture-handler` 3 deprecates. You ask for a fast feed and get FlashList's `estimatedItemSize`, a prop that FlashList 2 removed. The iOS simulator looks fine, and nobody opens the Android emulator. This page covers the screens; for the stack underneath them (Expo builds and OTA updates, React Native data layers, Riverpod and go_router architecture), start at the [mobile development overview](/en/cookbook/mobile-development/). ## Which package versions do these recipes assume? The agent's training data spans several majors of every package below, and each major changed an API the agent likes to use. The table shows what npm and pub.dev served on 2026-09-26. Put the majors in `AGENTS.md` (or `CLAUDE.md`) so every session inherits them, and let `npx expo install` or `flutter pub add` choose exact versions. | Package | Version | What the agent gets wrong | | --- | --- | --- | | `react-native` | 0.87.1 | Old-architecture bridge modules. Current libraries such as Reanimated 4 target the New Architecture. | | `@react-navigation/native` | 7.4.1 | Mixing the v6 and v7 configuration styles in one navigator. | | `@shopify/flash-list` | 2.3.2 | `estimatedItemSize`. Version 2 measures items itself, and the prop no longer exists. | | `react-native-reanimated` | 4.7.0 | Missing `react-native-worklets` (peer dependency `0.13.x`). Reanimated 4.7 also requires React Native 0.86 to 0.88. | | `react-native-gesture-handler` | 3.3.0 | `Gesture.Pan()`, which 3.x marks `@deprecated` in favour of `usePanGesture`. The 2.x line lives on npm under the `legacy` tag. | | `expo-image` | 57.0.5 | Reaching for `react-native-fast-image` instead. This page uses `expo-image`. | | `expo-notifications` | 57.0.21 | Reaching for `@notifee/react-native`, whose last npm release is 9.1.8 from 2024-12-20. | | `flutter_riverpod` | 3.4.3 | `StateNotifierProvider` from Riverpod 2, which Riverpod 3 moved to `legacy.dart`. | | `go_router` | 18.0.1 | Ignoring the SDK floor. Version 18 requires Flutter 3.44 and Dart 3.12. | ## Set up the agent once for mobile UI work Two things make every recipe below cheaper to verify: a type check that runs on every edit, and an instruction file that defines "done". Install your stack's vendor skills first. The [mobile overview](/en/cookbook/mobile-development/) has the install commands for the Expo, Flutter, and Callstack React Native skills and for MobileBuildMCP. Add this block to `AGENTS.md`, which Codex reads in trusted projects. Claude Code reads it when the repository has no `CLAUDE.md` (from v2.1.277, both release channels on 2026-10-12); otherwise copy the block into `CLAUDE.md`. For Cursor, paste the block into a project Rule. ```markdown ## Mobile UI: verify before done - Pinned majors: React Native 0.87, React Navigation 7, FlashList 2, Reanimated 4, Gesture Handler 3, expo-image, expo-notifications. Flutter 3.44+, Riverpod 3, go_router 18. - Before using a library API, read its types in node_modules or its pub.dev docs. - Gates: `npx tsc --noEmit`, the linter, and the test runner (React Native); `flutter analyze` and `flutter test` (Flutter). - Launch the app on one iOS simulator and one Android emulator. Save a screenshot of every changed screen to evidence/<task>/ios-*.png and evidence/<task>/android-*.png. - Forbidden in app code: localStorage, window.*, document.*, dart:html, dart:io Platform in widgets. - Never run a store submission, EAS build, or OTA publish. ``` The tools differ in how they enforce that block: **Claude Code** A `PostToolUse` hook puts type errors in front of Claude on the edit that caused them. Save this as `.claude/hooks/mobile-typecheck.sh` and make it executable: ```bash #!/usr/bin/env bash # .claude/hooks/mobile-typecheck.sh (PostToolUse, matcher "Edit|Write") set -uo pipefail file=$(jq -r '.tool_input.file_path // empty') case "$file" in *.ts|*.tsx) out=$(cd "$CLAUDE_PROJECT_DIR" && npx tsc --noEmit 2>&1) \ || { echo "tsc failed after editing $file:" >&2; head -n 40 <<<"$out" >&2; exit 2; } ;; *.dart) out=$(cd "$CLAUDE_PROJECT_DIR" && dart analyze "$file" 2>&1) \ || { echo "dart analyze failed on $file:" >&2; head -n 40 <<<"$out" >&2; exit 2; } ;; esac exit 0 ``` Register it in `.claude/settings.json`: ```json { "hooks": { "PostToolUse": [ { "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "${CLAUDE_PROJECT_DIR}/.claude/hooks/mobile-typecheck.sh", "args": [], "timeout": 120 }] } ] } } ``` The matcher filters on the tool name, not on a file glob, so the script filters by extension. On a large project this runs the full type check on every edit, which can take tens of seconds; the `timeout` of 120 seconds stops a slow run from stalling the session, and adding `--incremental` to the `tsc` call lets later runs reuse the previous type information. See [Claude Code hooks](/en/claude-code/automate/hooks-automation/) for the full event list. Before you merge, run `/code-review` on the branch. **Codex** Codex reads the `AGENTS.md` block in every session. For a repeatable, unattended run of one recipe, use `codex exec` with the `:workspace` permission profile (beta in Codex 0.157.1). That profile has no network access and writes only inside the project and the temp directory (it cannot write to `$HOME`): in our Codex 0.157.1 test on Linux, `curl` to the npm registry could not resolve the host and a write to `$HOME` hit a read-only file system. Package installs fail inside the run, and so does anything that needs simulator or emulator state outside the repository. We tested this offline-gate run only with the npm and TypeScript gates; Flutter is untested here, and `flutter analyze` or `flutter test` may need a writable SDK directory and `$HOME`, and so a different profile. Install dependencies first, give Codex only the offline gates, and fail the run unless every gate reports `PASS`: ```bash npm ci # Flutter (untested here): flutter pub get. The :workspace profile has no network mkdir -p evidence/feed-list codex exec -c default_permissions=":workspace" -o evidence/feed-list/summary.md \ "Apply the FlashList recipe in docs/prompts/feed-list.md. Do not install packages. Run the type check, linter and tests from 'Mobile UI: verify before done' in AGENTS.md; skip the simulator, emulator and frame-rate steps. Report each gate on its own line as PASS, FAIL or NOT RUN with the reason." s=evidence/feed-list/summary.md test -s "$s" && grep -q PASS "$s" && ! grep -Eq 'FAIL|NOT RUN' "$s" \ || { echo "Codex run incomplete or failing: see $s" >&2; exit 1; } ``` Save the FlashList prompt from this page as `docs/prompts/feed-list.md` first. The check fails closed: a missing or empty summary, a `FAIL`, or a `NOT RUN` stops the script. The device half of the evidence stays with you: launch the app on the iOS simulator and the Android emulator outside Codex, save the screenshots to `evidence/feed-list/`, and record the frame rates yourself. A green `summary.md` alone is not device evidence. Open the pull request and comment `@codex review` to get a second review of the diff against the same `AGENTS.md` rules. See [Codex code review](/en/codex/ship/code-review/). **Cursor** Paste the block into a project Rule so Cursor applies it in every session. For recipes that touch many files (navigation, native modules), start in Plan Mode so you approve the file list before the agent writes code. On the pull request, [Bugbot](/en/cursor-ide/ship/bugbot/) reviews the diff. The [Cursor mobile development guide](/en/cursor-ide/build/mobile-dev/) covers the IDE-side loop with simulators. ## React Native UI recipes Each recipe states the situation, gives the prompt, and names the evidence that proves the result. Paste a prompt as-is, and edit only the screen names. ### Build platform-adaptive navigation with React Navigation 7 Your product team wants a bottom tab bar on iOS and a navigation drawer on Android, both backed by the same screens and the same deep links. **Copy-paste prompt: platform-adaptive navigation** ```text Build platform-adaptive navigation with React Navigation 7 (read the installed @react-navigation/* types before writing config). - RootNavigator renders a bottom-tab navigator on iOS and a drawer navigator on Android. Both hold the same four stacks: Home, Search, Notifications, Profile. - Type every route in RootStackParamList; no `any` in navigation code. - Deep links: myapp://profile/:id and https://example.com/profile/:id open Profile with the id param, including from a cold start. - Android back: pop the nested stack first; on a root screen, ask before exiting. - Tests: resolve each deep link to its route and params with the linking config. Finish with the evidence list from AGENTS.md, plus the output of `npx uri-scheme open myapp://profile/42 --ios` and `--android`. ``` **Evidence:** the deep-link tests, and screenshots of Profile 42 opened by the link on both platforms. ### Build a responsive layout for phones, tablets, and foldables Your app stretches a phone layout across a tablet, and the list-detail screens waste two thirds of the display. **Copy-paste prompt: responsive layout system** ```text Create a responsive layout system for this React Native app. - useResponsive() built on useWindowDimensions (never Dimensions.get at module scope) returning { width, height, breakpoint, orientation }. Breakpoints: compact < 600, medium 600-839, expanded >= 840 (dp). - MasterDetail: compact shows the list and pushes the detail screen; medium and expanded show list (1/3) and detail (2/3) side by side. - ResponsiveGrid: 1, 2, or 3 columns by breakpoint, recomputed on rotation. - Respect safe areas with react-native-safe-area-context. - Tests: mock useWindowDimensions at 390, 700, and 1000 dp wide and assert which layout renders. Screenshots: phone portrait, tablet portrait, tablet landscape. ``` **Evidence:** the three breakpoint tests, and a tablet screenshot in each orientation. Rotation is where hard-coded widths break. ### Fix a janky feed with FlashList 2 and expo-image Your feed holds 1,000+ items with images and stutters when you scroll, and pull-to-refresh jumps the list. **Copy-paste prompt: FlashList 2 feed** ```text Rebuild FeedScreen on @shopify/flash-list 2. Do not add estimatedItemSize or any other v1 estimate prop; v2 measures items itself. - FeedItem in React.memo, compared on id and updatedAt only. Stable renderItem and keyExtractor (useCallback). If rows have different layouts, set getItemType. - Images with expo-image: fixed dimensions, a blurhash placeholder, and cachePolicy "memory-disk". - Pull-to-refresh prepends new items without moving the visible row; background refreshes show a "N new posts" pill instead of jumping. - Infinite scroll with onEndReached, a footer spinner, and an end-of-feed state. Measure before and after: record 10 seconds of fast scrolling on the Android emulator with the performance monitor on, and report the JS and UI frame rates. ``` **Evidence:** before and after frame rates from the same device and scroll, not "should be faster". The [React Native recipe](/en/cookbook/mobile-development/react-native/) covers the data layer behind the feed. ### Show offline state without losing the user's work Field technicians fill in forms without a signal, and today the app shows a spinner forever and drops the entry. **Copy-paste prompt: offline-first UI states** ```text Add offline UI states on top of the existing data layer (do not replace it). - useNetworkStatus() with @react-native-community/netinfo returning { isOnline, pendingCount, lastSyncedAt, syncNow }. - OfflineBanner: shows "Offline - N changes waiting" and a Retry button; hides within 2 seconds of reconnecting. - Every list row with unsynced changes shows a "Pending" badge; a failed sync shows "Not saved - tap to retry" and never silently discards the entry. - Forms save locally on submit and navigate back immediately. - Tests: mock NetInfo offline, submit a form, go online, and assert the badge clears and the entry reaches the mocked API exactly once. ``` **Evidence:** the offline-to-online test, and a screenshot of the banner and badge taken in airplane mode. For the storage and sync engine itself (MMKV with TanStack Query, or WatermelonDB for relational sync), use the [React Native recipe](/en/cookbook/mobile-development/react-native/). ### Write a native module when no library covers the hardware Your NFC hardware vendor uses a proprietary tag format that `react-native-nfc-manager` does not expose, so you need Swift and Kotlin code behind a typed TypeScript API. **Copy-paste prompt: Turbo Module for NFC** ```text Create a Turbo Module named NativeVendorNfc for the New Architecture. - Codegen spec in src/specs/NativeVendorNfc.ts: isAvailable(), startScan(), stopScan(), and events onTag({ id, payload }) and onError({ code, message }). - iOS (Swift): CoreNFC reader session, the NFCReaderUsageDescription key in Info.plist, and the NFC tag-reading entitlement. Return isAvailable false on devices without NFC instead of crashing. - Android (Kotlin): NfcAdapter with foreground dispatch, released in onPause. - useVendorNfc() hook: { isAvailable, isScanning, lastTag, error, start, stop }. - Jest tests for the hook with the native module mocked. After editing native code, do a full native rebuild for both platforms (no Fast Refresh) and report both build logs' last 20 lines. ``` **Evidence:** two clean native builds and the hook tests. CoreNFC does not run on the iOS simulator, so a person scans a real tag on one iPhone and one Android phone before merge. In an Expo app, ask for an Expo module instead; see the [Expo recipe](/en/cookbook/mobile-development/expo/). **Claude Code** Native edits need a rebuild, and a stale binary makes a correct change look broken. After any `.swift` or `.kt` edit, tell Claude to rebuild the native app: `npx expo run:ios` / `npx expo run:android` in an Expo development build, or `cd ios && pod install` followed by `npx react-native run-ios` / `npx react-native run-android` in bare React Native. `pod install` only syncs dependencies and compiles nothing. Keep `npx expo prebuild --clean` for a changed config plugin or `app.json` in a Continuous Native Generation project: it regenerates `ios/` and `android/` and deletes any direct edits there, so native code in an Expo app belongs in an Expo module. On macOS, [MobileBuildMCP](/en/ecosystem/mcp/framework-devtools-mcp/) lets Claude build, launch the simulator, and read the build log itself. **Codex** Run the native work in its own worktree so Xcode and Gradle sync state never mixes with your JavaScript branch. Tell Codex to finish every native edit with the same rebuild: `npx expo run:ios` / `run:android` (Expo), or `pod install` then `npx react-native run-ios` / `run-android` (bare React Native). MobileBuildMCP registers with `codex mcp add`; see the [dev-server MCP servers](/en/ecosystem/mcp/framework-devtools-mcp/) page for the command. **Cursor** Approve the file list in Plan Mode first: spec, Swift class, Kotlin class, manifest, entitlement, and hook. A missing entitlement file is the most common omission, and it fails only at run time on a device. ### Build a swipeable card stack with Reanimated 4 and Gesture Handler 3 Your matching screen needs a card stack that follows the finger at the display's frame rate and never stutters while JavaScript is busy. **Copy-paste prompt: swipeable card stack** ```text Build a swipeable card stack with react-native-reanimated 4 and react-native-gesture-handler 3. Read both packages' installed types first: Gesture.Pan() is deprecated in Gesture Handler 3, so use usePanGesture. - SwipeableCard maps translationX to rotation (max 15 degrees) and to like/nope overlay opacity. Past 120 px on release it animates off-screen with withTiming; otherwise it springs back with withSpring. - CardStack renders the top 3 cards with scale and translateY offsets; the next card animates up when the top card leaves. - Undo brings the last card back. Haptic feedback (expo-haptics) at threshold. - All animation values are shared values; no setState during a gesture. - Tests with react-native-gesture-handler/jest-utils (fireGestureHandler or createGestureController): a past-threshold swipe calls onSwipe('right'); a short swipe returns the card. ``` **Evidence:** the gesture tests, plus a screen recording from a physical Android phone, where dropped frames show that the simulator hides. Confirm `react-native-worklets` is in `package.json`. ### Ask for notification permission at the right moment Your app requests notification permission on first launch, most users decline, and a tapped notification opens the home screen instead of the order it mentions. **Copy-paste prompt: notification permission and deep links** ```text Implement the notification UX with expo-notifications (it works in bare React Native through Expo modules). Do not use @notifee/react-native. - A pre-permission screen shown after the user's first completed order, not on launch; "Not now" hides it for 14 days. - If permission is denied, Settings > Notifications shows a button that opens the system settings with Linking.openSettings(). - Android channels: orders (high), messages (default), promotions (low), created before the token request. - A tapped notification with data.url opens that screen, including from a cold start (useLastNotificationResponse). - Tests for the permission state machine and for data.url to route mapping. ``` **Evidence:** the state-machine tests, and a notification sent to a device and tapped from a killed app. The [Expo recipe](/en/cookbook/mobile-development/expo/) covers the token pipeline and server side. ## Flutter UI recipes The Flutter recipes use the widget and state APIs of Flutter 3.44+ and Riverpod 3. For package setup, provider architecture, and the go_router auth redirect, follow the [Flutter recipe](/en/cookbook/mobile-development/flutter/) first. ### Build a branded widget library that adapts per platform Every screen styles its own buttons, dark mode is half-finished, and the design team cannot see all variants in one place. **Copy-paste prompt: Flutter widget library** ```text Create a widget library in lib/widgets/ driven by ThemeData and a ThemeExtension<AppTokens> (colors, radii, spacing) with light and dark instances. No hard-coded colors or sizes inside widgets. - AppButton: primary, secondary, outline, ghost, destructive; sm, md, lg; loading and disabled states; a minimum 48x48 dp tap target. - AppTextField: label, helper, error, prefix/suffix, password visibility toggle. - AppCard, AppAvatar (image, initials fallback, presence dot), AppBottomSheet (drag handle, half and full snap points). - A Widgetbook catalogue listing every variant in light and dark. - Widget tests per widget, and golden tests for AppButton in both themes. Run flutter analyze and flutter test and report the results. ``` **Evidence:** passing golden tests in both themes. Goldens catch visual regressions that nobody spots in a diff. Generate them on the same OS as CI, because font rendering differs between macOS and Linux. ### Render loading, error, and empty states from Riverpod Your screens show a blank page while data loads and a red error box when the API fails, and each screen handles it differently. **Copy-paste prompt: async screen states with Riverpod 3** ```text Standardise async screen states with Riverpod 3 code generation (@riverpod, no imports from package:flutter_riverpod/legacy.dart). - AsyncStateView<T> widget taking an AsyncValue<T> and builders for data, loading (skeleton, not a spinner), error (message plus Retry that calls ref.invalidate), and empty. - Keep previous data visible during refresh (skipLoadingOnRefresh). - Migrate OrdersScreen and ProfileScreen to it. - Widget tests with ProviderScope overrides for each of the four states, and a test that Retry triggers exactly one new fetch. ``` **Evidence:** the four state tests per screen. The "exactly one fetch" test matters because Riverpod 3 also retries failing providers on its own. ### Make Flutter screens feel native on iOS and Android Your Flutter app uses Material dialogs and switches on iOS, and iOS users notice. **Copy-paste prompt: adaptive Flutter widgets** ```text Create platform-adaptive widgets in lib/adaptive/ that branch on Theme.of(context).platform (never dart:io Platform, so tests can override it). - showAdaptiveAppDialog: AlertDialog on Android, CupertinoAlertDialog on iOS, one API. - AdaptiveSwitch (Switch.adaptive), AdaptiveTextField, and an adaptive date picker (Material dialog on Android, CupertinoDatePicker in a bottom sheet on iOS). - Page transitions from PageTransitionsTheme: Cupertino on iOS, the Material default on Android. - Widget tests that render each widget with platform set to TargetPlatform.iOS and TargetPlatform.android and assert the expected widget type. ``` **Evidence:** the paired platform tests, and one screenshot per platform of the dialog and the date picker. ### Keep bottom navigation state with go_router shell routes Switching tabs resets each tab's scroll position and navigation stack, and on a tablet the bottom bar looks out of place. **Copy-paste prompt: adaptive shell navigation with go_router 18** ```text Rebuild the main navigation with go_router 18 StatefulShellRoute.indexedStack: four branches (Home, Search, Inbox, Profile), each keeping its own stack and scroll position. - The shell shows a NavigationBar below 600 dp width and a NavigationRail at 600 dp and wider. - Tapping the active tab pops that branch to its root. - Typed routes with go_router_builder, including /products/:id inside Home. - Keep the existing auth redirect unchanged. - Widget tests: switch tabs and back and assert the pushed product page is still there; render at 400 and 800 dp and assert bar versus rail. ``` **Evidence:** the state-preservation test and the two width tests. ## Prepare a React Native or Flutter app for store submission Your app is feature-complete, and the release checklist lives in one person's head. This recipe turns it into a script that CI can run on every release candidate. **Copy-paste prompt: store submission preparation** ```text Prepare this app for App Store and Google Play submission. Change config only; do not submit, upload, or run a paid cloud build. - iOS: every NS*UsageDescription the code actually needs (grep the APIs used; remove unused ones), the privacy manifest (PrivacyInfo.xcprivacy), version and build number. - Android: applicationId, versionCode and versionName, targetSdk 36, release signing read from environment variables (never committed), R8 enabled. - scripts/verify-release.sh: builds release for both platforms (iOS needs a macOS runner; fail, never skip, when Xcode is absent), fails if a release bundle contains console.log or debugPrint calls, debug-only packages, or a non-production API URL. - RELEASE_CHECKLIST.md listing what a human checks on a real device. Run verify-release.sh and report its output. ``` **Evidence:** a green `verify-release.sh` run and the checklist signed off by the release owner. Google Play requires new apps and app updates to target Android 16 (API level 36) from 2026-08-31, per the Android developers target-API page checked on 2026-09-26. Whichever tool prepares the release, the rule is the same: run `verify-release.sh` in CI on every release branch (the iOS half on a macOS runner), let the script's exit code decide pass or fail, and have a person sign the checklist before anything reaches a store. The tools differ only in where you review the change. In Claude Code, run the prompt in plan mode (`/plan`) so the release owner approves the file list, then run `/code-review` on the branch before you open the pull request. In Codex, start the preparation as a cloud task that opens a pull request with the config changes and `RELEASE_CHECKLIST.md`, and the release owner approves the version bump and signing configuration there. In Cursor, review the `Info.plist`, `build.gradle`, and privacy-manifest changes in one diff before you accept them; a wrong `versionCode` or a leftover debug entitlement is visible there at a glance. ## How do you verify a mobile UI recipe without reading every line? Every recipe above ends with evidence the agent produces and you check. Match the evidence to the kind of change: | Change | Evidence that proves it | Who signs off | | --- | --- | --- | | Layout and adaptive UI | Screenshots on iOS and Android, phone and tablet, both orientations | The developer who opened the task | | Lists and animations | Frame rates before and after, from the same device and scroll; a physical-device recording | The developer | | State, navigation, deep links | Unit and widget tests for each state and each link, including cold start | Reviewer of the pull request | | Native modules | Clean native builds on both platforms, plus a manual run on real hardware | The developer, on a device | | Release config | A green `verify-release.sh` and a signed checklist | Release owner or tech lead | In Claude Code the type-check hook catches wrong APIs on the edit that introduced them; in Codex and Cursor the `npx tsc --noEmit` / `flutter analyze` gate in `AGENTS.md` catches them when the agent runs it before finishing. The tests and screenshots prove behaviour. Put all of it in the pull request with the [evidence bundle](/en/workflows/ship/evidence-bundle/) format, and see [mobile app testing patterns](/en/workflows/test/mobile-testing/) for device matrices and flaky tests. ## What breaks when agents write React Native and Flutter UI? - **APIs from an older major.** The agent writes `estimatedItemSize`, `Gesture.Pan()`, or `StateNotifierProvider`. Recovery: keep the version table in `AGENTS.md`, and tell the agent to read the installed types before it writes library code. In Claude Code the hook catches most of these as type errors; in Codex and Cursor the `AGENTS.md` type-check gate does, when the agent runs it. - **Invented or abandoned packages.** The agent adds a package that does not exist, or one with no release in years. Recovery: check every new dependency on npm or pub.dev before merge; see [dependency verification](/en/workflows/test/dependency-verification/). - **Web APIs in mobile code.** `localStorage`, `window.innerWidth`, or `dart:html` compile in some setups and crash on a device. Recovery: extend the "Forbidden in app code" line of the `AGENTS.md` block and reject any change without device screenshots. - **Stale native binaries.** A native change looks broken because Fast Refresh does not rebuild Swift or Kotlin. Recovery: rebuild the binary with `npx expo run:ios` / `run:android` (Expo), or `pod install` then `npx react-native run-ios` / `run-android` (bare React Native). `npx expo prebuild --clean` compiles nothing and deletes direct edits to `ios/` and `android/`. - **Simulator-only success.** NFC, push, and camera features work only on hardware or need entitlements that the simulator skips. Recovery: name the device test in the recipe's evidence, and keep one iPhone and one Android phone available for it. - **Gradle and CocoaPods breaks.** The agent adds a library that needs a newer Android Gradle Plugin or iOS deployment target. Recovery: paste the full build error back, and ask the agent to state the library's minimum versions before it changes build files. ## Where to go next with mobile UI - [Mobile development overview](/en/cookbook/mobile-development/): pick your stack and install its skills - [Expo development patterns](/en/cookbook/mobile-development/expo/): routing, EAS builds, and staged OTA updates - [React Native development patterns](/en/cookbook/mobile-development/react-native/): offline data, performance, and CI to the stores - [Flutter development patterns](/en/cookbook/mobile-development/flutter/): Riverpod, go_router, Dio, and the check command - [Native iOS and Android recipes](/en/cookbook/mobile-development/native-ios-android/): Swift/SwiftUI and Kotlin/Compose with an agent - [Mobile app testing patterns](/en/workflows/test/mobile-testing/): device matrices, Maestro flows, and platform-specific tests --- # Native iOS and Android Recipes URL: https://developertoolkit.ai/en/cookbook/mobile-development/native-ios-android/ Description: Swift/SwiftUI and Kotlin/Compose with an agent: one build-and-test script per platform, simulator and emulator loops, fast builds, and UI-test evidence. Native iOS and Android development with a coding agent works when each platform has one script that builds the app, runs its tests on a pinned simulator or emulator, and saves the results as evidence. Claude Code, Codex, and Cursor iterate against that script, and an MCP server such as MobileBuildMCP or mobile-mcp lets the agent see the running app. You ask the agent for a new SwiftUI settings screen. It writes clean Swift, announces "done", and the project does not build, because the new file never reached the Xcode target. On the Android side, the agent runs `./gradlew clean build` on every change, waits minutes for a result, and pastes thousands of lines of Gradle output into its own context. Neither agent ever looked at the screen it built. This page fixes those three gaps: build feedback, speed, and proof. ## What you get from an agent-ready native project - Two copy-paste scripts, `scripts/ios-check.sh` and `scripts/android-check.sh`. Each one boots a pinned device, runs the tests, writes a short summary for the agent, and saves the full evidence under `build/evidence/`. - An instructions block for `AGENTS.md`, `CLAUDE.md`, or a Cursor rule that makes "the script exits 0" the definition of done. - Verified install commands for the two mobile MCP servers, plus the Codex plugins for iOS and Android, per tool. - Build-time rules that keep the agent's inner loop short: narrow test selection, warm devices, and caches. - Recipes for a SwiftUI screen, a Jetpack Compose screen, and a crash reproduction, each ending in UI-test evidence rather than a diff you have to read. ## Why native apps need a different agent loop Web agents get cheap feedback: a dev server reloads in a second and a browser MCP shows the page. Native projects take longer to give that feedback, for three reasons: 1. **The project file is part of the build.** Xcode decides what compiles from the target membership in `project.pbxproj`, and Gradle from the module layout. An agent that writes a correct file in the wrong place gets a build error or, worse, a file that silently never compiles. 2. **Builds are slow and loud.** A clean `xcodebuild` or Gradle build prints thousands of lines. Streamed into the agent's context, that output costs tokens and pushes the task instructions out of view. 3. **The UI lives in a separate process.** The simulator and the emulator are separate programs. Without a test runner or an MCP server, the agent has no way to know whether the screen renders, and neither do you. So the recipes on this page do not start with a feature prompt. They start by giving the agent a single, quiet, reliable command per platform, and they judge the agent by what that command proves. ## Set up the build-and-verify loop 1. **Pin one simulator and one emulator.** List what exists with `xcrun simctl list devices available` and `emulator -list-avds` (the `emulator` binary lives in `$ANDROID_HOME/emulator`). Pick one of each and write the names into the scripts below. A pinned device means a test failure is about your code, not about which phone the agent happened to boot. 2. **Add `scripts/ios-check.sh`.** It keeps DerivedData inside the repository, writes the full log to a file, and prints only the lines the agent needs: ```bash #!/usr/bin/env bash # scripts/ios-check.sh — build, test and collect evidence on one pinned simulator. # Usage: scripts/ios-check.sh [TestTarget/TestClass ...] (no argument = all tests) set -euo pipefail SCHEME="${SCHEME:-App}" SIM="${SIM:-iPhone 17}" OUT="build/evidence/ios" rm -rf "$OUT" && mkdir -p "$OUT" ONLY=() for t in "$@"; do ONLY+=("-only-testing:$t"); done xcrun simctl bootstatus "$SIM" -b >/dev/null # boots the simulator if needed, waits until ready set +e xcodebuild test \ -scheme "$SCHEME" \ -destination "platform=iOS Simulator,name=$SIM" \ -derivedDataPath build/DerivedData \ -resultBundlePath "$OUT/tests.xcresult" \ ${ONLY[@]+"${ONLY[@]}"} > "$OUT/xcodebuild.log" 2>&1 STATUS=$? set -e xcrun xcresulttool get test-results summary --path "$OUT/tests.xcresult" > "$OUT/summary.json" 2>/dev/null || true grep -E "error:|\*\* (BUILD|TEST) (SUCCEEDED|FAILED)|failed" "$OUT/xcodebuild.log" | tail -40 echo "exit=$STATUS evidence=$OUT" exit $STATUS ``` The `${ONLY[@]+...}` form matters: macOS still ships Bash 3.2, where an empty array under `set -u` aborts the script. `xcresulttool get test-results` needs Xcode 16 or later. 3. **Add `scripts/android-check.sh`.** It reuses a running emulator, clears logcat so the log covers only this run, and copies the Gradle test reports into the evidence folder: ```bash #!/usr/bin/env bash # scripts/android-check.sh — unit + instrumented tests on one pinned emulator, evidence collected. # Usage: scripts/android-check.sh [com.example.app.SomeUiTest] (no argument = all tests) set -euo pipefail AVD="${AVD:-Pixel_8_API_35}" MODULE="${MODULE:-app}" OUT="build/evidence/android" rm -rf "$OUT" && mkdir -p "$OUT" if ! adb get-state >/dev/null 2>&1; then emulator -avd "$AVD" -no-window -no-audio -no-boot-anim > "$OUT/emulator.log" 2>&1 & adb wait-for-device until [ "$(adb shell getprop sys.boot_completed | tr -d '\r')" = "1" ]; do sleep 2; done fi adb logcat -c FILTER=() if [ $# -gt 0 ]; then FILTER=("-Pandroid.testInstrumentationRunnerArguments.class=$1"); fi set +e ./gradlew ":$MODULE:testDebugUnitTest" ":$MODULE:connectedDebugAndroidTest" \ ${FILTER[@]+"${FILTER[@]}"} > "$OUT/gradle.log" 2>&1 STATUS=$? set -e adb logcat -d > "$OUT/logcat.txt" cp -R "$MODULE/build/reports" "$OUT/reports" 2>/dev/null || true cp -R "$MODULE/build/outputs/androidTest-results" "$OUT/androidTest-results" 2>/dev/null || true grep -E "FAILED|BUILD (SUCCESSFUL|FAILED)|e: " "$OUT/gradle.log" | tail -40 echo "exit=$STATUS evidence=$OUT" exit $STATUS ``` The optional argument narrows only the instrumented run to one class; unit tests always run in full, because they are cheap. 4. **Tell the agent the rules.** Paste this block into `AGENTS.md` for Codex, `CLAUDE.md` for Claude Code, or a project rule for Cursor. Claude Code reads `AGENTS.md` when the repository has no `CLAUDE.md` (v2.1.277 or later, both release channels on 2026-10-12), so one file can serve both CLIs. If you have not written an instructions file before, start with [AGENTS.md and CLAUDE.md](/en/developer-scorecard-guide/claude-md-context/): ```markdown ## Native build and test loop - iOS: run `scripts/ios-check.sh`, optionally with a test class such as `AppUITests/SettingsUITests`. Never call `xcodebuild` without `-derivedDataPath build/DerivedData`. - Android: run `scripts/android-check.sh`, optionally with a fully qualified test class. Never run `./gradlew clean` unless the user asks. - A task is done only when the relevant script prints `exit=0`. Quote its summary lines in your final message. - Every control a test touches gets a stable ID: `.accessibilityIdentifier(...)` in SwiftUI, `Modifier.testTag(...)` in Compose. Never locate elements by visible text alone. - Never edit snapshot references (`__Snapshots__/`, `src/test/snapshots/`) or weaken an existing assertion to make a test pass. Stop and report the failure instead. - New Swift files go inside an existing synchronized folder; do not edit `project.pbxproj` by hand. ``` 5. **Commit the scripts and run them once yourself.** A script that fails on a clean checkout teaches the agent to ignore it. Run both, open `build/evidence/`, and add `build/` to `.gitignore` if it is not there yet. **Why the scripts hide most of the output** The full log is still on disk in `build/evidence/`. The agent sees about 40 lines: the errors and the pass or fail verdict. When it needs more, it can `grep` the log itself. That keeps a slow build from eating the context window that should hold your spec. ## Connect the agent to the simulator and emulator Tests prove the behaviour you wrote down. For exploratory work (does the screen look right, what happens when I tap here), the agent needs to see and drive the device. Two MCP servers cover this. If you have never added an MCP server, read the [introduction to MCP](/en/ecosystem/mcp/) first: - **MobileBuildMCP** (formerly XcodeBuildMCP, maintained by Sentry) builds, runs, and debugs iOS and macOS projects on simulators and devices. It needs macOS 14.5+ and Xcode 16+. Its most-used tool is `build_run_sim`, which builds the scheme, installs the app on a booted simulator, launches it, and captures logs. - **mobile-mcp** (Mobile Next) drives iOS simulators, Android emulators, and real devices through one tool set: `mobile_list_elements_on_screen` for an accessibility snapshot, `mobile_take_screenshot`, `mobile_click_on_screen_at_coordinates`, `mobile_get_device_logs`, `mobile_get_crash`, and more. Version 1.0.5 advertises 32 tools. Popularity: on 2026-09-26 MobileBuildMCP had 6.4k GitHub stars and npm `mobilebuildmcp` 2.7.1 (published 2026-09-23); on 2026-09-28 mobile-mcp had 7,958 GitHub stars, with npm `@mobilenext/mobile-mcp` 1.0.5 (published 2026-09-23). Sources: the GitHub repositories `getsentry/MobileBuildMCP` and `mobile-next/mobile-mcp`, and the npm registry. **Claude Code** Add the servers from the terminal. The default `local` scope keeps them out of teammates' sessions until you decide to share them with `-s project`: ```bash claude mcp add mobilebuild -- npx -y mobilebuildmcp@latest mcp claude mcp add mobile-mcp -- npx -y @mobilenext/mobile-mcp@latest ``` The Claude Code desktop app on macOS also has an iOS Simulator pane (beta since July 2026), so you can watch the simulator next to the session. To keep the agent away from snapshot references, add deny rules to `.claude/settings.json`: ```json { "permissions": { "deny": [ "Edit(**/__Snapshots__/**)", "Edit(**/src/test/snapshots/**)" ] } } ``` **Codex** Add the servers with `codex mcp add` (the `--` separates the server command): ```bash codex mcp add mobilebuild -- npx -y mobilebuildmcp@latest mcp codex mcp add mobile-mcp -- npx -y @mobilenext/mobile-mcp@latest ``` Simulator builds can outlast the default MCP tool timeout. MobileBuildMCP's client docs tell Codex users to raise it per server in `~/.codex/config.toml`, because Codex ignores a top-level `tool_timeout_sec` for MCP calls: ```toml [mcp_servers.mobilebuild] command = "npx" args = ["-y", "mobilebuildmcp@2.7.1", "mcp"] # pinned, like the committed configs tool_timeout_sec = 600 ``` Codex's official plugin marketplace also lists `build-ios-apps` (skills such as `ios-debugger-agent`, `swiftui-ui-patterns`, and `swiftui-performance-audit`, with an XcodeBuildMCP configuration) and `test-android-apps` (skills `android-emulator-qa` and `android-performance`); checked in `openai/plugins` on 2026-09-26. Install them from the TUI: run `/plugins` and search by name. Two details from the plugin files (version 0.1.2 of each): `build-ios-apps` starts the server under its old package name, `xcodebuildmcp@latest`, with four workflows switched on (`simulator,ui-automation,debugging,logging`), and it can mirror the simulator in the Codex in-app browser. If you also added `mobilebuild` by hand, disable one of the two, or the agent sees every build tool twice. **Cursor** Add a project-scoped `.cursor/mcp.json` so every teammate who opens the repository gets the same servers: ```json { "mcpServers": { "mobilebuild": { "command": "npx", "args": ["-y", "mobilebuildmcp@2.7.1", "mcp"] }, "mobile-mcp": { "command": "npx", "args": ["-y", "@mobilenext/mobile-mcp@1.0.5"] } } } ``` The versions are pinned because this file is committed: with `@latest`, every teammate's next session silently runs whatever was published overnight. Bump the pins in a pull request, like any other dependency. Cursor's agent runs `scripts/ios-check.sh` and `scripts/android-check.sh` in its terminal like any other command. For Cursor-specific mobile tips, see [Cursor mobile development](/en/cursor-ide/build/mobile-dev/). **Before you connect a device server** Both servers send telemetry by default: set `MOBILEBUILDMCP_SENTRY_DISABLED=true` for MobileBuildMCP (the old `xcodebuildmcp` package, which Codex's `build-ios-apps` plugin still launches, reads `XCODEBUILDMCP_SENTRY_DISABLED`) and `MOBILEMCP_DISABLE_TELEMETRY=1` for mobile-mcp if your policy requires it. mobile-mcp can also drive a real, USB-connected phone, which means the agent can read whatever is on that screen. Use a test device with test accounts, never your personal phone. MobileBuildMCP's device tools also need code signing configured in Xcode. **When to use which.** Use MobileBuildMCP when the problem is the Xcode build itself (schemes, signing, a Swift macro, a crash on launch). Use mobile-mcp when the problem is behaviour on screen, on either platform. Enable only the server a session needs: every advertised tool definition takes context on every turn. mobile-mcp 1.0.5 advertises all 32 tools at once. MobileBuildMCP exposes only its `simulator` workflow by default; widen it with the `MOBILEBUILDMCP_ENABLED_WORKFLOWS` environment variable (for example `simulator,ui-automation,debugging,logging`) only when the task needs UI automation or the debugger. In Claude Code that is `claude mcp add mobilebuild -e MOBILEBUILDMCP_ENABLED_WORKFLOWS=simulator,ui-automation -- npx -y mobilebuildmcp@latest mcp`. Codex's `build-ios-apps` plugin sets `XCODEBUILDMCP_ENABLED_WORKFLOWS` instead only because it runs the old `xcodebuildmcp@latest` package; `mobilebuildmcp` 2.7.1 ignores that name. **Working inside Xcode instead of a terminal.** MobileBuildMCP's client documentation (checked 2026-09-26) describes Xcode 26.3 or later hosting the Codex and Claude Code agents under **Xcode Settings > Intelligence**. Those in-Xcode agents start with a minimal `PATH`, so a server launched with `npx` often fails to start; the documentation wraps the command in `/bin/zsh -lc` with Homebrew and nvm on the `PATH`. The check scripts on this page work the same from either place. ## How to keep native build times inside the agent's loop A slow loop changes agent behaviour: the agent batches many edits between builds, and a failure then has many possible causes. Keep three loops, each with its own cost: | Loop | What runs | Command | When the agent runs it | | --- | --- | --- | --- | | Inner | Unit tests of the changed module (Swift Testing or XCTest; JUnit) | `xcodebuild test ... -only-testing:AppTests/CartTests` · `./gradlew :feature:cart:testDebugUnitTest --tests '*CartViewModelTest'` | After every edit | | Middle | One UI test class on the pinned device | `scripts/ios-check.sh AppUITests/CartUITests` · `scripts/android-check.sh com.example.cart.CartScreenTest` | Before it claims "done" | | Outer | Every suite, snapshot verification, both platforms | The same two scripts without arguments, in CI | On every pull request | Rules that keep the inner and middle loops fast: - **Never clean by reflex.** Tell the agent in its instructions file that `clean` is forbidden unless you ask. Most "fix it with a clean build" instincts come from stale DerivedData or Gradle caches, and the failure list below has the targeted fix for them. - **Keep devices warm.** Both scripts boot the device only when it is not running. Leave the simulator and the emulator up for the whole session. - **Turn on Gradle's caches.** Add `org.gradle.caching=true` and `org.gradle.configuration-cache=true` to `gradle.properties`. The configuration cache skips re-running build scripts when nothing in them changed. - **Split build from test on iOS when you rerun.** `xcodebuild build-for-testing` followed by `xcodebuild test-without-building` reruns a flaky test without recompiling. Use it for triage only: after a code change the agent must rebuild. - **Measure before tuning.** `xcodebuild -showBuildTimingSummary` prints where the time went, and `./gradlew --profile` writes a local HTML report under `build/reports/profile/`. Ask the agent to read the report and propose one change, then measure again. **Copy-paste prompt: find the slowest part of the build** ```text Run `./gradlew :app:assembleDebug --profile` twice (the second run shows the incremental cost), then read the newest report under build/reports/profile/. List the five slowest tasks with their durations, explain why each one runs on an incremental build, and propose ONE change to gradle.properties or a build script that removes the biggest cost. Do not apply it yet. Show me the change and the command you will use to prove it helped. ``` ## Recipe: a SwiftUI screen with UI-test evidence The prompt below asks for the behaviour first, as tests, and makes the script's exit code the finish line. **Copy-paste prompt: SwiftUI settings screen with proof** ```text Build a SwiftUI SettingsView with a "Daily reminder" Toggle and a DatePicker that is only enabled when the toggle is on. The state lives in an @Observable SettingsModel persisted to UserDefaults. Work in this order: 1. Write Swift Testing tests (import Testing, @Test, #expect) for SettingsModel: default is off, toggling persists, the time survives a relaunch (new model instance reading the same defaults suite). 2. Write an XCUITest class AppUITests/SettingsUITests that launches the app with the launch argument "-uiTesting", opens Settings, turns the toggle on, and asserts the DatePicker is enabled. Attach a screenshot after each step with XCTAttachment and lifetime .keepAlways. 3. Implement until `scripts/ios-check.sh AppUITests/SettingsUITests` prints exit=0, then run `scripts/ios-check.sh` with no argument. Put new files in the existing synchronized folders. Give every control an accessibilityIdentifier. Finish with the script's summary lines and the list of tests you added. ``` The screenshots land inside `build/evidence/ios/tests.xcresult`, next to the test that took them. The attachment code the agent should produce looks like this: ```swift let app = XCUIApplication() func snap(_ name: String) { let shot = XCTAttachment(screenshot: app.screenshot()) shot.name = name shot.lifetime = .keepAlways // keep it even when the test passes add(shot) } func testEnablingReminderEnablesTimePicker() { app.launchArguments = ["-uiTesting"] app.launch() app.buttons["settings.open"].tap() snap("1-settings-open") app.switches["settings.reminderToggle"].tap() snap("2-reminder-on") XCTAssertTrue(app.datePickers["settings.reminderTime"].isEnabled) snap("3-time-picker-enabled") } ``` Check one thing the agent often gets wrong: the `-uiTesting` launch argument has to change app behaviour (an in-memory `UserDefaults` suite, no onboarding). If nothing in the app reads it, the UI test depends on whatever state the last run left behind and will flake. ## Recipe: a Jetpack Compose screen with UI-test evidence **Copy-paste prompt: Compose cart screen with proof** ```text Build a Jetpack Compose CartScreen backed by a CartViewModel (StateFlow<CartUiState>) with three states: Loading, Empty, and Items(list, total). Quantity steppers update the total immediately. Work in this order: 1. JUnit tests for CartViewModel with a fake repository: empty cart gives Empty, incrementing a line updates the total, a repository error gives an error state with a retry action. 2. A Compose UI test com.example.cart.CartScreenTest using createAndroidComposeRule<MainActivity>(): find nodes by Modifier.testTag, tap "+" on the first line, assert the total text changes. 3. Implement until `scripts/android-check.sh com.example.cart.CartScreenTest` prints exit=0, then run `scripts/android-check.sh` with no argument. Do not run ./gradlew clean. Finish with the script's summary lines and the tests you added. ``` A correct Compose test finds nodes by tag, not by text, so a copy change does not break it: ```kotlin @get:Rule val composeRule = createAndroidComposeRule<MainActivity>() @Test fun incrementUpdatesTotal() { composeRule.onNodeWithTag("cart.line.0.increment").performClick() composeRule.onNodeWithTag("cart.total").assertTextEquals("Total: 24.00") } ``` For visual evidence on Android without an emulator, add a screenshot-test library such as Paparazzi: `./gradlew :app:recordPaparazziDebug` records reference images, and `./gradlew :app:verifyPaparazziDebug` fails when the rendering changes. On iOS, `swift-snapshot-testing` plays the same role with `assertSnapshot(of: view, as: .image)`. Both record references on the first run, so review and commit those references yourself. ## Recipe: reproduce a crash the agent cannot see A crash report with a stack trace is a spec for a failing test. Hand it over with the device server connected: **Copy-paste prompt: turn a crash into a failing test** ```text Here is a crash from our Android beta (stack trace below). Using the mobile-mcp tools: 1. Launch the debug build on the running emulator, follow the steps in the report, and capture mobile_get_device_logs and a screenshot when it crashes. 2. Write the smallest instrumented or unit test that reproduces the crash. Run it with scripts/android-check.sh and show me it FAILS for the same reason as the report. 3. Only then fix the code, rerun the script until exit=0, and explain the root cause in two sentences. Do not change or delete any existing test. <paste the stack trace here> ``` The order matters. A test that failed before the fix and passes after it is evidence. A fix with no failing test first is a guess that happened to compile. ## How to verify the agent's native work without reading every line The scripts turn every change into the same bundle of artifacts, and review starts from that bundle, not from the diff: | Evidence | Where it lives | What a reviewer checks | | --- | --- | --- | | Test verdict | Last lines of the script output, `summary.json`, JUnit XML under `androidTest-results/` | `exit=0` on both platforms; the count of tests went up, never down | | UI screenshots | `tests.xcresult` attachments (open in Xcode), Paparazzi or snapshot-testing images | The screens match the spec; snapshot diffs are intentional | | Runtime logs | `xcodebuild.log`, `logcat.txt` | No new crashes, ANRs, or error spam during the UI tests | | Test changes | The test files in the diff | New tests assert the acceptance criteria; no assertion was weakened, no snapshot re-recorded without a reason | Three rules make this trustworthy: 1. **CI runs the same scripts.** A green result in the agent's session is a claim; the same script in CI on a clean macOS runner is the proof. Keep the scripts in the repository so the two cannot drift. 2. **The agent cannot edit the oracle.** Snapshot references and the tests that encode the acceptance criteria are protected, as described in [protecting the oracle](/en/workflows/test/protect-the-oracle/). Claude Code gets per-path deny rules (the Claude Code tab above). For Codex and Cursor this page relies on a tool-neutral guard instead, and it backs up Claude Code too: CODEOWNERS on the reference folders, plus a CI step that fails when they change without a label. ```text # .github/CODEOWNERS **/__Snapshots__/ @your-org/mobile-leads **/src/test/snapshots/ @your-org/mobile-leads ``` ```yaml # CI job step (check out with fetch-depth: 0 so origin/main is available) - name: Block unlabelled snapshot changes if: ${{ !contains(github.event.pull_request.labels.*.name, 'snapshot-update') }} run: | if git diff --name-only origin/main... | grep -E '__Snapshots__/|src/test/snapshots/'; then echo "Snapshot references changed without the snapshot-update label"; exit 1 fi ``` 3. **A named person signs off on the evidence.** The developer who assigned the task reviews the evidence bundle and the test diff. The code diff gets a full human read only where risk requires it: signing, entitlements, payments, and anything touching `Info.plist` permissions or `AndroidManifest.xml`. The pull-request contract for this bundle is described in [the evidence bundle](/en/workflows/ship/evidence-bundle/), and the reasoning for reviewing evidence instead of diffs in [reading evidence instead of code](/en/ladder/evidence-not-diffs/). ## When native agent loops break **Common failures and how to recover** **The new Swift file compiles in the editor but not in the build.** The file is outside every target. Convert the group to a synchronized folder in Xcode 16 or later (right-click the group, **Convert to Folder**) so any file placed inside it joins the target, then tell the agent where new files go. Do not let it hand-edit `project.pbxproj`; a merge conflict there is expensive to untangle. **"Unable to find a destination matching the provided destination specifier."** The pinned simulator name does not exist in this Xcode version. Run `xcrun simctl list devices available`, update `SIM` in the script, and commit it. Do not let the agent pick "any iPhone" on its own; that unpins the device. **Builds fail inside the sandbox with permission errors.** Xcode writes to `~/Library/Developer/Xcode/DerivedData` by default, which is outside the project. The scripts pass `-derivedDataPath build/DerivedData` for exactly this reason; check that the agent is not calling `xcodebuild` directly. **The emulator never finishes booting in CI.** Headless runners often lack hardware acceleration. Check the emulator log in `build/evidence/android/emulator.log`, and use a runner with KVM enabled or Gradle Managed Devices instead of a hand-started emulator. **The agent re-records snapshots to make a test pass.** Setting `record: .all` in swift-snapshot-testing or running `recordPaparazziDebug` turns every visual regression green. Deny edits to the reference folders, and treat any changed reference image in a pull request as a change that needs a reason. **The build fails with stale module or cache errors.** Errors such as a module compiled with a different compiler, a missing precompiled header, or a Gradle configuration-cache mismatch come from caches, not from your code. On iOS, delete only `build/DerivedData/ModuleCache.noindex` (or `build/DerivedData` as a whole, which the scripts own). On Android, run `./gradlew --stop` and remove `.gradle/configuration-cache`. Then rerun the check script. Do not run a full `clean`: it throws away every warm cache and makes the next few agent iterations slow. **A teammate's MCP server behaves differently from yours.** Someone's session pulled a newer `@latest` release overnight. Pin the server version in every committed config (`.cursor/mcp.json`, or the `.mcp.json` that `claude mcp add -s project` writes), use the same pinned version in `~/.codex/config.toml`, and upgrade it deliberately. **MCP calls time out during a build.** In Codex, set `tool_timeout_sec` inside the server's own `[mcp_servers.<name>]` block. In any tool, prefer the check script for the full build and use the MCP server for launching and inspecting the app. **The context fills with build output.** The agent is running `xcodebuild` or `./gradlew` directly instead of the scripts. Point it back to the rule in its instructions file and ask it to `grep` the saved log for the error it needs. ## Model and effort for native work Start on your tool's default model and raise effort before you switch model; current defaults and prices are on the [models hub](/en/ecosystem/models/). Native tasks are more often limited by build feedback than by the model, so fix the loop first. ## Where to go next with native iOS and Android agents - [Mobile app testing patterns](/en/workflows/test/mobile-testing/) — Device matrices, Detox and Maestro flows, and gesture and offline tests across platforms. - [The evidence bundle](/en/workflows/ship/evidence-bundle/) — The pull request contract that turns the scripts' output into a reviewable proof. - [Framework dev-tools MCP servers](/en/ecosystem/mcp/framework-devtools-mcp/) — MobileBuildMCP next to the other servers that put a running app in the agent's loop. - [React Native patterns](/en/cookbook/mobile-development/react-native/) — The cross-platform alternative, with Expo, FlashList, and EAS Build. - [Flutter patterns](/en/cookbook/mobile-development/flutter/) — Riverpod, go_router, and widget tests when one Dart codebase serves both platforms. - [Mobile development overview](/en/cookbook/mobile-development/) — All mobile recipes, and which stack each one fits. --- # React Native Development Patterns URL: https://developertoolkit.ai/en/cookbook/mobile-development/react-native/ Description: React Native with Claude Code, Codex, and Cursor: offline-first state, FlashList v2, biometric gates, release-build debugging, and the gates that prove it. React Native development with an AI agent works when the agent knows the pinned library versions and every change passes gates that need no human reader: type check, lint, Jest with React Native Testing Library, a Maestro flow on a device, and a release build. With those gates, the agent can own offline data, list performance, and biometric auth. This page is for developers and tech leads who ship a React Native app to the App Store and Google Play. Your `FlatList` stutters on a mid-range Android phone once it passes a few hundred rows. The release build crashes on a native module that the development build never loaded. The offline screen from last week's demo drops writes when the network flaps. None of this shows up on the simulator on your laptop, and all of it is library-specific work an agent does well once it is told which library and which version. New to agent setup for mobile work? Start with [the mobile development overview](/en/cookbook/mobile-development/), which covers choosing a stack, installing its skills and verifying on simulators. ## What this React Native guide gives you - A version table and a project-instructions block that stop the agent from writing APIs from an older major - A scaffold prompt that produces an Expo app with tests and gates on day one - An offline-first prompt for `react-native-mmkv` v4 and TanStack Query, including mutations that survive an app kill - A FlashList v2 prompt, and the Android command that proves the jank is gone - A biometric gate prompt that falls back instead of locking users out - A verification table: which gate proves what, and who signs off - A map of the failures that never appear on the simulator, with recovery steps ## Which React Native versions does this page assume? Agents mix APIs from several majors because their training data spans them. Put the versions in the prompt or in the project instructions. The table lists what npm served on 2026-09-26. | Package | Version on 2026-09-26 | What changes for the agent | | --- | --- | --- | | `react-native` | 0.87.1 (Expo SDK 57 pins 0.86.3) | The New Architecture is the only architecture: 0.82 removed the opt-out (React Native changelog) | | `expo` | 57.0.25 | Install native packages with `npx expo install`, never by hand-editing versions | | `@shopify/flash-list` | 2.3.2 (SDK 57 pins 2.0.2) | v2 runs on the New Architecture only and takes no size estimates | | `react-native-mmkv` | 4.3.2 | v4 is a Nitro Module: `createMMKV()` and `storage.remove()`, not `new MMKV()` and `storage.delete()` | | `@tanstack/react-query` | 5.104.0 | Persist with `@tanstack/react-query-persist-client` and `@tanstack/query-sync-storage-persister` | | `@testing-library/react-native` | 14.0.1 | v14 drops React 18, makes `render` and `renderHook` async, and needs the `test-renderer` package as a peer | | `jest-expo` | 57.0.5 | The Jest preset Expo documents for unit tests; it mocks the native side of the Expo SDK | If you start a new app, start on Expo. The default `create-expo-app` template is TypeScript with Expo Router. SDK specifics, EAS, and over-the-air updates are on [Expo development patterns](/en/cookbook/mobile-development/expo/); this page covers the React Native work that is the same with or without Expo. ## Give the agent React Native context before the first prompt Three things change the agent's output more than any prompt wording: the version table above, a list of gates it must run, and domain skills or MCP servers that let it check its own work on a device. **Project instructions.** Put this block in `CLAUDE.md` for Claude Code, in `AGENTS.md` for Codex, and in a project rule for Cursor. The content is identical in all three tools. ```markdown ## React Native rules - Expo SDK 57, React Native 0.86 (New Architecture only). Add native packages with `npx expo install`. - react-native-mmkv v4: `createMMKV()`, `storage.remove()`. FlashList v2: no `estimatedItemSize`. - Tests: Jest via `jest-expo` + @testing-library/react-native v14 with `test-renderer` (`await render(...)`). Not Vitest. ## Before you say a task is done 1. `npx tsc --noEmit` 2. `npx expo lint` 3. `npx jest --ci` 4. `npx expo install --check` 5. For UI changes: run the matching Maestro flow in `.maestro/` and paste the result. ``` **Skills.** Expo publishes official skills in [expo/skills](https://github.com/expo/skills) (2,612 GitHub stars on 2026-09-26); the per-tool install is on the Expo page. Callstack, a React Native consultancy (community, not Meta), publishes production skills such as `react-native-best-practices` and `upgrading-react-native` in [callstackincubator/agent-skills](https://github.com/callstackincubator/agent-skills). The cross-agent `skills` CLI (1.7.0) installs them for Claude Code, Codex, and Cursor alike: ```bash npx skills@latest add callstackincubator/agent-skills --skill react-native-best-practices ``` Skills load only when a task needs them, so they cost little context. See [installing and managing skills](/en/ecosystem/skills/installing-managing/). **MCP servers.** The Maestro CLI ships its own MCP server (`maestro mcp`), which lets the agent tap, scroll, and assert on a live emulator, simulator, or Android device while it works. For iOS builds and simulators, MobileBuildMCP (formerly XcodeBuildMCP) is covered on [dev-server MCPs](/en/ecosystem/mcp/framework-devtools-mcp/). Each MCP server adds its tool list to every session, so connect Maestro only in the app repository. **Claude Code** ```bash # after installing the Maestro CLI (Java 17+) claude mcp add maestro -- maestro mcp ``` **Codex** ```bash codex mcp add maestro -- maestro mcp ``` **Cursor** Add the server to `.cursor/mcp.json`: ```json { "mcpServers": { "maestro": { "command": "maestro", "args": ["mcp"] } } } ``` The Maestro README (fetched 2026-09-26) documents `maestro mcp`; the per-client lines above follow each tool's standard stdio syntax. Check [Maestro's MCP setup docs](https://docs.maestro.dev/get-started/maestro-mcp) if your client needs extra options. ## Scaffold a React Native app with gates from day one Ask for the test harness and the gates in the scaffold prompt. An app that starts without them never gets them, and every later agent change is then unverifiable. **Copy-paste prompt: scaffold a verifiable Expo app** ```text Scaffold a React Native app with `npx create-expo-app@latest` using the default template (TypeScript, Expo Router). Then: 1. Add the tsconfig path alias `@/*` -> `src/*`. 2. Install `jest-expo`, `jest`, `@types/jest` with `npx expo install ... -- --dev`, plus `@testing-library/react-native` v14 and its peer `test-renderer` as dev dependencies, and configure Jest with the jest-expo preset. 3. Write one test that renders the home screen with `await render(...)` and asserts on visible text via `screen.getByText`. 4. Add package.json scripts: `typecheck` (tsc --noEmit), `lint` (expo lint), `test` (jest --ci). 5. Create `.maestro/smoke.yaml` that launches the app and asserts the home title is visible. Do not run `expo prebuild` and do not commit `ios/` or `android/`. Finish by running typecheck, lint, and test, and paste the output. ``` The prompt is the same in every tool; only the invocation differs. Save the prompt above as `scaffold-prompt.txt`, then start the agent with it. **Claude Code** ```bash claude "$(cat scaffold-prompt.txt)" ``` From v2.1.283 (both release channels on 2026-10-12), interactive sessions start in auto mode, where a classifier reviews each action; sessions with `disableAutoMode` set, models auto mode does not support, and `claude -p` (except on third-party providers or with telemetry off, where it starts in auto mode from v2.1.285) start in **Manual** and ask before each shell command. Either way, the `npx` installs are expected, and anything that writes outside the project is not. **Codex** ```bash codex "$(cat scaffold-prompt.txt)" ``` The scaffold downloads packages, so approve the network requests when Codex asks. Do not run it with `--dangerously-bypass-approvals-and-sandbox` outside a disposable, network-restricted container. **Cursor** Paste the prompt into the agent panel. Cursor runs the commands in its terminal and shows each file edit for review. Keep the terminal output visible: the last step's test output is your acceptance evidence. Use the bare workflow (`npx @react-native-community/cli@latest init`) only when you need native code that config plugins cannot express. You then own the `ios/` and `android/` projects, and the native-drift failures below become yours. ## Build an offline-first data layer that survives an app kill "Add offline support" gets you an `AsyncStorage` wrapper that loses queued writes. Name the storage engine, the cache layer, and the durability requirement. **Copy-paste prompt: offline-first TanStack Query with MMKV v4** ```text Build an offline-first data layer with react-native-mmkv v4 and TanStack Query v5. - Storage: `createMMKV({ id: 'query-cache' })`. Wrap it in a sync storage adapter (getItem/setItem/removeItem) and pass it to `createSyncStoragePersister` from @tanstack/query-sync-storage-persister. - Wrap the app in `PersistQueryClientProvider`; in `onSuccess`, call `queryClient.resumePausedMutations()`. - Wire `onlineManager.setEventListener` to @react-native-community/netinfo. - Register every offline mutation with `queryClient.setMutationDefaults` so a paused mutation can resume after the app is killed (functions are not persisted). - Example: `useAddTask` with an optimistic update and rollback in `onError`. - Tests (jest-expo): (1) a mutation made offline is persisted and replays once when online; (2) a replayed mutation is not sent twice; (3) rollback restores the cache. Run the tests and paste the output. ``` The persister glue should stay this small. If the agent writes more, it is probably reinventing the persister: ```ts import { createMMKV } from 'react-native-mmkv'; import { createSyncStoragePersister } from '@tanstack/query-sync-storage-persister'; const storage = createMMKV({ id: 'query-cache' }); export const persister = createSyncStoragePersister({ storage: { getItem: (key) => storage.getString(key) ?? null, setItem: (key, value) => storage.set(key, value), removeItem: (key) => { storage.remove(key); }, }, }); ``` The durability question is the one the agent gets wrong: what happens when the app is killed mid-sync and reopened offline? Without `setMutationDefaults`, the restored mutation has no function to call and silently never replays. Test 1 in the prompt fails on exactly that bug, which is why it is in the prompt. If you need two-way relational sync rather than a replayed cache, that is a sync-engine decision (for example WatermelonDB); confirm the version you pick supports the New Architecture before you prompt for it. ## Fix a FlatList that janks on Android Swapping the hot list to `@shopify/flash-list` recycles row views instead of mounting one per row. Version 2 changed the rules: it takes no size estimates and runs only on the New Architecture. As before, it keeps a separate recycling pool per `getItemType` value, which v2 relies on more because it measures rows itself. An agent trained on v1 adds `estimatedItemSize`, which v2 no longer needs. **Copy-paste prompt: FlatList to FlashList v2** ```text Convert the FlatList in src/screens/ProjectList.tsx to @shopify/flash-list v2 (install with `npx expo install @shopify/flash-list`). - Do not add estimatedItemSize or any other v1 estimate prop. - Wrap the row in React.memo, give it a stable keyExtractor, and memoize renderItem. - Return getItemType for the three row kinds (header, project, ad) so each recycles into its own pool. - Wire onEndReached to my useInfiniteQuery hook with cursor pagination. - Before changing anything, list the props that forced re-renders in the old list. - Update the RNTL test so it still asserts the first and last visible rows. Run typecheck and tests and paste the output. ``` A green test proves the list renders, not that it is smooth. To prove the performance claim, measure a release build on a real mid-range Android device before and after the change: ```bash npx expo run:android --variant release adb shell dumpsys gfxinfo com.example.app reset # scroll the list for 20 seconds, then: adb shell dumpsys gfxinfo com.example.app | grep -i "janky frames" ``` Replace `com.example.app` with your application ID. Paste both numbers into the pull request. If mixed row types have no `getItemType`, v2 recycles a tall card into a short slot and you see flicker or wrong heights, the v2 version of the old wrong-estimate jank. ## Add a biometric gate that does not lock users out Face ID works in the simulator with **Enrolled** switched on. On a real phone with no enrolled biometrics, or after too many failed attempts, a naive gate locks the user out. `authenticateAsync` from `expo-local-authentication` can fail because the user cancels, nothing is enrolled, the hardware is missing, the user is locked out, or the prompt times out. **Copy-paste prompt: biometric gate with a fallback** ```text Build a `useBiometricGate` hook with expo-local-authentication and expo-secure-store. - Store the refresh token with `SecureStore.setItemAsync(key, token, { requireAuthentication: true })`. - On app open: `hasHardwareAsync()`, `isEnrolledAsync()`, then `authenticateAsync()`. - If hardware is missing, nothing is enrolled, the user cancels, or the user is locked out, route to the passcode screen. Never leave the user on a blank gate. - If reading the token fails after a biometric change, clear it and ask for a normal sign-in rather than retrying in a loop. - Tests (jest-expo, mock expo-local-authentication): one test per branch above, each asserting which screen the user lands on. Run the tests and paste the output. ``` The unit tests prove the branching. Then check each platform once on a physical device, because the simulator does not reproduce lockout. ## Build a feature end to end in reviewable steps For a feature built from scratch, drive the agent through ordered steps instead of one large prompt. Each step ends at a gate, so you accept the step on evidence and never read the full diff at the end. 1. **Screen and types.** "Create a `ProjectList` route with a typed `useProjects()` TanStack Query hook that returns mock data." Gate: `npm run typecheck` passes. 2. **Real data and every state.** "Replace the mock with a fetch to `/api/projects`. Add a loading skeleton, an empty state, and an error state with a **Retry** button that calls `refetch()`." Gate: RNTL tests for loading, rows, empty (`[]`), and retry, run with `npm test`. 3. **Performance.** Paste the FlashList prompt. Gate: the `gfxinfo` janky-frames numbers before and after, on a release build. 4. **Behaviour on a device.** "Write `.maestro/project-list.yaml` that opens the list, scrolls to the end, and asserts the last row. Add an Android-only flow that runs `setAirplaneMode: enabled`, pulls to refresh, and asserts the error state and **Retry**." Gate: `maestro test .maestro/` passes. Maestro's airplane-mode commands are Android-only because of iOS simulator restrictions. ## How do you verify React Native agent output without reading every line? Each gate answers one question. Make the agent run all of them and attach the output to the pull request, the same [evidence bundle](/en/workflows/ship/evidence-bundle/) the rest of the site uses. | Gate | Command | What it proves | | --- | --- | --- | | Types | `npx tsc --noEmit` | No API from the wrong major slipped in (`new MMKV()` fails here) | | Lint | `npx expo lint` | Hook rules and unused code | | Unit and component | `npx jest --ci` | Branches: offline replay, biometric fallbacks, empty and error states | | Dependency alignment | `npx expo install --check` | No native package drifted from the SDK's pinned version | | Behaviour on a device | `maestro test .maestro/` | Navigation, gestures, and offline states on a real runtime | | Release build | `npx expo run:ios --configuration Release`, `npx expo run:android --variant release` | The code path that users run, with `__DEV__` false | | Performance | `adb shell dumpsys gfxinfo <application-id>` | Janky frames before and after, on a named device | **Who signs off.** The developer who wrote the task owns the acceptance criteria and the Maestro flows. A change to an existing flow or test needs a second person's approval, because an agent that edits the test to pass has removed the proof; see [protect the oracle](/en/workflows/test/protect-the-oracle/). Device matrices and device farms are on [mobile app testing](/en/workflows/test/mobile-testing/). **Copy-paste prompt: finish a task with evidence** ```text Before you report this task done, run in order: `npx tsc --noEmit`, `npx expo lint`, `npx jest --ci`, `npx expo install --check`, and `maestro test .maestro/` against the running development build. Paste each command's last 20 lines. If any gate fails, fix the code, not the test or the flow. If you believe a test or flow is wrong, stop and explain why instead of editing it. ``` ## Debug release-only bugs with React Native DevTools React Native DevTools is the default debugger for Hermes apps and replaced the Chrome DevTools flow in React Native 0.76. Press <kbd>j</kbd> in the terminal where Metro or Expo runs. Flipper is not the answer: its README names v0.239.0 as the last release with React Native support. Reactotron (`reactotron-react-native` 5.3.1 on npm) is a common add-on for persistent network and state logs. **Copy-paste prompt: a request that fires in dev but not in release** ```text The app calls /api/sync on launch. It works in the development build but never fires in a release build (`npx expo run:ios --configuration Release`). 1. Search for `__DEV__` checks, console-stripping Babel plugins, and environment variables read at build time on the path from app start to that request. 2. List the three most likely causes, ranked, with the file and line for each. 3. Add a log line that survives a release build (not console.log) and tell me exactly what to look for in React Native DevTools or the device log. Do not change code until I confirm the cause. ``` ## Ship React Native builds to TestFlight and Google Play On Expo, EAS Build and EAS Submit own the native compile, credentials, and store upload; the fingerprint-gated pipeline and staged over-the-air updates are on [Expo development patterns](/en/cookbook/mobile-development/expo/). On the bare workflow you wire Fastlane into CI yourself, and the agent will write a lot of YAML. Constrain it: **Copy-paste prompt: bare React Native release workflow** ```text Create a GitHub Actions workflow that runs on version tags only. Jobs: build the iOS app with Fastlane and upload to TestFlight; build an Android App Bundle with Gradle and upload to the Play internal track. Requirements: - `actions/checkout@v7` with `persist-credentials: false`, and an explicit top-level `permissions: contents: read`. - Signing keys and store API keys come only from repository secrets; list each secret name I must create. Never echo a secret. - Run typecheck, lint, and tests before any build step. Explain each job in two sentences. ``` Review the workflow against [CI/CD pipeline patterns](/en/cookbook/devops-recipes/ci-cd-pipelines/) before you merge it. Never let the agent trigger a production upload to test the workflow. ## What breaks in React Native that the simulator never shows? **Metro serves stale code.** Edits do not appear, or a module that exists is "not found". Restart with `npx expo start --clear` (`npx react-native start --reset-cache` on bare React Native) before anything else, and tell the agent you already did, so it does not send you in a circle. **Dev and release behave differently.** `__DEV__` is false in release, console calls can be stripped, and build-time environment variables may be unset. Reproduce with a release build, then use the debugging prompt above. **An old native library crashes on launch.** React Native 0.82 removed the opt-out from the New Architecture, so a library that never migrated crashes or renders blank. Ask the agent to check the library's New Architecture support and find a maintained version or replacement. Downgrading React Native is not a fix. **Native builds drift.** Someone bumps a native dependency and every other machine breaks. On Expo, run `npx expo install --check`, then `npx expo prebuild --clean` instead of hand-editing `ios/` or `android/`. On bare React Native, run `cd ios && pod install --repo-update` and `cd android && ./gradlew clean`. **The agent writes an older major's API.** `new MMKV()`, `storage.delete()`, `estimatedItemSize`, or a synchronous `render()` from RNTL 13. The type check catches the first two; point the agent at the version table and the project-instructions block. **E2E tests flake in CI only.** Usually timing, not a bug. Ask the agent to replace fixed sleeps with waits on an element, and confirm that CI tests the same build artifact you tested locally. ## Where to go next with React Native - [Expo development patterns](/en/cookbook/mobile-development/expo/): Expo skills and MCP, Expo Router auth gates, the EAS pipeline, and staged updates - [React Native and Flutter UI recipes](/en/cookbook/mobile-development/mobile-patterns/): twelve UI prompts with the device evidence for each - [Mobile app testing](/en/workflows/test/mobile-testing/): Detox, Maestro, and device matrices - [Native iOS and Android recipes](/en/cookbook/mobile-development/native-ios-android/): when a feature needs Swift or Kotlin - [Flutter development patterns](/en/cookbook/mobile-development/flutter/): if you are weighing Dart against React Native ---