Skip to the lesson
CivOps AI Academy · M01Paper to Glass: Digital Forms, Checklists and Inspections as Governed Records
0%

Chapter 1 · Sessions 1–2

What the old way holds, and the tables that replace it

Before anything is built, you find out what paper and which form tools the plant really uses and pays for, and you write the first form down field by field. Then one prompt adds the module's eight tables to your Foundation schema, with the tests that prove they refuse bad data, and you try them on the development project before the pipeline takes them to production.

30 min5 stepsSessions 1 and 28 frm_ tablesabout 7.5 hours hands-on across six sessions

By the end of this chapter you can

  • Inventory the plant's paper forms and form tools from the sheets and the bills, inventing nothing.
  • Write the first form to replace field by field, and settle its open questions with the person who reviews it.
  • Add the frm_ tables to the Foundation schema with one prompt, prove them on the development project, and let the pipeline apply them to production.

Check your names once. Every prompt, command and address below uses them.

Saved with your progress. Every prompt, command and address in the course now uses these names. Change them any time from Your names at the top of the page.

What Paper to Glass replaces

Paper to Glass turns any paper form, checklist, round or inspection into a governed digital record: filled in on the floor even with no signal, scored, signed, trended, and turned into follow-up work. It replaces the mobile forms and inspection tools a plant usually pays for. The module library names SafetyCulture (iAuditor) [6], GoFormz [7], Fulcrum, GoCanvas, ProntoForms, Jotform, Operations1 and Microsoft Forms with Power Apps. It is also the first module on the platform: later modules reuse its forms for their own data capture.

The edge of Paper to GlassInside: designer, ingestion, execution, scoring and routing, and field-to-table mapping. Outside, each with its owner: controlled SOPs in M06, step-enforced production in M04 and SPC charts in M09. INSIDE PAPER TO GLASS (M01)Form designerPaper ingestionExecutionScoring and routingField-to-table mappingOUTSIDE, WITH ITS OWNERControlled SOPsowned by M06Step-enforced productionowned by M04SPC chartsowned by M09, which reads form results
The edge of Paper to Glass. Inside: designer, ingestion, execution, scoring and routing. Outside, each with its owner: controlled SOPs (M06), step-enforced production (M04) and SPC charts (M09, which reads form results).

Every form has one category. Choosing it is the first decision in Session 1, because it decides who acts on the form.

CategoryWhat it isStamping plant example
inspectionA look at a thing against a standard, with pass or failPress pre-start check
checklistItems ticked off in orderDie change checklist
roundThe same points visited on a rhythmHourly gauge round on six presses
auditA scored review of an area or processWeekly 5S walk of the press shop
permitPermission for risky work, signed before it startsHot-work permit for a die repair
logA running record, one entry at a timeCoil delivery log
surveyQuestions to people, not checks of thingsOperator feedback after a trial
recordOne event written down onceTorque wrench calibration record
otherAnything elseA one-off site walk

The standards a form record is held to

Where a form is a regulated record (GxP), the US rule for electronic records and signatures, 21 CFR Part 11 [2], and the EU's Annex 11 apply. Everywhere else, the same design simply makes the record trustworthy. The test for every choice in this module is ALCOA+, from the FDA's and the MHRA's data-integrity guidance [3][4]: a record is Attributable, Legible, Contemporaneous, Original and Accurate, plus Complete, Consistent, Enduring and Available. A template version is documented information under ISO 9001 clause 7.5 [1].

ALCOA+ in Paper to GlassNine ALCOA+ attributes in a grid, each beside the feature that meets it. AttributablePerson and signatureLegibleTyped fieldsContemporaneousCapture timesOriginalImmutable submissionAccurateLimits on fieldsCompleteRequired fieldsConsistentPinned version, server clockEnduringArchive, not deleteAvailableSearch and PDFThe first five are ALCOA; the last four are the plus.
ALCOA+ in Paper to Glass. Each attribute beside the part of the module that meets it.
Step 1

Session 1: Inventory the forms you use and the tools you pay for

40 minutes, most of it on the floor

Why

The module must replace real things, not guesses. A walk of two areas finds the sheets nobody mentions in meetings, and the bills tell you what the old way costs. Writing it down with Claude Code takes minutes; the rule that it invents nothing means every number in it can be traced to a sheet or an invoice when you later claim a saving.

Do this

Walk two areas with their supervisors. For every paper form, checklist, round, inspection, audit, permit and log, write down: the name printed on it, who fills it in, how often, where the sheet goes afterwards, and what people work around (boxes left blank, filled in from memory at shift end, photos sent by text). Ask for one blank copy of each. Photograph a filled one only with the supervisor's agreement, and never one that names a person unless they agree.

Then, for every tool used for forms (a form app, a spreadsheet, a shared folder), open its bill on the vendor's own account page and write down the amount and the renewal date exactly as printed, and what export it offers. If you cannot see the bill, write who can. In Claude Code:

Terminal (Mac) or PowerShell (Windows)
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code, after replacing the <...> part
I am starting the Paper to Glass module (M01). It replaces our paper forms and form tools with the platform. Do not write any code in this session.

On a new branch m01/inventory, create docs/forms-inventory.md from my notes below, with two tables:
1. Forms: the name as printed on the sheet, the category (one of inspection, checklist, round, audit, permit, log, survey, record, other), the area, who fills it in (a job, never a person's name), how often, where the sheet goes afterwards, and what people work around.
2. Tools we pay for or use for forms: name, owner (a job), how people sign in, the bill amount and renewal date exactly as I give them, and the export it offers (CSV, API, PDF only, none).

Rules:
- Use only what is in my notes. Never fill in a price, a count, a date or a vendor feature I have not given you. Write "unknown, ask <who>" instead.
- If a form could be two categories, choose the one that decides who acts on it and say why in one line.
- End with "Questions to settle" for anything my notes leave unclear.

Open a pull request titled "M01: forms inventory", wait for the checks to finish, and tell me the result in plain words.

My notes:
<paste your notes from the walk and the bills here>

You will see recreated screen

claude — acme-platform
⏺ Write(docs/forms-inventory.md)
+| Press pre-start check | inspection | press shop | operator | each shift start | binder at the press | often filled at shift end from memory |
+| Hourly gauge round | round | press shop | quality technician | hourly | clipboard, then a drawer | gauges 4 and 5 often blank on nights |
+| Hot-work permit | permit | maintenance | maintenance lead | per job | supervisor's tray | signature needed before work: permit, not checklist |
1
⏺ Write(docs/forms-inventory.md)
+| Form app (mobile inspections) | quality lead | email + password | unknown, ask finance | unknown, ask finance | CSV export of submissions |
2
⏺ Pull request #38 adds docs/forms-inventory.md: 14 forms in two areas, 2 tools. The form app's bill and renewal date are marked unknown, ask finance, because your notes did not include them. Three questions to settle at the end.
Claude Code writes the inventory from your notes only. Where your notes had no figure, it says who to ask.
  1. Categories with a reason where a form could be two.
  2. No invented price: the figure comes from the invoice or it says who has it.

Check it worked

The pull request adds one file, docs/forms-inventory.md. Every form has a category; every price and renewal date is copied from a bill or says who to ask; no person is named.

If it goes wrong

Claude Code filled in a price or a count you never gave it

Say: Remove every figure I did not give you and write unknown, ask <who> instead. Agents fill empty places so a page looks finished: on our platform a report guessed a customer's revenue from headcount and showed it as fact. A saving you claim in Session 6 is only as good as the figures here.

You cannot see the bill for a tool

Write who can (finance, the person whose card pays it) and ask them for the invoice, not an estimate. The tool stays in the table with unknown until then.

A supervisor does not want filled forms photographed

Use the blank copy only. You need the questions and the limits, not anyone's answers.

Step 2

Session 1: Write the first form down field by field, and settle it with its reviewer

20 minutes

Why

Every later session builds this one form: its tables, screens, scoring and dashboards. Writing it field by field now, in words the reviewer can read, finds the missing limits and the unwritten rules while they cost a conversation. Found after the screens exist, each one costs a migration and a retest.

Do this

Choose the first form: one filled in often, with at least one number that has a limit, and a clear person who reviews it. Then:

Paste into Claude Code, after replacing the <...> parts
Read docs/forms-inventory.md and docs/naming-standard.md. The first form we will replace is "<form name>", because <one sentence why>.

On a new branch m01/first-form, write docs/forms/first-form.md, the form field by field for someone who does not write code. For each item on the sheet:
- field_key (lower case, words joined by underscores, following the naming standard), the label as printed, and the type: one of text, number, choice, multi_choice, date, datetime, photo, signature, barcode, gps, file, table, calculated, section;
- whether it is required;
- for a number: its unit, lower limit and upper limit exactly as printed on the sheet or in the standard the sheet names, or "not printed, ask <reviewer's job>";
- whether it needs a photo, a signature, a barcode scan or a GPS stamp;
- whether it is scored, and what should happen when it fails: nothing, an action item, or a work request for maintenance.
Then: the category, who fills it in, how often (in words: every shift start, every Monday), the due window and grace period in minutes we work to today, and who reviews or approves it.
Do not invent a limit. End with "Questions for the reviewer". Open a pull request titled "M01: first form", wait for the checks, and show me the link.

Sit with the reviewer and read the file on GitHub together. Answer the questions, then:

Paste into Claude Code, after replacing the <...> parts
The reviewer answered the questions in docs/forms/first-form.md:
1. <their answer>
2. <their answer>
They also said: <anything else they changed>.
Update the file to match, add "Checked with <their job> on <today's date>" at the top, and push to the same pull request.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/forms/first-form.md)
+| die_clamp_pressure_bar | Die clamp pressure | number | required | bar, 180 to 220 | | scored; fail = action item |
+| light_curtain_ok | Light curtain tested | choice: pass, fail | required | | | scored; fail = work request |
+| guard_photo | Guard in place | photo | required | | photo | |
+| press_tag | Press | barcode | required | | scan the press tag | |
1
⏺ Write(docs/forms/first-form.md)
+## Questions for the reviewer
+1. Is 180 to 220 bar right for every die, or does it depend on the die?
+2. The sheet is due at shift start. How late is still on time today: 30 minutes, 60?
2
⏺ Pull request #39 adds docs/forms/first-form.md: 9 fields, 2 scored items, 1 photo, 1 signature. Two questions need the quality lead before Session 2.
The field list for the stamping plant's press pre-start check. Yours follows your sheet.
  1. One row per item on the sheet: type, limits and what a failure starts.
  2. The questions are the point of the step: a limit nobody has written down becomes a rule in a table next session.

