JOURNAL

Part 3/6: From idea to spec, plan and tasks

A spec is the contract between you and the agent. This part goes from the spec template and Behaviour table to a task table with a check per task, then test-first code with an injected clock, and walks through spec 0002 with Claude Code and Codex.

Conceptual illustration of coordinated workers, routing, state storage and security checks.

Read with AI

Choose content to copy and paste into your AI assistant. Nothing is sent automatically. CMS content is converted to Markdown; original Markdown is used when available.

Prefer to watch first? The whole series in one video (25 minutes) walks the full loop on the sample repo.

Give an agent the sentence “add daily click stats to the shortener” and it will add something. The trouble starts when you try to decide whether that something is finished. Which route? What does the response look like? Are days without clicks in the list or left out? Does an expired link still count? The agent made a choice for every one of those questions, quietly, and you only find out which choices it made by reading the whole diff.

This part is about removing that guesswork. We take a feature from idea to spec, from spec to a task table, and from the task table to code that is written test first, one task at a time. The spec is the contract between you and the agent: it says what “done” means in a form a machine can check. The task table is the plan you approve before any file changes. The tests are where the contract becomes executable.

We use the sample repo agentic-shortlink: first the finished spec 0001 (link expiry) as a worked example, then spec 0002 (daily click stats) as the exercise you run yourself with Claude Code and with Codex.

What you will have at the end

  • A spec template where every section has a job, and a Behaviour table whose rows become tests one to one.
  • A way to read a task table before approving it: files, checks, dependencies, and what is out of scope.
  • An injected clock, and a clear reason why agents writing time-based code need one.
  • Spec 0002 implemented by your agent, in plan mode with /implement-spec 0002 in Claude Code, or task by task with Codex, interactive or headless.
  • A reviewer’s list for the reference solution, and a three-part report format you can demand at the end of every task.

Prerequisites

You need the repo set up as in Part 2: Repo setup for Claude Code and Codex: Node 22, pnpm, the repo cloned and trusted in Claude Code, Codex installed, and pnpm check green. The roles behind this workflow (planner, executor, reviewer) are explained in Part 1.

Check: from the repo root on main:

pnpm check
# ...
#  Test Files  2 passed (2)
#       Tests  13 passed (13)

Why specs: the agent needs a definition of done it can check

An agent works in a loop: read, edit, run something, look at the result, repeat. It stops when it believes the job is done. If “done” lives only in your head, the agent substitutes its own idea of done, which is usually “the code compiles and the test I just wrote passes”. That is a low bar, and the agent sets it for itself.

Here is what I have seen with vague prompts like “add daily click stats”. None of it is malicious; each one is a reasonable guess that nobody asked for:

  • The agent invents the route and the response shape. You get /stats?period=day one time and /api/links/:slug/daily the next.
  • It returns only the days that have clicks, so a chart of “last 7 days” has three bars and no gaps.
  • It stores the user agent or IP “for richer analytics”, which you now have to explain to whoever handles privacy.
  • It calls new Date() inside the handler, and the test it writes passes today and fails on a run that crosses midnight UTC.
  • It reports “done, all tests pass” after running only its own new test file.

With a spec, the same agent gets a different task. The route, the query parameter, its limits, the response body, the error codes and the things it must not build are written down. Each behaviour is an example with concrete input and output, so the agent can turn it into a test, and you can check the result by reading a table instead of reading the agent’s mind. When the agent says “done”, you compare its report against the Definition of done line by line.

The spec template, section by section

Every spec in the repo starts from this file:

docs/specs/TEMPLATE.md

# NNNN: <feature name>

Status: draft | approved | done
Owner: <human who approves the plan>

## Problem

One paragraph: who needs this and why. No solution here.

## Scope

In:

- ...

Out (do not build):

- ...

## Behaviour

Describe the observable behaviour as concrete examples. Prefer request/response pairs.

| Given | When | Then |
| --- | --- | --- |
| ... | ... | ... |

## Definition of done

Every line must be checkable by a machine or by reading one file.

- [ ] Tests in `test/<file>.test.ts` cover every row of the Behaviour table
- [ ] `pnpm check` passes (lint, typecheck, tests)
- [ ] No change to existing response fields unless listed under Behaviour
- [ ] README API section updated

## Risk

Reversible? Data migration? Public contract change? Pick the review level from AGENTS.md.

## Notes for the agent

Files likely to change, patterns to follow, traps.

Each section answers one question the agent would otherwise answer for you:

SectionQuestion it answersWhat goes wrong without it
Status, OwnerIs this ready to build, and who approves the plan?Agents start on drafts; nobody owns the approval.
ProblemWho needs this and why?The agent optimises for the wrong user.
Scope: InWhat exactly gets built?Features grow while the agent works.
Scope: OutWhat must not be built, even if it looks useful?“Helpful” extras: extra columns, extra endpoints, backfill scripts.
BehaviourWhat is the observable result for a given input?No tests that match your intent; the agent tests its own guesses.
Definition of doneHow do we know it is finished?“Done” means “compiles”.
RiskHow much review does this need?A schema change gets the same review as a typo fix.
Notes for the agentWhich files, which patterns, which traps?The agent rediscovers the codebase and picks a different pattern.

