13B.1 Capstone Planning and Scoping

Ship & get hiredLesson 1 of 614,979 words9 parts
Module 13B · 0 of 5 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6

Modules 02 to 12 gave you the parts — call the APIs, retrieve, ground, give tools, evaluate, observe, defend — and lessons 13A.1 to 13A.7 gave you the product lens: what to build, how it should feel, how it should be architected, how to measure it and what real products teach us. This lesson is where those pieces become one shippable product. The capstone is deliberately different from every lesson before it: there is no single concept to master, only a system to deliver. It is an integration test of everything the path taught, and it doubles as the portfolio centerpiece that Module 14B turns into career material. This lesson is the planning lesson that comes before the builds: how to choose your track, how to scope an MVP you can actually finish, how to write requirements that survive contact with reality, how to score your own work against a rubric, how to set up the repository hygiene a reviewer will judge, how to use AI coding assistants responsibly while you build, and how to work in public so the project improves while you build it. It ends with the copy-ready templates the whole module reuses, the capstone.yaml schema, and the last two files of the ai_product package: a repo scaffold generator and a scope linter you can run on your own plan.

What you'll learn

  • What the capstone is for: the integration argument, the portfolio argument, and the tracks you can pick: the required guided builds A, B and D, the elective voice build C, and bring-your-own
  • How to choose a track — a decision table covering interest, data availability, risk tier, time and what you most want to demonstrate, with different advice for freshers and for experienced switchers
  • Scoping done properly: MVP vs stretch goals, the walking skeleton, vertical slices vs horizontal layers, time-boxing with a 4-week and an 8-week plan, cutting scope without cutting evals, a per-milestone definition of done, and the warning signs of scope creep
  • Requirements that survive contact: personas, user stories and job stories, acceptance criteria expressed as eval cases, non-functional requirements (latency, cost, safety), a data and licensing plan, a risk register and an assumptions list
  • The required deliverables for every capstone (tests, an eval set, tracing, a cost report and a security checklist), what counts as evidence for each, and how they map to the rubric
  • The capstone rubric this module introduces and lessons 13B.2 to 13B.6 apply: eight criteria, four levels each, with observable evidence — plus self-assessment and peer-review instructions and what "portfolio-ready" means
  • Project hygiene: a uv project layout (single package vs workspace), the lint/type/test toolchain, .env.example, a CI skeleton, solo issue tracking, commit conventions, an ADR folder, and README and demo-script skeletons
  • How to work with AI coding assistants responsibly: what to delegate, review discipline, tests as the contract, avoiding over-reliance, checking every dependency it adds (slopsquatting), putting your rules in an instruction file, giving it the least authority, disclosing assistance, and never pasting secrets or private data into a tool
  • How to work in public: milestone demos, asking for review, interviewing three real people, and scheduling that survives a busy week
  • Seven copy-ready templates — PRD one-pager, ADR, risk register, eval plan, milestone plan, demo script, retro — each with a filled-in fictional example
  • capstone.yaml: the schema your plan lives in, ai_product/scope_check.py, which lints it, and ai_product/scaffold.py, which generates the repo skeleton from it

What you don't need

  • API keys or any provider account. Everything runnable in this lesson is pure Python 3.11+ standard library; the provider keys appear only in the .env.example file the scaffold writes for your future project.
  • The capstone builds themselves. Lessons 13B.2, 13B.3 and 13B.5 implement the three guided tracks; this lesson plans them and gives you the bring-your-own path.
  • A team, a course deadline or an employer. The templates assume one person with a few hours a week; scale the time-boxes, not the method.
  • Front-end skills. The capstone's interface work goes through the event contracts, wireframes and httpx clients the module already teaches (13A.2, 13A.5); this lesson is about the plan around them.

Setup

This lesson needs only Python 3.11 or newer and the standard library — no uv add, no .env, no services. The two ai_product files it introduces (scope_check.py, scaffold.py) are designed to run standalone:

bash
# after saving ai_product/scope_check.py and ai_product/scaffold.py side by side:
python3 ai_product/scope_check.py capstone.yaml          # lint a plan
python3 ai_product/scaffold.py --config capstone.yaml --target ./my-capstone   # generate a repo

If the ai_product/ folder does not exist yet because you skipped ahead, create it: mkdir -p ai_product. Everything else in the lesson — the templates, the rubric, the checklists — is text you copy into your own project documents.


What you must be able to do after this lesson#

  • Choose a capstone track (A, B, D, C or bring-your-own) using the decision table
  • Scope a capstone as a walking skeleton with an MVP, stretch goals and a time-boxed plan
  • Write acceptance criteria as eval cases and list the non-functional requirements
  • List the five required deliverables: tests, eval set, tracing, cost report and security checklist
  • Score your own work against the eight-criteria capstone rubric using observable evidence

Why this matters for an AI engineer#

The capstone is where the path stops being a sequence of lessons and becomes a portfolio. The skills it exercises — scoping under uncertainty, writing testable requirements, documenting decisions, shipping with evidence — are exactly the skills interviews and first jobs probe for, because they are the skills that separate someone who followed a tutorial from someone who delivered a system. Every row below is a thing you will hear in a review, an interview or a stand-up, and the section that makes it make sense:

You'll hear... You'll understand it after...
"Is this an MVP or are you gold-plating?" 2.1 MVP vs stretch
"Build the walking skeleton first." 2.2 The walking skeleton and vertical slices
"That's scope creep — park it." 2.6 Scope-creep warning signs
"Write it as a job story, not a feature list." 3.1 User stories and job stories
"Every acceptance criterion should be an eval case." 3.2 Acceptance criteria as eval cases
"What's the latency budget? The cost per task?" 3.3 Non-functional requirements
"Put it in the risk register before you build it." 3.5 The risk register
"Score it against the rubric — where's the evidence?" Part 4: The capstone rubric
"Single package or a uv workspace?" 5.1 Repository layout
"The AI wrote it — can you explain it?" Part 6: Working with AI coding assistants responsibly
"Demo it at the milestone, not just at the end." Part 7: Working in public and getting feedback
"Fill in the PRD before you write the prompt." Part 8: The templates
"Run scope_check.py on your capstone.yaml." 9.2 scope_check.py — linting the plan

Part 1: What the capstone is for#

1.1 The integration argument#

Every lesson in this path taught one thing well: one API pattern, one retrieval strategy, one agent loop, one evaluation technique. Real products do not work that way. A support copilot is simultaneously a RAG system, a tool-using agent, a streaming UX, an evaluation target, an operational service and a safety surface — and the hard parts live in the seams: the place where the retriever's output becomes the prompt, where the approval gate sits between the agent's plan and its action, where the eval set has to cover not just answer quality but citation correctness, tool discipline and refusal behaviour.

The capstone is deliberately the first time you own all the seams at once. That is why it is an integration exercise and not a bigger version of any single lesson:

  • Modules 03–05 gave you inputs: provider APIs, prompts, parsed and chunked data.
  • Modules 06–08 gave you the engine: retrieval, grounding, tools, agents.
  • Module 09 gave you the senses: vision, documents, speech.
  • Modules 10A to 12 gave you the quality system: evals, production operations, safety.
  • Lessons 13A.1–13A.7 gave you the judgement layer: what to build, how it should feel, how to architect it, how to measure it, what the case studies warn about.

A capstone that only exercises the engine — say, a chatbot that answers questions — demonstrates almost nothing the path hasn't already shown. A capstone that exercises the product — scoping, requirements, evals wired into CI, a risk register, a launch review — demonstrates the thing employers actually hire for: the ability to turn a probabilistic component into a dependable feature.

flowchart TB
    subgraph foundation ["Modules 02–05: inputs and prompts"]
        A["03 LLM APIs"] & B["04 Prompting"] & C["05 Data engineering"]
    end
    subgraph engine ["Modules 06–09: the engine"]
        D["06 Embeddings & search"] & E["07 RAG"] & F["08 Tools & agents"] & G["09 Voice & multimodal"]
    end
    subgraph quality ["Modules 10A to 12: the quality system"]
        H["10 Evaluation"] & I["11 Production & LLMOps"] & J["12 Safety & security"]
    end
    subgraph product ["Module 13A: the product layer"]
        K["13A.1–13A.7 thinking, UX,<br/>architecture, metrics, cases"] --> L["13B.1 planning & scoping"]
    end
    foundation --> engine --> quality --> L
    L --> M["13B.2–13B.5 the three builds"]
    L --> N["13B.6 ship & operate"]
    M --> O["Your portfolio centerpiece"]
    N --> O

1.2 The five tracks#

You have five ways to do the capstone. Four are guided builds with a product definition, a reference architecture and milestone plans already worked out; the fifth is yours. Capstones A, B and D are the required builds of this module. Capstone C, the voice agent, is an elective. Whichever build you work on, and whatever you bring yourself, it must ship the required deliverables of 4.6. Capstone D, a tool-using or two-agent app connected to one outside system (a ticket tool, for example), is new in this lesson's track list: its guided build is lesson 13B.4, Capstone Build D.

Track Lesson Product What it demonstrates Risk tier Keyless path
A — Support copilot (required) 13B.2 Answers customer questions with citations, drafts agent replies, looks up orders, creates tickets and issues refunds under approval, escalates to humans Grounded RAG + tools + HITL approvals + agent-assist UX — the fullest integration of Modules 07, 08, 10, 11, 12 Draft and act-with-approval Whole build runs on ScriptedModel and fixtures
B — Document intelligence (required) 13B.3 Upload documents, extract structured data with provenance, validate, human review, Q&A over the corpus Async job pipelines, schema-driven extraction, review queues, batch economics Extract and review Fixtures and a stdlib document generator cover logic; OCR/vision calls are illustrative
C — Voice agent product (elective) 13B.5 A realtime voice agent (appointment booking / order status) with tools, handoff, evals and guardrails Realtime transport, turn-taking, latency budgets, voice-specific safety Act-with-confirmation A trace-driven simulator replays audio-event timelines; only real audio needs providers
D — Tool-using or two-agent app (required) lesson 13B.4, Capstone Build D (new) An agent or a pair of agents connected to one outside system (for example a ticket tool): reads, proposes writes, and acts only after human approval Tool use with least privilege, an approval step before every write, a per-run budget and kill switch, vendor-neutral tracing, an eval gate and a security checklist Act-with-approval, reversible writes A fake of the outside system with the real API shape and a scripted model; the real service is a labelled swap
E — Bring your own this lesson + 13B.6 Any AI product you can scope, permission-free, demoable in public Everything — you write the PRD, the ADRs, the eval plan and the launch review yourself Your choice, justified in the risk register Your choice; the rubric applies unchanged

The guided tracks are not just recipes. Each one hands you a scoped product — personas, non-goals, milestones, a risk tier already thought through — which is exactly the artifact this lesson teaches you to produce for yourself. Doing a guided build well, including its planning documents, is a complete capstone. Doing a bring-your-own capstone well additionally demonstrates the scoping judgement itself — which is why the module's stretch project has you scope, build and ship an original product and score it against this lesson's rubric with evidence per criterion (the Bring-your-own capstone stretch project).

1.3 Choosing a track#

Four questions decide it. Answer them honestly — the wrong track chosen for prestige reasons is the most common capstone failure.