Check it worked

docs/forms/first-form.md is merged with every field typed, every number's limits from the sheet or the reviewer, the due window and grace period in minutes, and a line saying who checked it and when.

Fastest path

If the reviewer cannot meet, send them the link to the file on GitHub with the questions in the email. Do not start Session 2 until the answers are back.

If it goes wrong

A limit is printed nowhere and nobody knows it

Leave it empty and write it as an open question. A guessed limit flags good parts as failures, or misses bad ones, from the first day. The reviewer owns the answer.

The sheet has free-text boxes for everything

Ask the reviewer what people actually write there. Most free-text boxes hide two or three choices ("OK", "adjusted", "stopped") that are worth counting later.

The eight tables

The module library puts standard columns on every table: id, created_at, created_by, updated_at, updated_by, row_version, archived_at and ext, and a tenant_id. On your platform every module table carries site_id in place of tenant_id, as every Foundation table does (Session 5), so each table keeps one simple access rule. The module has no people table, site list or file store of its own: it points at shared tables, the spine, prefixed core_. The shared file docs/spine-map.md says which Foundation table plays each core_ name (sites for core_site, equipment for core_equipment), so every module you build meets the same map. Its own tables share the prefix frm_.

The eight frm_ tablesEight tables. A template has many versions and a version has many fields. An assignment points at a template. A submission points at a version and an assignment and has many responses and triggered actions. An ingestion job produces a version. frm_templatefrm_template_versionfrm_fieldfrm_assignmentfrm_submissionfrm_ingestion_jobfrm_responsefrm_triggered_actionhas manyhas manypoints atpinned tofromproduceshas manyhas many
The eight frm_ tables. A template has versions, a version has fields; an assignment points at a template; a submission points at a version and has responses and triggered actions; an ingestion job produces a version.
TableOne row isColumns (req = required; {a, b} = only these values; → points to)
frm_templateA form's headercode text req, unique; name text req; category req {inspection, checklist, round, audit, permit, log, survey, record, other}; owner_id → core_person; site_id → core_site; current_version_id uuid; status req {draft, published, retired}
frm_template_versionOne version of the form: its fields, logic and scoring as JSONtemplate_id → frm_template req; version_no int req; schema json req; logic json; scoring json; published_at ts; published_by → core_person; change_note text; source_ingestion_id uuid
frm_fieldOne field of one version, copied out for analytics and limitstemplate_version_id → frm_template_version req; field_key text req; label text req; field_type req {text, number, choice, multi_choice, date, datetime, photo, signature, barcode, gps, file, table, calculated, section}; required bool req; uom_id → core_uom; lsl num; usl num; options json; sort_order int; data_tag_id → core_data_tag
frm_assignmentA template given to a target, once or on a scheduletemplate_id → frm_template req; target_type req {equipment, location, area, person, role, site}; target_id uuid; assignee_person_id → core_person; assignee_role_id → core_job_role; rrule text; due_window_min int; grace_min int; active bool req; next_due_at ts
frm_submissionOne filling-in of one versionsubmission_no text req, unique; template_version_id → frm_template_version req; assignment_id → frm_assignment; subject_type text; subject_id uuid; status req {in_progress, submitted, in_review, approved, rejected, void}; started_at ts req; submitted_at ts; submitted_by → core_person; score num; max_score num; geo json; device_id text; captured_offline bool; signature_id → core_e_signature
frm_responseOne answer, in the column that matches its typesubmission_id → frm_submission req; field_key text req; value_text text; value_num num; value_bool bool; value_ts ts; value_json json; out_of_limit bool; failed bool; answered_at ts; attachment_id → core_attachment
frm_triggered_actionFollow-up work started by a failed answersubmission_id → frm_submission req; field_key text; action_type req {action_item, work_request, ncr, observation, notification, webhook}; target_module text; target_record_id uuid; status req {pending, created, failed}
frm_ingestion_jobOne paper form read by AI and reviewed by a personsource_attachment_id → core_attachment req; status req {queued, extracting, in_review, approved, rejected, failed}; extracted json; mean_confidence num; reviewer_id → core_person; reviewed_at ts; resulting_version_id → frm_template_version

Three rules keep the record honest, and the module library names breaking each one as a pitfall. A published version never changes: a change is a new version, and every submission stays pinned to the version it was filled in on. Every answer is a typed row, not one JSON blob, so limits, trends and failure counts are simple questions [5]. The record time is the server's clock, with the phone's capture time kept beside it, because a phone's clock can be wrong.

JSON blob or typed rowsThe same submission stored as one JSON blob, where a search opens every blob, and as typed frm_response rows, where one query answers it. One JSON blob{ "answers": { "pressure": "…", "temperature": "…", "signed": true } }Every pressure above its limit:open every blob, one by one.Typed frm_response rowsfieldvalue_numout_of_limitpressure…truetemperature…falsesigned——Every pressure above its limit:one query on value_num and out_of_limit.
The same submission stored two ways. In one JSON blob, finding every pressure above its limit means opening every blob. As typed rows, it is one question.
Step 3

Session 2: Check the spine before adding to it

10 minutes

Why

The module points at shared tables for people, sites, units, files and signatures. If Claude Code cannot find them it will create its own, and you end up with two lists of sites that drift apart. A read-only report first shows what exists, what plays the same role under another name, and what is really missing, so the next step adds only that.

Do this

Paste into Claude Code
Read docs/spine-map.md (if another module made it), docs/SCHEMA-PLAN.md, docs/naming-standard.md, docs/matrix.json and every file in supabase/migrations. Do not change anything.

Paper to Glass (M01) needs these shared ("spine") tables and helpers. For each one, tell me: exists (file and line), exists under another name in our schema (which table plays that role, for example our sites table for core_site), or missing:
core_person, core_site, core_job_role, core_uom, core_data_tag, core_attachment, core_e_signature, core_action_item, core_number_sequence, core_ai_suggestion, core_comment, core_approval, core_audit_log, and a trigger that sets updated_at, updated_by and row_version on every update.

Then tell me which of the module library's standard columns (id, created_at, created_by, updated_at, updated_by, row_version, archived_at, ext) our tables already use; our module tables carry site_id in place of tenant_id. Tell me how our generated access rules decide which rows a person may see.

Finish with a short plan: the rows M01 adds to docs/spine-map.md, and what one spine migration would add before any frm_ table, reusing instead of duplicating.

You will see recreated screen

claude — acme-platform
⏺ Read(supabase/migrations/20261016091500_create_first_tables.sql)
⎿ Read 96 lines
⏺ core_site: exists as sites (line 4). core_equipment: exists as equipment (line 12). core_person: no table; people are Supabase sign-in users with a row in memberships (line 40). core_job_role: exists as the role column on memberships, with the six roles from docs/matrix.json.1
⏺ Missing: core_uom, core_data_tag, core_attachment, core_e_signature, core_action_item, core_number_sequence, core_ai_suggestion, core_comment, core_approval, core_audit_log and the update trigger.2
⏺ Plan: one spine migration adds the eleven missing pieces with the standard columns and a site_id, and reuses sites, equipment and memberships. Access rules today are one rule per table on site_id, generated from docs/matrix.json; the new tables follow the same rule.3
The report: what exists, what plays the role under another name, what is missing.
  1. Reuse, not duplicate: your sites table plays core_site.
  2. Only these are new.
  3. The plan you approve before the next step.

Check it worked

Every spine name is marked exists, exists as, or missing, and the plan reuses your Foundation tables instead of creating second copies.

If it goes wrong

The plan creates core_site next to your sites table

Say: Reuse sites for core_site and equipment for core_equipment. Never create a second table for something we already keep. Two names for one thing is how a rename goes half done: on our platform three ids for the same demo company were live at once, and pages quietly showed zeros.

The plan adds a tenant_id column

Say: Our module tables carry site_id in place of tenant_id, as docs/spine-map.md says, so each table keeps one access rule.

docs/spine-map.md already maps a name differently

Another module decided it first. Keep its mapping, unless it is wrong for everyone; then change it in its own pull request that every module's tests run against.

Step 4

Session 2: One prompt: the spine pieces, the frm_ tables, their tests and the seed

20 minutes

Why

Writing the tables, the tests that try to break them and the made-up data in one pull request means the proof arrives with the change, and the next sessions have data to build screens on. The full column list is in the prompt, so Claude Code builds exactly the module library's tables and does not invent its own.

Do this

Paste into Claude Code
Read docs/forms/first-form.md, docs/naming-standard.md, docs/matrix.json and the spine plan you just gave me.

On a new branch m01/schema:

1. A spine migration first (npx supabase migration new m01_spine) with only the missing pieces from the plan, reusing our existing tables where they play the role. Add M01's rows to docs/spine-map.md (create it if missing). Each new table has the standard columns (id uuid primary key default gen_random_uuid(), created_at, created_by, updated_at, updated_by, row_version, archived_at, ext jsonb) and site_id in place of tenant_id. Include core_touch_row() (sets updated_at, updated_by and adds one to row_version), core_audit_log written by core_audit_row() after every insert, update and delete, and a trigger that refuses any update or delete of core_audit_log. Every function has set search_path = ''.