The Behaviour table is the test list

The Behaviour table is the most important part. Each row is Given / When / Then: a starting state, one action, one observable result. Write rows as concrete examples with real values, preferably request and response pairs. “Returns stats” is not a row. “GET /api/links/promo/stats/daily?days=3 returns 200 with these three objects” is.

The rule I follow: one row becomes at least one test, and every test traces back to a row. When I review, I put the rows on one side and the test names on the other and draw lines. A row without a test is unverified behaviour. A test without a row is either a missing row in the spec or an agent testing something nobody asked for.

Two more rules from the new-spec skill in the repo: include at least two failure rows (bad input, unknown resource), and keep every Definition of done item checkable by a machine or by reading one file. “Code is clean” is not checkable. “pnpm check passes” is.

Note: if the idea has no spec yet, the repo has a skill for that: /new-spec <short description> in Claude Code reads the template and the existing specs, asks you up to five questions, and writes a draft spec without touching code. In this part both specs already exist, so we skip it.

Worked example: spec 0001, link expiry

Spec 0001 is finished, so it shows the whole path from spec to tested code. Here it is as committed:

docs/specs/0001-link-expiry.md

# 0001: Link expiry

Status: done
Owner: maintainer

## Problem

Campaign links should stop working after a campaign ends. Today every link lives forever.

## Scope

In:

- Optional `expiresInDays` (1 to 365) when creating a link
- Expired links stop redirecting
- Stats show whether a link has expired

Out (do not build):

- Changing the expiry of an existing link
- Background cleanup of expired rows
- Time zones other than UTC

## Behaviour

| Given | When | Then |
| --- | --- | --- |
| now = 2026-01-01T00:00Z | `POST /api/links {url, expiresInDays: 7}` | 201, `expiresAt = 2026-01-08T00:00:00.000Z` |
| no `expiresInDays` | create | `expiresAt = null`, never expires |
| `expiresInDays: 0` or `366` | create | 400 `invalid_request` |
| link expires in 1 day | `GET /:slug` before expiry | 302 to the target URL |
| link expired (now >= expiresAt) | `GET /:slug` | 410 `{ "error": "expired" }`, click not counted |
| link expired | `GET /api/links/:slug` | 200 with `expired: true` |

## Definition of done

- [x] `test/expiry.test.ts` covers every row above, using an injected clock (no real timers)
- [x] `pnpm check` passes
- [x] Existing fields in responses unchanged; `expiresAt` and `expired` added
- [x] README API section updated

## Risk

Medium: adds a nullable column (`expires_at`) and a new status code on a public route. Reversible: the column is nullable and ignored by old code.

## Notes for the agent

- Inject time through `createApp({ now })`; never call `Date.now()` in route handlers.
- Keep the expiry check in one exported function (`isExpired`) so stats and redirect agree.

A few things to notice. The Out list names three things an agent might reasonably add (editing expiry, a cleanup job, time zones) and forbids them. The first Behaviour row fixes the clock (now = 2026-01-01T00:00Z), so the expected expiresAt is an exact string, not “about a week from now”. The Notes tell the agent how to handle time and where to put the expiry rule, which are exactly the two places where an agent would otherwise improvise.

From spec to task table

Before any code, the planner (an agent in plan mode, read only) turned the spec into this table, and the owner approved it:

docs/tasks/0001-link-expiry.md

# Tasks for spec 0001: link expiry

Generated by the planner (plan mode, read-only), approved by the owner before any code was written.
Each task is small enough for one agent run and has its own check.

| # | Task | Files | Check | Depends on |
| --- | --- | --- | --- | --- |
| T1 | Add nullable `expires_at` column and map it in `LinkRepo` | `src/db.ts`, `src/repo.ts` | `pnpm typecheck` | none |
| T2 | Accept `expiresInDays` in `POST /api/links`, compute `expiresAt` from the injected clock | `src/app.ts` | `pnpm vitest run test/expiry.test.ts -t "sets expiresAt"` | T1 |
| T3 | Add `isExpired`; return 410 on redirect and `expired` in stats; do not count clicks | `src/app.ts` | `pnpm vitest run test/expiry.test.ts` | T2 |
| T4 | Update README API section | `README.md` | review | T3 |
| T5 | Full gate | none | `pnpm check` | T1-T4 |

Parallelism: T1-T3 touch the same files, so they run in sequence in one worktree. T4 can run in parallel once T3's response shape is fixed.

Each task has four properties that make it safe to hand to an agent:

  1. Small. One focused run. T1 is a column and a mapping; it does not also add the route.
  2. Files listed. You know before the run which files may change. A diff that touches anything else is a signal to stop and ask why.
  3. A check that is a command. pnpm typecheck, or a single test filtered with -t. Only the README task says “review”, because a human reads prose better than a test does.
  4. Dependencies. T2 needs T1’s column; T3 needs T2’s field.

How parallelism is decided

The rule is simple: tasks that share a file run in sequence; tasks with no shared file may run in parallel. T1 to T3 all touch src/app.ts or src/repo.ts, so they run one after another in one worktree. Running them in parallel would produce three branches that each edit the same functions, and the merge is where an agent’s work gets lost. T4 only touches README.md, so it can run beside the others once T3 has fixed the response shape it documents.