Question What to ask How it points
Interest Which problem do you want to think about for six weeks? Interest is the only renewable resource in a self-directed project. A boring track finished beats an exciting track abandoned at week 4.
Data availability Do you have (or can you legally make) the inputs the product needs? Support copilot: synthetic tickets + a public docs corpus. Document intelligence: you generate fictional invoices/contracts (10A.2). Voice agent: scripted call traces; real audio optional. BYO: whatever you can source without private or scraped personal data (3.4).
Risk tier What autonomy level do you want to defend? Assist/draft tracks are safest to demo publicly. Act-with-approval (A) shows the most engineering. Decide-tier (C's booking confirmations) shows the most judgement — and the most ways to go wrong publicly.
What you want to demonstrate Which module do you most want to prove mastery of? RAG+tools → A. Pipelines+extraction → B. Realtime+latency → C. Tools, agents and security → D. Breadth+judgement → E. Match the track to the story you want your portfolio to tell.

Freshers vs experienced switchers. If you are new to professional software, pick a guided track — the scoping is already done and your energy should go into execution and understanding why the scope is what it is. If you have shipped systems before, the bring-your-own track (or a guided track with deliberate modifications) demonstrates more: the scoping documents are the differentiator, and you already know how to run a project. Either way, do the planning documents for real — they are assessed by the rubric, not the code alone.

1.4 What "done" means for a capstone#

A capstone is done when it is a product, not a demo — the distinction 13A.1, Part 1 drew. Concretely, for this module that means: it runs end to end on fixtures without keys; it has an eval suite wired into CI; it has a documented risk register and launch review (12.10, applied in 13B.6); it has a README a stranger can follow; and it has a three-minute demo that shows the happy path and one honest failure. Part 4 turns that sentence into a scored rubric.

What this means for you as an engineer: the capstone's value is inversely proportional to how much of it a tutorial could have produced. Every choice you make yourself — the track, the scope cut, the risk you accepted, the eval you wrote — is the portfolio signal. Choose the track that lets you finish, then make the finishing visible.


Part 2: Scoping#

Scoping is the skill the capstone exists to teach, because it is the skill every AI project dies without. The failure mode is always the same: the plan describes the product you wish you were building, the calendar describes the product you can build, and nobody writes down which one wins. This part gives you the machinery to make them agree — on paper, before the first commit.

2.1 MVP vs stretch goals#

MVP (minimum viable product) means the smallest version that delivers the core value and can be evaluated. For an AI product there is a trap in the usual definition: "viable" can't mean "the model answers correctly", because correctness is probabilistic and you can't ship-and-see. It has to mean "the pipeline runs end to end, the eval suite measures it, and a user can complete the core job". An AI MVP without evals isn't an MVP — it's a prototype with a login screen.

The standard prioritisation vocabulary helps here:

  • Must — without it the product doesn't exist or can't be evaluated. The walking skeleton, one real user job, the eval suite, the safety floor for your risk tier.
  • Should — needed for the product to be good, not merely existent. Citations, a second persona's workflow, one degradation path.
  • Could — nice if the time-box survives. Extra document types, a second channel, analytics polish.
  • Won't (this time) — explicitly out. Written down, so "we'll add it later" doesn't silently become "we're building it now".

2.2 The walking skeleton and vertical slices#

The single most important scoping decision: build the thinnest end-to-end path first, then thicken it. Two named techniques cover this:

  • Walking skeleton (Alistair Cockburn's term, also called a tracer bullet in The Pragmatic Programmer): a tiny implementation of the whole system that touches every layer once — UI → API → orchestration → model call → storage — with the simplest possible version of each. Its job is to prove the architecture seams work before you invest in any one of them.
  • Vertical slices: each milestone delivers a thin but complete feature for one user job ("agent asks a question, gets a cited answer"), rather than a horizontal layer ("all of the retrieval", then "all of the prompting", then "all of the UI"). Vertical slices are demoable and evaluable from week one; horizontal layers produce a pile of untested components until the end.
flowchart LR
    subgraph horizontal ["Horizontal layers — the trap"]
        H1["Week 1–2: all retrieval"] --> H2["Week 3–4: all prompting"] --> H3["Week 5–6: all UI"] --> H4["Week 7+: pray it integrates"]
    end
    subgraph vertical ["Vertical slices — the capstone way"]
        V0["M0 walking skeleton:<br/>one question, one answer,<br/>end to end, fake model"] --> V1["M1 slice:<br/>grounded cited answer"] --> V2["M2 slice:<br/>+ tools with approval"] --> V3["M3 slice:<br/>+ agent-assist UX"] --> V4["M4+: safety, evals,<br/>ops, polish"]
    end

Why this matters specifically for AI products: the model is the least predictable component, and a horizontal plan finds that out in week 6 when the retrieval output turns out not to fit the prompt budget, or the tool-call format the UI assumed doesn't match what the model emits. A walking skeleton finds the seam mismatches in days, on ScriptedModel fixtures, with no API key required. Every guided build in this module is milestone-planned this way — 13B.2 starts at "M0 walking skeleton with ScriptedModel" for exactly this reason.

2.3 Time-boxing: the 4-week and 8-week plans#

A time-box is a fixed deadline that scope conforms to — the opposite of "done when it's done". For a self-directed capstone, two shapes cover most situations:

The 4-week plan (intense, ~10–15 h/week — a break, a holiday, a sprint between jobs):

Week Milestone Exit check
1 M0 walking skeleton + planning docs (PRD, ADR-0001, risk register v0) End-to-end path runs on fixtures; scope_check.py passes
2 M1 first vertical slice + eval seed (10–20 cases) Slice works on fixtures; eval suite runs in CI or locally
3 M2 the differentiating slice (tools / extraction / voice loop) + safety floor The risky part is proven, not assumed
4 M3 polish, docs, launch review, demo recording Rubric self-score ≥ the level you targeted; demo script rehearsed

The 8-week plan (sustainable, ~5–7 h/week alongside work or study):

Weeks Milestone Exit check
1–2 Planning docs + M0 walking skeleton Same as above, plus first user interviews done
3–4 M1 grounded slice + eval seed grows to 30+ cases Eval gate exists; citations/provenance visible
5–6 M2 differentiating slice + M3 second slice or safety hardening Two vertical slices demoable
7 Evals mature, CI gate live, cost/latency report Numbers you can quote in an interview
8 Docs, launch review, demo, retro, portfolio write-up Rubric self-score; README a stranger can follow

Rules that make a time-box real:

  • The deadline is fixed; the scope is variable. If week 5 slips, you cut a should-priority slice, never the eval suite or the walking skeleton's lessons.
  • One milestone = one demo-able increment. If you can't show it working, it's not a milestone, it's a task.
  • Buffer is a milestone, not a luxury. The last 15–20% of the time-box is for the unglamorous work: flaky evals, README gaps, the demo that didn't record. Plans without buffer are fantasies.

2.4 Cutting scope without cutting evals#

The most common bad cut is "we'll add evals later" — and it is always wrong, because evals are the only instrument that tells you whether a scope cut improved or degraded the product. The eval suite is the contract; the features are negotiable.

What you cut, in order of safety:

  1. "Could"-priority features — always first. A second document type, an extra channel, a nicer empty state.
  2. Breadth within a feature — three document types becomes one done well; five personas becomes two.
  3. Polish — animations, themes, extra copy variants.

What you never cut:

  • The eval suite — shrink the case count if needed (30 solid cases beat 200 thin ones, per 10A.2, Part 5), never the suite itself.
  • The failure paths — error states, the approval gate, the abstention path. These are where AI products actually differ from demos.
  • The docs — ADRs, risk register, README. They're cheaper to write during the build than to reconstruct at the end, and they're rubric criteria.

2.5 Definition of done per milestone#

A definition of done (DoD) is the checklist a milestone must pass before it counts as finished — the agile answer to "is it done?" being a matter of opinion. For AI milestones the DoD has a non-negotiable extra clause: measured, not felt.

A milestone DoD template:

markdown
## DoD — M2: tools with approvals
- [ ] Feature works end to end on fixtures (no API key needed)
- [ ] New eval cases added for this slice; suite still green
- [ ] Approval gate blocks the consequential action until approved (demo it)
- [ ] Failure path exercised once on purpose (kill the retriever, watch the UX)
- [ ] `meta`/events carry request_id + model/prompt version (11A.1 tracing fields)
- [ ] Docs updated: ADR if a decision changed, runbook note if ops changed
- [ ] Demo script section for this milestone rehearsed once

Two AI-specific additions to the usual DoD: an eval delta (the suite ran and the score is recorded, even if it's "no change") and a failure rehearsal (you deliberately broke something and watched the system degrade honestly). A milestone whose DoD is "it works on my machine, looks right" is not done; it's a claim.

2.6 Scope-creep warning signs#

Scope creep in AI projects has a distinctive flavour: it hides inside capability ("the model can probably also…") rather than requests. Watch for these:

Warning sign What it looks like The correction
"While we're in there…" A small addition that requires touching the prompt, the schema, the evals and the UI File it as a "could" item; revisit at the next milestone boundary
New persona mid-build "Teachers will also want to use this" in week 5 Personas are frozen after week 1; a new persona is a new product
"Just one more eval dimension" Accuracy + groundedness + safety + fairness + latency all at 80% depth Depth beats breadth: fully measure the two dimensions that gate launch, stub the rest
Provider feature FOMO "The new realtime API would be cool" Capabilities enter through the risk register and an ADR, not through enthusiasm
The demo drives design "It would demo better if…" Demo value is a selection criterion for scope, not a reason to expand it — write the demo script early and let it constrain, not inflate
Polish before proof Beautiful error pages for a pipeline that can't finish a request Order is fixed: skeleton → slices → evals → safety → polish. Polish is the last 10%

The scope health checklist (run it every Monday):

  • Does every in-flight task map to a "must" or "should" item in the PRD?
  • Has any milestone's DoD been met? (If not, why is new work starting?)
  • Is the eval suite green and growing (new cases from real failures)?
  • Have I said "no, park it" to anything this week? (If not, I'm probably saying yes to too much.)
  • Is the time-box on track, or do I need to cut a "could" today?

What this means for you as an engineer: scoping is not pessimism; it is the mechanism that makes finishing possible. The capstone's hardest sentence is "this will not be in v1" — say it early, write it down, and say it kindly to yourself.


Part 3: Requirements that survive contact#

A requirements document for an AI product fails in a specific way: it describes the model's behaviour ("the model should answer accurately") instead of the system's contract ("given this input, the system returns this shape, within this budget, and this is how we know it's good enough"). The fix is to write requirements the way you write eval cases — concrete, testable, and falsifiable. This part builds the six artifacts that make up a capstone's requirements pack, using the support copilot as the running example.

3.1 User stories and job stories#

User stories describe what a persona wants and why, in the classic format:

As a support agent, I want a draft reply with citations to the handbook, so that I can respond to a customer in under a minute without guessing at policy.

Three rules keep stories honest: one persona per story, one job per story, and a reason that isn't "because it's AI". A story that reads "as a user, I want to chat with AI" has no testable job — it's a feature, not a story.

Job stories (from the Jobs-to-be-Done tradition, associated with Alan Klement and Bob Moesta's work) drop the persona-as-role and focus on the situation:

When a customer emails about a delayed order, the agent wants the order status and the relevant policy in one place, so they can reply without opening three systems.

Job stories age better — "a support agent" is a role that changes; "a customer emails about a delayed order" is a situation that keeps happening. For an AI product, write both: user stories for the interface contract, job stories for the workflow reality. The classic INVEST checklist (Independent, Negotiable, Valuable, Estimable, Small, Testable) applies to both — and "Testable" for an AI feature means expressible as an eval case, which is the next section.

Worked example, support copilot:

ID Story Acceptance (eval-linked)
US-1 As a customer, I want an answer to "where is my order?" with the order status and a link to tracking, so I don't have to email twice eval: order_status_grounded — status matches fixture order; eval: citation_present — every factual claim has a source
US-2 As a support agent, I want a draft reply I can edit and send, so I save typing but keep judgement eval: draft_uses_grounded_facts — no invented order details; harness: draft_endpoint_returns_editable_text
US-3 As a support lead, I want every refund to require a named approval, so the copilot can't issue one alone harness: approval_gate_blocks_unapproved_refund — deterministic test, not an eval

Note the last row: not every acceptance criterion is a model-quality eval. Deterministic behaviour — a gate that blocks, a schema that validates, an idempotency key that dedupes — is tested with ordinary unit tests (01B.8). The eval suite covers the probabilistic parts; pytest covers the deterministic ones. Confusing the two is the most common requirements mistake in AI projects.

3.2 Acceptance criteria as eval cases#

The bridge between product requirements and evaluation is 10A.2's EvalExample: every acceptance criterion that depends on model behaviour should map to one or more eval cases. The mapping looks like this:

json
{"example_id": "US1-order-status-001", "inputs": {"question": "where is my order A-1042?", "order_fixture": "orders.jsonl#A-1042"}, "expected": {"must_contain": ["shipped"], "must_cite": true, "must_not_claim": ["delivered"]}, "split": "test", "tags": {"story": "us-1", "source": "capstone-acceptance"}, "difficulty": "easy", "language": "en", "rubric": [], "provenance": {"source": "expert", "recorded_by": "capstone-acceptance", "created_at": "2026-11-07", "pii_reviewed": true, "notes": "seeded from acceptance criteria"}, "notes": "US-1: status must match fixture; invented delivery claims fail"}

Every field validates against EvalExample's extra="forbid" schema: tags is a dict of slice dimensions (not a list), rubric is a list of criterion dicts (empty here — deterministic expectations live in expected), and provenance is the nested audit object, matching the shape 13A.3's feedback exporter emits. Note the seam before you wire it up: this file is consumed by evalkit.dataset.load_dataset (10A.2, 8.2), while the CI runner — evalkit.cli run in 10A.8, 6.1 — deliberately reads a smaller {"id", "input", "tags"} format. Your app's adapter is where the two meet; 5.4 shows the CI side and 9.3 seeds both files.

Three disciplines make this work:

  • One criterion, one or more cases. "Answers with citations" isn't one case — it's a slice of cases across question types (status lookup, policy question, complaint, ambiguous request). 10A.2, Part 3 owns case design; your job is to seed it from acceptance criteria so coverage is traceable.
  • Traceability is bidirectional. Every eval case should name the story it serves (tags: {"story": "us-1", "source": "capstone-acceptance"}, provenance.source: "expert"); every story's acceptance criteria should name its cases. When an eval fails in CI, you should be able to answer "which user promise did we just break?" in one lookup.
  • Negative criteria count. "Must not invent an order status" is as much an acceptance criterion as "must cite sources" — write the must_not_claim cases deliberately (10A.2, 3.4 covers should-not cases).

3.3 Non-functional requirements: latency, cost, safety#

Functional requirements say what the system does; non-functional requirements (NFRs) say how well it must do it. For an AI product the three that gate launch are:

NFR What to write Where the numbers come from
Latency A budget per interaction type, not one number: e.g. "first token ≤ 2 s p95 for chat; full answer ≤ 15 s p95; tool-using turn ≤ 30 s p95" 13A.2's latency budgets per feature type; measure on fixtures, report percentiles (13A.6's metrics.py)
Cost Cost per task/session ceiling, e.g. "≤ $0.04 per resolved ticket at expected volume" 13A.6's unit-economics calculator with the price tables from 02.9/03.7; include retries and human-review cost
Safety The autonomy tier and its required controls: "draft-with-approval for refunds; injection defences on retrieved content; PII redaction in logs" 13A.1's risk tiers; 12.1's risk classes

Write NFRs as budgets with a measurement plan, not aspirations: "p95 first-token ≤ 2 s, measured over the eval run on fixtures, reported in the launch review". An NFR you can't measure isn't a requirement — it's a hope. The support copilot example: latency p95 ≤ 8 s for a grounded answer (retrieval + generation), cost ≤ $0.05 per answer at fixture volume, safety tier "draft + act-with-approval" with the approval gate as the control.

3.4 Data and licensing plan#

Every capstone needs a one-paragraph answer to "where does the data come from, and may we use it?" The rules are strict because the failure is catastrophic for a portfolio piece:

  • Never use private, scraped or personal data. No real customer tickets, no scraped reviews, no "anonymised" datasets you can't prove are anonymous. The plan rule is absolute: fixtures you generate or licence-clean public data only.
  • Public datasets: check the licence before use — CC-BY, CC0, MIT, Apache-2.0 are workable; "for research only" and custom restrictive licences are not. 10A.2, 2.6 and 10A.2, 9.4 own the detail.
  • Synthetic data is usually the right answer for capstones: fictional companies, fictional customers, fictional documents. 10A.2 gives you the generation pipeline; the support copilot's ticket corpus and the document app's invoices are both synthetic by design.
  • Generated-by-a-model data carries the licence of the model terms — check the provider's terms for whether outputs can be used to build datasets (they generally can for your own use, but verify as of November 2026 and record what you checked).

The plan artifact is short: sources, licence per source, volume, freshness, and the "no personal data" attestation. If a stakeholder (or interviewer) asks "where did your data come from?", the answer should take ten seconds.

3.5 The risk register#

A risk register is the project-management artefact security teams borrowed: a table of things that could go wrong, each with likelihood, impact, mitigation and owner. For an AI capstone it does double duty — it's both your project risk list ("I might run out of time") and your product risk list ("the model might invent a refund policy").

12.1's threat modelling owns the security depth — STRIDE, OWASP LLM Top 10, the lethal trifecta; your register should link to that analysis for the security rows rather than duplicate it. The register's schema:

ID Risk Likelihood Impact Mitigation Owner Status
R1 Retrieved ticket contains prompt injection Medium High Input guard + tool policy layer (12.2, 12.6) self open
R2 Model invents order status High Medium Grounding requirement + citation eval + abstention path self open
R3 Time-box slips on voice latency tuning Medium Medium Cut "could" slices first; simulator covers logic keyless self open
R4 Eval set too small to detect regressions Medium High Seed from acceptance criteria; grow from production-style failures self open

Two disciplines: every risk gets a mitigation or an explicit acceptance ("we accept R3 because the simulator covers the logic; real-audio polish is a stretch goal"), and the register is reviewed at every milestone — a risk that was "low" in week 1 and is biting in week 5 gets its mitigation upgraded, not its likelihood re-labelled.

3.6 The assumptions list#

The humblest and most useful artefact: a list of everything you're assuming rather than knowing, each with how you'd check it. Examples for the support copilot:

  • "The docs_qa retriever returns relevant handbook chunks for support questions" → check: run 10 fixture questions, eyeball top-3 hits in week 1.
  • "ScriptedModel fixtures are enough to develop the UX" → check: yes for logic; no for latency/quality feel — schedule one real-provider smoke test late.
  • "A single persona (support agent) is enough for the MVP" → check: user interview in week 1–2 confirms or kills it.
  • "The provider's structured-output subset supports our extraction schema" → check: schema lint against 03.4's subset tables before building on it.

Assumptions are where plans go to die quietly; listing them is how you find the bodies early. Review them at each milestone alongside the risk register — an assumption validated is a risk retired; an assumption falsified is a scope conversation.

What this means for you as an engineer: requirements for an AI product are a contract between the probabilistic and the deterministic. Stories say what users need; eval cases say how you'll know the model part works; NFRs say how well; the data plan says what you're allowed to touch; the risk register and assumptions say what could invalidate all of it. Write all six before the first commit — they take a day and save a month.


Part 4: The capstone rubric#

4.1 Why a rubric#

A rubric converts "is this good?" — a question everyone answers differently — into "which level is this, and what evidence puts it there?". For the capstone it does three jobs:

  • Self-assessment during the build: at each milestone, score honestly and the gaps tell you what to work on next. A rubric is a diagnostic, not a verdict.
  • Peer review: when someone else reviews your capstone (or you review a classmate's), the rubric is the shared vocabulary — "you're at L2 on safety evidence, here's what L3 looks like" beats "it's pretty good".
  • Portfolio signal for Module 14B: Module 14B's portfolio strategy tells you to show evidence; the rubric's levels are designed so each one names the evidence a reviewer can check. A capstone scored honestly at L3 with receipts is worth more than a claimed L4 with none.

This lesson introduces the rubric; 13B.2–13B.6 apply it at each build's end, and 13B.6 runs the final self-assessment.

4.2 The eight criteria#

# Criterion What it covers
1 Functionality The product does the job the PRD promised, end to end, for the personas it named
2 Quality and evals An eval suite exists, is wired into CI, covers the acceptance criteria, and its scores are reported honestly
3 UX The interface follows the module's patterns: streaming/smoothing, trust and disclosure, failure states, accessibility
4 Architecture Clean layering (ports/adapters), the right patterns for the product shape, ADRs for significant decisions, no scattered provider calls
5 Safety and security Risk register acted on: injection defences, PII handling, approval gates, permission boundaries — proportionate to the risk tier
6 Operations and cost Tracing, runbook, cost/latency numbers, a launch review, a kill switch or equivalent — the "3 a.m. test" from 11C.4
7 Documentation README a stranger can follow, PRD, ADRs, eval report, system card (12.9), demo script
8 Demo A rehearsed demo that shows the product working and one honest failure — the difference between a demo and a claim

4.3 The four levels#

The scale is deliberately criterion-relative: "L3" doesn't mean the same absolute quality everywhere, it means the evidence expected at that level for that criterion. Score each criterion independently — a capstone can be L4 on documentation and L2 on UX, and the profile is more informative than a single average.

Criterion L1 — Foundation L2 — Competent L3 — Proficient L4 — Exemplary
Functionality Core job works on the happy path, fixtures only Works on fixtures and edge cases from the risk register Works across personas/slices; degrades honestly on out-of-scope input Handles the messy reality: ambiguous, adversarial and off-distribution inputs with designed responses
Quality and evals Eval suite exists, run manually Suite in CI; covers acceptance criteria; scores reported Suite slices by persona/difficulty; regression gate blocks bad merges; failure-driven cases added Eval-driven development visible: cases grew from real failures; judge calibrated; online-vs-offline split considered
UX Functional interface, errors shown Streaming + failure states handled; copy is honest Follows 13A.2–13A.4 patterns: smoothing, disclosure, abstention UX, a11y checklist applied UX decisions defended with reasoning; accessibility verified; failure gallery exercised in the demo
Architecture Works; structure incidental Layered; provider behind a port; prompts not hard-coded in handlers ADRs for key decisions; jobs/idempotency where needed; multi-tenant or scoped data model Architecture choices justified against alternatives; seams tested with fakes; extensible without rewrites
Safety and security Risk register exists; obvious controls present Tier-appropriate controls implemented (approvals, injection guards, redaction) Controls tested (red-team pass on own app); residual risks documented Threat model walked; security requirements traced to tests; disclosure/recourse designed
Operations and cost App runs; logs exist Tracing + basic metrics; cost per task estimated SLO-ish budgets measured; runbook exists; launch review done Cost optimised with levers justified; incident drill performed; deprecation/upgrade plan noted
Documentation README exists README + PRD + at least one ADR Full set: PRD, ADRs, eval report, system card, runbook Docs a stranger could onboard from; decisions traceable; honest limitations stated
Demo Demo exists Rehearsed; shows happy path Shows happy path and a designed failure; recorded fallback exists Demo tells the product story; Q&A anticipated; links to evals and docs

How to score: for each criterion, pick the level whose evidence you can actually show — not the level you aspire to. Write one line of evidence per criterion ("L3 quality: evals/cases.jsonl has 42 cases, CI gate eval_gate fails PRs below baseline"). The evidence lines are what make the score credible to a reviewer — and to yourself at 11 p.m. in week 7.

4.4 Self-assessment and peer review#

Self-assessment cadence: score once at the end of the walking-skeleton milestone (mostly L1 everywhere — that's expected and fine), again mid-build, and finally before the demo. The mid-build score is the useful one: it tells you which criterion is your bottleneck while there's still time to fix it.

Peer review instructions (for a classmate, a colleague or a future you in three months):

  1. Read the PRD and the risk register first — judge the product against its own promises, not your taste.
  2. Run the eval suite and the demo script yourself; don't take the README's word.
  3. Score each criterion independently, writing the evidence line before the level.
  4. Flag any criterion where evidence and level disagree — that's where the interesting conversation is.
  5. End with the two highest-leverage improvements, not a list of nitpicks.

A useful calibration trick: score someone else's work first — a classmate's capstone, or any public portfolio repository whose README makes claims you can check — before scoring your own, so your standards are anchored to the descriptors, not to your hopes.

4.5 What "portfolio-ready" means#

A capstone is portfolio-ready when:

  • Every criterion is L2 or above — the product demonstrably works and is documented.
  • At least three criteria are L3+ — and they're the ones that tell your story (for most builds: quality/evals, safety, and demo or operations).
  • No criterion is L1 at submission — an L1 anywhere means a hole a reviewer will find; fix it or document why it's out of scope.
  • The evidence lines exist for every score — a rubric score without evidence is a vibe.
  • The repo is keyless-runnable: a stranger can clone it, run the evals on fixtures, and watch the demo path work without any API key. This is the capstone's superpower — most portfolios can't offer it.

"Portfolio-ready" is not "perfect". It is honest, evidenced and finished — which is rarer and more impressive.

What this means for you as an engineer: the rubric is the contract between your effort and your self-knowledge. Score early, score honestly, and let the gaps — not the grades — drive the last three weeks.

4.6 Required deliverables for every capstone#

Every capstone ships five deliverables, whichever build you chose and whether it is guided or your own. They are not extra credit. The rubric criteria above can only be scored with them (a "Quality and evals" level needs an eval set, an "Operations and cost" level needs tracing and a cost report, a "Safety and security" level needs a checklist), and the launch review in 13B.6, Part 1 asks for the evidence of each.

Deliverable Minimum to count Evidence a stranger can check Rubric criteria it feeds Where it is taught
Tests Unit tests for the deterministic parts (validators, gates, budgets, parsers) that run with no key and no network One command (pytest or python3 -m unittest) passes in CI 1 Functionality, 4 Architecture 10A.8, 03.10
Eval set At least a small labelled set that includes the hard and the hostile cases, run by a gate that can fail the build The eval command prints metrics and a pass or fail, and exits non-zero on failure 2 Quality and evals 10A.1, 10A.2, and the framework track from 10B.1
Tracing Vendor-neutral spans for each model call and tool call, with ids, counts and outcomes, and no secrets or customer text A readable trace of one full run (a tree or a JSON lines file) 6 Operations and cost 03.12, 11A.1
Cost report Cost per task (not per call) from recorded token usage, with the price table and its date A table or script output, and the pricing page date 6 Operations and cost 03.7, 11B.1, 13A.6
Security checklist Prompt injection, least privilege and tool misuse (or data and upload risks, for non-agent builds), each row with a control and a proof A checklist file where every row names a control, the code that implements it and the test or trace that proves it 5 Safety and security 12.1, 12.2, 12.6, 12.10

Rules that apply to all five:

  • The eval gate uses DeepEval by default. evalkit from 10A.10 is accepted as an alternative. Inspect AI is an optional extra for Capstone D. Whichever you use, keep a framework-neutral gate as well (plain metrics and an exit code), so the gate does not depend on one library.
  • Tracing is vendor-neutral. A hosted platform may sit on top, but the spans must exist in your own format first.
  • Keyless first. All five run on fakes, so a stranger can clone the repo and check them with no API key. Real-model runs are labelled and recorded separately.
  • Honest numbers. A small eval set gives smoke tests, not measurements. Say how many cases you have next to every percentage.

The three required guided builds show the five deliverables on worked examples: the support copilot (13B.2), DocIntel (13B.3) and Capstone D, the tool-using or two-agent app with one outside system (lesson 13B.4). Capstone D is the one that shows all five in the smallest space, including a per-run budget, a kill switch and an approval step before any write.

Required deliverables checklist (copy it into your plan document):

  • Tests run in CI with no key (command named).
  • Eval set committed, gate wired into CI, gate proven to fail once (how many cases).
  • Tracing on every model and tool call, one trace saved, no secrets or customer text.
  • Cost report with price table date and cost per task.
  • Security checklist with a control and a proof per row.

Part 5: Project hygiene#

Deep-dive

The difference between a hobby repo and a portfolio repo is mostly hygiene: a layout a stranger can navigate, a toolchain that catches your mistakes before a reviewer does, secrets that can't leak, CI that proves the claims your README makes, and documents that explain why you built what you built. None of this is AI-specific — it's professional software practice applied to an AI product — but AI projects fail hygiene in characteristic ways (keys in prompts, eval data committed carelessly, "works on my machine" model calls). This part is the checklist.

5.1 Repository layout: single package vs workspace#

Two shapes cover every capstone:

Single package — one pyproject.toml, one importable package, everything inside. Right for ~90% of capstones, including all three guided builds.

text
support-copilot/
├── pyproject.toml
├── .env.example
├── .gitignore
├── README.md
├── capstone.yaml
├── src/
│   └── support_copilot/
│       ├── __init__.py
│       ├── app.py          # FastAPI wiring
│       ├── orchestrator.py
│       └── ...
├── ai_product/             # the module's shared toolkit, vendored or path-dep
├── evals/
│   └── cases.jsonl
├── docs/
│   ├── prd.md
│   ├── risk-register.md
│   └── adr/
│       ├── 0001-use-uv-and-fastapi.md
│       └── 0002-...md
└── tests/

uv workspace — when your capstone genuinely has two+ packages (e.g. the product app plus a shared evals/core library you want installable separately). uv's workspace support is real and stable as of November 2026: a root pyproject.toml declares members and a single shared lockfile keeps every member on consistent dependencies.

toml
# pyproject.toml (workspace root)
[project]
name = "capstone"
version = "0.1.0"
requires-python = ">=3.11"
dependencies = ["support-copilot", "evals"]

[tool.uv.sources]
support-copilot = { workspace = true }
evals = { workspace = true }

[tool.uv.workspace]
members = ["packages/*"]
exclude = ["packages/seeds"]

Each member is an ordinary project with its own pyproject.toml; uv run --package support-copilot ... runs a command inside that member, and uv lock/uv sync operate on the whole workspace at once. Workspace member dependencies are editable — changes in packages/evals are live in the app without reinstalling.

Decision rule: start single-package. Convert to a workspace only when you can name the second package and why it must be separately versioned — "it feels cleaner" is not a reason; uv workspaces solve dependency unification, not aesthetics. For a one-person capstone the honest answer is almost always single package, and 13B.1's scaffold.py generates that shape.

5.2 The toolchain: lint, types, tests, pre-commit#

A reviewer (or CI) should be able to run one command and know the code is mechanically sound. The standard Python toolchain as of November 2026:

Tool Job Package to add
ruff Lint + format in one fast tool ruff
mypy or pyright/basedpyright Static type checking mypy, pyright
pytest Unit + integration tests pytest (as in 01B.8)
pre-commit Run the checks on every commit pre-commit

A minimal pyproject.toml tool section:

toml
[dependency-groups]
dev = ["ruff", "mypy", "pytest", "pre-commit"]

[tool.ruff]
line-length = 100
target-version = "py311"

[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "SIM"]

[tool.mypy]
python_version = "3.11"
strict = true

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q"

And .pre-commit-config.yaml:

yaml
repos:
  - repo: https://github.com/astral-sh/ruff-pre-commit
    rev: v0.17.4
    hooks:
      - id: ruff
      - id: ruff-format
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v6.0.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: detect-private-key   # never commit a key, even by accident

Two notes on the file. uv add --dev ruff mypy pytest pre-commit writes the newest release of each into pyproject.toml as a lower bound such as ruff>=0.17.4, so a file you generate yourself will show bounds where the listing above shows bare names. And rev: is the one place a version stays: pre-commit needs a git tag to fetch each hook repository, and pre-commit autoupdate moves the tags forward.

Two capstone-specific rules: detect-private-key is non-negotiable — it's the cheapest defence against the classic "pasted a real key into .env.example" portfolio disaster; and type-check your ports, not your prompts — strict = true on the seams (ModelPort, RetrieverPort from 13A.5) catches integration bugs that no eval will.

5.3 Secrets and .env.example#

The rules, in order of importance:

  1. Never commit .env or any real key. .gitignore gets .env, .env.local, *.pem, secrets/ on line one — before you write a single feature.
  2. .env.example documents the shape of configuration, never values. Placeholder text only:
bash
# .env.example — copy to .env and fill in. NEVER commit .env.
OPENAI_API_KEY=sk-...          # optional: only needed for live provider calls
ANTHROPIC_API_KEY=sk-ant-...
GEMINI_API_KEY=...
OPENROUTER_API_KEY=...
# The capstone must run keyless on fixtures; keys are for the optional live path.
SCRIPTED_MODEL=1               # set to 0 to use real providers
  1. Load keys the way 01B.2 taught: python-dotenv + pydantic-settings, never os.environ["KEY"] scattered through handlers.
  2. The keyless path is a feature, not a fallback: your README's quickstart should work with zero secrets. That's what makes the portfolio reproducible — and it's why SCRIPTED_MODEL=1 exists.

5.4 CI skeleton#

Continuous integration for an AI capstone has three tiers, mapped to 11C.2's test pyramid:

yaml
# .github/workflows/ci.yml — skeleton; see 11C.2 for the full eval-gate machinery
name: ci
on: [push, pull_request]
jobs:
  fast:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/setup-uv@v10.3.3
      - run: uv sync --all-groups
      - run: uv run ruff check . && uv run ruff format --check .
      - run: uv run mypy src tests
      - run: uv run pytest tests/ -x        # deterministic tests only — no network, no keys
  evals:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: astral-sh/setup-uv@v10.3.3
      - run: uv sync --all-groups
      # evalkit.cli is the Module 10A runner wrapper (10A.8 §6.1). --task/--scorer
      # are module:function imports your app supplies in app/evals.py — that
      # adapter owns the fixture model and the graders, so this job needs no
      # keys. Case files are {"id","input","tags"} JSONL — the runner's contract,
      # NOT the EvalExample schema of evals/cases.jsonl.
      - run: uv run python -m evalkit.cli run --cases evals/ci_cases.jsonl --task app.evals:call_model --scorer app.evals:score --out runs/ci --model scripted-fixture

The critical property: the fast job must pass with no secrets and no network — that's what makes it trustworthy. The evals job runs the evalkit runner against ScriptedModel fixtures by default — note it reads evals/ci_cases.jsonl, the runner's {"id", "input", "tags"} format, not evals/cases.jsonl: the EvalExample dataset feeds evalkit.dataset and judge calibration, while app/evals.py is the adapter that bridges the two (the seam 10A.8, 6.1 describes, and 9.3 seeds both files). Live-provider evals are a separate, manually-triggered workflow (11C.2, 4.2 covers the safe-PR pattern). If your CI needs a key to go green, it isn't a CI gate — it's a demo.

5.5 Solo workflow: issues, commits, ADRs#

Working alone doesn't mean working without process — it means the process is your documentation.

  • Issue/kanban board: GitHub Issues + Projects (or a plain TODO.md if you prefer zero ceremony). One card per milestone task and per parked "could" item — the parked items are your scope-creep defence (2.6).
  • Commit conventions: Conventional Commits (feat:, fix:, docs:, eval:, chore:) — the eval: type is worth inventing for eval-set changes so git log --grep=eval: shows your quality history. Small commits, one logical change each; the history is part of the portfolio.
  • ADRs: Michael Nygard's 2011 post coined the format — Context, Decision, Status, Consequences. For a capstone you need maybe 3–6 ADRs: the big ones are "single package vs workspace", "ScriptedModel-first development", "approval-gate placement", "eval harness choice". 13A.5 teaches ADRs and the C4 model; Part 8.2 gives you the template.
  • Branches: feature branches per milestone (m1-grounded-answers), merged when the milestone DoD passes. Solo doesn't mean trunk-only — the branches are how you keep "working on M2" from breaking "M1 still demoable".

5.6 README and demo-script skeletons#

Two documents deserve their own skeletons because reviewers read them first:

README (the 10-minute test — Part 8 has the full template): what it is, a screenshot or ASCII demo, quickstart that works keyless, architecture diagram, eval results table, limitations, links to PRD/ADRs/runbook. The single most important line: "Runs with no API keys on fixtures; set SCRIPTED_MODEL=0 and add keys for live providers."

Demo script: three minutes, written before the demo, structured as hook → working feature → designed failure → evidence (evals, cost, latency) → close. 13B.6 owns the full demo craft; the skeleton is in 8.6.

What this means for you as an engineer: hygiene is the difference between "a project I built" and "a product I shipped". A stranger should be able to clone your repo at 11 p.m., run the tests with no keys, read the README, and understand what you built and why — that stranger is often the interviewer.


Part 6: Working with AI coding assistants responsibly#

Deep-dive

You have spent twelve modules learning to build AI systems; now you will spend six weeks building one with an AI coding assistant — probably the same models you studied. That is not cheating; it is the actual job. But it changes what the capstone demonstrates, and how you must work to keep the demonstration honest.

6.1 What to delegate, and what to keep#

The delegation boundary that works:

Delegate freely Keep for yourself
Boilerplate: project scaffolding, dataclass shapes, test fixtures, CI YAML Architecture decisions (which pattern, which port boundary) — these are ADRs and rubric evidence
Mechanical refactors, renaming, import fixes Eval case design — the cases are the product spec; a generated eval set grades the generator's assumptions, not yours
Writing docs from your notes (README drafts, ADR prose) Requirements and scoping — PRD, user stories, risk register. If the assistant writes them, they're the assistant's product, not yours
Explaining error messages, suggesting fixes for failing tests Security review of tool/agent boundaries — the lethal-trifecta reasoning (12.1, 08A.14) is judgement you must own
First drafts of prompts (then you iterate against evals) Prompt decisions — what the system is allowed to do, what it must refuse, what it must cite

The test for any task: if a reviewer asked "why did you build it this way?", could you answer without the assistant? If not, it's your task, not a delegation.

6.2 Review discipline and tests as the contract#

AI-generated code fails differently from human code: it's plausible — right-looking imports, sensible names, comments that explain what it thinks it's doing — and subtly wrong in ways that compile. The defences, all covered earlier in the path:

  • Tests are the contract: the assistant writes against your tests, not its own judgement. Write or review the failing test first (08A.15's verification-loop discipline), then let it implement. Never accept generated code that has no test proving the behaviour.
  • Review every diff like a stranger wrote it — because functionally, one did. Check: does it handle the error path, does it leak a secret, does it make a network call in a test, does it match the port interface you defined.
  • Pin what it produces: generated lockfiles, schemas and fixtures get reviewed like code; a plausible-looking cases.jsonl with invented field names is a portfolio bug waiting for a reviewer to find.
  • Git hygiene applies to agents too: the assistant's work lands on your milestone branch, in small commits, so you can revert a bad generation without losing the good (08A.15, 5.3).
  • Verify every dependency it adds. Assistants sometimes recommend packages that do not exist; attackers can register those invented names with malicious code, an attack called slopsquatting (measured across 16 models in the USENIX Security 2025 paper "We Have a Package for You!"; newer models may behave differently, so treat the exact rates as dated). Before uv add, open the package's PyPI page, check the project link, release history and that the name is the one you meant, then pin the version. 12.7's supply-chain material owns the depth.
  • Write the rules down where the assistant reads them. Most coding assistants read a repository instruction file (AGENTS.md is an open convention several tools share; Claude Code reads CLAUDE.md). Put the commands that run the tests and linter, the "no network in tests" rule, the ScriptedModel-first rule and the ban on committing .env there — it is the cheapest way to make the assistant follow your port boundaries, and it becomes part of your documentation evidence.
  • Give it the least authority that works. Run it on a milestone branch in your project folder, not with production credentials, deploy keys or a real .env in reach; approve destructive shell commands one at a time. This is the same lesson as the Replit case in 13A.7, 4.1: a rule in a prompt is not a control, so keep the credentials out of reach rather than asking the tool not to use them.

6.3 Over-reliance, disclosure and the portfolio#

Three honesty rules:

  1. You must be able to explain every line in your repo. Not "the assistant wrote it" — why it's there, what it does, what breaks if it's wrong. The capstone interview will probe exactly this; a repo you can't explain is a liability, not a shortcut. If you can't explain a section, delete it or learn it before submission.
  2. Disclose assistance where appropriate. A short note in the README or a NOTICE/AI_ASSISTANCE.md file ("built with AI coding assistance; all design decisions and eval cases authored and reviewed by the maintainer") is honest, increasingly normal, and signals maturity rather than weakness. Some employers and academic contexts require disclosure — check yours; the repo itself should never pretend the assistance didn't happen.
  3. Never paste secrets or private data into a tool. No .env contents, no real customer data, no private documents — into any chat, agent or coding tool, ever (12.4 owns the data rules; the path's ground rules make it absolute). The fixtures you feed an assistant are the same licence-clean data your product uses — nothing more.

6.4 What this means for you as an engineer#

Working with AI assistants well is itself a capstone skill — it's the job. The discipline that transfers to employment: delegate the mechanical, own the judgement, test everything, explain everything, disclose honestly. The assistant is a very fast junior engineer who never sleeps and occasionally invents APIs — treat it exactly that way.


Part 7: Working in public and getting feedback#

Deep-dive

A capstone built in secret is a capstone half-finished. Working in public — milestone demos, review requests, user interviews — is how the project improves and how you build the feedback muscle employers test for. It also de-risks the final stretch: feedback arrives during the build, not after.

7.1 Milestone demos#

A milestone demo is a 5–10 minute showing of one working slice — not a status report. The format that works:

  • Show, don't tell: the live (or recorded) path — "watch the agent ask, retrieve, cite, draft" — beats a slide about what it will do.
  • Include one failure: "and when retrieval finds nothing, here's what the user sees" demonstrates the failure-state work that separates products from demos (13A.4).
  • Record a fallback: live demos fail; a screen recording of the same path is your insurance (13B.6 covers demo craft).
  • End with the numbers: eval score, cost per task, latency — the metrics from 13A.6 make the demo evidence, not theatre.

Cadence: demo at M0 (the skeleton — unglamorous but proves the seams), at each vertical slice, and at the launch review. Three demos beat one grand finale.

7.2 Asking for review#

Specific asks get specific help. "Thoughts?" gets none. The pattern:

  • Ask for the thing you need: "Does the approval-gate UX make the authority boundary clear?" not "review my app".
  • Give context in one paragraph: what it does, who it's for, what you've tried, where you're stuck.
  • Make it easy to answer: a link to the running fixture path, a specific file or screen, a bounded question.
  • Return the favour: review someone else's capstone or PR with the same specificity — the rubric's peer-review instructions (4.4) are the shared vocabulary.

Where: your course/community channel if you're studying; a public repo's issues/discussions if working in public; a colleague if employed. Async written feedback is fine and often better than synchronous — it forces specificity.

7.3 User interviews with three real people#

The cheapest UX research in the course: three real people using your fixture-driven product. Not five — three is enough to find the big problems; more mostly repeats them.

  • Recruit for the persona, not for enthusiasm: a support agent, a document reviewer, a caller — whoever your PRD named. Friends who "kind of do support" count; friends who don't count less.
  • Give them a task, not a tour: "answer this customer question using the tool" beats "explore the app". Watch where they hesitate, what they misread, what they try that isn't there.
  • Ask about the job, not the AI: "how do you handle this today?" reveals whether your product solves a real workflow — the question 13A.1's framing asks at the start and you re-ask with evidence at the end.
  • Consent and privacy: get permission to observe and note; don't record screens or voices without it; anonymise anything you quote in docs (12.4).
  • Synthesize to changes, not opinions: three interviews produce patterns ("all three missed the citation affordance") and outliers ("one wanted dark mode"). Act on patterns; log outliers as "could" items.

The deliverable is one page: what you asked, what three people did, the three changes it caused. That page is rubric evidence and interview material.

7.4 Scheduling and momentum#

Self-directed projects die of drift, not difficulty. The anti-drift system:

  • A fixed weekly slot in your calendar — same day, same time, protected. Two 3-hour slots beat seven scattered hours for deep work.
  • A public deadline: tell someone (or post) the date you'll demo. Social commitment is the cheapest accountability mechanism there is.
  • Weekly review, ten minutes: last week's exit check met? This week's milestone clear? Any assumption falsified, any risk escalated? Update capstone.yaml and the kanban — the planning docs are living, not tombstones.
  • The kill/reframe checkpoint: at the midpoint, re-run 13A.1's kill criteria honestly. Continuing a failing capstone is as bad a decision as killing a good one early — but you can only make it if you scheduled the checkpoint.

What this means for you as an engineer: working in public is a forcing function — demos expose unfinished seams, reviews expose wrong assumptions, interviews expose imaginary users. The capstone that survives contact with three real people and one honest reviewer is the one worth putting in a portfolio.


Part 8: The templates in full#

Reference

Seven documents, each copy-ready. The rule for all of them: the blank template is what you copy; the filled example shows what "done" looks like — every example uses the fictional support copilot from 13B.2. Keep these in docs/ in your repo; they are rubric criteria (documentation) and interview evidence.

8.1 PRD one-pager#

markdown
# PRD: <product name> — one page

**Track:** guided-a | guided-b | guided-c | byo     **Time-box:** <4|8> weeks     **Risk tier:** assist | draft | act-with-approval | decide

## Problem
<One paragraph: the job-to-be-done and the pain today. No AI mention needed yet.>

## Users
- **<persona>:** <goal, context, what they do today instead>

## What it does (must)
1. <user story US-1, one line>
2. <US-2>

## What it must not do (non-goals)
- <explicit exclusions — these are scope-creep armour>

## How we'll know it works
- Eval cases: <N cases covering US-1..k, in evals/cases.jsonl>
- Deterministic tests: <the pytest-covered behaviours>
- NFRs: latency p95 <X ms>, cost/task <$Y>, safety tier <tier>

## Data & licences
<sources, licence per source, "no personal/private data" attestation>

## Risks (top 3)
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|

## Milestones
M0 skeleton → M1..Mn slices → launch review. See docs/milestones.md.

## Kill criteria
<the conditions under which you'd stop or reframe — from 13A.1 Part 6>

Filled example (abridged): Track guided-a, 6 weeks, tier draft-with-approval. Problem: support agents answer ~40 repetitive order-status emails/day from memory, getting policy details wrong. Users: support agent (draft replies), support lead (approve or reject staged refunds). Must: grounded answers with citations, editable drafts, order lookup, ticket creation, refund-under-approval, human escalation. Non-goals: no phone channel, no proactive outreach, no autonomous refunds, no real customer data. Evals: 30 cases seeded from US-1..US-5. NFRs: p95 answer ≤ 8 s, ≤ $0.05/task. Data: synthetic tickets + public handbook, CC-BY. Risks: injection via retrieved ticket (med/high → guard+policy), invented order status (high/med → grounding eval + abstention), scope slip (med/med → cut "could" slices). Kill: if grounded-answer eval < 70% at week 4 with no clear fix path, reframe to assist-only.

8.2 ADR#

markdown
# ADR NNNN: <short decision title>

- Status: proposed | accepted | deprecated | superseded by ADR-XXXX
- Date: YYYY-MM-DD

## Context
<The forces at play — technical, product, time. Facts, not justification yet.>

## Decision
<The choice, in full sentences: "We will ..." >

## Alternatives considered
- <option A>: <why not>
- <option B>: <why not>

## Consequences
<What this makes easier/harder. Include the negative ones — an ADR with only
upsides is marketing, not architecture.>

Filled example: docs/adr/0002-approval-gate-placement.md — Context: refunds are the highest-impact tool action; the agent loop (08) supports pre-tool hooks and the product layer (13A.3) has an ApprovalGate state machine. Decision: enforce approval in the orchestrator before dispatch — the gate wraps ToolRegistry.dispatch, not the provider call — so every consequential tool shares one choke point and the audit trail is complete. Alternatives: approval inside each tool (duplicates logic, misses future tools); approval in the UI only (bypassable, no server-side guarantee). Consequences: +one latency hop on gated calls; −agents can't self-approve by construction; the gate becomes a tested seam.

8.3 Risk register#

markdown
# Risk register — <product> — updated <date>

| ID | Risk | Category | Likelihood | Impact | Mitigation | Owner | Status |
|---|---|---|---|---|---|---|---|
| R1 | <what could go wrong> | product | low/med/high | low/med/high | <control or accepted risk> | self | open/mitigated/accepted |

Categories: product (scope, quality, time), model (hallucination, drift, refusal), security (injection, PII, tool abuse — link 12.1), ops (cost, latency, provider outage), data (licence, coverage, drift). Filled: see the table in 3.5 — three rows minimum, reviewed at every milestone.

8.4 Eval plan#

markdown
# Eval plan — <product>

## Suites
| Suite | What it measures | Cases | Runner | Gate |
|---|---|---|---|---|
| core | acceptance criteria per story | ~30 | evalkit + ScriptedModel | CI |
| safety | injection, refusal, PII | ~10 | llm_guard_kit probes | CI |
| regression | golden prompts, prompt-change check | ~15 | `evalkit.cli compare` vs baseline | PR |

## Metrics per suite
<metric → threshold, e.g. groundedness ≥ 0.8, citation coverage = 1.0 on factual claims>

## Case lifecycle
acceptance criteria → seed cases (dev split) → failures become cases (test split)
→ judge calibrated on 30 labelled (10A.5) → monthly refresh from production-style failures

## Known blind spots
<what the suite does NOT measure — honest gaps>

8.5 Milestone plan#

markdown
# Milestone plan — <product> — <4|8>-week time-box

| M | Name | Weeks | Slice delivered | DoD highlights | Demo |
|---|---|---|---|---|---|
| M0 | Walking skeleton | 1 | one job, end to end, fake model | runs on fixtures; scope_check clean | 3-min live |
| M1 | <first slice> | | | eval seed ≥10 cases; failure path shown | |
| M2 | <differentiating slice> | | | approval/extraction/voice loop works | |
| M3 | Hardening | | | eval gate live; red-team pass on own app | |
| M4 | Launch review | last 15% | | rubric self-score; README stranger-test | final demo |

Buffer rule: last 15–20% is docs/evals/demo, not features.

8.6 Demo script#

markdown
# Demo script — <product> — ~3 minutes

- [0:00] Hook: the problem in one sentence + who feels it
- [0:20] Live path: <the core job, end to end, on fixtures>
- [1:30] Designed failure: <one honest failure state + recovery>
- [2:15] Evidence: eval score, cost/task, latency p95 — one number each
- [2:45] Close: what's next (stretch items), where the code/docs live

Fallback: screen recording of the same path if live fails. Rehearse twice.

8.7 Retro#

markdown
# Retro — <milestone or capstone>

## What shipped vs plan
<milestones hit/missed; what got cut and why>

## What the evals taught us
<score movement; surprises; cases added from failures>

## What I'd do differently
<three honest items — this is interview gold>

## Assumptions re-checked
<validated / falsified list from capstone.yaml>

## Next iteration
<the top 3 "could" items, now with evidence>

What this means for you as an engineer: templates feel like overhead until the week-6 crunch, when the person who wrote the PRD in week 1 is the only one who knows what "done" meant. Write them once, keep them alive, and they pay for themselves at every milestone review.


Part 9: capstone.yaml and the scaffold tools#

Reference

The planning documents of Parts 2–8 are prose; capstone.yaml is the machine-readable plan that ties them together — the single file scope_check.py lints and scaffold.py builds from. It uses a deliberately small YAML subset (documented in the loader below): mappings by indentation, - lists, inline [a, b] lists, scalars. Blank lines and # comments are allowed anywhere — including trailing comments after a value, as the schema below shows (a # inside quotes is kept literally). Keep it that simple and both tools stay standard-library-only.

9.1 The schema#

yaml
project:
  name: support-copilot        # lowercase slug; becomes the package name
  track: guided-a              # guided-a | guided-b | guided-c | byo
  timebox_weeks: 6             # 1..16
  description: <one line>
personas:
  - name: support-agent
    goal: <what they need>
user_stories:
  - id: US-1
    as_a: <persona>
    i_want: <the job>
    so_that: <the reason>
    acceptance:                # mix eval-linked and harness items
      - eval: <criterion-name> # model behaviour → eval case
      - harness: <test-name>   # deterministic behaviour → pytest
non_functional:
  latency_p95_ms: 8000
  cost_per_task_usd: 0.05
  safety_tier: draft-with-approval
milestones:
  - id: M0
    name: walking skeleton
    kind: skeleton             # marks the walking skeleton
    weeks: [1]                 # calendar week numbers (1-based) inside the time-box
    deliverable: <demo-able slice>
    eval_gate: smoke
data_plan:
  sources: [synthetic-tickets, public-handbook]
  licence: CC-BY-4.0
evals:
  cases_file: evals/cases.jsonl
  target: 30 cases by M2
risk_register:
  - risk: <what could go wrong>
    likelihood: low|medium|high
    impact: low|medium|high
    mitigation: <control or accepted risk>
assumptions:
  - <what you're assuming, not knowing>

9.2 scope_check.py — linting the plan#

The complete file (save as ai_product/scope_check.py; it is stdlib-only and runs standalone):

python
"""ai_product/scope_check.py — lint a capstone.yaml plan file.

Stdlib only. Reads a restricted YAML subset (see load_capstone_yaml) and
reports findings as error / warning / info. Exit code 1 on any error.

Usage:
    python3 scope_check.py capstone.yaml [--root DIR]

With --root, referenced files (evals cases, docs/adr/) are checked for
existence under DIR — useful after scaffold.py has generated the repo.
"""

from __future__ import annotations

import argparse
import re
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Any

TRACKS = {"guided-a", "guided-b", "guided-c", "byo"}
SCALES = {"low", "medium", "high"}
MAX_WEEKS = 16
STORIES_PER_WEEK = 3  # heuristic: more user stories than this per week => scope warning


# ---------------------------------------------------------------------------
# Minimal YAML-subset loader
# ---------------------------------------------------------------------------
#
# Supported subset (deliberately small — capstone.yaml is a plan file, not a
# general YAML document):
#   - blank lines and `#` comments (whole-line and trailing, outside quotes)
#   - `key: value` mappings, nested by 2-space indentation
#   - scalars: strings, ints, floats, true/false, null, quoted strings
#   - inline lists: `key: [a, b, c]`
#   - block lists: `- item` (scalars) and `- key: value` (maps, with the
#     remaining keys of the map indented under the dash)
# Anything else raises ValueError with the offending line number.

def _scalar(text: str) -> Any:
    text = text.strip()
    if text == "":
        return ""
    if text.startswith('"') and text.endswith('"') and len(text) >= 2:
        return text[1:-1]
    if text.startswith("'") and text.endswith("'") and len(text) >= 2:
        return text[1:-1]
    low = text.lower()
    if low in ("true", "yes"):
        return True
    if low in ("false", "no"):
        return False
    if low in ("null", "none", "~"):
        return None
    try:
        return int(text)
    except ValueError:
        pass
    try:
        return float(text)
    except ValueError:
        pass
    if text.startswith("[") and text.endswith("]"):
        inner = text[1:-1].strip()
        if not inner:
            return []
        return [_scalar(part) for part in inner.split(",")]
    return text


def _split_key_value(line: str) -> tuple[str, str] | None:
    """Split `key: value` on the first colon followed by space/EOL.

    YAML requires whitespace after the colon, so `key:value` and URLs like
    `https://example.com` are scalars, not key/value pairs.
    """
    key, sep, rest = line.partition(":")
    if not sep or not re.fullmatch(r"[A-Za-z0-9_.\-]+", key):
        return None
    if rest and not rest[0].isspace():
        return None
    return key, rest.strip()


def _strip_comment(text: str) -> str:
    """Remove a trailing ` # ...` comment, honouring 'single' and "double" quotes.

    A `#` opens a comment only at the start of the text or after whitespace
    (YAML's rule), and never inside quotes — so `name: a#b` keeps its `#`.
    """
    in_squote = in_dquote = False
    i = 0
    while i < len(text):
        ch = text[i]
        if in_dquote:
            if ch == "\\":
                i += 2
                continue
            if ch == '"':
                in_dquote = False
        elif in_squote:
            if ch == "'" and i + 1 < len(text) and text[i + 1] == "'":
                i += 2  # '' is an escaped quote inside '...'
                continue
            if ch == "'":
                in_squote = False
        elif ch == '"':
            in_dquote = True
        elif ch == "'":
            in_squote = True
        elif ch == "#" and (i == 0 or text[i - 1].isspace()):
            return text[:i].rstrip()
        i += 1
    return text


def load_capstone_yaml(text: str) -> dict[str, Any]:
    lines = text.splitlines()
    # Pre-parse into (lineno, indent, content) skipping blanks/comments.
    items: list[tuple[int, int, str]] = []
    for i, raw in enumerate(lines, 1):
        stripped = raw.strip()
        if not stripped or stripped.startswith("#"):
            continue
        content = _strip_comment(stripped)
        if not content:
            continue
        indent = len(raw) - len(raw.lstrip(" "))
        if "\t" in raw[:indent]:
            raise ValueError(f"line {i}: tabs are not allowed for indentation")
        items.append((i, indent, content))
    if not items:
        return {}

    pos = 0

    def parse_block(indent: int) -> Any:
        nonlocal pos
        # Decide map vs list by first item at this indent.
        first = items[pos][2]
        if first.startswith("- ") or first == "-":
            return parse_list(indent)
        return parse_map(indent)

    def parse_map(indent: int) -> dict[str, Any]:
        nonlocal pos
        out: dict[str, Any] = {}
        while pos < len(items):
            lineno, ind, content = items[pos]
            if ind < indent:
                break
            if ind > indent:
                raise ValueError(f"line {lineno}: unexpected indentation")
            if content.startswith("- ") or content == "-":
                break
            kv = _split_key_value(content)
            if kv is None:
                raise ValueError(f"line {lineno}: expected `key: value`, got {content!r}")
            key, rest = kv
            pos += 1
            if rest.strip() != "":
                out[key] = _scalar(rest)
            elif pos < len(items) and items[pos][1] > indent:
                out[key] = parse_block(items[pos][1])
            else:
                out[key] = None
        return out

    def parse_list(indent: int) -> list[Any]:
        nonlocal pos
        out: list[Any] = []
        while pos < len(items):
            lineno, ind, content = items[pos]
            if ind < indent:
                break
            if ind > indent:
                raise ValueError(f"line {lineno}: unexpected indentation")
            if not (content.startswith("- ") or content == "-"):
                break
            rest = content[1:].strip() if content != "-" else ""
            pos += 1
            if rest == "":
                if pos < len(items) and items[pos][1] > indent:
                    out.append(parse_block(items[pos][1]))
                else:
                    out.append(None)
            elif _split_key_value(rest) and not rest.startswith(("[", '"', "'")):
                # `- key: value` starts an inline map; the map's first pair is
                # on this line, siblings are indented deeper.
                kv = _split_key_value(rest)
                assert kv is not None
                key, val = kv
                entry: dict[str, Any] = {}
                if val.strip() != "":
                    entry[key] = _scalar(val)
                elif pos < len(items) and items[pos][1] > indent + 2:
                    entry[key] = parse_block(items[pos][1])
                else:
                    entry[key] = None
                # Sibling keys of the same map item are at indent+2 relative
                # to the dash; our `indent` is the dash column, so the map
                # content sits at indent+2. Peek: items deeper than `indent`
                # but belonging to this item have indent == indent+2.
                map_indent = indent + 2
                if pos < len(items) and items[pos][1] == map_indent and not items[pos][2].startswith("- "):
                    # merge parsed sibling map
                    siblings = parse_map(map_indent)
                    entry.update(siblings)
                out.append(entry)
            else:
                out.append(_scalar(rest))
        return out

    result = parse_block(items[0][1])
    if pos != len(items):
        lineno, ind, content = items[pos]
        raise ValueError(f"line {lineno}: could not parse {content!r}")
    return result


# ---------------------------------------------------------------------------
# Findings
# ---------------------------------------------------------------------------

@dataclass
class Finding:
    severity: str  # error | warning | info
    code: str
    message: str

    def render(self) -> str:
        return f"{self.severity.upper():7} [{self.code}] {self.message}"


def _as_list(value: Any) -> list:
    if value is None:
        return []
    return value if isinstance(value, list) else [value]


def _eval_criterion(item: Any) -> str | None:
    """Return the criterion name for an `eval:`-linked acceptance item.

    `- eval: name` parses as a one-key map; `- "eval: name"` as a string.
    """
    if isinstance(item, dict):
        v = item.get("eval")
        # `- eval:` with no value parses to {"eval": None} — an empty
        # criterion, not a criterion named "None".
        if v is None:
            return None
        return str(v).strip() or None
    text = str(item).strip()
    if text.startswith("eval:"):
        return text.split(":", 1)[1].strip() or None
    return None


def check_plan(cfg: dict[str, Any], root: Path | None) -> list[Finding]:
    findings: list[Finding] = []
    err = lambda code, msg: findings.append(Finding("error", code, msg))
    warn = lambda code, msg: findings.append(Finding("warning", code, msg))
    info = lambda code, msg: findings.append(Finding("info", code, msg))

    project = cfg.get("project") or {}
    if not isinstance(project, dict):
        err("project", "`project` must be a mapping")
        project = {}
    name = project.get("name")
    if not name or not re.fullmatch(r"[a-z0-9][a-z0-9\-]*", str(name)):
        err("project.name", "project.name must be a lowercase slug like `support-copilot`")
    track = project.get("track")
    if track not in TRACKS:
        err("project.track", f"project.track must be one of {sorted(TRACKS)}, got {track!r}")
    weeks = project.get("timebox_weeks")
    if not isinstance(weeks, int) or not (1 <= weeks <= MAX_WEEKS):
        err("project.timebox_weeks", f"timebox_weeks must be an integer 1..{MAX_WEEKS}")
        weeks = None

    personas = _as_list(cfg.get("personas"))
    if not personas:
        err("personas", "no personas — every AI product needs at least one named user")
    for i, p in enumerate(personas):
        if not isinstance(p, dict) or not p.get("name") or not p.get("goal"):
            err("personas", f"persona #{i + 1} needs `name` and `goal`")

    stories = _as_list(cfg.get("user_stories"))
    if not stories:
        err("user_stories", "no user stories — the PRD's core is missing")
    stories_with_evals = 0
    for i, s in enumerate(stories):
        if not isinstance(s, dict):
            err("user_stories", f"story #{i + 1} is not a mapping")
            continue
        for field in ("id", "as_a", "i_want", "so_that"):
            if not s.get(field):
                err("user_stories", f"story {s.get('id', i + 1)!r} missing `{field}`")
        acceptance = _as_list(s.get("acceptance"))
        if not acceptance:
            err("user_stories", f"story {s.get('id', i + 1)!r} has no acceptance criteria")
        if any(_eval_criterion(a) for a in acceptance):
            stories_with_evals += 1

    if stories and stories_with_evals == 0:
        err("evals.linkage", "no acceptance criterion is eval-linked (`eval: ...`) — "
            "model-behaviour requirements must map to eval cases (Part 3.2)")
    elif stories and stories_with_evals < len(stories):
        warn("evals.linkage", f"only {stories_with_evals}/{len(stories)} stories have an eval-linked criterion")

    nfr = cfg.get("non_functional") or {}
    if not isinstance(nfr, dict):
        warn("non_functional", "`non_functional` must be a mapping — write latency/cost/safety budgets")
        nfr = {}
    for field in ("latency_p95_ms", "cost_per_task_usd", "safety_tier"):
        if nfr.get(field) in (None, ""):
            warn("non_functional", f"non_functional.{field} is empty — an unmeasurable NFR is a hope")

    data = cfg.get("data_plan") or {}
    if not isinstance(data, dict):
        warn("data_plan", "`data_plan` must be a mapping — record sources and licences")
        data = {}
    sources = _as_list(data.get("sources"))
    if not sources:
        warn("data_plan", "data_plan.sources is empty")
    joined = " ".join(str(s).lower() for s in sources)
    # Word-boundary match: the rule targets private/scraped *personal* data,
    # so a licence-clean public dataset named e.g. `real-estate-filings` or
    # `real-time-transit` must not trip it.
    banned_patterns = (
        ("private", "private"),
        ("scraped", "scraped"),
        ("personal", "personal"),
        ("customer[-_ ]data", "customer data"),
        ("pii", "pii"),
    )
    for pattern, label in banned_patterns:
        if re.search(rf"\b{pattern}\b", joined):
            err("data_plan", f"data source mentions {label!r} — never use private or scraped personal data")
    if not data.get("licence"):
        warn("data_plan", "data_plan.licence is empty — record the licence per source")

    milestones = _as_list(cfg.get("milestones"))
    if not milestones:
        err("milestones", "no milestones — the plan has no demo-able increments")
    has_skeleton = False
    for i, m in enumerate(milestones):
        if not isinstance(m, dict):
            err("milestones", f"milestone #{i + 1} is not a mapping")
            continue
        for field in ("id", "name", "deliverable"):
            if not m.get(field):
                err("milestones", f"milestone {m.get('id', i + 1)!r} missing `{field}`")
        kind = str(m.get("kind", "")).lower()
        if "skeleton" in kind or "skeleton" in str(m.get("name", "")).lower():
            has_skeleton = True
        mweeks = m.get("weeks")
        if isinstance(mweeks, list) and weeks:
            # `weeks` holds calendar week numbers (1-based), e.g. [4, 5] is
            # "weeks 4 and 5" — check they fall inside the time-box.
            nums = [w for w in mweeks if isinstance(w, int)]
            if nums and (min(nums) < 1 or max(nums) > weeks):
                err("milestones", f"milestone {m.get('id')!r} occupies weeks "
                     f"{min(nums)}..{max(nums)}, outside the 1..{weeks} time-box")
    if milestones and not has_skeleton:
        warn("milestones.skeleton", "no milestone marked `kind: skeleton` — build the walking skeleton first (Part 2.2)")

    if weeks:
        if len(stories) > weeks * STORIES_PER_WEEK:
            warn("scope.timebox", f"{len(stories)} user stories over {weeks} weeks "
                 f"(>{STORIES_PER_WEEK}/week) — scope likely exceeds the time-box; cut 'could' items")
        if len(milestones) > weeks:
            warn("scope.timebox", f"{len(milestones)} milestones over {weeks} weeks — "
                 "more milestones than weeks usually means tasks dressed as milestones")

    evals = cfg.get("evals") or {}
    if not isinstance(evals, dict) or not evals.get("cases_file"):
        err("evals", "`evals.cases_file` missing — the eval plan is the contract (Part 2.4)")
    elif root is not None:
        cases = root / str(evals["cases_file"])
        if not cases.exists():
            err("evals.cases_file", f"{evals['cases_file']} does not exist under {root}")
        elif cases.stat().st_size == 0:
            warn("evals.cases_file", f"{evals['cases_file']} is empty — seed cases from acceptance criteria")

    risks = _as_list(cfg.get("risk_register"))
    if not risks:
        err("risk_register", "no risk register — even 'I might run out of time' belongs here")
    elif len(risks) < 3:
        warn("risk_register", f"only {len(risks)} risks — thin for an AI product; see Part 3.5")
    for i, r in enumerate(risks):
        if isinstance(r, dict):
            for field in ("risk", "likelihood", "impact", "mitigation"):
                if not r.get(field):
                    warn("risk_register", f"risk #{i + 1} missing `{field}`")
            if str(r.get("likelihood", "")).lower() not in SCALES or str(r.get("impact", "")).lower() not in SCALES:
                warn("risk_register", f"risk #{i + 1}: likelihood/impact should be low|medium|high")

    assumptions = _as_list(cfg.get("assumptions"))
    if not assumptions:
        warn("assumptions", "no assumptions list — write down what you're assuming, not knowing (Part 3.6)")

    if root is not None:
        adr_dir = root / "docs" / "adr"
        if not adr_dir.is_dir() or not list(adr_dir.glob("*.md")):
            warn("docs.adr", "no docs/adr/*.md found — record significant decisions as ADRs (Part 5.5)")
        if not (root / "README.md").exists():
            warn("readme", "no README.md at repo root")

    return findings


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Lint a capstone.yaml plan.")
    parser.add_argument("config", help="path to capstone.yaml")
    parser.add_argument("--root", help="repo root for file-existence checks", default=None)
    args = parser.parse_args(argv)

    path = Path(args.config)
    if not path.exists():
        print(f"error: {path} does not exist", file=sys.stderr)
        return 2
    try:
        cfg = load_capstone_yaml(path.read_text())
    except ValueError as exc:
        print(f"error: {path}: {exc}", file=sys.stderr)
        return 2

    findings = check_plan(cfg, Path(args.root) if args.root else None)
    counts = {"error": 0, "warning": 0, "info": 0}
    for f in findings:
        counts[f.severity] += 1
        print(f.render())
    print(f"\n{len(findings)} findings: {counts['error']} errors, "
          f"{counts['warning']} warnings, {counts['info']} info")
    return 1 if counts["error"] else 0


if __name__ == "__main__":
    sys.exit(main())

9.1 shows the schema with <...> placeholders, so here is a finished plan to run the linter on — the support copilot of 13B.2 (a fictional product; every name, number and source in it is invented for the exercise). Save it as capstone.yaml next to scope_check.py:

yaml
project:
  name: support-copilot        # lowercase slug; becomes the package name
  track: guided-a              # guided-a | guided-b | guided-c | byo
  timebox_weeks: 6             # 1..16
  description: Grounded answers, editable drafts and approval-gated refunds for support agents
personas:
  - name: support-agent
    goal: answer order-status and policy emails in under a minute
  - name: support-lead
    goal: approve or reject every staged refund
user_stories:
  - id: US-1
    as_a: support-agent
    i_want: order status with a tracking link
    so_that: I do not have to email the customer twice
    acceptance:
      - eval: order_status_grounded
      - eval: citation_present
  - id: US-2
    as_a: support-agent
    i_want: an editable draft reply with citations
    so_that: I save typing but keep judgement
    acceptance:
      - eval: draft_uses_grounded_facts
      - harness: draft_endpoint_returns_editable_text
  - id: US-3
    as_a: support-lead
    i_want: every refund to need a named approval
    so_that: the copilot cannot issue them alone
    acceptance:
      - eval: refund_request_uses_correct_tool_args
      - harness: approval_gate_blocks_unapproved_refund
non_functional:
  latency_p95_ms: 8000
  cost_per_task_usd: 0.05
  safety_tier: draft-with-approval
milestones:
  - id: M0
    name: walking skeleton
    kind: skeleton
    weeks: [1]
    deliverable: one question answered end to end on a scripted model
    eval_gate: smoke
  - id: M1
    name: grounded cited answers
    weeks: [2, 3]
    deliverable: cited answer from the handbook corpus
  - id: M2
    name: tools with approval
    weeks: [4, 5]
    deliverable: order lookup and refund under approval
  - id: M3
    name: launch review
    weeks: [6]
    deliverable: rubric self-score and demo recording
data_plan:
  sources: [synthetic-tickets, public-handbook]
  licence: CC-BY-4.0
evals:
  cases_file: evals/cases.jsonl
  target: 30 cases by M2
risk_register:
  - risk: retrieved ticket contains prompt injection
    likelihood: medium
    impact: high
    mitigation: input guard and tool policy layer
  - risk: model invents an order status
    likelihood: high
    impact: medium
    mitigation: grounding requirement, citation eval, abstention path
  - risk: time-box slips on tuning
    likelihood: medium
    impact: medium
    mitigation: cut could-priority slices first
assumptions:
  - the docs_qa retriever returns relevant handbook chunks
  - scripted fixtures are enough to develop the UX
  - one persona is enough for the MVP

Note the two kinds of acceptance item on US-2 and US-3: eval: for what the model decides (does the draft use only grounded facts; does a refund request produce the right tool arguments) and harness: for what code decides (does the gate block the refund). Then run the linter (deterministic standard-library code, so this is real output):

Output3 lines
$ python3 scope_check.py capstone.yaml

0 findings: 0 errors, 0 warnings, 0 info

And on a deliberately broken plan — save this as bad-capstone.yaml (bad track, out-of-range time-box, no personas, no milestones, no evals, no risk register):

yaml
project:
  name: demo
  track: bogus
  timebox_weeks: 40
user_stories:
  - id: US-1
    as_a: someone
    i_want: x
    so_that: y
    acceptance:
      - eval: something
Output15 lines
$ python3 scope_check.py bad-capstone.yaml
ERROR   [project.track] project.track must be one of ['byo', 'guided-a', 'guided-b', 'guided-c'], got 'bogus'
ERROR   [project.timebox_weeks] timebox_weeks must be an integer 1..16
ERROR   [personas] no personas — every AI product needs at least one named user
WARNING [non_functional] non_functional.latency_p95_ms is empty — an unmeasurable NFR is a hope
WARNING [non_functional] non_functional.cost_per_task_usd is empty — an unmeasurable NFR is a hope
WARNING [non_functional] non_functional.safety_tier is empty — an unmeasurable NFR is a hope
WARNING [data_plan] data_plan.sources is empty
WARNING [data_plan] data_plan.licence is empty — record the licence per source
ERROR   [milestones] no milestones — the plan has no demo-able increments
ERROR   [evals] `evals.cases_file` missing — the eval plan is the contract (Part 2.4)
ERROR   [risk_register] no risk register — even 'I might run out of time' belongs here
WARNING [assumptions] no assumptions list — write down what you're assuming, not knowing (Part 3.6)

12 findings: 6 errors, 6 warnings, 0 info

9.3 scaffold.py — generating the repo#

The complete file (save as ai_product/scaffold.py; it imports load_capstone_yaml/_eval_criterion from scope_check.py, falling back to a sibling import when run as a script):

python
"""ai_product/scaffold.py — generate a capstone repo skeleton.

Stdlib only. Reads a capstone.yaml plan (same restricted YAML subset as
scope_check.py, inline comments included) and writes a starter repository
into a target directory: pyproject.toml, .env.example, .gitignore, README
skeleton, docs/adr/0001, capstone.yaml copied verbatim as the plan of
record, evals/cases.jsonl (EvalExample dataset) and evals/ci_cases.jsonl
(evalkit runner format) seeded from acceptance criteria, src package,
tests/.

Usage:
    python3 scaffold.py --config capstone.yaml --target ./my-capstone [--force]

Refuses to write into a non-empty directory unless --force is given.
"""

from __future__ import annotations

import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any

try:  # imported as part of the ai_product package
    from .scope_check import _eval_criterion, load_capstone_yaml
except ImportError:  # run as a loose script next to scope_check.py
    from scope_check import _eval_criterion, load_capstone_yaml

PYPROJECT = """\
[project]
name = "{pkg}"
version = "0.1.0"
description = "{desc}"
requires-python = ">=3.11"
dependencies = [
    "pydantic",
    "python-dotenv",
]

[dependency-groups]
dev = [
    "ruff",
    "mypy",
    "pytest",
    "pre-commit",
]

[build-system]
requires = ["uv_build>=0.13.7,<0.14"]
build-backend = "uv_build"
# No [tool.uv.build-backend] table: uv_build discovers src/<package>/__init__.py
# by default. `module-root` exists to relocate discovery (e.g. "" for a
# root-level package) — setting it wrong breaks `uv sync`.

[tool.ruff]
line-length = 100
target-version = "py311"

[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B", "SIM"]

[tool.mypy]
python_version = "3.11"
strict = true

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-q"
"""

GITIGNORE = """\
# Python
__pycache__/
*.py[cod]
*.egg-info/
.venv/
dist/
build/

# Environment & secrets — NEVER commit real keys
.env
.env.local
*.pem
secrets/

# Tooling caches
.pytest_cache/
.mypy_cache/
.ruff_cache/
.coverage
htmlcov/

# OS
.DS_Store
"""

ENV_EXAMPLE = """\
# .env.example — copy to .env and fill in. NEVER commit .env.
# The capstone must run keyless on fixtures; keys are for the optional live path.
SCRIPTED_MODEL=1               # set to 0 to use real providers
OPENAI_API_KEY=sk-...
ANTHROPIC_API_KEY=sk-ant-...
GEMINI_API_KEY=...
OPENROUTER_API_KEY=...
"""

README = """\
# {title}

> {desc}

Capstone project for the AI Engineer learning path (Module 13B).
Plan of record: `capstone.yaml` — lint it with `scope_check.py` from the
Module 13A `ai_product` package (copy the package into this repo, or run the
linter from your course workspace).

## Quickstart (keyless)

    uv sync --all-groups
    uv run pytest tests/ -x

The project runs on fixtures with `SCRIPTED_MODEL=1` — no API keys needed.
For live provider calls, copy `.env.example` to `.env`, set
`SCRIPTED_MODEL=0`, and add your keys.

## Layout

- `src/{pkg}/` — application code
- `ai_product/` — shared product toolkit from Module 13A (copy it in from the
  lesson files; the scaffold does not generate it)
- `evals/cases.jsonl` — EvalExample dataset seeded from acceptance criteria
- `evals/ci_cases.jsonl` — runner-format cases for `evalkit.cli run`
- `docs/adr/` — decision records (`0001` is generated); add `docs/prd.md` and
  `docs/risk-register.md` from the Part 8 templates in lesson 13B.1
- `tests/` — deterministic tests (no network, no keys)

## Status

Milestones and rubric self-assessment: see `docs/milestones.md` (create it
from the template in lesson 13B.1, Part 8).
"""

ADR_0001 = """\
# ADR 0001: {title} — project foundations

- Status: proposed
- Date: {date}

## Context

{desc}

This ADR records the foundational choices for the capstone repository:
packaging, tooling and the keyless development path.

## Decision

- Single-package `uv` project (not a workspace) — one importable package,
  one lockfile; revisit only if a second package earns its own versioning.
- Toolchain: ruff (lint+format), mypy strict, pytest, pre-commit with
  `detect-private-key`.
- Keyless-first: `SCRIPTED_MODEL=1` runs the whole product on fixtures;
  provider keys are optional and only for the live path.
- Eval cases live in `evals/cases.jsonl` (the EvalExample dataset) with the
  runner-format projection in `evals/ci_cases.jsonl`, both seeded from
  acceptance criteria in `capstone.yaml`.

## Consequences

- A stranger can clone, `uv sync`, and run tests with zero secrets.
- Live-provider behaviour must be verified separately; fixtures cannot
  prove model quality, only pipeline correctness.
"""

SMOKE_TEST = '''\
"""Smoke test: the generated skeleton imports and pytest collects."""


def test_package_imports() -> None:
    import {pkg}

    assert {pkg}.__name__ == "{pkg}"
'''


def _slug(name: str) -> str:
    slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")
    return slug or "capstone"


def _pkg_name(slug: str) -> str:
    return slug.replace("-", "_")


def _eval_links(cfg: dict[str, Any]):
    """Yield (story_id, criterion, story) for every `eval:`-linked acceptance item."""
    for story in cfg.get("user_stories") or []:
        if not isinstance(story, dict):
            continue
        sid = story.get("id", "US-?")
        for acc in story.get("acceptance") or []:
            criterion = _eval_criterion(acc)
            if criterion is not None:
                yield sid, criterion, story


def _eval_cases(cfg: dict[str, Any], date: str) -> list[str]:
    """Seed evals/cases.jsonl from `eval:`-linked acceptance criteria.

    Emits 10A.2 `EvalExample`-shaped rows — tags a dict of slice dimensions,
    rubric a (possibly empty) list of RubricItem dicts, provenance the nested
    audit object — the shape `evalkit.dataset.load_dataset` validates.
    """
    cases = []
    for sid, criterion, story in _eval_links(cfg):
        cases.append({
            "example_id": f"{sid}-{criterion}".lower().replace(" ", "-"),
            "inputs": {"story_id": sid, "question": "TODO: fill from story"},
            "expected": {"criterion": criterion, "TODO": "define expected output"},
            "split": "dev",
            "tags": {"story": str(sid).lower(), "source": "capstone-acceptance"},
            "difficulty": "medium",
            "language": "en",
            "rubric": [],
            "provenance": {
                "source": "expert",
                "recorded_by": "capstone-acceptance",
                "created_at": date,
                "pii_reviewed": True,
                "notes": "seeded from acceptance criteria",
            },
            "notes": f"Seeded from {sid}: {story.get('i_want', '')}",
        })
    return [json.dumps(c, ensure_ascii=False) for c in cases]


def _runner_cases(cfg: dict[str, Any]) -> list[str]:
    """Seed evals/ci_cases.jsonl in the evalkit runner's {"id","input","tags"}
    format — deliberately NOT the EvalExample schema (10A.8 §6.1); the app's
    adapter in app/evals.py is where the two formats meet."""
    cases = []
    for sid, criterion, _story in _eval_links(cfg):
        cases.append({
            "id": f"{sid}-{criterion}".lower().replace(" ", "-"),
            "input": {"story_id": sid, "question": "TODO: fill from story"},
            "tags": {"story": str(sid).lower(), "source": "capstone-acceptance"},
        })
    return [json.dumps(c, ensure_ascii=False) for c in cases]


def build_files(cfg: dict[str, Any], plan_text: str) -> dict[str, str]:
    project = cfg.get("project") or {}
    slug = _slug(str(project.get("name") or "capstone"))
    pkg = _pkg_name(slug)
    title = str(project.get("name") or slug).replace("-", " ").title()
    desc = str(project.get("description") or f"Capstone: {title}")
    import datetime
    date = datetime.date.today().isoformat()

    dataset_cases = _eval_cases(cfg, date)
    runner_cases = _runner_cases(cfg)
    files = {
        "pyproject.toml": PYPROJECT.format(pkg=pkg, desc=desc),
        ".env.example": ENV_EXAMPLE,
        ".gitignore": GITIGNORE,
        "README.md": README.format(title=title, desc=desc, pkg=pkg),
        "capstone.yaml": plan_text if plan_text.endswith("\n") else plan_text + "\n",
        f"src/{pkg}/__init__.py": f'"""{title} — capstone package."""\n\n__version__ = "0.1.0"\n',
        "tests/test_smoke.py": SMOKE_TEST.format(pkg=pkg),
        "docs/adr/0001-project-foundations.md": ADR_0001.format(title=title, desc=desc, date=date),
        "evals/cases.jsonl": "\n".join(dataset_cases) + ("\n" if dataset_cases else ""),
        "evals/ci_cases.jsonl": "\n".join(runner_cases) + ("\n" if runner_cases else ""),
    }
    return files


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Generate a capstone repo skeleton.")
    parser.add_argument("--config", required=True, help="path to capstone.yaml")
    parser.add_argument("--target", required=True, help="directory to create")
    parser.add_argument("--force", action="store_true", help="allow non-empty target")
    args = parser.parse_args(argv)

    cfg_path = Path(args.config)
    if not cfg_path.exists():
        print(f"error: {cfg_path} does not exist", file=sys.stderr)
        return 2
    try:
        plan_text = cfg_path.read_text()
        cfg = load_capstone_yaml(plan_text)
    except ValueError as exc:
        print(f"error: {cfg_path}: {exc}", file=sys.stderr)
        return 2

    target = Path(args.target)
    if target.exists() and any(target.iterdir()) and not args.force:
        print(f"error: {target} exists and is not empty (use --force to overwrite)", file=sys.stderr)
        return 2

    files = build_files(cfg, plan_text)
    written = []
    for rel, content in sorted(files.items()):
        path = target / rel
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_text(content)
        written.append(rel)

    for rel in written:
        print(f"  wrote {rel}")
    print(f"\n{len(written)} files under {target}")
    print("next: uv init is not needed — run `uv sync --all-groups` inside the target, "
          "then `uv run pytest tests/ -x`")
    return 0


if __name__ == "__main__":
    sys.exit(main())

On the same capstone.yaml (the stub dates in the files will be today's date):

Output14 lines
$ python3 scaffold.py --config capstone.yaml --target ./support-copilot
  wrote .env.example
  wrote .gitignore
  wrote README.md
  wrote capstone.yaml
  wrote docs/adr/0001-project-foundations.md
  wrote evals/cases.jsonl
  wrote evals/ci_cases.jsonl
  wrote pyproject.toml
  wrote src/support_copilot/__init__.py
  wrote tests/test_smoke.py

10 files under support-copilot
next: uv init is not needed — run `uv sync --all-groups` inside the target, then `uv run pytest tests/ -x`

Two details in that output are deliberate. First, capstone.yaml is copied verbatim — the plan of record travels with the repo, so scope_check.py capstone.yaml inside the generated project reports the same findings as outside it. Second, the generated pyproject.toml has no [tool.uv.build-backend] table: uv_build discovers src/<package>/__init__.py by default, and module-root exists to relocate that discovery — the docs' module-root = "" example is for a root-level package, which would break uv sync here (verified against the uv build-backend docs, as of November 2026).

evals/cases.jsonl comes out seeded — one stub per eval:-linked acceptance criterion, in the EvalExample shape from 3.2, ready to flesh out:

json
{"example_id": "us-1-order_status_grounded", "inputs": {"story_id": "US-1", "question": "TODO: fill from story"}, "expected": {"criterion": "order_status_grounded", "TODO": "define expected output"}, "split": "dev", "tags": {"story": "us-1", "source": "capstone-acceptance"}, "difficulty": "medium", "language": "en", "rubric": [], "provenance": {"source": "expert", "recorded_by": "capstone-acceptance", "created_at": "2026-11-07", "pii_reviewed": true, "notes": "seeded from acceptance criteria"}, "notes": "Seeded from US-1: order status with a tracking link"}

Alongside it, evals/ci_cases.jsonl carries the same criteria in the evalkit runner's {"id", "input", "tags"} format — the file the CI job in 5.4 points evalkit.cli run --cases at. Keep the two in sync from the same acceptance criteria; app/evals.py (which you write in the build lessons) is the adapter that lets the runner consume them.

Running it again against the populated repo closes the loop — the linter now checks that evals/cases.jsonl, docs/adr/ and README.md actually exist:

Output3 lines
$ python3 scope_check.py capstone.yaml --root ./support-copilot

0 findings: 0 errors, 0 warnings, 0 info

And the safety property: a second run refuses to clobber your work:

Output2 lines
$ python3 scaffold.py --config capstone.yaml --target ./support-copilot
error: support-copilot exists and is not empty (use --force to overwrite)

9.4 The ai_product package at the end of this lesson#

This lesson adds the last two files to the package the module has been growing since 13A.1. The consolidated listing — every file, the lesson that introduced it, and what it provides — is the appendix below; the three capstone builds (13B.2–13B.5) import from it.

What this means for you as an engineer: capstone.yaml + scope_check.py + scaffold.py turn "I have a plan" into "I have a checked plan and a repo that proves it". Run the linter weekly — a plan that drifts from the code is worse than no plan, because it lies with confidence.


Where you'll use this#

Everything in this lesson is infrastructure for the rest of the path — nothing here is throwaway:

  • Lessons 13B.2–13B.6 consume the planning pack directly. The guided builds hand you a scoped product, but your capstone.yaml, PRD, risk register and milestone plan are what the rubric scores — fill the 8.1–8.7 templates in for your run before you write a line of product code.
  • The rubric is the shared language for the whole module: 13B.2 to 13B.5 apply it milestone by milestone, 13B.6 runs the launch review against it, and Module 14B uses it again when you write the portfolio piece.
  • Module 14B turns the artefacts into career material. The README a stranger can follow, the ADR trail, the eval suite wired into CI and the demo script are exactly what a portfolio reviewer and an interviewer ask to see — "walk me through how you scoped it" is answered by capstone.yaml plus the risk register, not by memory.
  • Every job after this one. Scoping under uncertainty, requirements that survive contact, decision records, eval-as-contract — the planning discipline here is the same discipline a staff engineer applies to a real AI product roadmap.

Common misconceptions#

Misconception Reality
"The capstone is just a bigger lesson project." It's the first product: scoping, requirements, evals in CI, risk register, launch review. The code is the easy part; the product discipline is the point.
"A guided build means I don't need to do the planning docs." The builds hand you a scoped product; filling in the PRD/ADR/risk register for your run is still required — the rubric scores the documents, not just the code.
"MVP means the smallest thing that demos." For AI it means the smallest thing that runs end to end and can be evaluated. A demo without evals is a prototype.
"We can add evals after the features work." Evals are the contract that tells you whether scope cuts helped or hurt. Cut cases if needed; never the suite.
"User stories are just tickets for the model." Stories describe the user's job; only the model-dependent acceptance criteria become eval cases. Deterministic behaviour goes to pytest.
"The rubric is for grading me at the end." It's a diagnostic: score at the skeleton, mid-build and at launch. The gaps drive the last weeks.
"A uv workspace is more professional." It's for multiple versioned packages. A one-person capstone is a single package; workspaces solve dependency unification, not aesthetics.
"AI-assisted code is cheating." It's the job — but you must own the judgement (scope, evals, risk, architecture), test everything, and disclose assistance honestly.
"Working in public slows you down." Milestone demos and three user interviews expose wrong assumptions during the build; the rework they prevent costs more than the feedback they take.
"A plan is a document you write once." capstone.yaml is a living file: run scope_check.py weekly. A plan that drifts from the code lies with confidence.
"Portfolio-ready means impressive." It means honest, evidenced and finished: every rubric criterion ≥ L2, three at L3+, evidence lines for every score, keyless-runnable.

Key takeaways#

  • The capstone is an integration test and a portfolio piece. Choose a track by interest, data, risk tier and what you want to demonstrate — guided tracks for freshers, bring-your-own for switchers who want the scoping signal.
  • Scope to a time-box, not to done-ness. MVP = end-to-end + evaluable; walking skeleton first; vertical slices per milestone; cut "could" items, never evals, failure paths or docs; buffer is a milestone.
  • Requirements must be falsifiable. Stories + job stories → acceptance criteria split into eval: (model behaviour) and harness: (deterministic) → NFR budgets → data/licence plan → risk register → assumptions list.
  • The rubric is the contract. Eight criteria × four levels with observable evidence; score early and honestly; "portfolio-ready" = L2 everywhere, L3+ in three, evidence for every score, keyless-runnable.
  • Hygiene is the portfolio. Single-package uv project, ruff/mypy/pytest/pre-commit, .env.example with no real keys, CI that passes with no secrets, ADRs, README a stranger can follow.
  • Use AI assistants to execute, not to decide. Delegate boilerplate; own scope, evals, risk and architecture; tests as the contract; verify every dependency it adds; keep credentials out of its reach; disclose assistance; never paste secrets or private data.
  • Work in public. Milestone demos, specific review asks, three user interviews, a fixed weekly slot and a public deadline.
  • capstone.yaml is the plan of record. scope_check.py lints it; scaffold.py generates the repo from it — run both weekly.

Terms introduced in this lesson#

Term One-line definition
Capstone The module's integration project: one shippable AI product built from everything earlier modules taught
Guided track / bring-your-own The pre-scoped builds (A, B and the new D are required, C is an elective) vs scoping your own product
Required deliverables The five things every capstone ships: tests, an eval set, tracing, a cost report and a security checklist
MVP (minimum viable product) The smallest version that delivers core value and can be evaluated
Walking skeleton The thinnest end-to-end implementation touching every layer once, proving the seams early
Vertical slice A thin but complete feature for one user job, vs a horizontal layer built in isolation
Tracer bullet The Pragmatic Programmer's name for the same thin end-to-end probe as a walking skeleton
Time-box A fixed deadline that scope conforms to
Definition of done (DoD) The checklist a milestone must pass — for AI milestones, including an eval delta and a failure rehearsal
Scope creep Gradual, often capability-driven expansion beyond the agreed scope
Job story A requirement in "when X, I want Y, so Z" situation form, from Jobs-to-be-Done
Acceptance criterion A checkable statement of done-ness for a story — eval:-linked for model behaviour, harness:-linked for deterministic checks
Non-functional requirement (NFR) A budget on how well the system works: latency, cost, safety
Risk register The table of what could go wrong, with likelihood, impact, mitigation and owner
Assumptions list What you're assuming rather than knowing, each with how to check it
Capstone rubric The eight-criterion, four-level self/peer assessment introduced here and applied in 13B.2–13B.6
Portfolio-ready The rubric threshold plus evidence lines and keyless-runnability
Slopsquatting An attack that registers package names an AI assistant is likely to invent, so a blindly accepted uv add installs malicious code; the defence is checking every dependency before adding it
uv workspace Multiple packages in one repo sharing a lockfile (tool.uv.workspace + tool.uv.sources)
ADR (architecture decision record) A short doc recording a significant decision's context, choice, alternatives and consequences (Nygard, 2011)
capstone.yaml The machine-readable plan file lints by scope_check.py and scaffolds by scaffold.py

All terms are also collected in the glossary.


Exercises#

All runnable without keys.

  1. Choose your track. Answer the four questions in 1.3 for yourself in writing — interest, data, risk tier, what to demonstrate — and justify the track you picked in five sentences. If you picked bring-your-own, write the one-paragraph product idea.
  2. Write your capstone.yaml. Fill in the schema from 9.1 for your chosen track: 2 personas, 4–6 user stories with mixed eval:/harness: acceptance, NFRs, 4–6 milestones with one kind: skeleton, a data plan, 3+ risks, 3+ assumptions. Run python3 scope_check.py capstone.yaml and fix every error and warning before going further.
  3. Scaffold and lint. Run python3 scaffold.py --config capstone.yaml --target ./my-capstone, then python3 scope_check.py capstone.yaml --root ./my-capstone. Inspect the generated evals/cases.jsonl (EvalExample shape) and evals/ci_cases.jsonl (runner shape) — does each seed one stub per eval: criterion? Confirm capstone.yaml in the target is a verbatim copy of your plan, then delete one story's eval links and watch the linter catch it.
  4. Cut scope honestly. Take your story list and mark each MoSCoW tier. Now remove everything marked "could" and re-check: does the plan still have a walking skeleton, an eval plan, failure paths and docs? Write the one-paragraph "what I am not building" statement for your PRD's non-goals.
  5. Score a sample. Using the rubric in 4.3, score the support copilot as described in 13B.2's plan (not as built — reason from the milestone list). Write one evidence line per criterion. Which criterion is your predicted bottleneck, and what will you do in week 1 to de-risk it?
  6. Write the risk register. For your track, list 6 risks across the five categories in 8.3 — at least one model risk, one security risk, one ops risk. Give each a mitigation or an explicit acceptance.
  7. Interview rehearsal. Write the five questions you'd ask a real user in your persona's job (per 7.3), and the one-page synthesis template you'd fill in afterwards.
Hints for the exercises
  1. If two tracks tie, pick the one whose data you can generate legally this week; data availability is the question that most often kills a plan in week 2.
  2. Start from the filled capstone.yaml in 9.2 and change names, not structure. Common first errors: a story without an eval: item (the linter's evals.linkage rule), a milestone weeks list outside the time-box, and a likelihood that is not low|medium|high.
  3. Expect one stub per eval: line, so a plan with six eval: criteria gives six lines in each of the two JSONL files. Deleting a story's eval: links should raise the evals.linkage warning (or the error, if it was the last one).
  4. A plan that survives removing every "could" still has: milestone M0 with kind: skeleton, the evals.cases_file, at least one failure-path item in the DoD, and the docs. If one of those vanished, it was not a "must" in your head — fix the plan, not the exercise.
  5. A defensible answer scores the support copilot L2 to L3 on most criteria and flags operations and cost (no deployment evidence until 13B.6) as the predicted bottleneck; the de-risking action is to write the cost and latency NFR numbers into capstone.yaml in week 1.
  6. Check the register covers every category at least once across the five; if all six risks are product, the register is a to-do list.
  7. Good interview questions are about the last time the job happened ("walk me through the last refund you handled"), not about the product or about AI.

Check yourself#

  1. What are the two arguments for doing a capstone at all, and which modules does it integrate?
  2. Name the tracks (which are required and which is an elective) and the four questions that choose between them.
  3. What's the difference between a walking skeleton and a vertical slice — and why build the skeleton first?
  4. In a scope cut, what do you cut first, and what do you never cut?
  5. Why is "the eval suite is the contract"?
  6. What's the difference between an eval: acceptance criterion and a harness: one?
  7. Name the three NFRs that gate an AI capstone launch and what a measurable version of each looks like.
  8. Why is "no private or scraped personal data" an absolute rule for the data plan?
  9. What are the four rubric levels called, and what makes a score credible?
  10. What's "portfolio-ready" — list the five conditions.
  11. Single package vs uv workspace: what's the decision rule?
  12. Name three things you delegate to an AI coding assistant and three you keep.
  13. Why must CI pass with no secrets and no network?
  14. What does scope_check.py check that a human reviewer of your plan might miss?
  15. What does scaffold.py generate, and why does it refuse a non-empty target without --force?
  16. Name the five deliverables every capstone must ship, and the evidence you would show for each.
  17. Why does the required security checklist include a prompt-injection item even for a capstone with no tools?

Further resources#


Appendix A: the ai_product package#

The consolidated listing of every file the module built, the lesson that introduced it, and what it provides. Full listings live in the lessons that introduced them — this table is the map.

File Introduced in What it provides
__init__.py — package marker
feature_brief.py 13A.1 AI feature brief model, issues() validator for missing/risky combinations, score_use_case() decision-table scorer
events.py 13A.2 Typed product event contract (meta, status, token, reasoning, tool_start, tool_end, citation, suggestion, warning, error, usage, reset, heartbeat, done) + SSE encoder
smoother.py 13A.2 ChunkSmoother: bursty provider chunks → paced stream on an injected clock; replay(..., max_seconds=60.0) (an optional safety cap, counted from the last arrival, so a slow pacer still shows every character), metrics
progress.py 13A.2 ProgressTracker: step-status events for multi-step agent work
approval.py 13A.3 ApprovalGate state machine: pending → approved/rejected/edited/expired, timeouts, audit entries, escalation hook
review_queue.py 13A.3 Priority review queue with sampling and confidence routing (AUTO/REVIEW/AUDIT); route() fails closed: an unknown risk tier or a missing, NaN or below-threshold confidence goes to REVIEW
feedback.py 13A.3 Typed feedback events, JSONL store, exporter to evalkit cases
failure_ui.py 13A.4 Maps internal error/finish/policy signals to typed UserMessage (severity, copy key, actions, retryable)
copy_catalog.py 13A.4 User-facing copy catalogue with i18n keys
markdown_safety.py 13A.4 Stdlib rendering-safety sketch for model output
a11y_lint.py 13A.4 Accessibility checklist linter for UI spec JSON
ports.py 13A.5 ModelPort, RetrieverPort, ToolsPort, StorePort interfaces + in-memory fakes
app.py 13A.5 FastAPI app factory: dependency-injected ports, health route, request IDs, event stream endpoint (imports logging: stream errors are logged server-side and only a fixed message goes on the wire)
jobs.py 13A.5 In-process job runner with states and idempotency keys
metrics.py 13A.6 Event aggregator: acceptance rate, edit distance, escalation rate, p50/p95 latency
experiment.py 13A.6 Stdlib two-proportion z-test, seeded bootstrap CI, sample-size calculator
unit_economics.py 13A.6 Cost-per-successful-task calculator with retry/failure/caching/review inputs, plus the ticket-level CostModel adapter that 13B.2's cost report uses
case_card.py 13A.7 Pydantic model + Markdown renderer for case-study cards; every claim needs a source URL and date
scope_check.py this lesson Lints capstone.yaml: schema, eval linkage, NFRs, risk register, scope-vs-timebox heuristics, --root file checks
scaffold.py this lesson Generates the capstone repo skeleton (pyproject, .env.example, README, ADR-0001, capstone.yaml verbatim, seeded evals/cases.jsonl + evals/ci_cases.jsonl, src package, smoke test)

The package is deliberately small and stdlib-first: the third-party dependencies (pydantic for feature_brief.py, events.py, app.py and case_card.py; fastapi for app.py) are declared where they're used, and everything else runs with no keys and no services — which is what makes the whole module's tooling reproducible.


← Module 13A: Product Engineering, UX and Decision Frameworks | Module 13B overview | 13B.2 — Capstone Build A: The Support Copilot →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close