Turn a written requirement for booking cancellation into acceptance criteria, tests and a small change that fits the existing code, then prove it works.
Outcome: Turn a clear requirement into a verified change.
Note
Reading as a visitor
Everything in this lesson is free to read. Sign in and enrol to answer the questions and record your progress.
Derive observable outcomes and boundary cases from a written requirement before writing code.
Express each acceptance criterion as a test that fails without the change and passes with it.
Fit a change to the existing code's conventions: error format, response shape, transactions and routing.
Brief an AI coding agent with the requirement and constraints, and review its diff against them.
Verify a change with the test suite and by exercising the running service.
Prerequisites
Reading and writing TypeScript, including async and await.
HTTP basics: methods, status codes, JSON request and response bodies, bearer tokens.
Basic SQL: SELECT, UPDATE and what a transaction is.
Running commands in a terminal and calling an HTTP API with curl.
Concepts
From requirement to outcomes
A requirement is ready to implement when you can list the observable outcomes it implies: for each kind of request, what the caller sends and what comes back. Writing that list first turns a paragraph of prose into something you can test, and it shows the gaps while they are still cheap to close.
Take the cancellation requirement for the booking service. Read closely, it implies at least these outcomes:
Situation
Response
Owner cancels at least 24 hours before the start
200, status CANCELLED, refund_cents equal to price_cents
Owner cancels less than 24 hours before the start
200, refund_cents 0
The booking is already cancelled
409 ALREADY_CANCELLED
The booking has already started
Worked example
This walk-through takes a different small feature through the same steps you will use in the exercise: requirement, outcomes, tests, change, verification and review. It is an illustration only. You do not need to build it, and it is not assessed.
The requirement
Users with many bookings want to see only the active ones. GET /bookings should accept an optional status query parameter, CONFIRMED or CANCELLED, and return only the caller's bookings with that status. Without the parameter it behaves as today. Any other value is an invalid request.
1. List the outcomes and settle the open questions
Request
Response
GET /bookings?status=CONFIRMED
200, only the caller's confirmed bookings, soonest first
GET /bookings?status=CANCELLED
200, only the caller's cancelled bookings
Concept questions
Sign in and enrol to answer and save your progress.
Exercise
The requirement
Your workspace holds the booking service described in README.md. Users can book but cannot cancel. Add cancellation:
POST /bookings/:id/cancel (no request body, bearer token required)
The owner of a booking can cancel it until it starts.
Cancelling at least 24 hours before starts_at refunds price_cents in full. Cancelling later refunds nothing.
The response is 200 with the booking in the usual { "data": … } shape, with status: "CANCELLED", cancelled_at set and refund_cents filled in.
The cancelled time becomes free: anyone can book it again.
The cancelled booking is kept, not deleted, and still appears in the owner's GET /bookings.
Errors use the standard error envelope:
Situation
Reflection
Recorded for you to look back on. It is not graded and does not by itself show understanding.
Prompt: Which part of the requirement was easiest to get subtly wrong, and how did you make sure you had it right? Describe one decision you made that the requirement did not spell out, and, if you used an agent, one thing in its change that you had to correct or reject.
Each row is an acceptance criterion and each one becomes at least one test. The list also makes the boundaries visible. "At least 24 hours" includes exactly 24 hours, so the comparison is "greater than or equal". "Until it starts" means a booking whose start time has arrived can no longer be cancelled. Decide these questions on purpose; otherwise they are decided by whichever comparison operator happens to be typed.
Read the requirement for what it does not say
Some phrases hide work, or hide its absence. "The time becomes free" sounds like a task, but before writing code for it, check what the existing code already does: if the overlap check and the availability query only consider confirmed bookings, changing the status is enough. "Keep the cancelled row" rules out a DELETE and tells you the booking list will show cancelled bookings as history.
Time-dependent rules need one more decision: read the clock once per request. If the handler calls new Date() separately for the "has it started" check, the refund calculation and cancelled_at, the three can disagree by a few milliseconds, and at a boundary that is the difference between a full refund and none.
Fit the change to the codebase
A scoped change should look as if it had always been there. The booking service already has conventions for everything this feature needs:
errors are thrown as HttpError through helpers such as notFound and conflict in src/errors.ts, and src/app.ts turns them into the standard error envelope;
bookings are returned through bookingView, so every endpoint has the same response shape;
route parameters are validated with a JSON schema, as on GET /bookings/:id;
requireUser resolves the caller, and transaction in src/db.ts wraps work in BEGIN and COMMIT;
the schema in db/migrations/001_init.sql already has status, refund_cents and cancelled_at columns.
That last point is worth checking before anyone writes a migration. Following these conventions keeps the diff small, keeps the API consistent for its clients, and makes the change easy to review.
State changes and concurrency
Cancelling is a read-then-write: read the booking, decide, update it. Two requests for the same booking can arrive together, from a double click or a client retrying after a timeout. Without care, both read CONFIRMED, both update, and both callers see 200. Reading the row with SELECT … FOR UPDATE inside a transaction makes the second request wait until the first commits, and then it sees CANCELLED and gets 409. The lesson on preventing double bookings covers this in depth; for now, lock what you are about to change.
Verification is evidence, not a feeling
A change is verified when tests that express the criteria fail without it and pass with it, the existing tests still pass, and you have exercised the running service at least once. npm run verify runs the type check and the tests. A test you have never seen fail proves little: break the code on purpose, for example by flipping the refund comparison, and watch the boundary test fail. For rules that depend on the current time, put test data clearly on each side of the boundary rather than on it, and check what your helpers actually return.
Working with an agent
Give the agent the requirement word for word, the outcomes table, and the constraints: no new dependencies, no edits to applied migrations, existing behaviour unchanged. Ask for a short plan and the list of tests before any code. In Claude Code, plan mode keeps the agent from editing while you agree the plan; in OpenCode the Plan agent serves the same purpose.
Then review the diff against the requirement, not against the agent's summary. Common problems with this kind of feature:
a new migration for columns that already exist, or an edit to 001_init.sql, which breaks start-up;
DELETE instead of an update, losing the history;
403 for someone else's booking, which reveals that the id exists;
the refund measured from created_at instead of starts_at, or > where "at least" means >=;
tests that assert whatever the code returns instead of what the requirement says;
"all tests pass" from an agent that did not run them.
Run the tests yourself, and keep the agent on the feature: if it starts refactoring unrelated code, stop it and narrow the task.
GET /bookings
200, all the caller's bookings, as today
GET /bookings?status=PENDING
400 VALIDATION_FAILED
Writing the table raises questions the requirement does not answer:
Is the value case-sensitive? Yes. The values mirror the status field in every booking response, so clients already have the exact spelling.
What about ?status=, an empty value? It is not one of the two values, so it is a 400 like any other invalid value.
Several statuses at once? Out of scope: with only two statuses, "both" is the same as no filter.
Unknown query parameters such as ?sort=name? Today they are ignored. Rejecting them would change existing behaviour for every client, so they stay ignored.
2. Find the conventions to follow
Reading the code before writing any:
GET /resources/:id/availability in src/routes/resources.ts validates its query string with a JSON schema, so query validation already has a pattern.
The error handler in src/app.ts turns any schema validation failure into 400 VALIDATION_FAILED with the standard envelope. An enum in the schema gives the 400 with no extra code.
GET /bookings in src/routes/bookings.ts is one query with a join and ORDER BY b.starts_at, b.id. The filter belongs in that query, not in a JavaScript filter after it, so the database does the work and the ordering stays as it is.
One consequence is worth noting: Fastify validates the query string before the handler runs, so GET /bookings?status=PENDING without a token gets 400, not 401. POST /bookings already behaves the same way for an invalid body, so this is consistent.
3. Write the tests first
In test/bookings.test.ts, useTestApp() also returns the database, which lets a test set up a cancelled booking even though the base app has no cancel endpoint:
const { app, db } = useTestApp();
it("lists only bookings with the requested status", async () => {
const first = await book(ADA, { resource_id: LAB, starts_at: futureUtc(9), ends_at: futureUtc(10) });
const second = await book(ADA, { resource_id: LAB, starts_at: futureUtc(11), ends_at: futureUtc(12) });
// There is no cancel endpoint yet, so the fixture sets the status directly.
await db().query("UPDATE bookings SET status = 'CANCELLED' WHERE id = $1", [first.json().data.id]);
const confirmed = await app().inject({ method: "GET", url: "/bookings?status=CONFIRMED", headers: auth(ADA) });
assert.equal(confirmed.statusCode, 200);
assert.deepEqual(confirmed.json().data.map((b: { id: number }) => b.id), [second.json().data.id]);
const all = await app().inject({ method: "GET", url: "/bookings", headers: auth(ADA) });
assert.equal(all.json().data.length, 2);
});
it("rejects an unknown status with 400", async () => {
const response = await app().inject({ method: "GET", url: "/bookings?status=PENDING", headers: auth(ADA) });
assert.equal(response.statusCode, 400);
assert.equal(response.json().error.code, "VALIDATION_FAILED");
});
Run npm test before changing the handler. Both tests fail, and for the right reasons: the first returns both bookings (actual: [ 1, 2 ], expected: [ 2 ]) and the second gets 200 instead of 400. A test that passed at this point would be testing nothing.
4. Make the change
app.get<{ Querystring: { status?: "CONFIRMED" | "CANCELLED" } }>(
"/bookings",
{
schema: {
querystring: {
type: "object",
properties: { status: { type: "string", enum: ["CONFIRMED", "CANCELLED"] } },
},
},
},
async (request) => {
const user = await requireUser(db, request);
const { rows } = await db.query<BookingRow & { resource_name: string }>(
`SELECT b.*, r.name AS resource_name
FROM bookings b
JOIN resources r ON r.id = b.resource_id
WHERE b.user_id = $1 AND ($2::text IS NULL OR b.status = $2)
ORDER BY b.starts_at, b.id`,
[user.id, request.query.status ?? null],
);
return { data: rows.map((row) => bookingView(row, row.resource_name)) };
},
);
The schema deliberately has no additionalProperties: false. The app is configured to reject unknown fields rather than drop them, so adding it would turn today's ignored parameters into 400s, which is the behaviour change ruled out in step 1.
5. Verify
npm run verify: the type check passes and all tests pass, the two new ones included.
Against the running service, after npm run db:reset and npm start:
The first lists Ada's two seeded bookings; the second is a 400 because the value is case-sensitive.
6. Review an agent's version of the same change
Had an agent written this, the review would ask: did it filter in SQL or in JavaScript? Did it keep the ordering? Did it add additionalProperties: false and break other clients? Did it make the parameter case-insensitive without being asked? Did it add a test for the 400, and does each test fail without the change? Each question comes straight from the outcomes table, which is why the table comes first.
Status and code
No token, or an unknown token
401 UNAUTHENTICATED
No such booking, or someone else's booking
404 BOOKING_NOT_FOUND
The booking is already cancelled
409 ALREADY_CANCELLED
The booking has already started
409 BOOKING_STARTED
Steps
Read before you write. Look at how GET /bookings/:id handles ownership, how POST /bookings uses transaction and builds its response, and what columns db/migrations/001_init.sql already has. Check which bookings the overlap check and the availability query consider.
Turn the requirement into tests. Add a test file, for example test/cancel.test.ts, using the helpers in test/helpers.ts (useTestApp, auth, ADA, GRACE, LAB, hoursFromNow). Write at least one test per outcome above, including rebooking a cancelled slot. The Build server lab (LAB) has 60-minute slots, so bookings on it start and end on whole hours. Keep refund tests well away from the 24-hour boundary. Run npm test and confirm the new tests fail.
Implement the endpoint in src/routes/bookings.ts, following the conventions already used in that file.
Verify. Run npm run verify (type check and all tests). Then try it by hand:
npm run db:reset
npm start
The seed data gives Ada (dev-token-ada) booking 1, about two days ahead, and booking 3, about ten hours ahead. Booking 2 belongs to Grace.
curl -s -X POST localhost:3000/bookings/1/cancel -H 'Authorization: Bearer dev-token-ada' # full refund
curl -s -X POST localhost:3000/bookings/3/cancel -H 'Authorization: Bearer dev-token-ada' # refund 0
curl -s -X POST localhost:3000/bookings/2/cancel -H 'Authorization: Bearer dev-token-ada' # 404
curl -s -X POST localhost:3000/bookings/1/cancel -H 'Authorization: Bearer dev-token-ada' # 409 ALREADY_CANCELLED
curl -s -X POST localhost:3000/bookings/1/cancel # 401
curl -s -H 'Authorization: Bearer dev-token-ada' localhost:3000/bookings # both still listed
Send no Content-Type header with these requests. Fastify rejects an empty body declared as application/json with a 400 before your handler runs.
Constraints
Do not change package.json or package-lock.json, and do not add dependencies. The assessment runs your code with the project's original dependencies and does not start a submission whose lockfile differs.
Do not edit db/migrations/001_init.sql. Applied migrations are checksummed, and start-up fails if one changes. If you decide you need a schema change, add a new migration file, but check the existing columns first.
Keep every existing endpoint and response working as documented. Keep the service startable with node src/server.ts, keep GET /health, and keep reading DATABASE_URL and PORT.
What Check work assesses
Check work takes a snapshot of your workspace's source files and assesses it outside the lab. The platform starts your service with node src/server.ts against its own fresh database and its own users, resources and bookings (not the seed data), then calls the API over HTTP. Only the responses and the resulting data count, so printing PASS or editing your tests changes nothing.
The six acceptance criteria cover the full refund, the late cancellation, freeing the slot while keeping the cancelled booking in the owner's list, the two 409 cases, the 404 and 401 cases, and the existing create, overlap, validation and list behaviour. Refund checks use bookings well clear of the 24-hour boundary on each side.
Not assessed: your code style, your own tests, and what happens when two cancellations of the same booking arrive at once (do handle it, but the checks do not test it). Your reflection is recorded but not graded.
Tools
You can do this exercise with Claude Code, OpenCode or OpenHands in the lab. If you use an agent, give it the requirement above word for word, ask for a plan and a list of tests before code, and read its diff before you run Check work.
Acceptance criteria
AC1Cancelling at least 24 hours ahead returns 200 and refunds the full priceVerified behaviour
AC2Cancelling less than 24 hours ahead succeeds and refunds nothingVerified behaviour
AC3A cancelled booking frees its time and stays in the owner's booking listVerified behaviour
AC4Cancelling twice or after the start is refused with 409Verified behaviour
AC5Only the owner can cancel; others and unknown ids get 404, and no token gets 401Verified behaviour
AC6Existing booking behaviour still worksVerified behaviour
Verified behaviour is checked by running your submitted work from outside the lab. A structure check confirms that something is present and in the expected format; it does not prove it is correct.
Not assessed
The readability, structure and style of your code.
Your own tests: the assessment does not run them or judge how well they cover the requirement.
Behaviour under concurrent cancellation requests for the same booking.
Your reflection: it is recorded, not graded.
Hints
Try the exercise first. Each hint gives away a little more than the one before.
Check your work
Submit your work from the lab's Check work panel. Hidden checks run your submitted code from outside the lab; your own test output is never taken as a result. You can revise and resubmit.