How Claude Code worksPart 8
Contract first
On this page
In short: A waiter does not promise a dish that is not on the menu. In code, the menu is the contract: one file that says exactly which fields an API or table has. Generate your types from it, tell Claude the contract is the only truth, and add an alarm that runs the type check after every edit. An invented field then fails in seconds, not in front of a customer.
Part 7 wrote down what to build. This part makes sure what gets built talks to the real system, not an imagined one. The project in the examples, the Acme storefront, is made up.
Why Claude invents fields
Think of it like this: A new colleague who has seen a hundred restaurants will guess that this one serves chips. Usually right. Sometimes not.
Claude has read a great deal of code. When it needs the gift card balance and has not seen your API, the most likely name is balance or remaining. Your API calls it balanceCents. The guess reads well, may even compile in loose code, and shows a blank on the page.
Remember: this is not carelessness. It is what any capable newcomer does without the menu. The fix is to hand over the menu, and to check orders against it.
The contract, the types and the rule
- 1 · The contract: what the API really returns
One file both sides agree on. Here an OpenAPI schema for the gift card service.
# contracts/giftcards.yaml GiftCard: type: object required: [code, balanceCents, status] properties: code: { type: string } balanceCents: { type: integer } status: { type: string, enum: [active, used, expired] } - 2 · Generate types from it
Nobody types the field names by hand. A script turns the contract into code.
npm run contracts:gen # writes src/generated/giftcards.ts
- 3 · Claude builds against the generated types
The rule in
CLAUDE.mdsays where the truth is.## Data - API shapes come only from src/generated/. Never edit it. - If a field you need is missing, stop and say so. Do not invent it. The contract changes first.
- 4 · An invented field fails at once
Claude writes
card.remaining. The type check knows there is no such field.src/checkout/giftcard.ts:42 Property 'remaining' does not exist on type 'GiftCard'. Did you mean 'balanceCents'?
Under the hood: what can be a contract
- HTTP APIs: an OpenAPI schema. Generators turn it into TypeScript, Python or other types.
- Databases: the migration files or the schema. Many ORMs generate types from it.
- Events and messages: a JSON Schema per message.
- Another team’s service: their published schema, pulled in at a pinned version.
Whatever the format, the rule is the same: one file is the truth, code is generated from it, and nobody edits the generated code by hand.
The alarm and the facts
A rule in CLAUDE.md asks. A hook makes sure. Part 3 introduced hooks as smoke alarms; this one goes off when an edit breaks the types.
- The alarm: type check after every edit
A PostToolUse hook (Part 3) runs after Claude edits a TypeScript file. If the check fails, exit 2 sends the errors straight back to Claude.
// .claude/settings.json "hooks": { "PostToolUse": [{ "matcher": "Edit|Write", "hooks": [{ "type": "command", "command": "node .claude/hooks/typecheck.mjs" }] }] } - The script
Short and quiet when all is well.
// .claude/hooks/typecheck.mjs import { execSync } from 'node:child_process'; const input = JSON.parse(await new Promise(r => { let s = ''; process.stdin.on('data', d => s += d).on('end', () => r(s)); })); const file = input.tool_input?.file_path ?? ''; if (!/\.tsx?$/.test(file)) process.exit(0); try { execSync('npx tsc --noEmit', { stdio: 'pipe' }); } catch (e) { console.error(String(e.stdout).slice(0, 2000)); process.exit(2); } - State the facts before writing
A line in the planning skill makes Claude list the fields it will use, with where each one comes from.
For each field you will read or write, give: field -> contract file and line If a field is not in a contract, list it under "Missing from contract" and stop.
Important: keep the generated folder locked with a deny rule, such as Edit(./src/generated/**) from Part 5. Otherwise the quickest way to make an error go away is to edit the generated file, which hides the mismatch instead of fixing it.
When a contract earns its place
- Two sides must agree: frontend and API, service and database.
- Names are easy to guess wrong:
balanceorbalanceCents? - More than one person or session touches the same data.
- It is a throwaway script with no other side.
- The shape is internal to one file and has a test.
- The contract would only repeat what the type already says.
Where this fits in the bigger picture
Think of it like this: The spec says what the customer ordered. The contract says what the kitchen can actually make. A good colleague checks both before cooking.
The spec from Part 7 and the contract work as a pair. When the spec needs something the contract does not have, such as “show the remaining balance” before the API returns it, that is a real finding. Claude stops and reports it, you change the contract with the other team, and the build carries on from the truth.
Which one fits?
- Claude uses a field I do not recognise: Check the contractAsk "which contract line is this from?". If there is none, it was invented.
- The field really is missing: Change the contract firstUpdate the schema, regenerate the types, then build. Never the other way round.
- We have no contract yet: Write one for the boundaryStart with the API or table this feature touches. One file, then generate from it.
- Mistakes slip through to review: Add the type check hookA PostToolUse hook catches it seconds after the edit, while Claude still has the context to fix it.
- Claude edits the generated file: Lock itA deny rule
Edit(./src/generated/**), from Part 5. Generated code changes only by regenerating.
Your setup so far
- Part 1 · where it worksYou know which machine does what, and which folders Claude can reach.
- Part 2 · what it remembersOne task per notebook; photocopies in their own folder; helpers for noisy side jobs.
- Part 3 · how it behavesFridge rules for what is always true, recipe cards for procedures, alarms for musts, specialists for checks.
- Part 4 · what it can reachPhone lines to your tracker and tools, checked before trusted; your setup packed as one toolbox.
- Part 5 · what it may doKeys for routine work, a knock for anything that publishes, locked doors for secrets.
- Part 6 · how it stays sharpA clear desk: fresh sessions, focused summaries, helpers for big reads, rules only where they apply.
- Part 7 · what it builds fromA written spec with acceptance criteria, rules with IDs, and a plan agreed before code.
- Part 8 · how it avoids guessingContract first: generated types are the only truth, and a hook makes Claude state the facts.
- NextPart 9 · verify against the spec
Three rules of thumb
If a field is not in it, it does not exist. Claude says so instead of guessing.
Field names come from a script, so a typo cannot get in.
A type check after each edit costs seconds. A wrong field found in production costs a day.
QuizThe spec says “show the card’s expiry date”, but the gift card contract has no expiry field. What should Claude do?
Show the answer
Answer: Stop and report that the contract is missing the field
The contract is the menu. If the dish is not on it, the answer is to change the menu with the kitchen, not to cook something that looks similar.
Words in this post:
- Contract: one file that defines the exact shape of data between two sides.
- OpenAPI: a common format for describing HTTP APIs.
- Generated types: code written by a script from the contract, never by hand.
- Type check: a tool that confirms code uses only the fields the types define.
- PostToolUse hook: a script that runs after Claude uses a tool, such as an edit.
Hook details were checked against the Claude Code hooks documentation in November 2026. These features change often, so the docs are the final word for your version.
Next, Part 9: Verify against the spec proves the work is done, one acceptance criterion at a time.
Setting up Claude Code or AI agents for your team?
I help teams build this: agents, RAG search and Claude Code setups that hold up in production.
Series
How Claude Code works
- How Claude Code worksWhere Claude runs
- How Claude Code worksSessions and forks
- How Claude Code worksSkills, hooks and subagents
- How Claude Code worksMCP servers and plugins
- How Claude Code worksPermissions and safety
- How Claude Code worksContext and cost
- How Claude Code worksSpecs as the source of truth
- How Claude Code worksContract firstyou are here
- How Claude Code worksVerify against the spec
- How Claude Code worksHandoffs and memory
- How Claude Code worksYour setup as a kit
- How Claude Code worksRolling it out