The Files and Depends on columns together give you the schedule. Running tasks in parallel in separate worktrees is the subject of Part 4.

From Behaviour rows to tests

Here is the test file for spec 0001:

test/expiry.test.ts

import { describe, expect, it } from "vitest";
import { makeApp } from "./helpers.js";

const DAY = 24 * 60 * 60 * 1000;

describe("link expiry (spec 0001)", () => {
  it("sets expiresAt from expiresInDays", async () => {
    const { post } = makeApp(new Date("2026-01-01T00:00:00Z"));
    const body = await (await post({ url: "https://example.com", expiresInDays: 7 })).json();
    expect(body.expiresAt).toBe("2026-01-08T00:00:00.000Z");
  });

  it("redirects before expiry and returns 410 after", async () => {
    const { app, post, advance } = makeApp();
    await post({ url: "https://example.com", slug: "soon", expiresInDays: 1 });
    expect((await app.request("/soon")).status).toBe(302);
    advance(DAY);
    expect((await app.request("/soon")).status).toBe(410);
  });

  it("does not count clicks on expired links", async () => {
    const { app, post, advance } = makeApp();
    await post({ url: "https://example.com", slug: "old", expiresInDays: 1 });
    advance(2 * DAY);
    await app.request("/old");
    const stats = await (await app.request("/api/links/old")).json();
    expect(stats).toMatchObject({ clicks: 0, expired: true });
  });
});

And this is the mapping a reviewer should do, row by row. Some rows are covered in test/links.test.ts, which already had the create and validation tests:

Behaviour rowTestStatus
now = 2026-01-01, expiresInDays: 7 gives expiresAt = 2026-01-08...expiry.test.ts: “sets expiresAt from expiresInDays”covered
no expiresInDays gives expiresAt = nulllinks.test.ts: “creates a link with a generated slug” asserts toBeNull()covered
expiresInDays: 0 or 366 gives 400 invalid_requestlinks.test.ts: “rejects invalid input” with expiresInDays: 0, status onlypartial
before expiry, GET /:slug gives 302expiry.test.ts: “redirects before expiry and returns 410 after”covered
expired, GET /:slug gives 410, click not countedsame test (410) and “does not count clicks on expired links”covered
expired, GET /api/links/:slug gives expired: true“does not count clicks on expired links” (toMatchObject)covered

I did this mapping while writing this post and found the gap in row 3: 366 is not tested, and the test checks the status but not the invalid_request code. The Definition of done box is ticked anyway. The code does reject 366 (.max(365) in the zod schema), so nothing is broken today, but nothing would catch someone changing that limit either. That is the point of the exercise: a ticked box is a claim, and the row-to-test mapping is how you verify it. It takes two minutes. I left this gap in the repo on purpose as a warm-up: add an it.each([0, 366]) case to test/expiry.test.ts that also asserts error: "invalid_request", and watch it pass.

The injected clock, and why agents need it

Every test above builds the app through one helper:

test/helpers.ts

import { createApp } from "../src/app.js";
import { openDb } from "../src/db.js";
import { LinkRepo } from "../src/repo.js";

export const ADMIN_KEY = "test-admin-key";

export function makeApp(start = new Date("2026-01-01T00:00:00Z")) {
  let current = start;
  const repo = new LinkRepo(openDb(":memory:"));
  const app = createApp({
    repo,
    baseUrl: "http://sho.rt",
    adminApiKey: ADMIN_KEY,
    now: () => current,
  });
  const advance = (ms: number) => {
    current = new Date(current.getTime() + ms);
  };
  const post = (body: unknown) =>
    app.request("/api/links", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(body),
    });
  return { app, repo, advance, post };
}

createApp takes a now function. Production passes nothing and gets the default () => new Date(); tests pass a closure over current and move it forward with advance(ms). “One day later” in a test is one function call, not a sleep and not a fake timer library.

This matters more with agents than with people, for three reasons:

  1. Deterministic tests are the agent’s feedback signal. An agent iterates until the test is green. If the test depends on the real clock, green can mean “it happened to be 10:00 when it ran”. A flaky test teaches the agent nothing, and an agent facing a flaky test tends to loosen the assertion until it passes.
  2. Boundaries become testable. Expiry at exactly now >= expiresAt, a click at 23:59 UTC versus 00:01, the last N days ending today: with an injected clock these are one-line setups. With real time they are not tested at all.
  3. The rule is mechanically checkable. AGENTS.md says “never call Date.now() or new Date() in route handlers”, and the review rules flag it as high. You can check it with grep instead of trust.

Check: the only new Date() in the routes file is the default parameter, and the expiry tests pass:

grep -n "Date.now()\|new Date()" src/app.ts
# 26:export function createApp({ repo, baseUrl, adminApiKey, now = () => new Date() }: AppDeps) {

pnpm vitest run test/expiry.test.ts
#  Test Files  1 passed (1)
#       Tests  3 passed (3)

The exercise: spec 0002, daily click stats

Now you build a feature. Spec 0002 is on main with Status approved and every Definition of done box unticked:

docs/specs/0002-daily-click-stats.md

# 0002: Daily click stats

