# Lab 25: code reads the answer (/building-ai-workers/prompts-and-structured-output/lab)

---
type: Document
title: "Lab 25: code reads the answer"
description: "The lab for Chapter 25, in two sittings, each right after its part of the chapter: one change to the prompt with the whole suite behind it, then a schema the API holds, value checks, three gates and the port."
status: stable
order: 325.9
ksor:
  owner: team:panaversity
  audience:
    - public
  approval:
    by: process:panaversity
    at: 2026-11-30T00:02:23Z
chapter: '25'
part: III
expert_status: co-build
concepts: []
last_verified: '2026-11-29'
sources:
  - id: anthropic-structured-outputs
    title: Structured outputs (verified 2026-11-29)
    resource: https://platform.claude.com/docs/en/build-with-claude/structured-outputs
  - id: anthropic-prompting-sonnet-5-5
    title: Prompting Claude Sonnet 5.5 (Claude Platform docs, verified 2026-11-29)
    resource: https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/prompting-claude-sonnet-5-5
  - id: anthropic-stop-reasons
    title: Stop reasons and fallback (Anthropic, verified 2026-11-29)
    resource: https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons
  - id: openai-structured-outputs
    title: Structured model outputs (OpenAI, verified 2026-11-29)
    resource: https://developers.openai.com/api/docs/guides/structured-outputs
  - id: llamacpp-grammars
    title: 'GBNF guide: JSON Schemas to GBNF (llama.cpp, verified 2026-11-29)'
    resource: https://github.com/ggml-org/llama.cpp/blob/master/grammars/README.md
generated:
  at: 2026-11-30T00:02:23Z
  by: esl-rewrite/1.2.0+ksor.1
trust_tier: unverified
build_id: sha256:cc6fd9ac5f72207d4365ecbda63d87d1b64f99e05519b358a45b9f5d9bfd6f8f
dirty: true
ksor_version: 0.0.60
---

<!-- OPEN: lab folder not built -->

<!-- OPEN: every file name, script name and case count on this page that Lab 24 or this lab's folder must supply is proposed until the folder is built: the extraction prompt's file name, `docs/chapter-25/`, `data/invoices/new/`, `tests/fixtures/revisions/broad-rewrite/`, `tests/fixtures/output/wrong-total.json`, `src/extract/`, `ports/openai/extract/` and `npm run test:output` -->

<!-- OPEN: the lab's date, Monday, April 19, 2027, and INV-8340 for Midwest Packaging Co. are proposed in the chapter's spec and are not yet in specs/labs/part-2-facts.md -->

You fix the one case that Lab 24 left red, and prove the fix broke nothing. Then you give the reading of every extracted invoice to code. The code has a schema that the API holds, a check on each value, and three gates. The gates send every answer the code will not accept to Ana Morales. The lab takes 2 sittings, and a free plan can spread them over days.

| Sitting | Do it after | Tasks |
| --- | --- | --- |
| Sitting 1 | 25.1 to 25.6 | Setup, Tasks 1 and 2 |
| Sitting 2 | 25.7 to 25.11 | Tasks 3 to 5 |

### Before you start

> [!IMPORTANT]
> The lab's files are not published yet. The download link for `brightline-lab-ch25.zip` and the answer keys below will work once they are. Until then, read the tasks with the chapter.