2. The module migration (npx supabase migration new m01_frm_tables): these eight tables with the standard columns, a site_id, and every column below. req means not null; {a, b} is a check constraint; → is a foreign key; "person" and "site" mean the tables the plan uses for them.
frm_template: code text req (unique per site), name text req, category req {inspection, checklist, round, audit, permit, log, survey, record, other}, owner_id → person, current_version_id uuid, status req {draft, published, retired}
frm_template_version: template_id → frm_template req, version_no int req, schema jsonb req, logic jsonb, scoring jsonb, published_at timestamptz, published_by → person, change_note text, source_ingestion_id uuid
frm_field: template_version_id → frm_template_version req, field_key text req, label text req, field_type req {text, number, choice, multi_choice, date, datetime, photo, signature, barcode, gps, file, table, calculated, section}, required bool req, uom_id → core_uom, lsl numeric, usl numeric, options jsonb, sort_order int, data_tag_id → core_data_tag
frm_assignment: template_id → frm_template req, target_type req {equipment, location, area, person, role, site}, target_id uuid, assignee_person_id → person, assignee_role_id → job role, rrule text, due_window_min int, grace_min int, active bool req, next_due_at timestamptz
frm_submission: submission_no text req (unique per site, issued from core_number_sequence), template_version_id → frm_template_version req, assignment_id → frm_assignment, subject_type text, subject_id uuid, status req {in_progress, submitted, in_review, approved, rejected, void}, started_at timestamptz req, submitted_at timestamptz, submitted_by → person, score numeric, max_score numeric, geo jsonb, device_id text, captured_offline bool, signature_id → core_e_signature
frm_response: submission_id → frm_submission req, field_key text req, value_text text, value_num numeric, value_bool bool, value_ts timestamptz, value_json jsonb, out_of_limit bool, failed bool, answered_at timestamptz, attachment_id → core_attachment
frm_triggered_action: submission_id → frm_submission req, field_key text, action_type req {action_item, work_request, ncr, observation, notification, webhook}, target_module text, target_record_id uuid, status req {pending, created, failed}
frm_ingestion_job: source_attachment_id → core_attachment req, status req {queued, extracting, in_review, approved, rejected, failed}, extracted jsonb, mean_confidence numeric, reviewer_id → person, reviewed_at timestamptz, resulting_version_id → frm_template_version
Every table: row-level security on with no policies yet, the core_touch_row() and core_audit_row() triggers, and an index on every foreign key.

3. Add every new table to docs/matrix.json with no rights yet, so the policy generator knows they exist.

4. pgTAP tests in supabase/tests/m01_schema.test.sql: every new table exists, has a primary key and has row-level security on; a category outside the list, a submission with no template version and a word in value_num are each refused; an update of core_audit_log is refused.

5. Made-up data in supabase/seeds/m01.sql, listed under [db.seed] sql_paths in supabase/config.toml: marked SYNTHETIC, every time shifted onto today from one moment read once at the start, and safe to run twice: one template "SYNTHETIC · Press pre-start check" with version 1 published and version 2 a draft; five fields; one daily assignment (FREQ=DAILY, 60-minute due window, 15-minute grace) whose twelve due times fall in the last twelve days; eleven submissions with typed responses: nine inside their due window, two after it, and one due time with no submission; three of the eleven with at least one failed answer.
   The hand-worked example, with fixed dates, goes in tests/fixtures/m01-hand-count.json (the same twelve due times and eleven submissions), not in the seed. Add a test that loads the fixture into the test database and counts exactly that.

6. Do not connect to or change any Supabase project, and do not run supabase db push.