Status: approved (exercise for readers; reference solution on branch `solution/0002-daily-stats`)
Owner: maintainer

## Problem

A single click counter cannot show whether a campaign is still getting traffic. Owners want clicks per day.

## Scope

In:

- Record each successful redirect with its UTC date
- `GET /api/links/:slug/stats/daily?days=N` returns the last N days (default 7, max 90), oldest first, including days with zero clicks

Out (do not build):

- Per-hour buckets, referrers, user agents, IP addresses (no personal data is stored)
- Backfilling history for clicks recorded before this change

## Behaviour

| Given | When | Then |
| --- | --- | --- |
| link `promo` clicked twice on 2026-01-01 and once on 2026-01-03; now = 2026-01-03 | `GET /api/links/promo/stats/daily?days=3` | 200 `{ "slug": "promo", "days": [{"date":"2026-01-01","clicks":2},{"date":"2026-01-02","clicks":0},{"date":"2026-01-03","clicks":1}] }` |
| no `days` param | same request | 7 entries |
| `days=0`, `days=91`, `days=abc` | same request | 400 `invalid_request` |
| unknown slug | same request | 404 `not_found` |
| expired link visited | `GET /:slug` | 410, no row recorded (same rule as spec 0001) |

## Definition of done

- [ ] New table `link_clicks (slug TEXT, day TEXT, clicks INTEGER, PRIMARY KEY (slug, day))`, created in `openDb`
- [ ] Redirect increments both `links.clicks` and today's `link_clicks` row in one transaction
- [ ] `test/daily-stats.test.ts` covers every row above with the injected clock
- [ ] Deleting a link deletes its daily rows
- [ ] `pnpm check` passes; README API section updated

## Risk

Medium: new table and a write on the hot redirect path. Reversible: the table can be dropped without touching `links`.

## Notes for the agent

- Use an upsert: `INSERT ... ON CONFLICT(slug, day) DO UPDATE SET clicks = clicks + 1`.
- Build the zero-filled day list in TypeScript, not SQL; keep it a pure function with its own unit test.

Read it once as the agent will. The route, the default, the limits and the order (oldest first) are fixed. Zero days are included, which rules out a plain GROUP BY as the whole answer. Personal data is explicitly out. The expired-link row ties this spec back to spec 0001. The Notes say how to write the upsert and where the zero-fill lives.

The flow for the rest of this part follows the diagram below: you hand the spec to a planner that cannot edit, you get questions and a task table back, you approve it, then each task runs test first and reports with evidence.

Sequence diagram: the human gives spec 0002 to the planner in plan mode, the planner reads code and AGENTS.md without editing and returns questions and a task table, the human approves, then for each task the executor writes a failing test, writes code, gets red or green from the tests and reports done and verified with the command; finally the human runs pnpm check
From spec to tasks: plan without edits, approve, then one task at a time, test first.

Start on a branch so the reference solution stays out of your way:

git switch main
git switch -c feat/0002-daily-stats

Check: the spec is approved and nothing is built yet:

grep -n "Status" docs/specs/0002-daily-click-stats.md
# 3:Status: approved (exercise for readers; reference solution on branch `solution/0002-daily-stats`)

ls test
# expiry.test.ts  helpers.ts  links.test.ts

Running it in Claude Code

The repo ships a skill for exactly this. It is short enough to read in full, and you should, because it is the procedure the agent will follow:

.claude/skills/implement-spec/SKILL.md

---
name: implement-spec
description: Implement an approved spec from docs/specs end to end - plan, task table, test-first changes, full check, self-review. Use when asked to build a feature that has a spec.
argument-hint: "<spec number or path>"
---

Implement spec $ARGUMENTS.

## 1. Plan (no edits)

- Read the spec, AGENTS.md and every file the spec's Notes mention.
- Write `docs/tasks/<spec-file-name>.md` with a table: `# | Task | Files | Check | Depends on`. Each task fits one focused run and has a command that proves it is done.
- Mark which tasks can run in parallel (no shared files).
- Show the table and wait for the human to approve it.

## 2. Execute, one task at a time

For each task:

1. Write or extend the test for that task. Run it and confirm it fails for the right reason.
2. Make the smallest change that passes it.
3. Run the task's Check command. Do not move on while it is red.

## 3. Verify

- `pnpm check` must pass.
- If the change touches a route, start the server (`pnpm dev` with a temp `DATABASE_PATH`) and exercise one Behaviour row with curl-equivalent `app.request` in a test, not by hand.

## 4. Review

- Run the `reviewer` subagent, then pass its findings to the `refuter` subagent.
- Fix every CONFIRMED finding, re-run `pnpm check`.

## 5. Report

Tick the spec's Definition of done boxes that are now true. Then reply with:

- Done and verified: each item with the command that proved it
- Done, not verified: and why
- Skipped: and why
- Suggested commit message (Conventional Commits)

Do not push.