**The download.** Everything starts from `brightline-lab-ch25.zip` ([download it here](https://github.com/panaversity/agentfactory-v2-resources/releases/latest/download/brightline-lab-ch25.zip)). It holds the `brightline-ap` repository at its tag `ch24`, with this lab's files added, so you can do this lab without having done Lab 24.

**What you need.** Node, Python with uv, git, the GitHub CLI, and Claude Code, Codex and OpenCode, each signed in. Your staging key for the Claude API goes in `.secrets/anthropic.env`. Task 5 needs an OpenAI project key with a hard spending limit, in `.secrets/openai.env`. No key passes through a chat.

**The job.** It is Monday, April 19, 2027. This morning's check in code refused INV-8340, from Midwest Packaging Co., because its terms came back as "Net 30 days". One extraction case in the suite has been red since Lab 24, and the threshold of 40 of 41 allows it.

**How a task works.** Start a fresh session with the named coding agent in `brightline-ap/`, and give it the task's prompt in plan mode. Make your prediction before the agent shows the result. Check the evidence against **What good looks like**, then download the task's answer key. End with a line in `ports/ch25.md`. `docs/chapter-25/` holds the concepts as text for your agents.

<!-- OPEN: the cost of the live steps is not measured yet -->

**Set up (Claude Code).** Unzip the folder, then give the agent this prompt.

> Read `README.md` and `AGENTS.md`. Put this folder under git with a main branch, in one first commit, "Start from the end of Chapter 24", and tag it `lab25-start`. Install the packages for both languages, as `README.md` says. Run the suite from its recorded answers, with no key and no network. Show me the report: how many cases pass, the threshold, and the one case it allows to fail. Finish by showing me that git tracks nothing in `.secrets/`.

**What good looks like:** one commit at the tag `lab25-start`. The suite reports 40 of 41 cases passing, which meets the threshold, and it names one extraction case as the known failure.

### Sitting 1: one change, the whole suite

**Before you start, answer in a line each:** Who re-reads the answers after a prompt changes (25.1)? What are the six steps of a revision (25.6)? **After this sitting, you can:** trace a failing case to one part of a prompt, change only that part, and prove with the whole suite that nothing else broke.

**New words in this sitting's prompts.**

| Word in a prompt | What it means |
| --- | --- |
| Red case, green case | A case the suite fails, and a case it passes |
| Label | The value Ana wrote down for a field, which the suite compares with the worker's answer (Chapter 24) |
| Diff | The lines a change removes and adds, shown side by side |
| Owned file | A file only you may change. The agent proposes a change and waits. The golden set, the labels and the threshold are owned files |
| Replay | Run the suite on answers that were recorded earlier, with no request to the model |
| CI | The checks GitHub runs on every pull request ([Chapter 15](../code-review/overview.md)) |

#### Task 1. The red case, and the part that causes it (Claude Code)

**Goal:** the red case is stopped by a check in code, then fixed by one change to one part of the extraction prompt, and the failure has a name.

**Predict:** you will see the invoice, Ana's labels and the worker's answer side by side. Which part of the prompt causes the wrong field? Choose one: the line that says who the model is, the list of fields, the line that asks for JSON, or nothing the prompt says at all.

**In plain words.** You read one failing case as a test, find the piece the prompt is missing, and change that piece only.

> Read 25.6 in `docs/chapter-25/`. Run the suite from its recorded answers, and show me the one red case: the invoice's text, Ana's label for each field, and the worker's answer, side by side, with the field that differs marked. Stop there and wait for my prediction. Then:
>
> 1. Say whether the answer is valid JSON, and whether the extraction step's check in code passed it. Name the failure with one of the six names 25.6 lists if one fits, and say so if none does. Then name what the prompt is missing, with the four kinds in 25.6's table, and say whether an example is the fix, by 25.4's test.
> 2. Before any change to the prompt, write the check that would have stopped this answer live. It is plain code in `src/extract/validate.ts`, with no model call. It refuses an answer whose total is not its subtotal plus tax, to the cent, and returns `needs_review` with the reason in plain words. Add a test that feeds it the red case's recorded answer, and show me the test passing.
> 3. Show me the extraction prompt. For each field in the answer, quote the sentence of the prompt that tells the model what belongs in it, or say "no sentence".
> 4. Propose one change, to that part only, as a diff. Change no other line. Wait for my approval.
> 5. Save the revised prompt as a new file, with the next version in its name, as 25.1 does. Leave the old file as it is. Point the extraction step at the new version in the one place that names it.
> 6. Run the red case alone, live. That is one request. Show me the new answer beside Ana's labels.
> 7. Add a line to `ports/ch25.md`: the case, the name of the failure, the piece that was missing, and the one sentence that changed.

**What good looks like:** the red case's answer is valid JSON with every field in place, and the check in code passed its shape. Its total is the invoice's subtotal. None of the six names fits well, because they say what went wrong in an answer. The table in 25.6 says what the prompt was missing, in its last row: a constraint that names the variant, here which amount is the total. The exam guide calls the fix instruction clarity. An example is not the fix, because the structure of the answer was not invented. The new check stops the recorded answer, with a reason that names the total. The prompt has no sentence that says which amount is the total. The change is four words in one sentence: the total, including tax. After it, the red case matches Ana's labels on every field. Your prediction: the list of fields, which names the total and never says which amount it is.

**Checkpoint:** the red case is green in a live run, and the diff is one sentence.

**Saves:** `src/extract/validate.ts` with its first check and test, the new version of the extraction prompt in `prompts/`, and your first line in `ports/ch25.md`.

<!-- OPEN: the extraction prompt's file name comes from Lab 24 -->

**Check it now.** Download [Task 1's answer key](https://github.com/panaversity/agentfactory-v2-resources/releases/latest/download/brightline-lab-ch25-key-task-1.md).

#### Task 2. The whole suite (Claude Code)

**Goal:** proof that the fix broke no other case, and a threshold with no known failure left in it.

**Predict:** you changed one sentence about the total. Can a case whose total was already right turn red because of it? Say yes or no, and why.

**In plain words.** You run the suite. Then you look at a second revision that the lab recorded for you. It is a larger rewrite of the same prompt, which fixes the red case and breaks others.

> Read 25.1 and 25.6.
>
> 1. Run the whole suite on the new prompt version. The 15 extraction cases run live, which is 15 requests. The 26 question cases replay their recorded answers, because the worker's own prompt did not change. Show me a table with one row for each extraction case: its result before my change, and its result after.
> 2. If any case that was green is now red, stop and show me its answer beside Ana's labels. Do not fix it with a second edit. Undo my change, and propose a narrower one.
> 3. Replay the recorded run in `tests/fixtures/revisions/broad-rewrite/`. It is a larger rewrite of the same prompt. Show me its diff against the old prompt, and the same before and after table. For each case it turned red, quote the old sentence that case rested on.
> 4. The threshold file is an owned file. Propose a change to it: every case must pass, and no case is named as a known failure. Wait for my approval.
> 5. Open a pull request with the new prompt version and the threshold, with the suite's report in its description. Wait for the suite's check in CI, and show me its result. I will merge.

**What good looks like:** on your prompt, 41 of 41 cases pass, and no row went from green to red. The broad rewrite turns the red case green and turns two other cases red. Each of the two rested on a sentence that the rewrite reworded while it fixed something else. Without the full run, that rewrite would have looked like a fix. The threshold now asks for every case, the check in CI is green, and you merged. Your prediction: yes. The model reads the whole prompt each time, so a change in one sentence can change an answer that has nothing to do with it.

**Checkpoint:** the pull request is merged, the suite passes 41 of 41, and the threshold names no known failure.

**Saves:** the threshold file, the pull request, and the before and after table in `ports/ch25.md`.

**Check it now.** Download [Task 2's answer key](https://github.com/panaversity/agentfactory-v2-resources/releases/latest/download/brightline-lab-ch25-key-task-2.md).

**Checkpoint 1: a prompt changed like code.** Before Sitting 2, check that you can do these without looking back.

- Say why you change one thing at a time, and what the suite does that a person no longer does (25.1, 25.6).
- Say what the broad rewrite fixed, what it broke, and what caught it.
- Say why the red case passed Lab 24's check in code, although its total was wrong.

### Sitting 2: the schema, the gates and the port

**Before you start, answer in a line each:** What does a schema that the API holds check, and what does it never check (25.7)? What does the code read before it parses anything (25.10)? **After this sitting, you can:** move an extraction to a schema the API enforces, and check each value in code. You can also prove with three recorded answers that no answer the code will not accept reaches the due-date code.

**New words in this sitting's prompts.**

| Word in a prompt | What it means |
| --- | --- |
| Enum | A fixed list of allowed values. Brightline's five terms are one ([14.5](../structuring-programs/schema-rules.md)) |
| Nullable | A field that may be empty, written `null`. It lets the model say "not on the invoice" |
| Range | A rule on a number's size, such as "zero or more". In a JSON schema it is written `minimum` or `maximum` |
| Fixture | A saved answer that a test feeds to the code, so the test needs no key and gives the same result every time |
| Gate | A check that an answer must pass before the next step sees it. An answer that fails a gate goes to `needs_review`, with the gate's name and the reason |
| `stop_reason` | The field of a response that says why the model stopped ([21.3](../agent-loop-by-hand/one-turn-request-response-and-stop-reason.md)) |

#### Task 3. A schema the API holds, and the value checks (Claude Code)

**Goal:** the invoice extraction runs under a schema that the API enforces, with the five terms and "other" as an enum. The invoice's text reaches the model as a tool result. Code checks the ranges and each value. INV-8340 is a case in the suite, and it passes.

**Predict:** [14.5](../structuring-programs/schema-rules.md)'s schema says the amount must be zero or more. If you send that schema to the API as it is, what happens: the API enforces the range, ignores it, or refuses the request?

**In plain words.** Now the API holds the shape, so "Net 30 days" cannot be written at all. You send 14.5's ranges to the API once, to see what it does with them, and your code checks the ranges itself. And the schema checks only the shape, never the truth, so your code checks each value against the invoice's own numbers and Brightline's records.

> Read 25.7 and 25.9.
>
> 1. Add INV-8340 to the golden set, and Ana's labels for it to the labels file, from the files in `data/invoices/new/`. These are owned files, so show me the change and wait. Then replay this morning's recorded answer for it, and show me why the check in code refused it.
> 2. Write `schemas/invoice-extraction.schema.json` with the eight fields 25.7 shows. `terms` is an enum of Brightline's five terms and "other". `poNumber` is nullable. Every object refuses fields the schema does not name. Keep 14.5's ranges in this file: it is the full schema that your code checks against.
> 3. Send one live request with the full schema as it is, ranges included. That is one request. Show me the status code and the error's text.
> 4. Write `src/extract/api-schema.ts`, which builds what is sent to the API from the full schema, with every range and length rule stripped. Write a test that fails if anything it builds still holds `minimum`, `maximum`, `multipleOf`, `minLength` or `maxLength`.
> 5. Read 25.2, 25.5 and 25.8. Show me the request the extraction step sends, part by part: which text is in the system prompt, which is in the user turn, and where the invoice's text is. Move the invoice's text into the result of a strict tool, `get_invoice`, that the portal's code serves, JSON-encoded, as 25.5 shows. Leave tool choice on `auto`. Add a check that refuses an answer with no `get_invoice` call before it. It returns `needs_review`, with the gate `stop reason` and the reason in plain words. Add a test for it.
> 6. Change the extraction call to send the stripped schema in `output_config.format`, with the type `json_schema`. Save the prompt as its next version. It no longer needs to ask for JSON. It must still say what each field holds, to write `null` when the invoice does not carry a value, and to choose "other" when the terms are not one of the five.
> 7. Extend `src/extract/validate.ts` from Task 1. It stays plain code with no model call. It takes a parsed answer and the tables it needs, and it returns either `ok` or `needs_review` with the gate `values` and a reason in plain words. It makes 25.9's five checks, in 25.9's order. First, each range that step 4 stripped. Second, the total equals the subtotal plus tax, to the cent. Third, the vendor exists in Brightline's tables. Fourth, the purchase order exists there when the answer names one. Fifth, `terms` is not "other". Write a test for each check.
> 8. Run the whole suite, with the 16 extraction cases live. Each case now takes two requests, one that asks for the invoice and one that answers, so that is 32 requests. The 26 question cases replay, because the worker's prompt did not change. Show me INV-8340's row and the totals. Do the same in the Python twin, and run its tests.

**Check before you approve.** Predict first: an invoice's terms are not one of the five, and the model chooses "other". Does the API accept the answer, and does the due-date code ever see it? Then ask the agent to show the lines of `validate.ts` that handle "other", and the test that proves it.

**What good looks like:** this morning's answer for INV-8340 holds "Net 30 days", and the check refused it, with no retry. The request with ranges comes back as a 400 error, because the API rejects a schema that holds `minimum`.[^anthropic-structured-outputs] In the new request, the rules are in the system prompt and the task is in the user turn. The invoice's text is one JSON string in the result of `get_invoice`. An answer with no `get_invoice` call before it ends at `needs_review`, with the gate `stop reason`. With the stripped schema, INV-8340's terms come back as "Net 30" and the case passes. The suite passes 42 of 42. Every test of `validate.ts` passes in both languages. For "other", the API accepts the answer, because the shape is right. The value check stops it, and it goes to `needs_review`. Your prediction: the API refuses the request.

**Checkpoint:** 42 of 42 cases pass under the enforced schema, and no range is left in what is sent.

**Saves:** `schemas/invoice-extraction.schema.json`, `src/extract/api-schema.ts`, the `get_invoice` tool and its check, `src/extract/validate.ts` with their tests and Python twins, the next version of the extraction prompt, and the changed golden set and labels.

<!-- OPEN: the policy task waits for its schema -->

<!-- EDITOR: Task 3 changes the golden set, and 25.1 says the judge runs when the golden set changes. The task's own run replays the 26 question cases, and the judge's run in CI on this pull request is not a step of the task. The other option: add a step that waits for the judge's run in CI and shows its result. -->

<!-- EDITOR: Task 3 has a new step 5 that builds the request's parts, the `get_invoice` tool result and the check that the tool was called, so 25.2, 25.5 and 25.8 have practice. The other option: keep the lab without it, and have those three sections stop naming a lab task. The step's files and its request count are proposed until the lab is built. -->

**Check it now.** Download [Task 3's answer key](https://github.com/panaversity/agentfactory-v2-resources/releases/latest/download/brightline-lab-ch25-key-task-3.md).

#### Task 4. Three gates, three fixtures (Claude Code)

**Goal:** every answer passes three gates in order before the due-date code sees it. The gates are the stop reason, then the schema, then the values. Three tests prove each gate from a fixture.

**Predict:** the fixture `max-tokens.json` holds an answer that was cut at the token limit. Its text still parses as complete JSON, with every field. Should the worker use it?

**In plain words.** When the model declines, nothing looks like an error (25.10). You put the gates in one place, in order, and you feed each one a recorded answer that it must stop.

> Read 25.9 and 25.10.
>
> 1. Write `src/extract/gates.ts`. It is the only way an extracted invoice reaches the due-date code. It reads the response's stop reason first, before it parses anything:
>    - `end_turn`: run Task 3's check that a `get_invoice` call came before this answer. If none did, mark the invoice `needs_review`, with the gate `stop reason`. If one did, go on to the next gate.
>    - `refusal`: the model declined. Never parse the content, and never send the same request again. Mark the invoice `needs_review`, with the gate `stop reason`.
>    - `tool_use`: the model is asking for `get_invoice`. Run it, return its result and call again. This is not an answer yet.
>    - `max_tokens`: the answer was cut. Treat it as failed, even if its text parses. Send the request once more with a higher token limit. If the second answer is cut too, mark the invoice `needs_review`, with the gate `stop reason`.
>    - `model_context_window_exceeded`: the answer was cut, and a higher limit cannot help. Mark the invoice `needs_review`, with the gate `stop reason`, and send nothing again.
>    - Any other value: mark the invoice `needs_review`, with the gate `stop reason`.
> 2. The second gate parses the text. It matches each enum value to the schema's list ignoring upper and lower case, and passes on the list's own spelling. Then it checks the answer against the full schema, ranges excluded, because the ranges are the third gate's first check. A failure is `needs_review`, with the gate `schema`. Text with no JSON value in it fails here too.
> 3. The third gate is `validate.ts`. When a value check fails on something the invoice can settle (the total, or a purchase order or vendor that is not in the tables), send the failure back as a new message, at most twice. For a purchase order or a vendor, stop as soon as the same value comes back. Never send back terms of "other". After the second failed round, mark the invoice `needs_review`, with the gate `values`.
> 4. Write three tests in `tests/output-gates.spec.ts`, each from one fixture in `tests/fixtures/output/`:
>    - `refusal.json` expects `needs_review` at the gate `stop reason`, no parse, and no second request.
>    - `max-tokens.json` expects exactly one more request, with a higher token limit, and then `needs_review` at the gate `stop reason`. The test answers the second request with the same cut answer.
>    - `wrong-total.json` is valid against the schema, and its total is its subtotal. It expects `needs_review` at the gate `values`, with a reason that names the total. The test answers each retry with the same wrong total.
> 5. In every test, assert that the due-date code was never called.
> 6. Add a count by gate to the morning report: how many answers passed all three gates, and how many each gate stopped, with each stopped invoice's reason beside it for Ana. Count each stopped invoice once, at the first gate that stopped it.
> 7. Run the three tests, then the whole suite from recorded answers. Write the Python twin, and run its tests.

**Check before you approve.** Predict first: which line would you delete to make the worker accept the refusal fixture as an empty invoice? Then ask the agent to show where `gates.ts` reads the stop reason, and confirm that no parse comes before that line.

**What good looks like:** three tests pass in each language, and none reaches the due-date code. The refusal is stopped before any parse, and it is sent once only, because a decline is never retried unchanged (21.3). The cut answer is sent once more with a higher limit, then handed to Ana. A stop of `model_context_window_exceeded` is treated as cut too, as Anthropic's guide says. But it is not sent again, because a higher output limit does not make the window larger.[^anthropic-stop-reasons] The wrong total passes the first two gates, since its shape is right, and the third gate stops it. The report's count by gate shows every invoice in exactly one row: passed, or the first gate that stopped it. Your prediction: no. Anthropic's guide says to treat any answer that stopped at the token limit as failed, even if its text holds valid JSON.[^anthropic-prompting-sonnet-5-5]

**Checkpoint:** each of the three fixtures ends in `needs_review` with its own gate and reason, and the suite still passes 42 of 42.

**Saves:** `src/extract/gates.ts`, `tests/output-gates.spec.ts`, the three fixtures' tests in both languages, and the report's count by gate.

**Check it now.** Download [Task 4's answer key](https://github.com/panaversity/agentfactory-v2-resources/releases/latest/download/brightline-lab-ch25-key-task-4.md).

#### Task 5. The port (Codex. The open-weight part is advanced, OpenCode)

**By hand first.** In the OpenAI dashboard, check that your project has a hard spending limit. Paste its key into `.secrets/openai.env` with your editor.

**Goal:** the same extraction on OpenAI's Structured Outputs, through the same validator, with a decline mapped to the same gate. A record of what moved unchanged and what did not.

**Predict:** which of your files will have no diff after the port? Choose from the prompt, the schema that is sent, the gates and the validator.

**In plain words.** You move the same extraction to a second AI vendor, which enforces a schema too. Then you record which of your files changed, and which moved unchanged.

> Read 25.11. Work in `ports/openai/extract/`.
>
> 1. Run the recorded tests in `tests/fixtures/openai/` first. They need no key.
> 2. Write the same extraction on OpenAI's Responses API, with the schema in `text.format`, the type `json_schema` and `strict` on. Build what is sent from the same full schema. In strict mode every field is required, so write a field that may be empty as a union with `null`.
> 3. Map OpenAI's answer onto the same three gates. A `refusal` item in the content is the model declining: `needs_review` at the gate `stop reason`, never parsed and never sent again unchanged. A response whose status is `incomplete`, with the reason `max_output_tokens`, is a cut answer: one more request with a higher limit, then `needs_review`. Everything else goes to the schema gate, and then to `validate.ts`, unchanged.
> 4. Make the refusal test and the cut-answer test pass from the OpenAI fixtures, and run the wrong-total fixture through the same validator.
> 5. Run the 16 extraction cases live on the staging OpenAI project. Tell me how many requests that is before you send them. Show me a table of each case's result on both vendors.
> 6. Write the port's section in `ports/ch25.md`: what carried over unchanged, what changed, and why.

**What good looks like:** the validator, the golden set and the labels have no diff. The gates gained one small mapping. Your notes name at least these differences. OpenAI reports a decline as a `refusal` item in the content, and a cut answer as a status of `incomplete`, where Claude reports both in the stop reason.[^openai-structured-outputs] In OpenAI's strict mode every field is required, and an empty field is a union with `null`.[^openai-structured-outputs] OpenAI's schema accepts `minimum` and `maximum`, so a range could stay in what is sent, and your code checks it all the same.[^openai-structured-outputs] The wrong total is stopped at the gate `values` on both AI vendors, because no schema checks the truth. Your prediction: the validator. The prompt needed no change either, if it named no AI vendor.

**The open-weight part (advanced, OpenCode).** A reader on the main path can skip it.

> Read the open-source part of 25.11. Run the same 16 extraction cases on an open-weight model behind a local server that takes a JSON schema. I will choose the server and the model. Pass the stripped schema in the server's own parameter, and send every answer through the same gates and the same validator. Count how many answers each gate stopped, and compare the counts with the two hosted runs. Then find out whether this server enforced the schema, or accepted it and did nothing: send one request with a field the schema refuses, and show me what came back. Record all of it in `ports/ch25.md`.

**What good looks like:** a count by gate for the local run, beside the two hosted runs. Your notes say whether the server enforced the schema. Some local servers do. Others drop a rule they do not support and report no error, as llama.cpp's guide says: "Unsupported features are skipped silently."[^llamacpp-grammars] Where the schema is only requested, the schema gate catches more, and the same validator still decides.

**Finish: the pull request and the tag.**

> Update `README.md` and `docs/deploy.md` with the extraction's gates and the report's count by gate. Run `/code-review` and `/security-review` on the branch, and fix or answer every finding. Open the pull request, wait for its checks, and show me both reviews. I will merge. Then tag the merge `ch25`, push the tag, and from a clean clone of the tag run every test that needs no key.

**Checkpoint:** the tag `ch25` passes from a clean clone, and `ports/ch25.md` has a section for each port you ran.

**Saves:** `ports/openai/extract/`, the port's tests, `ports/ch25.md`, and the tag `ch25`.

**Check it now.** Download [Task 5's answer key](https://github.com/panaversity/agentfactory-v2-resources/releases/latest/download/brightline-lab-ch25-key-task-5.md).

**Checkpoint 2: code reads the answer.** Check that you can do these without looking back.

- Name the three gates in order, and one fault that each one catches.
- Say why the wrong total passed the schema, and what stopped it.
- Say what happens to a decline, and to a cut answer, and why the two are handled differently.
- Say which of your files moved to a second AI vendor unchanged.

### Required and optional

*Required:* the setup and Tasks 1 to 5, with the OpenAI part of Task 5. *Advanced:* the open-weight part of Task 5.

### Apply it to your vertical (optional)

Pick one document your own business reads every day, such as an order, a claim or a lab result. List its fields. Mark each one as free text, one of a fixed set, or a number. Then write three value checks that a schema could never make, each against a record your business already keeps.

### If something goes wrong

| What you see | Why | What to do |
| --- | --- | --- |
| A 400 error that names `minimum` or `maxLength` | A range or length rule is still in the schema that is sent | Strip it in `api-schema.ts`, and check it in `validate.ts` (Task 3) |
| A case that was green is red after your change | The change altered an answer it was not meant to change | Undo it, and propose a narrower one. Never add a second edit to the same change (Task 2) |
| The refusal test parses an empty answer | The code parsed before it read the stop reason | Move the stop reason to the first line of `gates.ts` (Task 4) |
| The cut-answer test loops | The retry has no limit | Allow exactly one retry, with a higher token limit (Task 4) |
| A live run differs from the recorded one | A model's wording changes from run to run | Compare the fields with Ana's labels, not the text. Record the difference in `ports/ch25.md` |

### Artifact checklist

- [ ] The extraction prompt's new versions in `prompts/`, each reviewed in a pull request
- [ ] The threshold file with no known failure, and INV-8340 in the golden set with Ana's labels
- [ ] `schemas/invoice-extraction.schema.json`, and `src/extract/api-schema.ts` with its test
- [ ] `src/extract/validate.ts` and `src/extract/gates.ts`, with their Python twins
- [ ] `tests/output-gates.spec.ts`, with `refusal.json`, `max-tokens.json` and `wrong-total.json` each ending in `needs_review`
- [ ] The morning report's count by gate
- [ ] `ports/openai/extract/`, and `ports/ch25.md` with every prediction and each port's notes
- [ ] The tag `ch25`

## Exam notes

<!-- OPEN: the register entries listed for this chapter (D-012, D-013, D-022) belong to the Architect exam, CCAR-F, and D-022 names "CCAR-F v1.0, effective July 2026". The chapter's main exam is CCDV-F, guide 1.1. The paragraph below fills the template for CCAR-F. Confirm the exam, the guide version and the date, and add the template's last sentence with its link once this exam has an appendix page: the template's link goes to Appendix C, which is CCAO-F's -->

<!-- EDITOR: the introduction paragraph is held back until the exam and the guide version are confirmed. The draft's text named CCAR-F guide 1.0, in force from July 2026, as register entry D-022 does. The other option: the local copy of that guide, which says version 1.1, effective November 2026. The paragraph is the opening of the plan's exam-note template, filled for CCAR-F, and it is written from the template once the version is known. -->

<!-- OPEN: D-012, D-013, D-022 have no note text yet -->

<!-- EDITOR: the port note the lab plan asks for, that OpenAI and open source are taught here and the developer exam does not examine them, is in 25.11 as a hand-written "Exam note" line, as 23.19 has one. It has no register entry. The other option: remove that line from 25.11 until the register has an entry. -->

<!-- EDITOR: Lab 25, Task 2's prediction now asks about a case whose total was already right. The draft asked about an invoice with no tax line, and neither the prompt nor the schema says what taxCents holds on such an invoice. The other option: decide that with the open field list in 25.7, and bring the example back. -->

<!-- EDITOR: Lab 25, Task 5 does not say how the invoice's text reaches the model on OpenAI. The source notes record that OpenAI advises untrusted input in user messages, where Claude advises a tool result. The choice made: leave the task as it is until the lab is built. The other option: have the port's notes name this difference, or say that get_invoice is ported as a function call. -->

[^anthropic-structured-outputs]: Structured outputs, Anthropic.
[^anthropic-stop-reasons]: Stop reasons and fallback, Anthropic.
[^anthropic-prompting-sonnet-5-5]: Prompting Claude Sonnet 5.5, Anthropic.
[^openai-structured-outputs]: Structured model outputs, OpenAI.
[^llamacpp-grammars]: GBNF guide: JSON Schemas to GBNF, llama.cpp.