Push, open a pull request titled "M01: frm tables", wait for every check to finish, and tell me in plain words: the tables added, the tests run, and the counts in the fixture. If a check fails, fix it and wait again before reporting. End with the exact commands I must type myself to try this on the development project.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase migration new m01_frm_tables)
⎿ Created new migration at supabase/migrations/20261102094500_m01_frm_tables.sql
1
⏺ Write(supabase/migrations/20261102094500_m01_frm_tables.sql)
+create table public.frm_response (
+ id uuid primary key default gen_random_uuid(),
+ site_id bigint not null references public.sites(id),
+ submission_id uuid not null references public.frm_submission(id),
+ field_key text not null,
+ value_text text, value_num numeric, value_bool boolean,
+ value_ts timestamptz, value_json jsonb,
+ out_of_limit boolean, failed boolean, answered_at timestamptz,
2
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m04s
⏺ Pull request #41 is green. The spine migration adds 11 pieces and docs/spine-map.md maps the rest onto sites, equipment and memberships; the module migration adds the 8 frm_ tables, all with row-level security on and no policies yet. 38 tests passed, 9 of them trying to store bad data. The fixture tests/fixtures/m01-hand-count.json has 12 due times: 9 on time, 2 late, 1 missing, and 3 submissions with a failed answer.3
Two migrations, the tests that try to break them, and the seed. Claude Code waits for GitHub before it reports.
  1. Two files, spine first: its time is earlier, so it runs first everywhere.
  2. Typed answer columns, one per kind of value: the second pitfall avoided.
  3. The fixture you will count by hand in Session 4.

Check it worked

Pull request M01: frm tables is green on GitHub, and the summary gives the table count, the test count and the fixture counts 12, 9, 2, 1 and 3; the seed is in supabase/seeds/m01.sql.

Fastest path

"Wait for every check and fix it before reporting" saves a round trip: Claude Code reads the failure while you do something else.

If it goes wrong

CI fails: relation "core_e_signature" does not exist

The module migration ran before the spine migration. Say: The spine migration must run first. Give it a timestamp before the module migration on this branch, re-run the tests and push. Only rename migrations that have not reached any database.

The answers went into one jsonb column

Say: Answers are typed rows in frm_response with value_text, value_num, value_bool, value_ts and value_json, as listed. JSON is only for the version's schema, logic and scoring.

The seed uses fixed dates such as 2026-10-01

Say: Count every time back from one moment read once at the start of the seed. We hit this: a seed with fixed dates was ten days old by the next week, and every "last shift" panel showed nothing.

Claude Code says it is green but the check on GitHub is red

Say: The check on the pull request is red. Run gh pr checks, read the failed log, fix the cause and wait for green before you report. A summary is a claim; the check on GitHub is the evidence.

Step 5

Session 2: Try it on the development project yourself, then merge

15 minutes

Why

Since Session 11 a merge applies migrations to production automatically, so the last place to catch a problem is before the merge. Applying the branch to the development project yourself, with its made-up data, shows the tables really build on a database that already has your Foundation data, which a fresh database in CI cannot show. Only a person does this, typing the password from the password manager.

Do this

In a terminal, not inside Claude Code:

Terminal or PowerShell
cd ~/code/acme-platform && git fetch && git switch m01/schema && git pull
Terminal or PowerShell
npx supabase link --project-ref tsrqponmlkjihgfedcba

It asks for the database password: copy it from the password manager entry for acme-platform-dev. Nothing shows as you paste; press Enter. Then check what will be applied, and apply the migrations and the seed to the development project. The first time a seed file is added, use --include-seed; after that, reload made-up data with npm run seed:dev. Never supabase db reset on a project.

Terminal or PowerShell
npx supabase migration list
Terminal or PowerShell
npx supabase db push --include-seed
Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor

The development project's Table Editor: the frm_ tables, with the SYNTHETIC template and eleven submissions.

When it looks right, owner two (sam@acme.com) approves the pull request and you merge it. The deploy pipeline then applies the two migrations to production:

Open

https://github.com/acme-ops/acme-platform/actions

The deploy run for the merge: green, with the two migrations applied.

You will see recreated screen

Terminal
$ npx supabase link --project-ref tsrqponmlkjihgfedcba
Finished supabase link.
$ npx supabase migration list
Local | Remote | Time (UTC)
20261102094000 | | 2026-11-02 09:40:00
20261102094500 | | 2026-11-02 09:45:001
$ npx supabase db push --include-seed
Do you want to push these migrations to the remote database? • 20261102094000_m01_spine.sql • 20261102094500_m01_frm_tables.sql [Y/n] y2
Finished supabase db push.
migration list shows the two new files on your branch but not yet on the development project; db push applies exactly those, then the seed.
  1. Two files on your branch, not yet on the development project.
  2. Check the project reference in the link command was tsrqponmlkjihgfedcba, the development project. If it lists files you do not expect, answer n.

You will see recreated screen

github.com/acme-ops/acme-platform/actions
M01: frm tables (#41)
Applying migration 20261102094000_m01_spine.sql...
Applying migration 20261102094500_m01_frm_tables.sql...
Finished supabase db push.
After the merge: the deploy run that applied the migrations to production.
  1. The pipeline, not a person, changed production, after review.
  2. Correct: real forms arrive in Session 4, real history in Session 6.

Check it worked

The development project has the frm_ tables and the SYNTHETIC rows from supabase/seeds/m01.sql; the deploy run for the merge is green; production's Table Editor (https://supabase.com/dashboard/project/abcdefghijklmnopqrst/editor) shows the frm_ tables, empty.

If it goes wrong

db push says: Remote migration versions not found in local migrations directory

The development project has a migration your branch does not, often another module's branch tried there and never merged. Do not force anything. In Claude Code: supabase db push on the development project says remote versions are not in the local directory. Tell me which versions differ and which branch each came from, without changing any project. Then decide with owner two.

The deploy run fails on the migration in production

Good: the pipeline stopped before the new code went live. Do not fix it in the dashboard. In Claude Code: The deploy failed applying m01 migrations in production. Show me the error from the run log and write the fix as a new migration on a new branch. Our production database once fell nine migrations behind main because nothing applied them; the pipeline exists so that cannot happen silently.

Rows marked SYNTHETIC appear in production

The seed ran on production. Stop and ask: Which command loaded the seed into production? List every SYNTHETIC row there without deleting anything. Made-up data in production must be found and removed only by a command that touches synthetic rows alone.

The seed fails with a duplicate key on the development project

Every seed must be safe to run twice. Say: supabase/seeds/m01.sql failed with a duplicate key when run again. Make it safe to run twice and add a test that runs it twice. Then reload with npm run seed:dev. Never use supabase db reset to get round it.

Knowledge check

A hot-work form must be signed by a supervisor before work starts. Which category fits it best?

Knowledge check

After the merge, who applies the frm_ migrations to production?

References

  1. ISO 9001:2015 Quality management systems: requirements (clause 7.5, documented information). https://www.iso.org/standard/62085.html
  2. eCFR: Title 21, Part 11, Electronic records; electronic signatures. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-A/part-11
  3. FDA: Data integrity and compliance with drug CGMP: questions and answers (2018). https://www.fda.gov/regulatory-information/search-fda-guidance-documents/data-integrity-and-compliance-drug-cgmp-questions-and-answers
  4. MHRA: Guidance on GxP data integrity (2018). https://www.gov.uk/government/publications/guidance-on-gxp-data-integrity
  5. PostgreSQL Documentation: Constraints. https://www.postgresql.org/docs/current/ddl-constraints.html
  6. Microsoft Store: SafetyCulture (iAuditor) feature list. https://apps.microsoft.com/detail/9nblggh5flq2
  7. GoFormz: mobile inspection management. https://goformz.com/use-cases/inspections
  8. Supabase CLI reference: supabase db push. https://supabase.com/docs/reference/cli/supabase-db-push

Chapter 2 · Session 3

Who may do what, and the three screens

People's rights to forms are decided once, in the role matrix, and the database rules, the route guard and the menus are generated from it. Then Claude Code builds the designer, the phone capture screen with its offline queue, and the supervisor's review queue, and the people who will use them try them on a phone.

25 min4 stepsSession 35 roles, 3 screens, 1 sync route

By the end of this chapter you can

  • Add the module's roles, rights and screens to docs/matrix.json and regenerate the rules and tests from it.
  • Have Claude Code build the three screens, with identity taken from the session and photos kept out of the project folders.
  • Prove the offline queue loses nothing and stores nothing twice, then watch an operator and a supervisor use the screens.

Rights start from nothing

Every role starts with no rights, and gets only what the job needs. Nobody gets delete: a correction is a new row or the status void, which keeps the record Original and Enduring. The matrix is the one place these decisions live; the access rules (row-level security [1]), the route list and the tests are generated from it, so they cannot disagree.

Role (a job)DesignsFills inReviewsReads
form designerDrafts: templates, versions, fields; assignments; ingestion jobsNoNoAll forms at the site
operatorNoOwn assignments; edits own submission only while in progress or rejectedNoPublished versions; own submissions
supervisorNoNoApprove or reject with a comment, never their ownSubmissions at the site
approverNoNoThe final approval stepSubmissions at the site
quality leadNoNoNoEverything in the module at the site
ScreenAddressWho may open it
Designer/forms/designerform designer
Capture, on a phone/forms/filloperator
Review queue/forms/reviewsupervisor, approver
Sync (the phone's queue sends here)/api/forms/syncoperator
Step 6

Session 3: The module's rows in the matrix, and the rules generated from them

20 minutes

Why

Writing rights into the matrix, not into code, means one reviewed line decides each right, and the database rules, the route guard and the tests all follow from it. Testing that a refused role is really refused, and that an allowed change really changes the row, catches the two access mistakes we hit most.

Do this

Paste into Claude Code
Read docs/matrix.json, scripts/gen-policies.mjs, lib/access/routes.ts and docs/access-review.md. Never edit a generated file by hand.

On a new branch m01/access, add Paper to Glass to the matrix:
- Roles (jobs, not people), reusing ours where they fit: form designer, operator, supervisor, approver, quality lead. Add only roles we do not have.
- Rights, starting from nothing:
  form designer: read every frm_ table at their site; insert and update frm_template, frm_template_version and frm_field only while the version is a draft (published_at empty); insert frm_assignment and frm_ingestion_job.
  operator: read published versions and their fields; insert frm_submission and frm_response for assignments at their site; read their own submissions; update their own submission and responses only while the status is in_progress or rejected; insert their own core_e_signature.
  supervisor: read submissions at their site; set status to in_review, approved or rejected; insert core_comment, core_approval and core_e_signature for a review; never on a submission they made.
  approver: the final core_approval step.
  quality lead: read everything in the module at their site.
  Nobody may delete. A correction is a new row or the status void.
- Screens: /forms/designer (form designer), /forms/fill (operator), /forms/review (supervisor, approver), and /api/forms/sync (operator).

Then run scripts/gen-policies.mjs and scripts/gen-routes.mjs so the policy migration, lib/access/routes.ts and docs/access-review.md come from the matrix. In supabase/tests/access.test.sql add one allowed and one refused test for every new cell, and: an operator at another site sees no submission here; a supervisor cannot approve their own submission; for every role that updates a row, read the row back and check it really changed.

Push, open a pull request titled "M01: who may do what", wait for every check, and tell me the result in plain words, quoting the new sections of docs/access-review.md.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/matrix.json)
+"frm_submission": {
+ "operator": { "insert": "own assignment", "update": "own, while in_progress or rejected" },
+ "supervisor": { "select": "site", "update": "status, never own" },
+ "quality lead": { "select": "site" }
1
⏺ Bash(node scripts/gen-policies.mjs)
⎿ Wrote supabase/migrations/20261104101000_policies.sql (+31 policies), lib/access/routes.ts, docs/access-review.md
⏺ Bash(gh pr checks --watch)
⎿ access / test pass 2m31s
2
⏺ Pull request #44 is green. 62 new access tests: 31 allowed, 31 refused, plus the cross-site test, the own-approval test and 7 read-back tests that check an update really changed the row. docs/access-review.md now has a section per role, for example: "supervisor: reads submissions at their site; approves or rejects, never their own."
One change to the matrix; everything else is generated from it, with tests in both directions.
  1. The decision, in the matrix, where owner two reviews it.
  2. Generated rules proven by tests in both directions.

Check it worked

The pull request is green, docs/access-review.md has a section for each new role, and the tests include the cross-site, own-approval and read-back tests.

If it goes wrong

A supervisor's Approve says success, but the status does not change

Postgres only updates rows the role can read, and the changed row must still pass the read rule. We hit this building this module. Say: For each role that updates frm_ rows, make its read rule cover the row before and after the change, regenerate, and add a test that reads the row back.

An operator can open /forms/review

Signed in is not the same as allowed. Say: Check lib/access/routes.ts against the matrix for /forms/review, regenerate it, and add a test that each refused role is refused.

A check fails that names a generated list, though your change looks fine

The generated files are older than the matrix. Say: Open the failed check's log, run the command it names to regenerate the files, commit them, and show me what changed. If the list shows a new unprotected route, stop.

Claude Code edits the generated policy SQL directly

Say: Revert that. Change docs/matrix.json and regenerate. A hand edit disappears the next time anyone regenerates.

Step 7

Session 3: The designer, the capture screen and the review queue

25 minutes

Why

The screens are where the record is made, so they decide whether it is attributable and complete. Two rules prevent the mistakes we made: the server takes who is signed in from the session, never from the page; and photos go to Supabase Storage, because the app's own folders cannot be written to on Vercel and anything in public/ can be opened by anyone.

Do this

Paste into Claude Code
Before writing any page or route, read the guides in node_modules/next/dist/docs/ for routing, server actions and proxy.ts in our version of Next.js, and our operator-screen rules from Session 12.

On a new branch m01/screens, build three screens against the development data:
1. /forms/designer: templates with their status; a draft version's fields in order (field_key, label, type, required, unit, lower and upper limit, evidence needed), editable; a published version read-only with a "New version" button.
2. /forms/fill: the operator's list of what is due (from frm_assignment.next_due_at), then the form one question at a time: targets at least 44 px, the number pad for numbers, a red flag the moment a number is outside its limits, photos from the phone's camera stored in a private Supabase Storage bucket (never in public/ or any project folder), and the signature at the end.
3. /forms/review: the supervisor's queue of submissions in status submitted, newest first, failed items first; one submission shows every answer, photo and the version it was filled in on.
Who is signed in comes from the session on the server, never from what the page sends. Every page and route goes through proxy.ts and the generated lib/access/routes.ts; add nothing public. Add Playwright tests at 360 and 390 px for each role that may open each screen, a test that each refused role is refused, and a signed-out test that each lands on sign-in.

Push, open a pull request titled "M01: screens", wait for every check and the Vercel preview, and tell me the preview link and what each test proved.

You will see recreated screen

https://acme-platform.vercel.app/forms/fill
Press pre-start check · P-03 · v11
Question 4 of 9
Die clamp pressure (bar)232
Back
Next3
The capture screen on a phone, one question at a time. A number outside its limits is flagged as it is typed, and still recorded as given.
  1. The version the form is filled on, in the header.
  2. Flagged, not refused: the record keeps the true reading.
  3. 44 px targets for a gloved thumb.

Check it worked

The pull request is green; the preview opens each screen for its roles at phone width; signed out, each lands on sign-in; a photo taken in the preview is in the Storage bucket, not in the repository.

If it goes wrong

Photos save in development and vanish on the preview

The code wrote them into a project folder. On Vercel those folders are read-only and each server copy is separate; we hit this when a register wrote where the server could not. Say: Store every photo in the private Supabase Storage bucket and add a test that fails if code writes into the project folders.

A photo opens from a plain address with no sign-in

It was put in public/. Files there skip every gate; on our platform customer emails sat there. Say: Move every uploaded file out of public/ into the private bucket, served only to signed-in roles from the matrix.

Every submission shows the same person as submitted_by

The page sent the name and the server trusted it; on our platform every record said it was made by the founder. Say: Take submitted_by from the signed-in session on the server and ignore anything the page sends. Add a test with two users.

Claude Code writes middleware.ts

This version of Next.js calls it proxy.ts. Say: Read node_modules/next/dist/docs/ on proxy.ts, use our existing proxy.ts, and delete middleware.ts.

From phone to serverAn offline submission is saved, queued with its own id on the phone and sent when possible. The server accepts it once, writes typed rows and confirms. PHONE (MAY BE OFFLINE)Save each answeras the person worksQueue the submissionown id, device_id, capture timesSend when it canretried until confirmedSERVERAccept it oncestamps its own timeWrite the typed rowsfrm_response, one per answerConfirm to the phonethe queue entry is clearedIf the confirmation is lost, the retry is recognised and not stored twice.
From phone to server. Each answer is saved on the phone; the finished submission waits in a queue with its own id; the server stores it once, stamps its own time, and confirms. A retry after a lost confirmation is recognised and not stored twice.
Step 8

Session 3: The offline queue, and the test that proves it

25 minutes

Why

A plant has dead spots, and a form that needs a signal fails exactly where it matters. The queue must lose nothing and store nothing twice: the submission's id is made on the phone, so a retry is recognised. We have had a save that said "created" and a minute later was gone, so the prompt asks for tests that are shown failing first, then passing.

Do this

Paste into Claude Code
On a new branch m01/offline, give /forms/fill its offline queue, reusing the outbox from Session 12. Rules:
- The submission's id is made on the phone with crypto.randomUUID() when the form opens. Every answer is saved to IndexedDB as it is given, so closing the app or losing signal loses nothing.
- device_id is made once per install and kept. captured_offline is true when the form was finished without a connection. started_at and each answered_at are the phone's times.
- On submit, the finished submission goes into the queue and is sent in the background with backoff, with its own id. The screen shows how many are waiting.
- /api/forms/sync inserts the submission and its responses in one transaction with on conflict (id) do nothing, takes submitted_by from the session, sets submitted_at from the server clock, and keeps the phone's finishing time in ext.device_submitted_at. The same id sent again adds nothing and answers "already received"; the same id with different answers is refused as a conflict and shown on the screen. A refused submission stays in the queue, visible, never deleted. If the sign-in has expired, the queue waits for sign-in and then sends.
- scripts/make-batch.mjs writes 50 synthetic submissions (every tenth outside its limits) in the queue's format, and a test-only button loads them into the queue. The button must not exist when VERCEL_ENV is production, read in one place only.

Playwright tests with the browser offline: submit three, close and reopen, the queue still shows three; go online, exactly three new submissions in the database, each with device_id, captured_offline, the phone's times and a later server submitted_at; send the same three again, still three; send a known id with different answers, the original is untouched and the conflict is shown. Show me each test failing with the on conflict line removed, then passing with it.

Push, open a pull request titled "M01: offline queue", wait for every check, and tell me the result in plain words.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx playwright test tests/forms-offline.spec.ts)
⎿ 4 failed (on conflict removed: 6 rows stored, expected 3)
1
⏺ Bash(npx playwright test tests/forms-offline.spec.ts)
⎿ 4 passed (12.8s)
⏺ Bash(gh pr checks --watch)
⎿ e2e / phone pass 4m02s
⏺ Pull request #46 is green. Three forms finished offline arrive exactly once each, with device_id, captured_offline and the phone's times; sending them again adds nothing; a conflicting copy is refused and shown. The test-only batch button is absent in production (tested).2
The proof: the tests fail with the safety line removed, and pass with it.
  1. Red first: without the safety line a retry stores the form twice. This is what proves the test can fail.
  2. Green, on GitHub, with the production guard tested.

You will see recreated screen

https://acme-platform.vercel.app/forms/fill
Press pre-start check · P-03Finished 06:04 · waiting
Press pre-start check · P-04Finished 06:11 · waiting
Hourly gauge roundRefused: changed on another device. Tap to see.2
The capture screen offline: what is waiting is shown, not hidden.
  1. The count is on screen, so nobody assumes a form was sent.
  2. A refusal stays visible until a person deals with it.

Check it worked

The pull request is green, and the summary says the tests failed with the safety line removed and passed with it.

If it goes wrong

The screen says "Sent" but no row arrives

A button that claims success while nothing happens is worse than an error. Say: Count a submission as sent only when the sync route answered with its id. Otherwise keep it in the queue and say so on screen. Add a test with the route switched off.

Two edits of the same rejected submission, and one is lost

The second save overwrote the first. We hit this: the app said "Created" and a minute later the record was gone. Say: Include row_version in every update of frm_submission and frm_response, refuse a stale save with a clear message, and test two saves from the same starting copy.

The test-only button appears on the live site

Say: Make the batch button refuse to exist when VERCEL_ENV is production, read that flag in one place, and add a test that fails if any other file reads it. On our platform a demo switch left on made every visitor an administrator.

The tests pass even with the safety line removed

Then they cannot fail, and prove nothing. Say: This test passes with the fix removed. Rewrite it to count rows in the database, show it red without the fix and green with it.

Step 9

Session 3: Try the screens on a phone, with the people who will use them

20 minutes

Why

A screen that passes every test can still be wrong for a gloved thumb in glare, or for a supervisor who reads forms between two other jobs. Twenty minutes watching the operator and the supervisor, without explaining anything, finds what the tests cannot.

Do this

Open

https://github.com/acme-ops/acme-platform/pulls

Open the M01 screens and offline queue pull requests: Vercel's comment on each has the preview link.

Open the preview on a real phone. If your previews read the development project, you see the SYNTHETIC form; if they read production, the list is empty until Session 4, and you try it then with your real form. Switch the phone to airplane mode, fill in one form, reconnect and watch it arrive. Then give the phone to the operator and the review queue to the supervisor. Say nothing; write down every place either stops or asks. Then:

Paste into Claude Code, after replacing the <...> part
Here are the notes from an operator and a supervisor trying the M01 screens:
<paste your notes>
Write each one as a one-line change request in docs/m01/try-out.md, marked screen, wording, or rule. Make the screen and wording changes on this branch with their tests; list the rule changes for me to decide. Push, wait for the checks, and tell me what changed.

Owner two approves each pull request; merge them in order: access, screens, offline queue.

You will see recreated screen

https://acme-platform.vercel.app/forms/review
Review · press shop
1
SubmittedFormPressFailed
06:14Press pre-start check v1P-031Open
06:09Press pre-start check v1P-010Open
P-03 · Die clamp pressure232 bar · limits 180–220 · flagged2
Reject with comment
Approve
The review queue as the supervisor sees it: failed items first, the version beside each answer.
  1. Newest first, and the failed count beside each.
  2. The answer as given, the limits it was checked against.

Check it worked

A form filled in airplane mode arrived once; docs/m01/try-out.md lists what the operator and supervisor hit; the three pull requests are merged.

If it goes wrong

The preview link answers 401

That is Vercel's preview protection, not your code. Sign in to Vercel on the phone, or share the preview from Vercel's Share button.

The phone zooms in when a field is tapped

Say: Set every input's font size to 16 px on the capture screen. Phones zoom into smaller text fields.

Knowledge check

Where is the decision "a supervisor may approve, but never their own submission" written first?

Knowledge check

A phone sends the same queued submission twice because the first confirmation was lost. What happens?

References

  1. Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
  2. Supabase Docs: Storage access control. https://supabase.com/docs/guides/storage/security/access-control
  3. MDN: IndexedDB API. https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  4. MDN: Crypto.randomUUID(). https://developer.mozilla.org/en-US/docs/Web/API/Crypto/randomUUID
  5. Playwright: BrowserContext.setOffline. https://playwright.dev/docs/api/class-browsercontext#browser-context-set-offline
  6. W3C: Web Content Accessibility Guidelines (WCAG) 2.2. https://www.w3.org/TR/WCAG22/

Chapter 3 · Session 4

The workflow, end to end

Your real form goes in as a draft and is published, and from then on it cannot change. It is assigned on a schedule, filled in, scored and signed on the server, reviewed, and a failed answer starts follow-up work with a link back. Two dashboards then have to match a count you make by hand.

25 min4 stepsSession 46 submission statuses1 hand count

By the end of this chapter you can

  • Make a published version impossible to change, in the database, and prove it.
  • Assign a form on a schedule; score and sign it on the server; turn a failed answer into linked work; review it with a comment.
  • Build the completion and overdue dashboards and check them against a hand count of the fixture.

Versions, statuses and the record clock

A template's status is draft, published or retired. A version is a draft while its published_at is empty; publishing sets it, and from then on the version and its fields are read-only. A change is a new version with a change note. A submission moves through in_progress, submitted, in_review, approved or rejected, or void, and always names the version it was filled on.

Versions and pinned submissionsOne template with two versions. Two submissions are pinned to version 1 and one to version 2. One templatefrm_templateVersion 1published, left unchangedVersion 2publishedreplaced bySubmission Apinned to version 1Submission Bpinned to version 1Submission Cpinned to version 2A submission never moves to another version.
One template, two versions, three submissions. Version 1 stays unchanged when version 2 is published; submissions never move between versions.

The schedule is a recurrence rule from the iCalendar standard, RFC 5545 [1]: FREQ=DAILY is every day; FREQ=WEEKLY;BYDAY=MO,WE,FR is Monday, Wednesday and Friday. The module stores the next due time in next_due_at.

One due time, to scaleA due time of 06:00 with a 60-minute window ending at 07:00, when the specification counts it overdue, then a 15-minute grace period; this course escalates after 07:15. Drawn to scale. 06:00 due07:0007:1507:30Window: 60 minutes, on timeGrace: 15 minEscalatedPast the due window at 07:00: overdue in the specification's KPI.This course escalates and publishes frm.assignment.overdue after 07:15.
One due time, to scale. Due at 06:00 with a 60-minute window: on time means submitted by 07:00, and from 07:00 the module library's overdue KPI counts it. This course escalates, and raises frm.assignment.overdue, only after the 15-minute grace period, at 07:15.

Signatures with a meaning

A signature records who signed, when, and what the signature means (performed, reviewed, approved). Part 11 asks for exactly these three in a signed electronic record, linked so they cannot be copied to another record [2]. Here, a signature is a core_e_signature row with a hash of the answers it signed, created only after the person confirms their password again.

action_typeWhat it createsWhere
action_itemA task with an owner and a due dateThe spine's core_action_item, when no other module is installed
work_requestA request for maintenanceM05 Maintenance
ncrA nonconformance reportM08 Quality
observationA recorded observation, such as a safety oneM11 Safety
notification, webhookA message, or a call to another systemOptional extension (integration mapping)
From a failed answer to follow-up workA failed answer sets a flag on its response row, a rule creates a triggered action row, and the target record is made in M05, M08, M11 or the core. Failed answerfailed or out_of_limiton frm_responseRule firesmakes a row infrm_triggered_actionWork requestmodule M05NCRmodule M08Observationmodule M11Action itemthe coreEach record id points back to the submission.
From a failed answer to follow-up work. The response is flagged, a triggered action row is made, and the target record links back to the submission.
Step 10

Session 4: Publish locks a version, in the database

20 minutes

Why

Editing a published form in place makes every earlier submission look as if it answered a question it was never asked. The module library makes this rule database-enforced, so no screen, import or agent can break it, and you prove it by trying. Your real form then goes in as version 1 on production, where it waits, unused, until it is assigned.

Do this

Paste into Claude Code
On a new branch m01/publish:
1. A new migration with a trigger on frm_template_version and frm_field that refuses any update or delete once the version's published_at is set, with the message "published versions cannot change: make a new version". frm_template.current_version_id may only point at a published version.
2. In the designer: Publish sets published_at and published_by from the session; "New version" copies the current version into a draft with version_no + 1 and asks for a change note.
3. Export a version (schema, logic, scoring and fields) as one JSON file, and import such a file as a new draft. An import never publishes.
4. pgTAP tests: updating a published version is refused; updating a field of a published version is refused; a draft can still be edited; current_version_id cannot point at a draft. Show each refusal test failing without the trigger, then passing.
Push, open a pull request titled "M01: published versions cannot change", wait for every check, and tell me the result in plain words.

Try it on the development project as in Step 5 (npx supabase db push, linked to tsrqponmlkjihgfedcba), then prove the refusal yourself:

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new

The development project's SQL editor. Paste the text below and press Run: it must fail.

Supabase SQL Editor, development project
-- Development project only. Must be refused by the trigger.
update public.frm_template_version set change_note = 'edited in place'
where published_at is not null;

Merge after owner two approves. Then, on the live site, enter your real form from docs/forms/first-form.md in the designer as version 1, and publish it:

Open

https://acme-platform.vercel.app/forms/designer

The designer on your live site, signed in as a form designer.

You will see recreated screen

supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new
update public.frm_template_version set change_note = 'edited in place'
where published_at is not null;
The refusal in the SQL editor: the database, not a screen, keeps the rule.
  1. Refused for everyone, including you in the dashboard. That is the point.

You will see recreated screen

https://acme-platform.vercel.app/forms/designer
Press pre-start check
Statuspublished · v1 · 2026-11-09 by quality lead1
#FieldTypeLimits
1press_tagbarcode
4die_clamp_pressure_barnumber180–220 bar
5light_curtain_okchoicepass / fail
New version2
Your real form in the designer, published as version 1.
  1. Who published it, and when, from the session.
  2. The only way to change it: a new version with a change note.

Check it worked

The update in the development SQL editor is refused with the trigger's message; the pull request's tests showed red without the trigger; your real form is published as version 1 on the live site.

If it goes wrong

The update in the SQL editor succeeds

The trigger is missing on the development project or was written for the wrong table. Run npx supabase migration list: if the publish migration is not under Remote, apply it. If it is, say to Claude Code: The update of a published version succeeded on the development project. Find why the trigger did not fire and add a test that would have caught it.

Claude Code made the rule a check in the designer screen only

Say: The rule must be in the database, as a trigger, so imports and agents keep it too. Keep the screen check as well, as a friendly message.

Step 11

Session 4: Assign it, score it, sign it, and turn a failure into work

30 minutes

Why

This is the part the old tool did for you, now on your platform and under your rules. Doing the schedule, the score, the signature and the follow-up in one prompt keeps them consistent: the server, not the phone, computes the score and stamps the time, so nobody can change a result by changing a phone; and every failed answer starts work that links back to it.

Do this

Paste into Claude Code
Read docs/forms/first-form.md and docs/matrix.json. On a new branch m01/workflow:
1. Assignments: a designer assigns a published template to a target (equipment, location, area, person, role or site) with an RRULE, a due window and a grace period in minutes. A scheduled job sets next_due_at from the rule. The overdue rule, written into docs/forms-rules.md: a due time with no submission is overdue from the end of its due window (what the dashboard counts); after the grace period it is escalated to the supervisor and frm.assignment.overdue is raised, once.
2. Scoring: weights live in the version's scoring JSON. On submit, the server (never the phone) adds the weights of the typed answers into score and max_score, and sets out_of_limit from lsl and usl and failed from the scoring.
3. Signature with meaning: on submit the operator confirms their password again; the server writes core_e_signature (signer from the session, meaning "performed", record_type frm_submission, record_id, a hash of the submitted answers, signed_at from the server clock, printed_name as shown on screen) and stores its id in signature_id.
4. Failed answers: each failed or out-of-limit answer makes a frm_triggered_action. With no other module installed, action_type is action_item and the target is a core_action_item that links back to the submission. If M05, M08 or M11 is installed, use its record instead. Status is created, or failed with the reason shown to the supervisor; never silently pending.
5. Review: reject needs a comment, stored in core_comment (owner_type frm_submission), and returns the submission to the operator with the answers intact; resubmit, then approve. Approval signs with meaning "approved" on a core_approval row. A form that needs a second approval (a permit) is approved only when the last core_approval step is.
Tests: a hand-worked score equals the stored one; a changed answer no longer matches the signature's hash; a failed answer makes exactly one linked record; a rejected form keeps its comment and answers; nobody approves their own submission.
Push, open a pull request titled "M01: the workflow", wait for every check, and tell me the result in plain words.

Try it on the development project (as in Step 5), merge after owner two approves, then on the live site assign your real form to one press for tomorrow's first shift.

You will see recreated screen

claude — acme-platform
☒ Assignments, next_due_at and the overdue rule (docs/forms-rules.md)
☒ Server-side scoring
☒ Signature with meaning and hash
☒ Failed answer → action item with a link back
☒ Reject with comment, resubmit, approve
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass · access / test pass · e2e / phone pass
⏺ Pull request #49 is green. A submission with clamp pressure 232 bar scored 7 of 9, as worked by hand; it made one action item linked to SUB-000112. Changing one answer after signing breaks the hash check. A supervisor could not approve their own submission.1
One prompt, five parts, each with the test that proves it.
  1. The numbers you can check yourself: the score and the one linked record.

Check it worked

docs/forms-rules.md holds the overdue rule; the tests prove the score, the signature hash, the one linked record and the comment; the real form is assigned on the live site.

If it goes wrong

The phone computes the score

Say: Compute score, max_score, out_of_limit and failed on the server from the stored answers and the version's scoring. Ignore any score the page sends.

A failed answer made two action items

The sync route ran the rule on the first send and again on the retry. Say: Make the failed-answer rule run once per response, keyed on the response id, and add a test that sends the same submission twice.

A triggered action stays pending for ever

Say: Show every frm_triggered_action that is pending for more than five minutes, or failed, at the top of the supervisor's queue, with the reason. A failed answer nobody acts on is a form nobody read.

Step 12

Session 4: Dashboards that match a hand count

20 minutes

Why

A dashboard nobody can reproduce by hand is a number nobody should trust. The fixture from Step 4 has known counts, so a count on paper tells you whether each query uses the same rule as the paper. We have shipped a chart that drew twelve hard-coded points and called them "In control"; every widget here must show "No data" rather than a number nobody measured.

Do this

Paste into Claude Code
Read docs/forms-rules.md. On a new branch m01/dashboards, add to the dashboard from Session 15:
- Completion rate: submitted on time divided by scheduled, in the period.
- Overdue: due times past their due window with no submission, with age, by area and assignee.
- First-pass pass rate: submissions with no failed answer divided by submissions.
- Failure Pareto: failed answers by question, by press and by area.
Each widget says where its number comes from (tables and rule) and shows "No data" when there is none, never 0 for unknown. Nothing is typed in or generated. Add a test that runs each query on tests/fixtures/m01-hand-count.json and expects: 12 scheduled, 9 on time, 2 late, 1 overdue, 8 of 11 with no failed answer.
Push, open a pull request titled "M01: dashboards", wait for every check and the preview, and tell me the numbers each widget shows on the development data.

Before you read Claude Code's numbers, count the fixture yourself, and write your count down. It is a readable file of twelve due times and eleven submissions with fixed dates:

Open

https://github.com/acme-ops/acme-platform/blob/main/tests/fixtures/m01-hand-count.json

The hand-worked example on GitHub: count submissions by submitted_at against each due time.

CountYoursExpected from the fixture
Due times scheduled12
Submitted inside the window9
Submitted after the window2
Due times with no submission (overdue)1
Submissions with no failed answer8 of 11

You will see recreated screen

https://acme-platform.vercel.app/dashboard
Completion rate75% · 9 of 12 on time1
Overdue1 · 6 days old · press shop2
First-pass73% · 8 of 11
From frm_assignment and frm_submission; overdue from the end of the due window (docs/forms-rules.md).
3
QuestionFailed
Die clamp pressure2
Light curtain tested1
The dashboard on the preview, against the seed. Each number says where it comes from.
  1. 9 ÷ 12: the same as your hand count.
  2. Counted from the window, as the rule says; escalation waits for the grace period.
  3. The Pareto: where the failures are.

Check it worked

Your hand count and every widget agree exactly: 12, 9, 2, 1 and 8 of 11. Then merge.

Fastest path

Count first, then read the dashboard. Reading it first makes it too easy to count your way to its answer.

If it goes wrong

The dashboard says 10 on time and you counted 9

Fix the query, not the count. Say: The completion widget says 10, my hand count of the fixture says 9. Show me which submission you count as on time and the rule you used, against docs/forms-rules.md. Usually one query uses the grace period and the other does not.

The test expects counts the fixture never makes

We found this in reviews of five Academy modules: later steps expected numbers the data did not create. Say: For every count this test expects, show me the fixture rows that create it. Fix the fixture, not the test.

A widget shows 0 where there is no data yet

Say: Show No data, not 0, when a widget has nothing to count, and test it with empty tables.

Knowledge check

Why must the server, not the phone, compute the score and stamp submitted_at?

Knowledge check

An item is due at 06:00 with a 60-minute window and a 15-minute grace period. In this course, when is it escalated?

References

  1. IETF RFC 5545: Internet Calendaring and Scheduling Core Object Specification (iCalendar). https://www.rfc-editor.org/rfc/rfc5545
  2. eCFR: 21 CFR 11.50, Signature manifestations. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-A/part-11/subpart-C/section-11.50
  3. PostgreSQL Documentation: Trigger functions (PL/pgSQL). https://www.postgresql.org/docs/current/plpgsql-trigger.html
  4. PostgreSQL Documentation: INSERT, including ON CONFLICT. https://www.postgresql.org/docs/current/sql-insert.html

Chapter 4 · Sessions 5–6

Move the data in, and switch the old way off

A scanned paper form becomes a draft, with AI proposing the fields and a person deciding each one. The old tool's history is rehearsed on the development project, then imported into production through the pipeline, with counts that must match. You run old and new side by side, prove the offline queue on a real phone, cut over and cancel what you no longer need.

25 min5 stepsSessions 5 and 6AI proposes, a person decidesCounts must match

By the end of this chapter you can

  • Turn a scan into a draft version with field-by-field human review, with any AI key handled by a person and registered by name.
  • Build the history import, rehearse it on the development project, then run it into production through the pipeline with matching counts.
  • Prove the module side by side with the old way, cut over on a date, and record the saving from real invoices.
One ingestion jobA paper form scan becomes an ingestion job, moves from queued to extracting to in_review, and on approval creates a draft template version. On rejection or failure nothing is created. Source filescan or photoqueuedextractingin_reviewaccept or edit fieldsDraft versionresulting_version_idapprovedNothing createdrejected or failed
One ingestion job. Queued, extracting, in review; a reviewer accepts or edits each proposed field; approval makes a draft version linked both ways. Rejected or failed jobs create nothing.

The job keeps its provenance: the file it came from, what the AI proposed, the average confidence, who reviewed it and when, and the version it produced. The proposal is also kept as a core_ai_suggestion. Anyone can later see which fields came from the machine and who accepted them: the record stays Attributable [3].

Step 13

Session 5: A scanned form becomes a draft, field by field

30 minutes

Why

Typing a long paper form into the designer is slow; reading it with AI is fast but can misread a limit, which passes a glance and fails an inspection. So the AI only proposes, and a person decides each field. The AI step is optional: typing the fields by hand is free. If you use it, the provider's key is entered by a person in Vercel, and listed by name only.

Do this

If you use the AI step, a person creates the provider's key in the provider's console, with a monthly spending limit, and types it into Vercel (Production and Preview, not exposed to the browser). Paste the value only, never NAME=value. Nobody pastes it into Claude Code, a chat or a file.

Open

https://vercel.com/acme-ops/acme-platform/settings/environment-variables

Add AI_API_KEY (or the name your Session 10 start-up check expects), Production and Preview.

Key or secretWhat it unlocksWhere it livesWho holds itNever
AI provider API key (AI_API_KEY)Calls to the AI model for paper ingestion, billed per pageVercel, server only (Production, Preview)pat@acme.com creates and types it; sam@acme.com can rotate itNever in a chat, a file, a NEXT_PUBLIC_ variable or the browser
Paste into Claude Code
On a new branch m01/ingest:
1. Upload of a scan or PDF as a core_attachment (private Storage bucket) creates a frm_ingestion_job, status queued.
2. If AI_API_KEY is set: one small module, lib/ai/models.ts, holds the model name and reply limit for this use, so no screen or route names a model. The job moves to extracting, sends the scan and nothing else, and asks for a list of fields: label, a type from frm_field's list, unit and limits only where printed, and a confidence for each. A limit it cannot read comes back empty, never guessed. It records the call's cost before saving and shows the cost per page before a batch runs. A failed call sets the job to failed with the reason shown. If the key is missing, the screen says so; it never pretends.
3. The proposal goes into extracted and core_ai_suggestion (status proposed), with mean_confidence; status in_review.
4. A review screen shows one proposed field at a time beside the scan: accept, edit or reject. reviewer_id and reviewed_at from the session. Approve creates a draft version with the accepted fields and links resulting_version_id and source_ingestion_id both ways. Nothing is published from here.
5. Add the key's name, AI_API_KEY, to docs/KEYS.md and to the Session 10 start-up check (name and shape only, never the value).
Tests with a stand-in for the AI that returns a fixed proposal: the job's statuses in order; a rejected field never becomes a field; approval makes a draft, never a published version; a missing key gives an honest message.
Push, open a pull request titled "M01: paper ingestion", wait for every check, and tell me the result.

After the merge, upload a blank scan of one form from your inventory (flat, lit, no names), review every field with the person who fills the form in, and write down: fields proposed, accepted without edit, and which kinds the AI got wrong. That ratio is the paper ingestion acceptance KPI.

You will see recreated screen

https://acme-platform.vercel.app/forms/ingest/17
Ingestion job 17 · in review · field 4 of 11
LabelDie clamp pressure
Typenumber ▾
Unit · lower · upperbar · 180 · (not read)1
Confidence0.622
Reject
Edit
Accept
The review screen: one proposed field at a time, beside the scan. A limit the AI could not read is empty, for the reviewer to fill in.
  1. Empty, not guessed: the reviewer fills it from the paper.
  2. Low confidence: look twice.

Check it worked

One scanned form became a draft version through field-by-field review, with reviewer, time and your acceptance count recorded; AI_API_KEY (if used) is in Vercel and in docs/KEYS.md by name only.

If it goes wrong

The feature fails although AI_API_KEY is set in Vercel

The value may be wrong: on our Academy a key's value was the variable's own name, pasted by mistake. Re-type the value only in Vercel and redeploy. The start-up check should name the key and what is wrong, never print it.

Calls from the plant network fail with 403 "forbidden"

Before changing any key, find who refused it: often a company proxy. Say: This call returned 403. Show me the response body and tell me whether it came from the provider, a proxy or a rate limit, without changing any key.

The key was pasted into a chat or committed

Treat it as public: revoke it in the provider's console the same day, create a new one, type it into Vercel, and note the date in docs/KEYS.md.

Step 14

Session 5: Build the import, and rehearse it on the development project

35 minutes

Why

Old records are evidence of what happened, so they come in read-only and are never counted as new work. Building the import as reviewed code, run from main by a workflow with an insert-only account, means real records reach production only through the pipeline, with their fingerprint and counts printed, never through a laptop or a chat. A rehearsal on the development project, with a copy IT approved in writing, finds the mapping problems first.

Do this

Take the export yourself from the old system's own export page, into a private folder outside the repository. Claude Code never reads it. Give it the first line of each file only, the column names:

Paste into Claude Code, after replacing the <...> part
We will move the old form tool's history in. The export file stay outside the repository and you will not read it. The first line of each, the column names only:
<paste the first line of the export: column names only, no data>

On a new branch m01/import:
1. scripts/import-m01.mjs, which reads the export file in this format and maps each row to an archived frm_submission (archived_at set, the original dates kept, ext.origin 'import', ext.source_tool and the original author's name as text) with its frm_response rows, matching the old question names to field_key values in our published template. Rows it cannot match are not imported but listed with the reason. It prints each file's sha256 and the counts: rows, records it would create, rows skipped. In dry-run mode it writes nothing.
2. A migration that creates this module's import account: a database role import_m01 that can log in, with insert only on frm_submission and frm_response and on an insert-only table import_log (module, file, sha256, counts, run_at, run_by), read on the private Storage bucket imports, and nothing else: no update, no delete, never the service role key. A trigger refuses any update of a submission or response whose ext.origin is 'import'. A file whose sha256 is already in import_log is refused.
3. .github/workflows/import-m01.yml, started only by hand from main (workflow_dispatch), with inputs target (development or production), file (its path in the bucket imports) and apply (default false). It downloads the file from the target project's bucket, signs in as import_m01 with a password a person stores as a GitHub secret (IMPORT_M01_PASSWORD_DEV and IMPORT_M01_PASSWORD_PROD, listed by name in docs/KEYS.md), and runs the script. For production with apply true it refuses unless docs/imports/m01-approved.md on main lists this file's sha256 and expected counts, and it fails on any count mismatch. It never prints a row of the export.
4. Tests on a made-up ten-row file per export (SYNTHETIC values): a dry run writes nothing; apply creates the expected counts; the same file again is refused; an unmatched question is listed; an imported row cannot be updated; import_m01 cannot update or delete anything.
Do not run the workflow and do not set any password. Push, open a pull request titled "M01: import", wait for every check, and tell me the result in plain words, with the secrets I must create myself.

Try it on the development project and merge it, as in Step 5. Then a person creates the import account's password in the password manager, sets it on each project in the SQL editor, and types the same value as the GitHub secret. Nobody pastes it into Claude Code or a file.

Supabase SQL Editor, each project
-- Typed by a person, once per project. The password comes from the password manager.
alter role import_m01 with login password '<from the password manager>';
Open

https://github.com/acme-ops/acme-platform/settings/secrets/actions

Add IMPORT_M01_PASSWORD_DEV and IMPORT_M01_PASSWORD_PROD: paste the value only, never NAME=value.

Key or secretWhat it unlocksWhere it livesWho holds itNever
import_m01 password (one per project)Inserting imported records into this module's tables, nothing elseGitHub Actions secrets, and the password managerpat@acme.com, sam@acme.comNever in a chat, a file or a log; set to NOLOGIN at cut-over

The rehearsal uses a copy of the export that IT has approved in writing for the development project, redacted where it holds personal, injury or pay data. It is the only real data a development project ever holds, and it is removed the same day.

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/storage/buckets

Development project, Storage: upload the approved copy to the private bucket imports.

Open

https://github.com/acme-ops/acme-platform/actions/workflows/import-m01.yml

Run workflow from main: target development, the file's path, apply false. Read the counts; then again with apply true.

Open three imported submissions on the development preview beside the same three in the old tool: answers, dates and photos must match. Then, the same day, remove the rehearsal from the development project: delete the file from the bucket, and run:

Supabase SQL Editor, development project
-- Development project only, the same day: remove the rehearsal's real records.
delete from public.frm_response where submission_id in
  (select id from public.frm_submission where ext->>'origin' = 'import');
delete from public.frm_submission where ext->>'origin' = 'import';
delete from public.import_log where module = 'm01';
Paste into Claude Code, after replacing the <...> part
On a new branch m01/rehearsal, write docs/imports/m01-rehearsal.md: the date of IT's written approval and who gave it (a job, not a name), what was redacted, the rehearsal's counts and skipped rows from the run log below, the three records checked, and the date the copy was removed from the development project:
<paste the counts and the dates>
Open a pull request titled "M01: rehearsal record", wait for the checks, and show me the link.

You will see recreated screen

github.com/acme-ops/acme-platform/actions/workflows/import-m01.yml
import-m01 · development · apply: false
file    history-2026-11.csv
sha256  9f2c…41ab
rows                  1,212
submissions to create 1,204
responses to create  10,836
rows skipped              8  (question 'Oil OK?' not in template v1)
The rehearsal on the development project: a dry run first, the file's fingerprint and every count printed.
  1. Every skipped row has a reason. Fix the mapping, or decide to leave them out, and write which.
  2. Read before you apply.

Check it worked

The import is merged; the import account's password is set on both projects and in GitHub secrets, by a person; the rehearsal ran dry, then applied, with every skipped row explained; three records matched the old tool; the copy was removed the same day and docs/imports/m01-rehearsal.md records it.

If it goes wrong

Claude Code asks to read the export "to get the mapping right"

Say no. Give it the column names and, if needed, a made-up row you write yourself. Real records reach the platform only through the import workflow.

IT will not approve a copy in writing

Then no real data goes to the development project. Rehearse with a made-up file in the same columns (Claude Code can write one from the header), and keep the first production run a dry run. Write the decision in docs/imports/m01-rehearsal.md.

The workflow cannot sign in as import_m01

The password on the project and the GitHub secret differ, or the secret holds NAME=value. Set both again from the password manager, value only. Never give the import account more rights to get past it.

Step 15

Session 6: Run side by side, and prove the offline queue on a real phone

30 minutes, after a week of running both

Why

A module is ready to replace the old way only when both have handled the same week and every difference is explained. The definition of done also asks for zero data loss across 50 queued submissions on a phone, which is the test that matters most on a floor with dead spots.

Do this

For one week, the same form runs both ways in the same area, with the same people. At the end, count the old way by hand (sheets in the binder, or the old tool's own report, named) and read the same numbers from your dashboard. Then:

Paste into Claude Code, after replacing the <...> parts
On a new branch m01/cutover, write docs/cutover.md with a side-by-side table for the week of <dates>: forms scheduled, completed on time, late, missing, and failed items, one column from my hand count of the old way and one from the platform's dashboard:
Old way (<paper binder / the old tool's report name>): <your counts>
Explain every difference in one line each, or mark it "not explained". Then add three checks, each with the query that proves it and its result on production: a published version cannot change; every submission names its version; submitted_at is the server's time and the phone's time is kept in ext. Do not change any data. Open a pull request titled "M01: side by side", wait for the checks, and show me the link.

Then the 53-submission test, on a real phone, on the development project's preview: airplane mode on; load the 50-submission batch with the test-only button; fill in three more by hand; reconnect. In the development project, all 53 must arrive exactly once, each with device_id, captured_offline and the phone's times. Force a second send: still 53.

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor

Count the new frm_submission rows: 53, not 52, not 106.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/cutover.md)
+| Week 45 | Old way (binder) | Platform |
+| Scheduled | 30 | 30 |
+| On time | 22 | 25 |
+| Missing | 4 | 1 |
+Difference: 3 sheets filled in at shift end from memory were counted on time in the binder; the platform has their true times.
1
⏺ Pull request #57 adds docs/cutover.md. Every difference is explained. On production: 0 published versions changed, 100% of submissions name their version, and every submission has both times.2
The side-by-side document: two columns, every difference explained.
  1. The platform shows what the paper hid: forms filled in late from memory.
  2. The three record rules, proven on production by query.

Check it worked

docs/cutover.md has no "not explained" line; the three queries pass on production; the phone test arrived 53 of 53, once each.

If it goes wrong

The phone test arrives 52, or 106

Do not cut over. Say: The 53-submission offline test stored <n>. Find which submission was lost or doubled, from device_id and ids, and add a test that would have caught it.

A difference cannot be explained

You are not ready. Run another week, and ask the supervisor to watch the specific form that differs.

Step 16

Session 6: Import into production through the pipeline

20 minutes

Why

Real records go into production once, through reviewed code, after a backup, from a file whose fingerprint and counts owner two approved in the repository. The workflow refuses any other file and fails on any count mismatch, and the import account can only insert, so nothing already there can be changed by it.

Do this

Open

https://github.com/acme-ops/acme-platform/actions

First, run the nightly backup workflow from Session 11 by hand (its Run workflow button) and wait for it to finish green.

Open

https://supabase.com/dashboard/project/abcdefghijklmnopqrst/storage/buckets

Production, Storage: upload the full export to the private bucket imports.

Open

https://github.com/acme-ops/acme-platform/actions/workflows/import-m01.yml

Run workflow from main: target production, the file's path, apply false. Copy the sha256 and the counts from the log.

Paste into Claude Code, after replacing the <...> part
On a new branch m01/import-approval, write docs/imports/m01-approved.md: today's date, the source (the old system's name and the export's date), and for each file its path, its sha256 and the expected counts exactly as in this dry-run log, with the skipped rows' reasons as a list:
<paste the sha256 and counts from the run log>
Open a pull request titled "M01: approve the import", wait for the checks, and show me the link.

Owner two reads the counts and approves; merge. Then run the workflow again from main: target production, the same file, apply true.

You will see recreated screen

github.com/acme-ops/acme-platform/actions/workflows/import-m01.yml
import-m01 · production · apply: true
submissions created  1,204
responses created   10,836
rows skipped             8 (listed in docs/imports/m01-approved.md)
import_log: m01, 9f2c…41ab
The production run: the approved fingerprint and counts checked first, then the import, with the same numbers.
  1. The approval is a file on main that owner two approved.
  2. The same numbers, or the run fails.

Check it worked

The backup ran green before the import; docs/imports/m01-approved.md is on main; the production run's counts equal it; three imported records open read-only on the live site and an edit is refused.

If it goes wrong

The workflow refuses: sha256 not in the approved file

The file in the bucket is not the one you approved, often a second export taken later. Do not edit the approved file to match. Upload the approved file, or dry-run the new one and approve it in a new pull request.

The run fails: counts do not match

Nothing was imported: the run is one transaction. Ask Claude Code: The m01 import failed on a count mismatch. Show me which count differs and why, from the log, without running anything.

The backup workflow has no Run workflow button

Say to Claude Code: Add workflow_dispatch to the nightly backup workflow so a person can run it before an import. Merge that first. A backup nobody has restored is only a hope: Foundation Session 23 drills the restore.

Step 17

Session 6: Cut over, and cancel what you no longer need

20 minutes

Why

Cutting over on a written date, with a way back, means nobody is unsure which record counts. The saving is real only when it comes from the old invoices and the vendor's own terms, so the cancellation happens after the export is safe and the import is checked, and the arithmetic is written down.

Do this

Paste into Claude Code, after replacing the <...> part
Add to docs/cutover.md on a new branch m01/cutover-date:
- the cutover date, who tells the floor, when the paper pads leave the area, where the old export is kept and by whom, and the date after which a paper form is no longer accepted as a record;
- the way back: what we do if the platform is unavailable during a shift (the printed blank form, entered later as a late submission with the reason);
- the saving: the old tool's bill and renewal date and the printing costs exactly as I give them below, minus what the module adds to our running costs (none unless the AI step is used: its cost per page from the platform's own record). Show the arithmetic.
Old bills and terms: <from your invoices and the vendor's account page>
Then mark each form in docs/forms-inventory.md replaced, retired or still on paper, with the date. Add a new migration that sets the import account import_m01 to NOLOGIN, now that the import is done. Open a pull request titled "M01: cutover", wait for the checks, and show me the link.

On the date: remove the paper pads, take the old tool's links and QR codes down, put up the platform's QR codes on each press, and watch the first day's submissions arrive. Then read the old vendor's cancellation terms on its own account page (notice period, renewal date, how long you can still export) and cancel, or write down the date the plan ends.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/cutover.md)
+## Cutover: 2026-12-01, press shop
+Way back: blank forms in the supervisor's office; entered within 24 h as late, with the reason.
+## Saving
+Old tool: as on invoice INV-2291 (annual, renews 2027-01-15). Printing: as on the print room's November invoice.
+Module running cost: none added; AI ingestion: as recorded per page.
1
⏺ Pull request #61 updates docs/cutover.md and docs/forms-inventory.md: 3 forms replaced, 11 still on paper, each dated. The saving section uses only the invoice figures you gave me.2
The cutover record: a date, a way back, and a saving with its arithmetic from real invoices.
  1. Every figure points at the document it came from.
  2. Forms still on paper are listed, not forgotten.

Check it worked

docs/cutover.md has the date, the way back and the saving with its arithmetic; the old tool is cancelled or its end date recorded; docs/forms-inventory.md shows each form's state; after the merge, import_m01 can no longer sign in.

If it goes wrong

The vendor's notice period means another year's renewal

Write the end date and the export window in docs/cutover.md, set a reminder before the notice deadline, and keep using the platform: the saving starts at the end date.

Someone still fills in the paper form

Ask why, and write the answer in docs/m01/try-out.md. It is usually the one thing the new way does worse: fix it rather than forbid the paper.

Before you go on · The module is done whenTick each one

Knowledge check

The AI proposes a number field with no upper limit. What should the reviewer do?

Knowledge check

How do real historical records reach production?

References

  1. Vercel Docs: Environment variables. https://vercel.com/docs/environment-variables
  2. GitHub Docs: Manually running a workflow. https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-workflow-runs/manually-running-a-workflow
  3. FDA: Data integrity and compliance with drug CGMP: questions and answers (2018). https://www.fda.gov/regulatory-information/search-fda-guidance-documents/data-integrity-and-compliance-drug-cgmp-questions-and-answers
  4. Supabase Docs: Database backups. https://supabase.com/docs/guides/platform/backups
  5. Supabase Docs: Storage buckets. https://supabase.com/docs/guides/storage/buckets/fundamentals
  6. PostgreSQL Documentation: CREATE ROLE (LOGIN, NOLOGIN). https://www.postgresql.org/docs/current/sql-createrole.html

Chapter 5 · 12 questions · 80% passes

Final assessment

Twelve questions across the element. Score 80% (10 of 12) to pass. Your LMS records your score and each answer; you can review the chapters and try again.

15 min12 questions≈ 15 minutesRetake allowed

Choose one answer for each question, then submit. You will see the right answer and why for every question.

1. What is a governed digital record, as Paper to Glass builds it?
2. Which module owns controlled SOP authoring and approval, which Paper to Glass leaves out?
3. Before the frm_ migrations are merged, where do you try them, and who runs the command?
4. Which ALCOA+ attribute says a record must be made at the time the work is done?
5. What happens to a published template version when the form needs to change?
6. Why are answers stored as typed rows in frm_response and not only as a JSON blob?
7. A form is filled in offline at 06:00 and synced at 09:30. What does the module keep?
8. Which RFC defines the recurrence rules (RRULE) used for scheduled rounds and inspections?
9. A queued submission is sent twice because the confirmation was lost. What must the server do?
10. A number answer falls outside the limits on its frm_field row. What should the module do?
11. In paper ingestion, who decides which AI-proposed fields go into the form?
12. How are historical submissions from an incumbent tool imported?