The session goes like this:

  1. Run claude in the repo root.
  2. Press Shift+Tab to cycle permission modes until plan mode is on (the repo’s CLAUDE.md says “Shift+Tab twice” from the default mode). In plan mode Claude can read and run read-only commands but cannot edit files.
  3. Type /implement-spec 0002. The skill receives 0002 as $ARGUMENTS, reads the spec, AGENTS.md and the files the Notes mention, and comes back with the task table as its plan. Because plan mode blocks edits, the table arrives as a proposal, not as a file.
  4. Read the table with the list in the next section. If something is wrong, say so in plain words (“T2 is too big, split the schema from the redirect change”) and let it revise. Approve only when every item on the list holds.
  5. When you approve, Claude leaves plan mode, writes docs/tasks/0002-daily-click-stats.md, and starts on T1.

I add one sentence when approving: “After each task, stop and give me the three-part report before starting the next one.” The skill already runs tasks one at a time; this makes the pause explicit, so you see each red-then-green before the next task builds on it.

What to check in the task table before approving

Your planner will not produce exactly the same table as mine, and it does not need to. This is the table I would approve for spec 0002, so you have something to compare against:

#TaskFilesCheckDepends on
T1Add pure utcDay, lastNDays, fillDays with unit testssrc/lib/days.ts, test/daily-stats.test.tspnpm vitest run test/daily-stats.test.ts -t "lastNDays"none
T2Add link_clicks table (cascade delete); recordClick(slug, day) in one transaction; dailyClicks; redirect passes today’s UTC daysrc/db.ts, src/repo.ts, src/app.ts, test/daily-stats.test.tspnpm vitest run test/daily-stats.test.ts -t "deletes daily rows" and pnpm vitest run test/expiry.test.tsT1
T3Add GET /api/links/:slug/stats/daily with zod-validated days (default 7, 1 to 90)src/app.ts, test/daily-stats.test.tspnpm vitest run test/daily-stats.test.tsT2
T4Update README API sectionREADME.mdreviewT3
T5Full gatenonepnpm checkT1-T4

Parallelism here: T1, T2 and T3 all add tests to test/daily-stats.test.ts, and T2 and T3 both edit src/app.ts, so they run in sequence. T4 can run beside T3’s tail once the response shape is settled. You could free T1 by putting the pure tests in their own file, but for helpers this small the sequence is cheaper than the coordination.

Whatever table you get, check these before you approve:

  • Every Behaviour row lands in some task’s check. Five rows in spec 0002; find each one.
  • Every Definition of done item has a task. The table, the transaction, the test file, cascade delete, pnpm check, README. Cascade delete is the one planners forget.
  • Every task has a command as its check, except docs. “Verify manually” on a code task means the task is not done until you do it.
  • Files match the repo’s layout. SQL only in src/repo.ts, schema in src/db.ts, the pure helper in src/lib/, the route in src/app.ts. A task that puts a query in app.ts fails review later; it is cheaper to fix now.
  • Dependencies and shared files agree. If two tasks list the same file, they are not parallel, whatever the table says.
  • Out of scope is respected. No hour buckets, no referrer or user agent columns, no IP addresses, no backfill script. Also no new dependency: a date library for “last N days” breaks AGENTS.md rule 4 (“no new dependencies without asking”).
  • Each task fits one run. If a task’s description has three “and”s and five files, ask for a split.

Check: right after approval, only the task file is new. Nothing in src/ should change before the task file exists:

git status --short
# ?? docs/tasks/0002-daily-click-stats.md

Test first, one task at a time

For each task the skill asks for the same three steps: write the test, run it and see it fail for the right reason, then make the smallest change that passes it and run the task’s Check. “For the right reason” matters. For T2, the right failure is that dailyClicks or the link_clicks table does not exist yet. A failure from a typo in the test, or an import error, proves nothing about the feature. Ask the agent to show you the failure message, not just say “it failed”.

After T5, the skill runs the reviewer subagent on the diff and passes its findings to the refuter subagent, then fixes what survives. Part 5 covers that pair in CI; here it runs locally before you see the final report.

Check: when the agent reports done. Your test count may differ if your agent wrote more or fewer tests; the reference solution gives these numbers:

pnpm vitest run test/daily-stats.test.ts
#  Test Files  1 passed (1)
#       Tests  10 passed (10)

pnpm check
#  Test Files  3 passed (3)
#       Tests  23 passed (23)

Running it in Codex

Codex reads the same AGENTS.md, so the rules are identical. It has no implement-spec skill in this repo, so the procedure goes into your prompt. The project config (.codex/config.toml) sets sandbox_mode = "workspace-write" and approval_policy = "on-request", which means Codex can edit files in the repo without asking. “Do not edit yet” in the prompt is a request, not a lock.

Interactive

Run codex in the repo root and send the planning prompt:

Read docs/specs/0002-daily-click-stats.md and AGENTS.md. Do not edit yet.
Propose docs/tasks/0002-daily-click-stats.md in the same format as
docs/tasks/0001-link-expiry.md: a table with # | Task | Files | Check | Depends on.
Each task must fit one focused run and have a command as its check.
Mark which tasks can run in parallel (no shared files).
List anything in the spec that is ambiguous as questions for me.

Review the table with the same list as above. When it is right, tell Codex to write the file, then run the tasks one per message:

Write the approved table to docs/tasks/0002-daily-click-stats.md. Do not touch other files.

Do T1 from docs/tasks/0002-daily-click-stats.md. Restate it as concrete outputs first.
Write the test first and show me it failing, then make it pass.
Run the task's Check command. Stop and report: done and verified (with the command),
done but not verified, skipped.

Repeat the second message for T2, T3 and so on. Read each report before you send the next task.

Headless

If you want the planning step to be enforced rather than requested, use codex exec for it. Its default sandbox is read-only, so it cannot write files even if it wanted to. -o saves its last message, which is the table:

mkdir -p agent-runs

codex exec "Read docs/specs/0002-daily-click-stats.md and AGENTS.md. Do not edit. \
Propose docs/tasks/0002-daily-click-stats.md in the format of docs/tasks/0001-link-expiry.md \
(# | Task | Files | Check | Depends on), mark parallel tasks, and list open questions." \
  -o agent-runs/0002-plan.md

Read agent-runs/0002-plan.md, fix what you disagree with, and save the table yourself as docs/tasks/0002-daily-click-stats.md. You are the approver; saving the file is the approval. Then run each task with write access:

codex exec "Do T1 from docs/tasks/0002-daily-click-stats.md. Follow AGENTS.md. \
Restate the task first, write the test first and confirm it fails, then make it pass. \
Run the task's Check. End with: done and verified (with commands), done but not verified, skipped." \
  --sandbox workspace-write \
  -o agent-runs/0002-T1.md

agent-runs/ is in .gitignore, so the reports never end up in a commit. Add --json if you want the full event stream on stdout for logging. In Part 4, scripts/agent-task.sh wraps this same call and gives each task its own worktree and branch.

Check: after each headless task, the report exists and the task’s own check is green when you run it yourself:

cat agent-runs/0002-T1.md
pnpm vitest run test/daily-stats.test.ts -t "lastNDays"
# all selected tests pass, 0 failed
git status --short
# only the files listed for T1

Reading the reference solution like a reviewer

When your version is green, compare it with the branch solution/0002-daily-stats. Do not look before; the point is to practise reviewing an agent’s work, and the reference is one good answer, not the only one.

git diff --stat main solution/0002-daily-stats
git show solution/0002-daily-stats:src/lib/days.ts

The pure helpers

src/lib/days.ts (solution branch)

const DAY_MS = 24 * 60 * 60 * 1000;

export function utcDay(date: Date): string {
  return date.toISOString().slice(0, 10);
}

export function lastNDays(now: Date, n: number): string[] {
  const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
  return Array.from({ length: n }, (_, i) => utcDay(new Date(today - (n - 1 - i) * DAY_MS)));
}

export function fillDays(days: string[], counts: Map<string, number>) {
  return days.map((date) => ({ date, clicks: counts.get(date) ?? 0 }));
}

Three small functions with no database and no clock. lastNDays takes now as an argument, so the caller decides what time it is. fillDays is the zero-fill the spec asked for, as a plain map over the day list. Because they are pure, they get plain unit tests with fixed inputs, and those tests are the cheapest place to catch an off-by-one in the date range.

The schema and the repo

src/db.ts (solution branch)

import Database from "better-sqlite3";

export type Db = Database.Database;

export function openDb(path: string): Db {
  const db = new Database(path);
  db.pragma("journal_mode = WAL");
  db.exec(`
    CREATE TABLE IF NOT EXISTS links (
      slug        TEXT PRIMARY KEY,
      url         TEXT NOT NULL,
      created_at  TEXT NOT NULL,
      expires_at  TEXT,
      clicks      INTEGER NOT NULL DEFAULT 0
    );
    CREATE TABLE IF NOT EXISTS link_clicks (
      slug    TEXT NOT NULL REFERENCES links(slug) ON DELETE CASCADE,
      day     TEXT NOT NULL,
      clicks  INTEGER NOT NULL DEFAULT 0,
      PRIMARY KEY (slug, day)
    );
  `);
  db.pragma("foreign_keys = ON");
  return db;
}

src/repo.ts (solution branch, the two new methods)

// ...
  recordClick(slug: string, day: string): void {
    this.db.transaction(() => {
      this.db.prepare("UPDATE links SET clicks = clicks + 1 WHERE slug = ?").run(slug);
      this.db
        .prepare(
          `INSERT INTO link_clicks (slug, day, clicks) VALUES (?, ?, 1)
           ON CONFLICT(slug, day) DO UPDATE SET clicks = clicks + 1`,
        )
        .run(slug, day);
    })();
  }

  dailyClicks(slug: string, fromDay: string, toDay: string): Map<string, number> {
    const rows = this.db
      .prepare("SELECT day, clicks FROM link_clicks WHERE slug = ? AND day BETWEEN ? AND ?")
      .all(slug, fromDay, toDay) as { day: string; clicks: number }[];
    return new Map(rows.map((r) => [r.day, r.clicks]));
  }
  // ...

The route

src/app.ts (solution branch, the query schema, the new route and the changed redirect)

// ...
const DailyStatsQuery = z.object({
  days: z.coerce.number().int().min(1).max(90).default(7),
});
// ...
  app.get("/api/links/:slug/stats/daily", (c) => {
    const query = DailyStatsQuery.safeParse({ days: c.req.query("days") });
    if (!query.success) {
      return c.json({ error: "invalid_request", issues: query.error.issues }, 400);
    }
    const link = repo.find(c.req.param("slug"));
    if (!link) return c.json({ error: "not_found" }, 404);
    const days = lastNDays(now(), query.data.days);
    const counts = repo.dailyClicks(link.slug, days[0] ?? "", days.at(-1) ?? "");
    return c.json({ slug: link.slug, days: fillDays(days, counts) });
  });
  // ...
  app.get("/:slug", (c) => {
    const link = repo.find(c.req.param("slug"));
    if (!link) return c.json({ error: "not_found" }, 404);
    if (isExpired(link, now())) return c.json({ error: "expired" }, 410);
    repo.recordClick(link.slug, utcDay(now()));
    return c.redirect(link.url, 302);
  });
// ...

The tests

test/daily-stats.test.ts (solution branch, shortened)

import { describe, expect, it } from "vitest";
import { fillDays, lastNDays } from "../src/lib/days.js";
import { ADMIN_KEY, makeApp } from "./helpers.js";

const DAY = 24 * 60 * 60 * 1000;

// ... describe("lastNDays / fillDays"): two unit tests for the pure helpers

describe("GET /api/links/:slug/stats/daily (spec 0002)", () => {
  it("returns zero-filled daily clicks, oldest first", async () => {
    const { app, post, advance } = makeApp(new Date("2026-01-01T10:00:00Z"));
    await post({ url: "https://example.com", slug: "promo" });
    await app.request("/promo");
    await app.request("/promo");
    advance(2 * DAY);
    await app.request("/promo");

    const res = await app.request("/api/links/promo/stats/daily?days=3");
    expect(res.status).toBe(200);
    expect(await res.json()).toEqual({
      slug: "promo",
      days: [
        { date: "2026-01-01", clicks: 2 },
        { date: "2026-01-02", clicks: 0 },
        { date: "2026-01-03", clicks: 1 },
      ],
    });
  });
  // ... "defaults to 7 days", "rejects days=0/91/abc", "returns 404 for unknown slugs"

  it("does not record clicks on expired links", async () => {
    const { app, post, advance } = makeApp(new Date("2026-01-01T00:00:00Z"));
    await post({ url: "https://example.com", slug: "old", expiresInDays: 1 });
    advance(DAY);
    expect((await app.request("/old")).status).toBe(410);
    const body = await (await app.request("/api/links/old/stats/daily?days=2")).json();
    expect(body.days.every((d: { clicks: number }) => d.clicks === 0)).toBe(true);
  });

  it("deletes daily rows with the link", async () => {
    const { app, post, repo } = makeApp(new Date("2026-01-01T00:00:00Z"));
    await post({ url: "https://example.com", slug: "tmp" });
    await app.request("/tmp");
    await app.request("/api/links/tmp", { method: "DELETE", headers: { "x-api-key": ADMIN_KEY } });
    expect(repo.dailyClicks("tmp", "2026-01-01", "2026-01-01").size).toBe(0);
  });
});

What a reviewer should look for

  • The transaction. recordClick wraps the counter update and the upsert in this.db.transaction(...)(). Note the trailing (): better-sqlite3’s transaction returns a function, and forgetting to call it means nothing runs. Without the transaction, a failure between the two statements leaves links.clicks and the daily rows out of step.
  • The upsert uses bound parameters. ON CONFLICT(slug, day) DO UPDATE SET clicks = clicks + 1, with ? placeholders, inside src/repo.ts. SQL anywhere else, or built with string concatenation, is a high finding under AGENTS.md.
  • Zero-fill is a pure function. The SQL only returns days that exist; fillDays adds the missing ones in TypeScript, as the Notes asked. If your agent did it with a recursive CTE, it may work, but it ignored a Note, and that is worth asking about.
  • Expired links are not recorded. In the redirect, the 410 return comes before recordClick. Swap those two lines and expired links start counting. The test “does not record clicks on expired links” fails if they are swapped.
  • Cascade delete needs the pragma. ON DELETE CASCADE in the schema does nothing in SQLite unless foreign_keys is on for that connection, and it is off by default. db.pragma("foreign_keys = ON") in openDb is what makes “Deleting a link deletes its daily rows” true. The test “deletes daily rows with the link” is the proof; without the pragma it fails.
  • Time is injected. The route and redirect call now(), never new Date(). Run the grep from earlier on your version.
  • Validation order. The reference validates days before looking up the slug, so /api/links/nope/stats/daily?days=abc returns 400, not 404. The spec does not say which wins. That is fine to accept, but if it matters to you, the fix is a new Behaviour row, not a silent code change.

Check: run the reference yourself and compare counts with yours:

git stash -u   # only if you have uncommitted work
git switch solution/0002-daily-stats
pnpm check
#  Test Files  3 passed (3)
#       Tests  23 passed (23)
git switch feat/0002-daily-stats

Restate first, report in three parts

Two lines in AGENTS.md’s “How to work” do most of the work of keeping an agent honest:

2. Restate the task as concrete outputs (files, endpoints, status codes) before editing. Build exactly that. Offer extras in one line; do not build them.
...
5. Finish with a summary in three parts: done and verified (with the command you ran), done but not verified, skipped.

Restating means the agent writes, before editing, the literal outputs of the task: which files, which functions, which routes, which status codes. It is a cheap checkpoint. If the restatement of T2 says “add a link_clicks table with a user_agent column”, you stop it there, not after the migration. A good restatement for T2 reads like this:

T2, restated:
- src/db.ts: new table link_clicks (slug, day, clicks, PRIMARY KEY (slug, day)),
  slug references links(slug) ON DELETE CASCADE; foreign_keys pragma on in openDb
- src/repo.ts: recordClick(slug, day) updates links.clicks and upserts today's
  link_clicks row in one transaction; new dailyClicks(slug, fromDay, toDay)
- src/app.ts: GET /:slug passes utcDay(now()) to recordClick; nothing else changes
- test/daily-stats.test.ts: "deletes daily rows with the link"
Not in T2: the stats route (T3), README (T4).

The three-part report separates what the agent proved from what it believes. This is the report I would accept for T2. It is an example of the format, written by hand, not a captured log:

Done and verified
- Daily rows are deleted with their link:
  pnpm vitest run test/daily-stats.test.ts -t "deletes daily rows"
  (failed first: link_clicks did not exist; passes now)
- Redirect and expiry behaviour unchanged:
  pnpm vitest run test/expiry.test.ts (3 passed)
- Types: pnpm typecheck (no errors)

Done, not verified
- Atomicity of recordClick: no test forces the second statement to fail;
  checked by reading the transaction wrapper in src/repo.ts.

Skipped
- Stats route and its tests (T3), README (T4), full pnpm check (T5).

What makes it good: every verified line has the command that verified it, the red-then-green is stated, the unverified part is named instead of hidden, and “skipped” points to the tasks that own those items. A report that says “Implemented T2, all tests pass” gives you nothing to check. Ask for a rewrite.

At the end of the whole spec, the skill also ticks the Definition of done boxes that are now true. Check each tick against the diff the same way we mapped spec 0001’s rows. A box is ticked by the same agent that did the work, so it is a claim until you have looked.

Common mistakes

Approving a plan without a check per task

A task without a command check is a task whose completion is the agent’s opinion. The planner will happily write “verify the endpoint works”. Send it back and ask for the exact pnpm vitest run ... -t "..." line. If no test can check the task yet, the task is probably the wrong size.

Tasks too big for one run

“Implement daily stats” as T1 is not a plan; it is the original prompt with a number in front. Long tasks drift as the agent’s context fills with output from earlier steps. A useful signal is the Files column. More than three or four files, or files in different layers, usually means two tasks.

Letting the agent change the spec silently

When a test is hard to make pass, an agent will sometimes “fix” the spec: drop a Behaviour row, change a limit, tick a box that is not true. The spec is the contract, so changes to it go through you. Check git diff main -- docs/specs/ at the end of every run; the only expected change is ticked boxes. If the agent found a real problem in the spec, it should say so in the report and wait.

Tests that call real time

An agent that does not know about makeApp(start) and advance(ms) will write new Date() in the test, or reach for a fake timer library. The test passes today and fails on a run that crosses midnight UTC. The spec says “with the injected clock” in the Definition of done for a reason. Grep the new test file for new Date() without an argument and for Date.now().

Skipping “Out of scope”

An empty Out list is an invitation. For daily stats the obvious extras are hour buckets, referrers and user agents, and every one of them is a privacy or storage decision that should not be made by an agent on the way past. Write the Out list even when it feels obvious, and check the plan against it.

Trusting the hooks before the workspace is trusted

When I built this repo, Claude Code ignored all of .claude/settings.json, permissions and hooks, until I opened it interactively and accepted the trust dialog. Before that, a test git add -A ran; after trusting, the guard hook blocked it with “Blocked by .claude/hooks/guard-bash.mjs: stage files explicitly”. On a fresh clone, open it interactively once before running anything headless.

Checklist

  • The spec has Status approved, an Owner, a filled Out list, and Behaviour rows with concrete values, including at least two failure rows.
  • Every Definition of done item can be checked by a command or by reading one file.
  • The plan was made in plan mode (Claude Code) or in a read-only sandbox (codex exec), and nothing in src/ changed before you approved it.
  • Every task in the table has files, a command check and dependencies; tasks sharing a file run in sequence.
  • The plan respects Out of scope and adds no dependencies.
  • Each task restated its outputs before editing and showed a failing test before the code.
  • Tests use makeApp(start) and advance(ms); no real time in tests or handlers.
  • Each task ended with a three-part report with commands.
  • You mapped every Behaviour row to a test yourself, and checked every ticked box against the diff.
  • git diff main -- docs/specs/ shows only ticked boxes.
  • pnpm check is green.

In the next part we take the task table and run tasks in parallel, each in its own worktree, and route some of them to different providers.

Series

  1. Architecture and model roles
  2. Repo setup for Claude Code and Codex
  3. Spec, plan, tasks
  4. Parallel work and multiple providers
  5. CI/CD with AI review
  6. Operating it: cost, security, learning
  7. Part 7: Applying the agent workflow to a real project

The sample repo for the whole series is github.com/luonghongthuan/agentic-shortlink. Spec 0002 is the exercise on main; the reference solution is on branch solution/0002-daily-stats.

Discussion

Comments are reviewed before publication. Your email is kept private.

← Back to allĐọc tiếng Việt