Skip to the lesson
CivOps AI Academy · M08Quality Management: Events, CAPA, Audits, Change, Risk and Supplier Quality on One Record Model
0%

Chapter 1 · Sessions 1 and 2

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

Before you build anything, you count what the old quality system really holds and what it really costs, from its own reports and its own bill. Then one careful prompt adds the module's eighteen tables to your platform, keyed to the tables you already have, with the tests that prove the database refuses bad quality records.

25 min4 stepsAbout 7.5 hours hands-on across six sessionsSessions 1 and 2

By the end of this chapter you can

  • Inventory the old eQMS from its own reports, user list and invoice, with nothing estimated.
  • Map the specification's spine names (core_site, core_lot, ...) to the tables your Foundation already has, and add only what is missing.
  • Have Claude Code write the eighteen qms_ tables, their rules and their tests in one pull request.
  • Write the module's made-up seed, supabase/seeds/quality.sql, load it on the development project and read it in the Table Editor.

What this module replaces, and what it leaves alone

Quality management runs quality events end to end: nonconformances and material review, deviations, complaints, CAPA (corrective and preventive action) with root cause and an effectiveness check, audits, change control, risk as FMEA (failure mode and effects analysis) and supplier quality, on one record model, with holds that really stop product. It replaces the electronic quality management system (eQMS) a business usually rents: MasterControl, ETQ Reliance, Veeva Vault QMS, TrackWise, Intelex, Qualio, Greenlight Guru, QT9 or Ideagen Quality [5][6]. Your plant may use none of them, and run on spreadsheets and binders instead; the module replaces those just the same.

The edge of Quality managementInside: quality events, NCR and material review, quality holds, CAPA, audits, change control, FMEA and supplier quality. Outside, each with its owner: document lifecycle in M06, training records in M07, SPC charts and capability in M09, and engineering change of product definitions in M14, which links here. INSIDE QUALITY MANAGEMENT (M08)Quality eventsNCR and material reviewQuality holdsCAPAAuditsChange controlFMEASupplier qualityOUTSIDE, WITH ITS OWNERDocument lifecycleowned by M06Training recordsowned by M07SPC charts and capabilityowned by M09Product-definition changeM14 ECO; links to M08
The edge of the module. Documents (M06), training records (M07), SPC charts (M09) and product engineering change (M14) belong to other modules; this one links to them.
StandardUsed in this module for
ISO 9001:2015, clauses 8.7, 10.2, 9.2 and 9.3 [1]Nonconforming outputs, corrective action, internal audit and management review
IATF 16949:2016 with the AIAG Core ToolsAPQP, PPAP, FMEA, MSA and SPC for automotive suppliers
AIAG-VDA FMEA Handbook (2019)The seven-step FMEA and the action priority (high, medium, low) that replaces ranking by RPN alone
ISO 13485:2016, FDA QMSR (21 CFR Part 820, effective 2 February 2026) and ISO 14971:2019 [2][3]Medical device quality systems, complaint handling and risk management
ICH Q9(R1) and ICH Q10Pharmaceutical quality risk management and quality system
21 CFR Part 11 and EU Annex 11 [4]Electronic records and electronic signatures
AS9100DAerospace quality systems: nonconformance and first-article linkage
Step 1

Session 1: Count what the old eQMS holds and costs, from its own reports

60 minutes

Why

The module is only worth building if it replaces real records, real users and a real bill. Numbers read from the tool's own screens and invoices are the baseline the cutover in Session 6 is checked against, and the saving you record at the end. An estimate here becomes a promise nobody can keep.

Do this

With the eQMS administrator and the quality manager, read these from the tool's own reports and the vendor's account page. Write each number with the name of the report it came from. Copy no customer, patient or employee names: counts and field names are enough.

  • Every tool that holds quality records: the eQMS, and the spreadsheets, shared folders, email threads and binders beside it.
  • Records for the last full year: events by type (NCR, deviation, complaint, audit finding, supplier corrective action request) and status; CAPAs open and closed; audits by type; change requests; FMEAs; approved suppliers.
  • Users by what they do: raise events, investigate, own CAPAs, audit, approve and sign.
  • The bill: amount, period, renewal date, notice period, paid users, as printed on the invoice.
  • What it can export (events, CAPAs, audits, attachments, history, signatures) and for how long after you cancel.
  • The holds question: when the tool holds a lot, what physically stops it being used or shipped? Ask production and the warehouse; do not test it on live product.
Paste into Claude Code, after replacing the <...> part
On a new branch qms/inventory, write docs/qms-inventory.md from what I give you below. Use only my numbers: where I wrote "unknown", write "unknown" and who can find out. Never estimate, round or fill a gap.

Tables:
1. Tools: name, owner, what it holds, bill per year, renewal date, notice period, export available (yes/no/partly), source of each figure.
2. Records for the last full year, by type and status, with the report each count came from.
3. Users by role (raise, investigate, own CAPA, audit, approve and sign), with how many have not signed in this year.
4. The holds question: for each lot flow (issue to production, shipping), "enforced by a system", "a flag people must notice" or "unknown".
5. Workarounds: what people do outside the tool, who, how often.
6. Standards the quality manager named, and whether electronic signatures are used for material review, hold release and closure.
7. The first workflow to replace and why, with the quality engineer and approver who will test it.

My notes:
<paste your notes here>

Open a pull request titled "QMS inventory" and show me the link.

You will see recreated screen

claude — acme-platform
> On a new branch qms/inventory, write docs/qms-inventory.md from what I give you below...
⏺ Write(docs/qms-inventory.md)
+| Tool | Owner | Bill per year | Renewal | Notice | Export | Source |
+| eQMS (cloud) | Quality manager | from invoice INV-2026-0412 | 2027-03-01 | 90 days | partly | vendor account page |
+| CAPA due-date spreadsheet | Quality engineer | none | none | none | yes | shared drive |
+## Records, last full year (report: Event Summary by Type)
+| ncr | 212 | ... |
+## The holds question
+| Issue to production | a flag people must notice |
+| Shipping | unknown: ask the warehouse lead |
1
⏺ Pull request #61 adds docs/qms-inventory.md. Two cells say unknown because your notes had no figure: the shipping hold, and how long exports stay available after cancelling. I did not fill them.2
Claude Code writes the inventory from your notes only. Where you had no number, it says so instead of inventing one.
  1. Every figure carries its source: an invoice, a report or a page. That is what makes it usable in Session 6.
  2. Unknowns stay unknown, with who can find out. This is correct behaviour; ask for it if you do not see it.

Check it worked

Pull request QMS inventory holds the seven tables. Every number names its source, and no cell holds a figure you did not give.

Fastest path

Collect the numbers on paper with the administrator first, then paste them all at once. One complete prompt replaces a dozen "and also add" messages.

If it goes wrong

Claude Code filled in a price, a count or a date you did not give it

Say: Remove every figure I did not give you and write unknown instead. We hit this on our own platform: screens showed savings and users that nobody had measured, because an agent filled the gaps so the page looked finished. An invented baseline makes the Session 6 saving meaningless.

The vendor's terms say exports end the day you cancel, or cost extra

Write it in the inventory now and plan Session 5 around it. Take the full export before you give notice, never on the last day.

The holds answer is "a flag people must notice"

That is the most common answer, and the most important thing this module fixes. Write it down as it is; Session 4 makes the database refuse the move.

Your platform's names for the spine

The specification describes the module against a shared spine of tables named core_site, core_lot, core_person and so on, with a tenant_id on every row. Your platform already has its own spine from Session 5, with your names. The module must point at your tables, never build a second list of sites, parts or lots beside them: two lists of lots means a hold on one list does not stop the other. So the first thing Session 2 does is write the map once, in docs/spine-map.md, and every later module reads it.

Specification saysOn the stamping plant's platformIf you have nothing like it
core_sitesitesNever missing: Session 5 made it
core_itempartsNever missing
core_lotlots (with the lot_status view)Never missing
core_equipmentequipmentNever missing
core_personSupabase sign-in users with membershipsAdd a people table that points at the sign-in user
core_party (suppliers and customers)usually missingAdd it in the spine migration
core_uom, core_item_classusually missingAdd them in the spine migration
core_e_signature, core_attachment, core_status_history, core_number_sequence, core_event_outbox, core_notificationusually missingAdd them in the spine migration: other modules need them too
tenant_id on every rowsite_id on every rowYour platform serves one company; site_id is the scope the access rules of Session 8 use
uuid idsthe id type your first migration usesKeep one id type across the platform
Step 2

Session 2: Map the spine, and add only what is missing

20 minutes

Why

The quality module needs signatures, attachments, numbering, suppliers and an outbox that other modules will share. Building them once, in a separate spine migration that is merged first, keeps them shared. Putting them inside the quality migration would make the next module copy them, and the platform would grow two of everything.

Do this

Terminal or PowerShell
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
Read docs/SCHEMA-PLAN.md, docs/naming-standard.md and every file in supabase/migrations. Do not change any existing table or migration.

On a new branch spine/qms-prerequisites:

1. Write docs/spine-map.md: for each of these specification names, the table or function on this platform that plays that role, or "missing": core_site, core_person, core_job_role, core_party, core_item, core_item_class, core_uom, core_equipment, core_lot, core_lot_genealogy, core_attachment, core_e_signature, core_approval, core_comment, core_status_history, core_number_sequence, core_notification, core_event_outbox, core_audit_log, and the helpers core_current_actor() and core_touch_row(). Also record: our scope column is site_id (we have one company, so no tenant_id), and our id type is the one the first migration uses.

2. For every "missing" item, write ONE new migration (npx supabase migration new spine_for_modules) that creates it with this platform's conventions: primary key, site_id where a row belongs to a site, created_at, created_by, updated_at, updated_by, row_version, archived_at, ext jsonb; times as timestamptz; row-level security on with no policies; core_e_signature and core_status_history and core_audit_log append-only with the existing append-only function. Add each new table to docs/matrix.json as a row with no rights yet.

3. Our holds table records hold and release decisions. Write in docs/spine-map.md how it and the module's future qms_hold become one rule: one function every route that moves a lot will call, which treats a lot as held if either table holds it. Do not change the holds table.

4. Add pgTAP tests in supabase/tests/ for every new table: exists, primary key, row-level security on, append-only where stated.

Push, open a pull request titled "Spine for modules", wait for every check to finish, and tell me the result in plain words. If a check fails, fix it and wait again before reporting.

You will see recreated screen

claude — acme-platform
⏺ Read(supabase/migrations/20261016091500_create_first_tables.sql)
⎿ Read 112 lines
1
⏺ Write(docs/spine-map.md)
+| Specification | This platform |
+| core_site | sites |
+| core_lot | lots (current status: lot_status view) |
+| core_item | parts |
+| core_party | missing: created in spine_for_modules |
+| core_e_signature | missing: created, append-only |
+Holds: lot_is_held(lot_id) returns true if holds or qms_hold holds it.
2
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m04s ci / lint-typecheck-test pass 1m12s
⏺ Pull request #62 is green. It maps 11 specification names to existing tables and creates 9 missing ones, each with row-level security on and no rights yet. Nothing existing was changed.
Claude Code reads the migrations before it writes the map, and creates only what is missing.
  1. It read your actual migrations, not a guess at them.
  2. The map: specification names on the left, your names on the right. Every later module reads this file.

Check it worked

Pull request Spine for modules is green, adds docs/spine-map.md and one new migration, and its Files changed tab shows no edit to any older migration.

If it goes wrong

Claude Code renamed lots to core_lot, or sites to core_site

Say: Revert every rename. Names are forever: map the specification names to ours in docs/spine-map.md instead. A rename that is only half done breaks every screen and query that used the old name, and we hit exactly that on our platform.

It put the spine tables inside a quality migration

Say: Move every table that is not qms_ into the spine_for_modules migration, merged first. Other modules need them.

It reports success but a check on GitHub is red

Say: A 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. We learned to trust the check, never the summary.

The eighteen tables

Every quality event, whatever the floor calls it, is one row in qms_quality_event. Three kinds need more fields, kept in small detail tables that point back at exactly one event. This is what lets you count every event of every kind in one query, which is the whole point of a quality system.

One supertype, three detail tablesThe qms_quality_event table holds every event, with event_type one of ncr, deviation, complaint, audit_finding, scar, observation or oos. Three detail tables, for NCR, complaint and deviation, each point at exactly one event. event_type is one of seven valuesncrdeviationcomplaintaudit_findingscarobservationoosqms_quality_eventevent_no, severity, status, owner,site, item, lot, equipment, supplierqms_ncr_detailquantity, defect code, MRB decisionqms_complaint_detailchannel, RMA, reportable, rationaleqms_deviation_detailplanned, impact, batches affectedEach detail row has a required, unique quality_event_id: at most one per event.audit_finding, scar, observation and oos use the event row alone.
One supertype, three detail tables. NCR, complaint and deviation each add one detail row; the other four types use the event row alone.

The reference below is the specification's, column by column: req means required, a list after a colon is the only values allowed, and an arrow is a link to another table (core_ names are read through your spine map). Every table also gets the standard columns from Step 2. You do not type any of it: Step 3's prompt carries it into your repository.

TableHoldsColumns
qms_quality_eventSupertype record for all quality eventsevent_no text req, unique; event_type text req: ncr, deviation, complaint, audit_finding, scar, observation, oos; title text req; description text; severity text req: critical, major, minor, observation; status text req: new, triage, investigation, disposition, capa_pending, closed, cancelled; site_id → core_site; occurred_at ts; reported_by → core_person; owner_id → core_person; item_id → core_item; lot_id → core_lot; equipment_id → core_equipment; supplier_party_id → core_party; customer_party_id → core_party; source_type text; source_id uuid; due_at ts; closed_at ts; closure_signature_id → core_e_signature
qms_defect_codeDefect taxonomycode text req, unique; name text req; category text; parent_id → qms_defect_code
qms_ncr_detailNonconformance detail and MRB dispositionquality_event_id → qms_quality_event req, unique; qty_affected qty; uom_id → core_uom; defect_code_id → qms_defect_code; containment text; disposition text req: pending, use_as_is, rework, repair, scrap, return_to_vendor, regrade; mrb_decided_at ts; mrb_signature_id → core_e_signature; copq_cost money
qms_complaint_detailComplaint-specific dataquality_event_id → qms_quality_event req, unique; channel text req: email, phone, portal, sales, field_service, regulator; contact_ref uuid; rma_no text; product_returned bool; reportable bool; reportability_rationale text; response_due_at ts; responded_at ts
qms_deviation_detailDeviation-specific dataquality_event_id → qms_quality_event req, unique; planned bool req; impact_assessment text; batches_affected json; product_impact text: none, potential, confirmed
qms_holdQuality hold on a lot, order, equipment or supplierhold_no text req, unique; target_type text req: lot, production_order, equipment, supplier, item, location; target_id uuid req; reason text req; quality_event_id → qms_quality_event; placed_by → core_person req; placed_at ts req; released_by → core_person; released_at ts; release_signature_id → core_e_signature; status text req: active, released, converted_to_scrap
qms_capaCorrective and preventive action recordcapa_no text req, unique; origin_event_id → qms_quality_event; title text req; problem_statement text req; method text req: eight_d, five_why, a3, dmaic, other; containment text; root_cause text; root_cause_category text: man, machine, method, material, measurement, environment, design, supplier, unknown; status text req: open, investigation, action_plan, implementation, effectiveness_check, closed, cancelled; owner_id → core_person req; due_at ts; effectiveness_criteria text; effectiveness_due_at ts; effectiveness_result text: pending, effective, not_effective; closed_at ts; closure_signature_id → core_e_signature
qms_capa_actionAction within a CAPAcapa_id → qms_capa req; action_type text req: containment, correction, corrective, preventive, training, document_change; description text req; owner_id → core_person; due_at ts; completed_at ts; verified_by → core_person; verified_at ts; linked_type text; linked_id uuid
qms_rca_artifactRoot-cause tool contentcapa_id → qms_capa req; tool text req: fishbone, five_why, is_is_not, fault_tree, pareto, timeline; content json req; author_id → core_person
qms_auditAudit instanceaudit_no text req, unique; audit_type text req: internal, supplier, customer, regulatory, certification, process, product, layered; standard_ref text; scope text; lead_auditor_id → core_person; auditee_party_id → core_party; site_id → core_site; planned_start date; planned_end date; status text req: planned, in_progress, reporting, closed, cancelled; report_attachment_id → core_attachment
qms_audit_itemChecklist item and resultaudit_id → qms_audit req; clause_ref text; question text req; result text: conform, minor_nc, major_nc, ofi, not_applicable, not_audited; evidence text; finding_event_id → qms_quality_event
qms_change_controlChange request with impact assessmentcc_no text req, unique; title text req; change_type text req: process, equipment, material, supplier, document, software, facility, product; classification text req: minor, major, critical; reason text req; impact_assessment json; risk_level text: low, medium, high; status text req: draft, assessment, approval, implementation, effectiveness_review, closed, rejected; owner_id → core_person req; implementation_due date; approved_signature_id → core_e_signature
qms_change_taskImplementation task of a changechange_control_id → qms_change_control req; task_type text req: document, training, validation, regulatory, equipment, supplier, it, other; description text req; owner_id → core_person; due_at ts; completed_at ts
qms_fmeaFMEA header (design, process or machinery)fmea_no text req, unique; fmea_type text req: design, process, machinery; item_id → core_item; process_ref text; revision text req; team json; status text req: draft, active, superseded
qms_fmea_lineFailure mode line with S/O/D and action priorityfmea_id → qms_fmea req; step_function text req; failure_mode text req; failure_effect text; severity int req; failure_cause text; occurrence int req; prevention_controls text; detection_controls text; detection int req; action_priority text req: high, medium, low; special_characteristic text: none, cc, sc; recommended_action text; owner_id → core_person; due_at ts; revised_severity int; revised_occurrence int; revised_detection int
qms_approved_supplierApproved supplier list entry by commoditysupplier_party_id → core_party req; item_class_id → core_item_class; status text req: pending, approved, conditional, probation, disqualified; approved_at date; requalify_due date; certifications json; risk_rating text: low, medium, high
qms_supplier_scorecardPeriodic supplier performancesupplier_party_id → core_party req; period_start date req; period_end date req; ppm num; on_time_pct num; scar_count int; responsiveness num; score num; grade text: a, b, c, d
qms_ppap_submissionPPAP status per part and suppliersupplier_party_id → core_party req; item_id → core_item req; level int req; elements json req; status text req: requested, submitted, approved, interim, rejected; submitted_at date; decided_at date
Step 3

Session 2: One prompt: the eighteen tables, their rules and their tests

25 minutes

Why

A rule kept in a table protects every screen, import and agent that will ever write to it. Writing the tables, their rules and the tests that try to break them in one pull request means the proof arrives with the change. It also gives Claude Code the exact column list, so it cannot invent a column or leave one out.

Do this

Paste into Claude Code
On a new branch qms/tables, add this module's own section to docs/spine-map.md, the one shared map (never a separate tables file), with exactly this content, then use it.

## M08 Quality management tables (from the module specification M08)
Every table also has the standard columns recorded above in this map. "req" means not null. A list after a colon is a check constraint. "→ core_x" means a foreign key to the table docs/spine-map.md maps core_x to. Types: ts = timestamptz, qty and money = numeric, json = jsonb, num = numeric.

### qms_quality_event
Supertype record for all quality events.
- event_no text req, unique
- event_type text req: ncr, deviation, complaint, audit_finding, scar, observation, oos
- title text req
- description text
- severity text req: critical, major, minor, observation
- status text req: new, triage, investigation, disposition, capa_pending, closed, cancelled
- site_id → core_site
- occurred_at ts
- reported_by → core_person
- owner_id → core_person
- item_id → core_item
- lot_id → core_lot
- equipment_id → core_equipment
- supplier_party_id → core_party
- customer_party_id → core_party
- source_type text
- source_id uuid
- due_at ts
- closed_at ts
- closure_signature_id → core_e_signature

### qms_defect_code
Defect taxonomy.
- code text req, unique
- name text req
- category text
- parent_id → qms_defect_code

### qms_ncr_detail
Nonconformance detail and MRB disposition.
- quality_event_id → qms_quality_event req, unique
- qty_affected qty
- uom_id → core_uom
- defect_code_id → qms_defect_code
- containment text
- disposition text req: pending, use_as_is, rework, repair, scrap, return_to_vendor, regrade
- mrb_decided_at ts
- mrb_signature_id → core_e_signature
- copq_cost money

### qms_complaint_detail
Complaint-specific data.
- quality_event_id → qms_quality_event req, unique
- channel text req: email, phone, portal, sales, field_service, regulator
- contact_ref uuid
- rma_no text
- product_returned bool
- reportable bool
- reportability_rationale text
- response_due_at ts
- responded_at ts

### qms_deviation_detail
Deviation-specific data.
- quality_event_id → qms_quality_event req, unique
- planned bool req
- impact_assessment text
- batches_affected json
- product_impact text: none, potential, confirmed

### qms_hold
Quality hold on a lot, order, equipment or supplier.
- hold_no text req, unique
- target_type text req: lot, production_order, equipment, supplier, item, location
- target_id uuid req
- reason text req
- quality_event_id → qms_quality_event
- placed_by → core_person req
- placed_at ts req
- released_by → core_person
- released_at ts
- release_signature_id → core_e_signature
- status text req: active, released, converted_to_scrap

### qms_capa
Corrective and preventive action record.
- capa_no text req, unique
- origin_event_id → qms_quality_event
- title text req
- problem_statement text req
- method text req: eight_d, five_why, a3, dmaic, other
- containment text
- root_cause text
- root_cause_category text: man, machine, method, material, measurement, environment, design, supplier, unknown
- status text req: open, investigation, action_plan, implementation, effectiveness_check, closed, cancelled
- owner_id → core_person req
- due_at ts
- effectiveness_criteria text
- effectiveness_due_at ts
- effectiveness_result text: pending, effective, not_effective
- closed_at ts
- closure_signature_id → core_e_signature

### qms_capa_action
Action within a CAPA.
- capa_id → qms_capa req
- action_type text req: containment, correction, corrective, preventive, training, document_change
- description text req
- owner_id → core_person
- due_at ts
- completed_at ts
- verified_by → core_person
- verified_at ts
- linked_type text
- linked_id uuid

### qms_rca_artifact
Root-cause tool content.
- capa_id → qms_capa req
- tool text req: fishbone, five_why, is_is_not, fault_tree, pareto, timeline
- content json req
- author_id → core_person

### qms_audit
Audit instance.
- audit_no text req, unique
- audit_type text req: internal, supplier, customer, regulatory, certification, process, product, layered
- standard_ref text
- scope text
- lead_auditor_id → core_person
- auditee_party_id → core_party
- site_id → core_site
- planned_start date
- planned_end date
- status text req: planned, in_progress, reporting, closed, cancelled
- report_attachment_id → core_attachment

### qms_audit_item
Checklist item and result.
- audit_id → qms_audit req
- clause_ref text
- question text req
- result text: conform, minor_nc, major_nc, ofi, not_applicable, not_audited
- evidence text
- finding_event_id → qms_quality_event

### qms_change_control
Change request with impact assessment.
- cc_no text req, unique
- title text req
- change_type text req: process, equipment, material, supplier, document, software, facility, product
- classification text req: minor, major, critical
- reason text req
- impact_assessment json
- risk_level text: low, medium, high
- status text req: draft, assessment, approval, implementation, effectiveness_review, closed, rejected
- owner_id → core_person req
- implementation_due date
- approved_signature_id → core_e_signature

### qms_change_task
Implementation task of a change.
- change_control_id → qms_change_control req
- task_type text req: document, training, validation, regulatory, equipment, supplier, it, other
- description text req
- owner_id → core_person
- due_at ts
- completed_at ts

### qms_fmea
FMEA header (design, process or machinery).
- fmea_no text req, unique
- fmea_type text req: design, process, machinery
- item_id → core_item
- process_ref text
- revision text req
- team json
- status text req: draft, active, superseded

### qms_fmea_line
Failure mode line with S/O/D and action priority.
- fmea_id → qms_fmea req
- step_function text req
- failure_mode text req
- failure_effect text
- severity int req
- failure_cause text
- occurrence int req
- prevention_controls text
- detection_controls text
- detection int req
- action_priority text req: high, medium, low
- special_characteristic text: none, cc, sc
- recommended_action text
- owner_id → core_person
- due_at ts
- revised_severity int
- revised_occurrence int
- revised_detection int

### qms_approved_supplier
Approved supplier list entry by commodity.
- supplier_party_id → core_party req
- item_class_id → core_item_class
- status text req: pending, approved, conditional, probation, disqualified
- approved_at date
- requalify_due date
- certifications json
- risk_rating text: low, medium, high

### qms_supplier_scorecard
Periodic supplier performance.
- supplier_party_id → core_party req
- period_start date req
- period_end date req
- ppm num
- on_time_pct num
- scar_count int
- responsiveness num
- score num
- grade text: a, b, c, d

### qms_ppap_submission
PPAP status per part and supplier.
- supplier_party_id → core_party req
- item_id → core_item req
- level int req
- elements json req
- status text req: requested, submitted, approved, interim, rejected
- submitted_at date
- decided_at date

Then write ONE migration (npx supabase migration new qms_tables) that creates all eighteen tables exactly as listed, and:
- numbers (event_no, hold_no, capa_no, audit_no, cc_no, fmea_no, qms_defect_code.code) unique per site;
- quality_event_id unique on each of the three detail tables;
- severity, occurrence, detection and the three revised ratings on qms_fmea_line are whole numbers from 1 to 10;
- a partial unique index on qms_quality_event (site_id, source_type, source_id) where source_id is not null, so a retry from another module never makes a second event;
- row-level security on every table with no policies, the touch-row trigger, and the audit trigger;
- each table added to docs/matrix.json as a row with no rights yet.

Write pgTAP tests in supabase/tests/qms.test.sql that prove the database refuses: an event_type outside the list, a second NCR detail for one event, a hold with an unknown target_type, a CAPA with an unknown status, and an FMEA line with severity 11. Show me each test failing before the constraint exists and passing after.

Do not connect to any Supabase project. Push, open a pull request titled "Quality tables", wait for every check, and tell me the result in plain words. If a check fails, fix it and wait again before reporting.

You will see recreated screen

claude — acme-platform
⏺ Edit(docs/spine-map.md)
⎿ Added the section M08 Quality management tables, 214 lines
1
⏺ Bash(npx supabase migration new qms_tables)
⎿ Created new migration at supabase/migrations/20261103101500_qms_tables.sql
⏺ Write(supabase/migrations/20261103101500_qms_tables.sql)
+create table public.qms_hold (
+ id bigint generated always as identity primary key,
+ site_id bigint not null references public.sites(id),
+ hold_no text not null,
+ target_type text not null check (target_type in ('lot','production_order','equipment','supplier','item','location')),
+ reason text not null check (length(trim(reason)) > 0),
+ status text not null check (status in ('active','released','converted_to_scrap')),
+ unique (site_id, hold_no)
+);
2
⏺ Bash(npx supabase test db)
⎿ qms.test.sql .. 5 of 5 failed (constraints removed on purpose) qms.test.sql .. ok (constraints restored)
3
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m31s
⏺ Pull request #63 is green. 18 tables, 71 checks and foreign keys, row-level security on every table with no policies yet. The five refusal tests failed with the rules removed and pass with them in place.
Claude Code writes the reference file first, then the migration from it, then proves each rule by breaking it.
  1. The column list is now the module's own section of the one shared map, so a later change can be checked against it.
  2. Every allowed-values list from the reference becomes a check the database enforces.
  3. Red first, then green: a test that cannot fail proves nothing.

Check it worked

Pull request Quality tables is green; Claude Code showed the five tests failing without the rules and passing with them; Files changed shows one new migration and no edited old one.

Fastest path

Asking for red-then-green in the same prompt saves the round trip where you find out a test could never fail.

If it goes wrong

A page or test fails later with "column does not exist"

The change reached the code but not a migration. Say: Rebuild the local database from supabase/migrations only, run supabase db diff, and write any difference as a new migration. We merged ten columns without a migration once; the fresh-database check is what catches it.

The check went green after Claude Code changed a test or loosened a limit

Read the Files changed tab before the summary. If a test or CI file changed, say: Undo every change to tests and CI files. Never weaken a check to get to green; if you think it is wrong, stop and explain. On our platform an agent that was refused one command used another to do the same thing.

A test only checks that a word appears in a file

Say: Rewrite every test that checks a name is present so it inserts a row and checks the database refuses it. We found three such tests in one night; all were green while the feature was broken.

Step 4

Session 2: A small made-up seed, tried on the development project

20 minutes

Why

Sessions 3 to 6 need records to click through and a hand count to check the dashboard against. A small, fixed set of made-up records, marked as made up, gives every later step a known answer. Trying the migration and the seed on the development project first, as yourself, proves they work on a real Supabase project before the deploy pipeline applies the migration to production on merge.

Do this

Paste into Claude Code
On the branch qms/tables, write supabase/seeds/quality.sql and list it under [db.seed] sql_paths in supabase/config.toml, after the Foundation seed. Never append to supabase/seed.sql, and never seed production. Rules:
- Every row is made up and marked SYNTHETIC: numbers start SYN-, names start "SYNTHETIC · ".
- Dates are shifted onto today: relative to the moment the seed runs, read once (the window is "the 90 days before today"), so the data never ages.
- Running it twice adds nothing (on conflict do nothing on the numbers).
- The hand-worked dashboard example (the same records with fixed dates, and the expected cost of poor quality 600, on-time 3 of 5, effectiveness 3 of 4, active holds 1) goes in tests/fixtures/quality-kpis.json, which the tests read; it is not seed rows.

Contents: two suppliers and one customer; four lots (one held, one free for Session 4, two released); one person per role (reporter, quality engineer, CAPA owner, auditor, approver). Eight events: four NCRs, one scar, one complaint, one deviation, one audit_finding; three closed, five open. NCR dispositions: scrap (cost 400; its parts were scrapped at the press, so no hold), use_as_is (50), rework (150), one pending. Two holds: one active on the held lot, one released with a signature. Six CAPAs: five due in the window (three closed on time and effective, one closed late and not_effective, one open past due); the sixth is the follow-up of the not_effective one, due after the window, named in its ext. One supplier audit with no site, six checklist items (four conform, one minor_nc linked to the audit finding, one ofi). One draft FMEA with no lines. Every signature is made up, by the approver, who neither reported nor owns the record.

Add a test that runs the seed twice on an empty database and checks each count above. Push to the same pull request and wait for the checks.

When it is green, try the migration and the seed on the development project yourself, in a terminal (not inside Claude Code). Paste the database password from the password manager entry Supabase: acme-platform-dev database password when asked.

Terminal or PowerShell
cd ~/code/acme-platform && git fetch && git switch qms/tables && npx supabase link --project-ref tsrqponmlkjihgfedcba
Terminal or PowerShell
npx supabase db push --include-seed
Open

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

The development project's Table Editor: open qms_quality_event.

That is the first load. After it, reload the made-up rows with npm run seed:dev, never with supabase db reset. Then owner two approves, and you merge. The deploy workflow from Session 11 applies the migration (never the seed) to production.

You will see recreated screen

Terminal
$ npx supabase link --project-ref tsrqponmlkjihgfedcba
Finished supabase link.
$ npx supabase db push --include-seed
Do you want to push these migrations to the remote database? • 20261103090000_spine_for_modules.sql • 20261103101500_qms_tables.sql [Y/n] y1
Applying migration 20261103101500_qms_tables.sql...
Seeding data from supabase/seeds/quality.sql...
Finished supabase db push.
The push lists the two new migrations, then seeds. This is the development project: never type the production reference here.
  1. Read the list before answering y: only the files this branch adds.

You will see recreated screen

supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor
qms_capaqms_holdqms_ncr_detailqms_quality_event
qms_quality_event
1
event_noevent_typeseveritystatus
SYN-QE-0001ncrmajorclosed
SYN-QE-0004ncrminordisposition
SYN-QE-0005scarmajorinvestigation
SYN-QE-0008audit_findingminortriage
The seed in the development project. Every number and name says it is made up.
  1. SYN- numbers: made up, removable, never mistaken for real records.
  2. Expected until Session 3 adds the access rules.

Check it worked

The Table Editor of acme-platform-dev shows eight SYN- events, six CAPAs and two holds; the pull request is merged; the deploy workflow run on main is green.

If it goes wrong

A week later, panels that show "the last 30 days" are empty

The seed used fixed dates. Say: Make every seeded time relative to one clock reading at seed time, keeping the gaps between rows; fixed-date examples belong in tests/fixtures/quality-kpis.json. Then reload with npm run seed:dev. We hit this: eleven days after seeding, the newest batch was 10.9 days old and every recent-hours panel was blank.

A later step expects a count the seed does not give

Say: List every count a later step or test expects and show the seed line that makes it. Fix the seed, not the check. Reviews of five of our modules found this same mismatch.

Claude Code offers to run db push for you

Refuse. The deny rule from Session 1 stops it anyway. You run it, on the development project, with the password you paste yourself.

password authentication failed

Copy the development project's password again, with no space at either end. It is a different password from production's.

Someone suggests supabase db reset --linked to start again

Do not. To start the made-up rows again on the development project, run npm run seed:dev.

Knowledge check

Why do NCRs, complaints and audit findings share one table, qms_quality_event?

Knowledge check

The specification names core_lot. Your platform already has lots. What does the module do?

References

  1. ISO 9001:2015, Quality management systems: requirements. https://www.iso.org/standard/62085.html
  2. ISO 13485:2016, Medical devices: quality management systems. https://www.iso.org/standard/59752.html
  3. eCFR: 21 CFR Part 820, Quality Management System Regulation. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-H/part-820
  4. eCFR: 21 CFR Part 11, Electronic records and electronic signatures. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-A/part-11
  5. Prezent: eQMS platforms for life sciences. https://www.prezent.ai/blog/qms-for-life-sciences
  6. SoftwareConnect: Veeva Vault QMS. https://softwareconnect.com/go/veeva-vault-qms-29564
  7. Supabase Docs: Testing your database. https://supabase.com/docs/guides/database/testing

Chapter 2 · Session 3

Who may raise, decide and sign, and their screens

Quality records carry signatures, so who may do what matters more here than anywhere else in the platform. You write the five roles into the role matrix, generate the access rules from it, prove every refusal, and build the first three screens, one on each surface.

20 min2 steps5 roles, 4 machine accounts

By the end of this chapter you can

  • Add the module's roles, scopes and two-person rules to docs/matrix.json, and regenerate the access rules and route list from it.
  • Prove with tests that each role is refused what it should be refused, and that an update really changes the row.
  • Build the reporter's phone screen, the triage queue and the approval queue, and pass the phone check.
Roles and machine accountsFive roles: reporter, quality engineer, CAPA owner, auditor and approver. Four machine accounts: intake, importer, escalation job and number issuer. Nobody signs a record they reported, own or investigated, and nobody gets delete. FIVE ROLESReporterraises events at their own siteQuality engineertriages, holds, runs CAPA, auditsCAPA ownerowns a CAPA and its actionsAuditorruns audits, raises findingsApproversigns decisions and closuresFOUR MACHINE ACCOUNTSIntakeevents from forms and modulesImporterloads the old historyEscalation jobdaily overdue checkNumber issuerthe only writer of numbersNobody signs a record they reported, own or investigated. Nobody gets delete.
Five roles and four machine accounts. Roles are jobs, not people. Nobody gets delete: a correction is a new row or a cancelled status.
RoleScopeMayMay never
ReporterOwn siteRaise an event, add photos, fix it while it is newRead other people's events, place a hold
Quality engineerOwn siteTriage, place holds, open CAPAs, verify actions, plan audits, keep FMEAs and suppliersSet a disposition, sign a release or closure
CAPA ownerOwn CAPAs and the actions they ownRoot cause, actions, effectiveness criteriaVerify their own action, close their own CAPA
AuditorAssigned audits; never their home siteRecord results, raise findingsAudit their own site
ApproverOwn siteSign dispositions, hold releases, closures, change approvalsSign a record they reported, own or investigated

Four machine accounts do the automatic work, each with only its own rights: intake (events from forms and other modules), qms_importer (Sessions 5 and 6, insert-only, set to NOLOGIN at cut-over), escalation (the daily overdue check) and number issuer (the only writer of event, hold and CAPA numbers). Their passwords are set by a person and listed by name in docs/KEYS.md. ISO 9001:2015 clause 9.2 asks that auditors are objective and impartial [1]; the home-site rule is how the database keeps that. 21 CFR Part 11 asks that a signature shows who signed, when and what it meant [2]; the approver's rights are only the signing columns.

Step 5

Session 3: The roles in the matrix, rules generated, refusals proven

35 minutes

Why

Access rules written by hand drift from what was agreed. Writing the roles once in docs/matrix.json and generating the database rules and the route list from it means the matrix, the database and the menus always agree. Walking every right the later sessions need, now, stops a refusal in the middle of the cutover.

Do this

Paste into Claude Code
Read docs/matrix.json, scripts/gen-policies.mjs, scripts/gen-routes.mjs, lib/access/routes.ts and docs/spine-map.md with its M08 section. Before writing any route code, read the relevant guide in node_modules/next/dist/docs/ (this Next.js version keeps request middleware in proxy.ts).

On a new branch qms/access, add to docs/matrix.json:
1. Roles: reporter, quality_engineer, capa_owner, auditor, approver; machine accounts: qms_intake, qms_importer, qms_escalation, number_issuer. In a separate migration create the machine accounts as database logins with NOLOGIN, no BYPASSRLS, owning nothing; I set their passwords myself on each project, and you list them by name (never a value) in docs/KEYS.md.
2. Scopes: reporter, quality_engineer and approver by site; capa_owner by the CAPAs they own and the actions they own; auditor by assigned audit, never one whose site is their home site (an audit with no site is open to any assigned auditor).
3. Rights per table, starting from nothing, from this list: reporter inserts events with status new and reads their own, edits them while new, inserts NCR detail while pending; quality_engineer reads all qms_ tables and writes everything up to capa_pending and effectiveness_check, places holds, verifies actions they do not own, never sets a disposition or a closure; capa_owner moves their CAPA from open to implementation and edits its actions, never verified_by; auditor updates assigned audits and items and inserts audit_finding events; approver updates only the signing columns (disposition, mrb_signature_id, release and closure columns, approved_signature_id) and inserts core_e_signature. Nobody gets delete. Every role reads the lookup tables it picks from. qms_importer only inserts, into every qms_ table including archived rows; it never reads, updates or deletes.
4. Two-person rules: nobody signs a record they reported, own or investigated; nobody verifies an action they own.
5. Screens and routes: /quality/report (reporter, quality_engineer), /quality/my-actions (capa_owner), /quality/events (quality_engineer), /quality/capa (quality_engineer, capa_owner), /quality/audits (auditor, quality_engineer), /quality/approvals (approver), /quality/kpis (approver, quality_engineer), /api/quality/holds, /api/quality/sign (approver only), /api/quality/intake (qms_intake only). No import page or route: real records arrive only through the import workflow in Session 6.

Then run node scripts/gen-policies.mjs and node scripts/gen-routes.mjs so the policies migration and lib/access/routes.ts come from the matrix. Write docs/qms-rights-walk.md: every insert, update and read Sessions 4 to 6 of this module need, one line each, and a test that fails if any line is not allowed by the matrix.

Add tests to supabase/tests/access.test.sql: for every role and table, one allowed and one refused; a reporter cannot read another person's event or place a hold; a quality engineer cannot set a disposition; an approver cannot sign an event they reported; an auditor cannot be assigned an audit at their home site; for every update a role may make, the row really changed in the database (not only a success code); a signed-out request to every new screen and route is refused.

Push, open a pull request titled "Quality access", wait for every check, and tell me the result in plain words. If a check fails, fix the matrix or the code, never the test, and wait again.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/matrix.json)
+"approver": { "scope": "site", "qms_ncr_detail": { "update": ["disposition", "mrb_decided_at", "mrb_signature_id"] },
+ "rules": ["not_reporter", "not_owner", "not_investigator"] },
1
⏺ Bash(node scripts/gen-policies.mjs)
⎿ Wrote supabase/migrations/20261110140000_policies_qms.sql (212 policies)
⏺ Bash(npx supabase test db)
⎿ access.test.sql .. 418 tests, ok qms-rights-walk .. 63 lines, all allowed
2
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 3m12s clamps pass 0m48s
⏺ Pull request #64 is green. 418 access tests: each role does what the matrix allows and is refused the rest. 63 rights that Sessions 4 to 6 need are all in the matrix. I changed no test.
The matrix is the only file you decide; the policies and the route list are generated from it.
  1. The approver may touch only the signing columns, and never a record they reported, own or investigated.
  2. The rights walk: every later step checked against the matrix now, not discovered as a refusal later.

Check it worked

Pull request Quality access is green; docs/qms-rights-walk.md exists and its test passes; the access tests include a refused case for every role.

If it goes wrong

A button reports success but nothing changes, or a "new row violates row-level security" error

The role may update the row but not read it afterwards. In Postgres an update only finds rows the role can read, and the changed row must still pass the read rule. Say: For each role that updates qms_ rows, make its read rule cover the row before and after the change, and test that the row really changed. We hit this in three of our modules.

A signed-in user of the wrong role can open the approval queue

Signed in is not the same as allowed. Say: Find every route that signs, approves or releases and add a refused-role test for each role that should be refused. On our platform any signed-in user could delete a whole site, because the check only asked whether someone was signed in.

Tests pass in the SQL editor but the app still shows another site's events

The app is using a login that skips row-level security (the owner or the service role key). Say: Confirm the app's server code uses the signed-in user's session, not the service role, for every qms_ read.

The generator refuses to run: a table is missing from the matrix

Correct: every table must have a row. Add the row with no rights, then grant only what the walk needs.

Step 6

Session 3: The first three screens, one on each surface

40 minutes

Why

The reporter's screen decides whether problems get reported at all, so it must work with a thumb on the shop floor. The triage queue and the approval queue are where events wait; if those queues are not visible, events age silently. Building them now, against the seed, lets real people try them before the workflow is wired behind them.

Do this

Paste into Claude Code
Read the operator, supervisor and manager screens from Foundation Sessions 12 and 13 and follow their layout, components and tests. Read node_modules/next/dist/docs/ before adding routes; check proxy.ts still denies every route not in lib/access/routes.ts.

On a new branch qms/screens, build against the seed on the development project:
1. /quality/report (operator surface, phone first): pick the lot, part and press; type, title, quantity, defect code; one or more photos from the phone camera; a list of my own events and their status. The server sets event_no, reported_by (from the session, never from the page), status new and the times.
2. /quality/events (supervisor surface): new events oldest first, with severity, type and age.
3. /quality/approvals (manager surface): decisions, hold releases and closures waiting for a signature.

Rules: 44 px tap targets, 16 px form fields, 15 px body text, no sideways scroll at 360 and 390 px, contrast at least 4.5:1. A list with no rows says "Nothing waiting", never a made-up row. Add screen tests at phone size for each role, including a refused role for each screen.

Push, open a pull request titled "Quality screens", wait for every check including the preview, and give me the preview address and the demo login for each role.
Open

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

Open the pull request, then its Vercel preview, on your phone.

You will see recreated screen

acme-platform-git-qms-screens-acme-ops.vercel.app/quality/report
Report a quality problem
LotSYN-L-0412 ▾1
PressP-03 ▾
What is wrongBurr on flange edge
How many40
Add photo2
Send
My eventsSYN-QE-0009 · new · 2 minutes ago
The reporter's screen on the preview, at phone width. The server, not the phone, fills in the number, the person and the time.
  1. Picked from the spine, never typed: the lot must exist.
  2. Opens the phone camera. Test it with your thumb, standing up.

You will see recreated screen

acme-platform-git-qms-screens-acme-ops.vercel.app/quality/approvals
Waiting for your signature
1
RecordDecisionWaiting
SYN-QE-0004 · NCRDisposition: rework2 days
SYN-H-0002 · HoldRelease5 hours
The approval queue: only the approver sees it, and only for records they did not report, own or investigate.
  1. Every row needs a signature; nothing here can be approved with a single click.

Check it worked

The preview opens on your phone; each screen passes the phone check; a reporter sent to /quality/approvals is refused; the screen tests are green.

If it goes wrong

Every event shows the same reporter, whoever was signed in

The page sent the person's identity and the server trusted it. Say: Take reported_by from the signed-in session on the server and ignore anything the page sends. Add a test with two users. We hit this: every record said it was created by the founder.

A link or button opens a blank 404

A link that compiles is not a link that works. Say: Start the build, sign in as each role, visit every page and link on the three screens, and report every 404 and console error. We once had 130 tool links pointing nowhere.

The approval queue shows example rows when the seed is empty

Say: Remove every made-up row. An empty queue says Nothing waiting. Our screens once showed seven users who did not exist.

Knowledge check

An approver tries to sign the disposition of an NCR they reported. What happens?

Knowledge check

A role's update returns success, but the row in the database has not changed. What is the likely cause?

References

  1. ISO 9001:2015, Quality management systems: requirements. https://www.iso.org/standard/62085.html
  2. eCFR: 21 CFR Part 11, Electronic records and electronic signatures. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-A/part-11
  3. Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
  4. W3C: Web Content Accessibility Guidelines (WCAG) 2.2. https://www.w3.org/TR/WCAG22/

Chapter 3 · Session 4

The workflow, end to end

One event goes the whole way: raised on a phone, triaged, its lot held so it cannot move, a material review decision signed, a CAPA that finds the cause and proves the fix, and a signed closure. Then the FMEA action priority, the audit, change and supplier checks, and a dashboard that must match your hand count.

30 min3 stepsThe three checks that define done

By the end of this chapter you can

  • Make a hold a block the database enforces, and prove it with the consume and ship test.
  • Require a signature for a material review decision and a CAPA closure, and an effectiveness result before closure.
  • Compute the AIAG-VDA action priority from the handbook table and test it against independent vectors.
  • Check the dashboard against a hand count of the made-up example.
Event statusesSix statuses in order: new, triage, investigation, disposition, capa_pending and closed. Cancelled is a way out, set by the approver; which statuses may move to it is your own rule in docs/qms-rules.md. A trigger refuses any other move. The allowed path of a quality eventnewreportedtriageset severityinvestigationfind the causedispositiondecide and signcapa_pendingCAPA openedclosedsignedcancelleda way out, set by the approverA trigger refuses any move not in the allowed list: new cannot jump to closed.
The path of an event. A trigger refuses any move not listed in docs/qms-rules.md, so new cannot jump to closed.
Advisory flag or enforced blockLeft, the pitfall: a hold flag on a lot only warns, and the lot moves anyway. Right, the rule: every route that moves material calls qms_assert_not_held first, which reads active holds and either allows the move or refuses it with the hold number. ADVISORY FLAG · THE PITFALLHold flag on the lota column someone must checkScreen shows a warninga person may click past itLot moves anywayconsumed or shippedENFORCED BLOCK · THE RULEConsume or ship routeM04, M12 or M13 ask firstqms_assert_not_heldreads the active qms_hold rowsAllowedno active holdRefusedhold_no in the message
Advisory flag or enforced block. Every route that moves a lot asks one function first; the database refuses the move, with the hold number.
Step 7

Session 4: Raise, triage, and a hold the database enforces

30 minutes

Why

A hold that is only a flag on a screen is as strong as the person reading it. The module's most important rule is that the database itself refuses to consume or ship a held lot, whoever or whatever asks. Proving it with a test that acts as someone who would otherwise be allowed is the first check that defines done.

Do this

Paste into Claude Code
Read docs/qms-rules.md and docs/spine-map.md with its M08 section. On a new branch qms/workflow-hold:

1. Raising: /api/quality/events inserts an event with status new; the server takes event_no from the number issuer, reported_by from the session and the time from its own clock, and writes the status history, the audit log and a qms.event.created row in the outbox. /api/quality/intake does the same for the qms_intake account with source_type and source_id; the same source posted twice makes one event.
2. Triage: a trigger refuses any status move not in docs/qms-rules.md. A complaint cannot leave triage without reportable and reportability_rationale.
3. Holds: /api/quality/holds places a hold (one qms_hold row and the lot's status set to on hold in the same transaction, earlier status kept in ext). Make the one function from docs/spine-map.md (the lot is held if holds or qms_hold holds it) the rule: a trigger refuses a lot being consumed into another lot while held, a trigger refuses a lot leaving on hold except by a signed release or a signed scrap or return_to_vendor disposition, and every route that moves a lot calls the function first.
4. Two test-only routes, /api/quality/test/consume and /api/quality/test/ship, acting as the Foundation operator role, switched off in production. Tests: both are refused on a held lot with the hold_no in the message, and allowed on a free lot.

Show me each new test failing with the trigger removed and passing with it. Push, open a pull request titled "Quality: raise, triage, hold", wait for every check, and tell me the result in plain words.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx vitest run tests/quality/hold.test.ts)
⎿ ✗ consume on held lot is refused (trigger removed: move accepted) ✗ ship on held lot is refused
1
⏺ Bash(npx vitest run tests/quality/hold.test.ts)
⎿ ✓ consume on held lot is refused: lot SYN-L-0412 is on hold SYN-H-0001 ✓ ship on held lot is refused ✓ consume on free lot is allowed
2
⏺ Bash(gh pr checks --watch)
⎿ ci / test pass 2m02s schema / test pass 2m40s
⏺ Pull request #65 is green. A held lot is refused by both stand-in routes, with the hold number in the message; a free lot moves. The same source posted twice made one event.
The proof of the hold: someone who may move lots is refused, by the database, with the hold number.
  1. Red first: with the rule removed, the held lot moved. That shows the test can fail.
  2. Green: the database, not the screen, refused the move.

Check it worked

Pull request Quality: raise, triage, hold is green, and you saw the hold tests fail without the trigger and pass with it.

If it goes wrong

The ship test passes, but only because the ship screen hides the button

That is the advisory flag again. Say: Call the stand-in route directly as the operator role, not through the screen, and expect the database to refuse.

A test has been green from the start and you never saw it red

Say: Remove the trigger, run the test and show me it fails; then restore it. Our page-presence check reported 350 present and 0 absent for weeks because it could only ever say yes.

Two people triage the same event at once and one change disappears

Say: Include updated_at in every update's where clause so a stale save is refused with a clear message, and test two saves from the same starting copy. We lost records this way before we added that check.

The six material review dispositionsThe approver signs one of six dispositions. Scrap and return to vendor reject the lot and convert the hold to scrap. Use as is, rework, repair and regrade keep the hold until the work is done, then it is released with a second signature. Dispositionsigned by the approverLOT REJECTED · HOLD CONVERTED TO SCRAPscraplot rejectedreturn_to_vendorlot rejected, goes backHOLD STAYS UNTIL THE WORK IS DONE, THEN RELEASEDuse_as_isaccepted as it isreworkredone to specificationrepairmade usableregradeused as a different gradeA disposition other than pending needs mrb_signature_id and mrb_decided_at.
Six dispositions. Scrap and return_to_vendor reject the lot and convert the hold; the other four keep it until the work is done and a second signature releases it.
CAPA statuses and the three gatesSix steps in order: open, investigation, action_plan, implementation, effectiveness_check and closed; a seventh status, cancelled, ends a CAPA that is withdrawn. Gate 1 leaves investigation only with a root cause and category. Gate 2 enters the effectiveness check only when no action is open or unverified. Gate 3 closes only with an effectiveness result that is not pending, and a signature. openinvestigationaction_planimplementationeffectiveness_checkclosedGate 1root_cause androot_cause_categorymust be filled inGate 2no action openor unverifiedGate 3result is not pendingclosure is signedCourse rule, not a standard: a not_effective result needs a follow-up CAPA number to close.
A CAPA and its three gates. No leaving investigation without a root cause, no effectiveness check while an action is open or unverified, no closure without a signed effectiveness result.
Step 8

Session 4: The signed decision, the CAPA and its effectiveness check

35 minutes

Why

A material review decision and a CAPA closure are the two moments a quality system is audited on. Each must carry a signature that shows who, when and what it meant, by someone other than the person whose work it judges. And a CAPA that closes without proof that the fix worked is only a to-do list; the database refusing that closure is the second check that defines done.

Do this

Paste into Claude Code
Read docs/qms-rules.md. On a new branch qms/workflow-capa:

1. Disposition: the approver chooses one of the six dispositions and signs with their password typed again: a core_e_signature row (signer from the session, meaning approved, record type and id, a hash of the decision, server time). A trigger refuses a disposition other than pending without mrb_signature_id and mrb_decided_at, a signer who is not the signed-in person, and a signer who reported, owns or investigated the event. Scrap and return_to_vendor reject the lot and convert the hold; the others keep the hold until a second signed release. Write qms.hold.released to the outbox.
2. CAPA: insert from the event with problem statement, method, owner and due date. Root cause tools as qms_rca_artifact rows (five_why, fishbone). Gate 1: refuse leaving investigation without root_cause and root_cause_category. Actions of each type; a training action writes qms.capa_action.training_required. Gate 2: refuse effectiveness_check while any action is open or not verified by someone other than its owner. Gate 3: refuse closing with effectiveness_result empty or pending, or without the approver's signature.
3. A daily job as qms_escalation that writes an in-app core_notification for overdue CAPAs, actions and events, using the days in docs/qms-rules.md.
4. Tests for every refusal above, each shown failing without its trigger and passing with it, and a test that changing one character of a signed decision makes its stored hash no longer match.

Push, open a pull request titled "Quality: decision and CAPA", wait for every check, and tell me the result in plain words.

You will see recreated screen

acme-platform-git-qms-workflow-capa-acme-ops.vercel.app/quality/approvals/SYN-QE-0004
Sign: disposition for SYN-QE-0004
Dispositionrework
MeaningApproved: I have reviewed this decision1
Your password••••••••••••••••2
Sign
Signing on the preview: the approver types their password again, and the screen says what the signature means.
  1. The meaning is part of the signature record, as Part 11 asks.
  2. Typed again at the moment of signing, never remembered by the page.
  3. The two-person rule, enforced by the database, shown in plain words.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase test db)
⎿ qms-capa.test.sql .. ok 14/14 ok closing a CAPA with effectiveness_result pending is refused ok effectiveness_check with an unverified action is refused ok a changed decision no longer matches its stored hash
1
⏺ Pull request #66 is green. A CAPA cannot close without a signed effectiveness result; a disposition cannot be set without a signature by someone independent of the event.
The CAPA gates, each proven by a refusal.
  1. The second check that defines done: no closure with a pending result.

Check it worked

Pull request Quality: decision and CAPA is green. On the preview, closing the seed's open CAPA with its result pending is refused.

If it goes wrong

Sign shows "Signed" but no core_e_signature row exists

A screen that claims success while nothing happened. Say: After signing, read the signature row back from the database and show it; if it is missing, show an error, never Signed. On our platform a Send button marked every email sent while none left the building.

The approver can sign their own event when using the API directly

The rule is only in the screen. Say: Move the not-reporter, not-owner, not-investigator rule into the trigger and test it by calling the route directly.

Claude Code proposes email or text alerts for overdue CAPAs

Say: In-app notifications only for now. Sending messages can cost money and needs its own keys; it is a separate decision.

Action priority, not RPN alone

Two lines with the same RPNTwo FMEA lines drawn to scale on a 1 to 10 rating scale. Line A has severity 10, occurrence 2 and detection 5. Line B has severity 2, occurrence 10 and detection 5. Both multiply to an RPN of 100, but the risk is very different. Line A: 10 × 2 × 5 = 10010Severity2Occurrence5DetectionLine B: 2 × 10 × 5 = 1002Severity10Occurrence5DetectionSame RPN, 100. Severity 10 is the worst effect on the scale; severity 2 is minor.Action priority reads the combination of ratings, not their product.
Two lines, one RPN. A severe, rare failure and a minor, common one both multiply to 100. Action priority reads the combination, not the product.

The AIAG-VDA FMEA Handbook (2019) replaces ranking by RPN with an action priority of high, medium or low, read from a table of severity, occurrence and detection [2]. The table is in the handbook, which AIAG sells; read its price on the publisher's page and use your own copy, never an unofficial one [3]. Because a typed value cannot be trusted, a trigger always sets action_priority from the function.

A hand count on the seedCost of poor quality is a bar of 600 made-up units: scrap 400, use as is 50, rework 150. CAPA on-time closure is 3 of 5 and CAPA effectiveness rate is 3 of 4. Cost of poor quality on the seed, to scale (1 px = 1 made-up unit)scrap 400use_as_is 50rework 150= 600CAPA on-time closureCAPA effectiveness rate3 ÷ 5 = 60%3 ÷ 4 = 75%green: closed by the due date · rose: closed late, or open past duegreen: effective · rose: not_effectiveA synthetic seed made up for the lab, not a measurement of any business.
The hand count of the made-up example (tests/fixtures/quality-kpis.json, the same records the seed loads onto today). Cost of poor quality 600 made-up units; CAPA on-time closure 3 of 5; effectiveness 3 of 4. The dashboard must show exactly these.
Step 9

Session 4: Action priority, the other workflows, and a dashboard that matches your count

35 minutes

Why

A function typed from a table can be wrong in one cell and nobody would notice. Checking all 1,000 combinations exist once, and checking vectors that a second person reads from the printed handbook, is the third check that defines done. The dashboard is only trusted when it equals a count made by hand from the same made-up records, kept as a test fixture.

Do this

Type the handbook's action priority table, by range, into docs/fmea-ap.csv (columns: s_from, s_to, o_from, o_to, d_from, d_to, ap). Ask a second person to read ten vectors from the printed handbook (one each of H, M and L, and the edges of each range) into docs/fmea-ap-vectors.csv. Then:

Paste into Claude Code
On a new branch qms/workflow-fmea:
1. Expand docs/fmea-ap.csv to every combination and test that all 1,000 combinations of severity, occurrence and detection from 1 to 10 appear exactly once. Write qms_action_priority(s, o, d) from it and a trigger on qms_fmea_line that always sets action_priority from it. Test the function against docs/fmea-ap-vectors.csv, which you must not edit. Show RPN beside action priority on the FMEA screen as a comparison only.
2. One test each: a minor_nc or major_nc audit item creates an audit_finding event and links it; an audit cannot close while an item has no result; a change cannot reach implementation without approved_signature_id or close with a task open, and approval writes qms.change_control.approved; scar_count on a scorecard is counted from the period's scar events, never typed; a planned deviation needs impact_assessment and product_impact.
3. The quality dashboard at /quality/kpis from queries over the tables only: events by type and status, cost of poor quality, CAPA on-time closure (closed by due date / due), effectiveness rate (effective / verified), active holds. A test loads tests/fixtures/quality-kpis.json into an empty database and expects exactly the answers written in it: cost of poor quality 600, on-time 3 of 5, effectiveness 3 of 4, active holds 1. A widget with no data says "No data", never 0.

Push, open a pull request titled "Quality: FMEA, checks, dashboard", wait for every check, and tell me the result in plain words.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx vitest run tests/quality/fmea-ap.test.ts)
⎿ ✓ 1000 combinations, each exactly once ✓ 10 of 10 vectors from docs/fmea-ap-vectors.csv match
1
⏺ Bash(npx vitest run tests/quality/kpis.test.ts)
⎿ ✓ copq 600 ✓ on-time 3/5 ✓ effectiveness 3/4 ✓ active holds 1
2
⏺ Pull request #67 is green. The action priority function matches all ten vectors your colleague read from the handbook. The dashboard numbers equal your hand count of the fixture.
The three proofs: every combination exists once, the independent vectors match, and the dashboard equals the hand count.
  1. The vectors file came from a second person and the printed book, not from the table you typed: otherwise the test only checks your typing.
  2. The dashboard's numbers come from the tables, and a test pins them to the hand count.

Check it worked

Pull request Quality: FMEA, checks, dashboard is green, and /quality/kpis on the preview shows 600, 3 of 5, 3 of 4 and 1 active hold.

If it goes wrong

The dashboard shows a number that differs from your hand count

Fix the query, never the count. Say: Show me the SQL behind this widget and the rows it counts; find why it differs from 3 of 5.

A widget shows 0 where there is no data

Zero is a real measurement. Say: Show No data when there are no rows, never 0. On our platform an unreadable sensor shown as 0 looked like a real reading.

Claude Code edits docs/fmea-ap-vectors.csv to make a test pass

Say: Restore the vectors file. If a vector fails, the table I typed is wrong: show me which cell. Never let a check be loosened to get to green.

You have no copy of the handbook

Do every other part of this step now and the action priority when the copy arrives. Ask the customer or certification body that requires the FMEA; do not use an unofficial copy.

Knowledge check

Why must the action priority test vectors come from a second person reading the printed handbook?

Knowledge check

What does the module do when someone tries to close a CAPA whose effectiveness result is pending?

References

  1. ASQ: What is root cause analysis?. https://asq.org/quality-resources/root-cause-analysis
  2. AIAG: Quality Core Tools (APQP, CP, PPAP, FMEA, MSA, SPC). https://www.aiag.org/expertise-areas/quality/quality-core-tools
  3. AIAG: AIAG & VDA FMEA Handbook. https://www.aiag.org/training-and-resources/manuals/details/FMEAAV-1
  4. ASQ: The Plan-Do-Check-Act (PDCA) cycle. https://asq.org/quality-resources/pdca-cycle
  5. PostgreSQL Documentation: CREATE TRIGGER. https://www.postgresql.org/docs/current/sql-createtrigger.html

Chapter 4 · Sessions 5 and 6

Move the records, and switch the old eQMS off

The import is built and tested on made-up data, rehearsed once on the development project with a copy IT has approved, and only then run into production through the pipeline, after a week of running both systems side by side. Then the old tool is switched off and the saving written down from real invoices.

30 min5 stepsEnds with the module gate

By the end of this chapter you can

  • Build an import that is safe to run twice, has a dry run, and keeps closed records read-only with their original signatures as evidence.
  • Rehearse it on the development project with a copy IT approved in writing, and remove the rehearsal the same day.
  • Run it into production through import-quality.yml, started by a person from main for an approved export, and check counts match.
  • Cut over, keep the history, and record the saving from invoices.
How the old history comes inThe export from the old eQMS splits in two. Open events, CAPAs and active holds are imported live with status, due dates and owners kept. Closed events, CAPAs and audits are imported archived and never editable, with original signatures kept as attached evidence. Export from the old eQMSevents, CAPAs, audits,attachmentsOpen events, CAPAs and active holdsImported live: status, due dates and owners kept.An active hold keeps its lot on_hold.Closed events, CAPAs and auditsImported archived: archived_at set, never editable.Original signatures kept as attached evidence.Old numbers are kept in ext.legacy_no; imported numbers get the prefix L-.A second run of the import adds no rows.
How the old history comes in. Open work arrives live; closed records arrive archived and read-only, with the original signatures kept as attached evidence, never recreated.

Two rules matter most. A signature the platform did not witness is never turned into a new signature: it is kept as evidence, with the old tool's signed record attached and its fingerprint stored. And the import changes production only through the pipeline: the script and its tests are reviewed and merged like any change, and a person starts the run on GitHub from main, for an export whose sha256 and counts were approved in a reviewed pull request; Claude Code never runs it.

Key or secretWhat it unlocksWhere it livesWho holds itNever
qms_importer password (development)Signing in as the insert-only import login on acme-platform-dev; listed by name in docs/KEYS.mdPassword manager; GitHub secret QMS_IMPORTER_PASSWORD_DEVpat@acme.com, sam@acme.comNever in a file, a chat or Claude Code
qms_importer password (production)Signing in as the insert-only import login on acme-platform-prod, until it is set to NOLOGIN at cut-over; listed by name in docs/KEYS.mdPassword manager; GitHub secret QMS_IMPORTER_PASSWORD_PRODpat@acme.com, sam@acme.comNever on a laptop outside the password manager
The old eQMS exportEvery quality record, with namesA private folder, then the private Storage bucket imports; its sha256 and counts in docs/imports/quality-approved.mdThe quality managerNever in the repository, a test, or a chat
Step 10

Session 5: The import, built and tested on a made-up export

35 minutes

Why

An import that cannot be run twice, that changes data when you only wanted to look, or that runs on a file nobody approved, turns the cutover into guesswork. Building it with a dry run, a report of everything it cannot map, a fingerprint check and tests on a made-up export means the real records are only ever touched by a script that has already been reviewed and proven.

Do this

First, with the quality engineer, write docs/qms-import-map.md: the counts in the export per type and status, and how old types, severities, statuses, defect codes, root cause headings, CAPA methods and audit types map to the module's values. People map by email, suppliers by name, lots by number.

Paste into Claude Code
Read docs/qms-import-map.md, the M08 section of docs/spine-map.md and docs/matrix.json. On a new branch qms/import:

1. scripts/import/qms-import.mjs: reads one export file (a zip), connects as the database login qms_importer (password from the environment variable QMS_IMPORTER_PASSWORD, never printed), and inserts in this order: defect codes, events and detail rows, holds, CAPAs, actions and root cause artifacts, attachments, audits and items, comments and history. It only inserts; it never reads, updates or deletes.
   - Open events, CAPAs and active holds come in live, with status, owners and due dates; an active hold sets its lot on hold, and a hold whose lot does not exist stops the import with a list.
   - Closed records come in archived (archived_at set) and are never editable: add a trigger that refuses update or delete of a row with archived_at set and ext.imported_from.
   - Original signatures go into ext.original_signatures, and the old signed record is attached with its sha256. No core_e_signature row is created for a signature the platform did not witness; the signature triggers skip rows with ext.imported_from.
   - Old numbers are kept in ext.legacy_no; imported numbers get the prefix L-; a record whose number or legacy_no already exists is skipped (on conflict do nothing) with all its children, so a second run adds nothing.
   - --dry-run writes a report (counts per type and status, every record it cannot map) and changes nothing. Every row carries ext.import_run.
2. supabase/snippets/qms-remove-run.sql, for the development project only: deletes only the rows whose ext.import_run is the run id I type in, and prints what it removed. I paste it into that project's SQL editor myself; nothing runs it automatically.
3. tests/import/ with a made-up export (SYN- names only): dry run changes nothing; counts match; a second run adds nothing; an archived row cannot be edited; an export whose sha256 is not approved is refused; a count that differs from the approved counts fails the run; the removal snippet removes only its own run.
4. .github/workflows/import-quality.yml: started by hand only (workflow_dispatch) and refusing to run from any branch but main, with inputs target (development or production) and dry_run. It downloads the export from the private Storage bucket imports of the target project and computes its sha256; it refuses unless that sha256 and the expected counts per type and status are recorded for that target in docs/imports/quality-approved.md on main; it runs the script with the matching secret (QMS_IMPORTER_PASSWORD_DEV or QMS_IMPORTER_PASSWORD_PROD); it fails on any count mismatch (the export must equal the approved counts, and imported plus skipped must equal the export); it writes the counts to the job summary and uploads the report as the run's artifact. No GitHub environment with required reviewers. Never print a secret.

Push, open a pull request titled "Quality import", wait for every check, and tell me the result in plain words. Do not run the workflow.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx vitest run tests/import)
⎿ ✓ dry run changes nothing ✓ counts per type and status match the export ✓ second run adds 0 rows ✓ archived row: update refused ✓ unapproved sha256 refused ✓ count mismatch fails the run
1
⏺ Write(.github/workflows/import-quality.yml)
+on:
+ workflow_dispatch:
+ inputs:
+ target: { type: choice, options: [development, production] }
+ dry_run: { type: boolean, default: true }
2
⏺ Pull request #68 is green. I did not run the workflow: a person starts it on GitHub, from main, and it refuses any export whose sha256 and counts are not in docs/imports/quality-approved.md. It needs two secrets you type yourself: QMS_IMPORTER_PASSWORD_DEV and QMS_IMPORTER_PASSWORD_PROD.
The import is proven on made-up records before any real record exists outside the old tool.
  1. Six tests on a made-up export, including the ones that protect production.
  2. Started by hand only: nothing imports on a push or a merge.

Check it worked

Pull request Quality import is green and merged; the workflow file shows only workflow_dispatch as its trigger, refuses any branch but main, and reads the approved sha256 and counts from docs/imports/quality-approved.md.

If it goes wrong

Claude Code asks you to paste the importer password so it can test

Refuse. Say: Use the made-up export and CI's own throwaway database. I type real passwords only into GitHub's secrets page and the project's SQL editor.

Claude Code wants to put a sample of the real export in tests/

Refuse. Real records never go into the repository or a test; the fixtures are made up and marked SYN-.

Claude Code suggests a GitHub environment with required reviewers

Say: No environments with required reviewers; the reviewed pull request that records the sha256 is the approval. On the Team plan they are not available for private repositories.

Step 11

Session 5: Rehearse the import on the development project

30 minutes

Why

The first run against real records will find things the made-up export did not: an unknown supplier, a person who left, a lot that was never in the system. Finding them on the development project, with a copy IT has approved in writing for this rehearsal, costs nothing. Finding them in production costs a cleanup. Removing the rehearsal the same day keeps the development project made-up only.

Do this

Ask IT to approve one copy of the export for this rehearsal, in writing, redacted where it holds personal or injury data (names of complainants and reporters, injury details in complaints). Work out its fingerprint in a terminal (on Windows, Get-FileHash in PowerShell):

Terminal (Mac)
shasum -a 256 ~/private/qms-export.zip
Paste into Claude Code, after filling the <...> parts
On a new branch qms/import-approval-dev, create docs/imports/quality-approved.md with a section "development rehearsal": export file qms-export.zip, sha256 <paste the value>, expected counts per type and status <paste them from docs/qms-import-map.md>, IT's written approval for one rehearsal on acme-platform-dev given on <date> by <role>, redacted where it held personal or injury data, and a line "removed on:" left empty. Open a pull request titled "Quality: approve rehearsal export".

Owner two approves the pull request and you merge it. On the development project, set the import login's password yourself in the SQL editor (alter role qms_importer login password '…', a long value from the password manager), then:

Open

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

New repository secret: name QMS_IMPORTER_PASSWORD_DEV, value pasted from the password manager (the value only).

Open

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

Storage: create a private bucket named imports if it does not exist, and upload the approved copy of the export.

Open

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

Run workflow from main: target development, dry_run true. Read the report. Then dry_run false.

The same day: paste supabase/snippets/qms-remove-run.sql with the run id into the development project's SQL editor, delete the file from the bucket, and record the date on the "removed on:" line through a pull request.

You will see recreated screen

github.com/acme-ops/acme-platform/actions/workflows/import-quality.yml
import-quality · target development · dry_run false
2
KindApprovedIn exportImportedSkipped
Events (open)3838380
Events (closed)1,2041,2041,2013
CAPAs1171171170
Active holds4440
Skipped: 3Supplier not in the spine: SUPPLIER-0091 (3 closed SCARs). Listed in the report artifact.3
The run summary on GitHub. The report says what came in, what was skipped and why.
  1. Green means it ran, and only because the export is the approved one: the counts decide.
  2. Approved, in the export and imported plus skipped must all agree, or the run fails.
  3. Each skip names the reason. Fix the spine or the map, then run again: the second run adds only what was skipped.

Check it worked

The development run's counts agree with docs/imports/quality-approved.md, every skipped row is explained, and three imported closed records match the old tool beside them. The same day, the rehearsal rows are removed with the snippet, the bucket file is deleted, and the date is recorded.

If it goes wrong

The run refuses: sha256 not approved

The file in the bucket is not the one recorded on main (a re-export changes it). Record the new value through a pull request owner two approves, or upload the approved file.

The run fails at sign-in although the secret exists

The value is probably wrong: on our Academy a key's value was its own name, pasted by mistake. Paste the value only, never NAME=value, and run again.

Counts differ and the report cannot say why

Do not go on to production. Say in Claude Code: The dry run reports 1,201 closed events and the export has 1,204. Explain each missing record from the report without running anything.

An imported closed CAPA can be edited

The read-only trigger is missing or skipped for that role. Stop, fix it with a new migration and a test, and rehearse again.

Step 12

Session 6: A week side by side, compared one record at a time

30 minutes, after a week of parallel running

Why

A week where every new event is raised in both tools shows whether the people, the screens and the rules work on real days. Comparing hand counts from the old tool with the new dashboard, and every open record one by one, turns "it seems fine" into evidence. A difference you cannot explain means you are not ready to switch off.

Do this

During the week, every new event and CAPA is raised in both tools, the old tool stays the record, and the quality engineer writes the old number into the new record's legacy number at triage. At the end of the week:

Paste into Claude Code, after replacing the <...> part
On a new branch qms/cutover, write docs/cutover.md from what I give you:
1. A table: events raised by type, events open, CAPAs due and overdue, actions overdue, active holds, audits planned; one column from the old tool's report (named) and one from /quality/kpis on the deployed address. Explain every difference I give you; where I wrote "unexplained", say we are not ready.
2. Open events and CAPAs from both tools matched by legacy number, with owner and due date; every mismatch and its fix.
3. The three definition-of-done checks, run against the deployed demo address, with the date and who ran each: a held lot is refused by consume and ship; a CAPA cannot close without an effectiveness result and a signature; action priority matches the handbook vectors.

My figures and notes:
<paste the old tool's counts, the dashboard's counts, and the check results>

Open a pull request titled "Quality cutover evidence".

You will see recreated screen

github.com/acme-ops/acme-platform/blob/qms/cutover/docs/cutover.md
docs/cutover.md
1
MeasureOld tool (Event Summary)New moduleDifference
Events raised2323none
Events open4141none
CAPAs overdue651: closed in new tool on Friday, old tool updated Monday
Active holds44none
Definition of doneHeld lot refused (consume, ship) · CAPA closure needs a result and a signature · AP matches 10 of 10 vectors2
The side-by-side table on GitHub, the evidence the cutover decision rests on.
  1. Every difference has a reason in plain words.
  2. The three checks that define done, run on the deployed address, dated.

Check it worked

docs/cutover.md is merged with no unexplained difference, every open record matched, and the three checks passing on the deployed address.

If it goes wrong

The dashboard and the hand count differ and nobody knows why

You are not ready. Find the cause first (a missed parallel entry, a status mapped differently, a query error), write it down, and extend the parallel week if needed.

People stopped using one of the tools mid-week

Restart the count from the day both were used again. A partial week compares nothing.

Step 13

Session 6: The final import into production, through the pipeline

30 minutes

Why

Production is where the records will live for years, so it is changed only by reviewed code started by a person from main, for an export whose fingerprint and counts were approved in a reviewed pull request, never from a laptop, an upload page or an agent. Running the same import you rehearsed, against the final export, with counts that must match, is the last proof before the old tool becomes read-only.

Do this

Before you start: tell the floor that new events go into the new module only from now, and ask the vendor's administrator to make the old tool read-only. Take the final export the same day, work out its sha256, and add a "production" section to docs/imports/quality-approved.md (file, sha256, expected counts per type and status, date) through a pull request; owner two approves and you merge. Set qms_importer's password on production yourself in its SQL editor. Then:

Open

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

Before the run, check the latest deploy on main is green, so production has every migration.

Open

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

New repository secret: QMS_IMPORTER_PASSWORD_PROD, the value only.

Open

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

Production Storage: a private bucket named imports; upload the final export.

Open

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

Run workflow from main: target production, dry_run true; read the report; then dry_run false; then once more (it must add nothing).

You will see recreated screen

github.com/acme-ops/acme-platform/actions/workflows/import-quality.yml
import-quality · target production · dry_run false
2
KindApprovedIn exportImportedSkipped
Events (open)3636360
Events (closed)1,2311,2311,2310
CAPAs1191191190
Active holds4440
The production run. Same script, same report, the final export.
  1. Started by a person on GitHub, from main, for the approved file.
  2. The counts that go into docs/cutover.md.
  3. Run the import once more: it must add nothing.

Check it worked

The run's sha256 matched the approved production entry, counts per type and status equal the approved counts, a second run added nothing, every active hold shows its lot on hold in production, and an imported closed CAPA cannot be edited. The counts are added to docs/cutover.md.

If it goes wrong

The run fails with "relation does not exist"

Production is missing a migration. Open the deploy workflow's latest run on main and the daily freshness check from Session 11; fix the deploy, never apply by hand from a laptop. Our production database once fell nine migrations behind main.

The dry run lists records the rehearsal did not

Expected for anything raised during the parallel week. Map them, merge the change, and run the dry run again before importing.

The run fails on a count mismatch

Do not switch off the old tool, and do not edit the approved counts to make it pass. Explain each difference from the report and the old tool; record a corrected export through a reviewed pull request and run again (it skips what exists).

Step 14

Session 6: Cut over, keep the history, and cancel with the saving written down

20 minutes

Why

A module is only finished when the old tool stops costing money and nobody needs it for anything. Keeping the final export, with its fingerprint, for the period your standards require means the past is safe without the old subscription. Writing the saving from real invoices is what proves the work paid for itself.

Do this

Turn off the old tool's email notices, remove its links from the intranet, and tell suppliers and auditors who used it where to go now. Store the final export, with its sha256, in private storage for the period the quality manager gives you. Set the import login to NOLOGIN on production and development (alter role qms_importer nologin in each project's SQL editor). Read the vendor's cancellation terms from your own account page and cancel, or write the date the plan ends. Then:

Paste into Claude Code, after replacing the <...> parts
On the branch qms/cutover, update docs/cutover.md and docs/qms-inventory.md from what I give you:
- cutover date, who told the floor, where the final export is stored, its sha256 and the retention period the quality manager set;
- in docs/KEYS.md, qms_importer set to NOLOGIN on both projects, with the date;
- the old tool's annual cost from invoice <number>, the cancellation date or plan end date, and the saving: old annual cost minus what the module costs to run on services we already pay for, as arithmetic from the invoices I give you, never an estimate;
- in docs/qms-inventory.md, each tool and workaround marked replaced, retired or still in use, with the date.
Then add this module's checks to docs/testing-protocol.md (the hold test, the CAPA closure test, the action priority vectors, the import counts), push, and tell me when the pull request is green.

My figures:
<paste the dates, invoice figures and storage location>

You will see recreated screen

claude — acme-platform
⏺ Write(docs/cutover.md)
+Cutover: 2026-11-30. Old tool read-only from 2026-11-30 07:00.
+Final export: private bucket archive/qms-2026-11-30.zip, sha256 9f2c…e41a, kept 15 years (quality manager).
+Old annual cost: invoice INV-2026-0412. Cancelled 2026-12-01, plan ends 2027-03-01.
1
⏺ Write(docs/testing-protocol.md)
+| Quality: held lot refused (consume, ship) | npx vitest run tests/quality/hold.test.ts | quality engineer |
+| Quality: CAPA closure needs a result and a signature | npx supabase test db | approver |
2
⏺ Pull request #70 is green. The saving is the invoice figure you gave me minus zero new services; I wrote the arithmetic, not a rounded total.
The last change: the evidence written down, and the module's checks added to the testing protocol.
  1. Every figure points at an invoice or a stored file.
  2. The module's gates join the platform's testing protocol, so they run on every later change.

Check it worked

The old tool is read-only or cancelled, qms_importer is NOLOGIN on both projects, the final export is stored with its fingerprint, docs/cutover.md shows the saving from invoices, and docs/testing-protocol.md lists the module's checks.

If it goes wrong

Someone asks to keep the old tool "just in case"

Ask what they would look up in it. If the answer is a record, find it in the new module; if it is not there, the import missed it, and that must be fixed before cancelling.

The retention period is not known

Ask the quality manager; standards, customer contracts and regulators set it. Do not guess; keep the export until it is decided.

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

Knowledge check

How do imported closed records keep their original signatures?

Knowledge check

Who starts the import into production, and how?

References

  1. GitHub Docs: Manually running a workflow. https://docs.github.com/en/actions/managing-workflow-runs/manually-running-a-workflow
  2. GitHub Docs: Using secrets in GitHub Actions. https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions
  3. Supabase Docs: Storage. https://supabase.com/docs/guides/storage
  4. Rajesh Kumar: top 10 QMS buyer criteria. https://www.rajeshkumar.xyz/blog/quality-management-systems-qms/
  5. SoftwareConnect: TrackWise eQMS. https://softwareconnect.com/reviews/trackwise/

Chapter 5 · 12 questions · 80% passes

Final assessment

Twelve questions across the module. 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. Why is Session 1's inventory taken from the old tool's own reports and invoice?
2. The specification names core_lot, and your platform already has lots. What does the module point at?
3. Why do all quality events share qms_quality_event, with small detail tables?
4. Who runs supabase db push against the development project in Session 2?
5. What makes a quality hold different from an advisory flag?
6. Where are the rights of the five roles decided?
7. A role's update returns success but the row has not changed. What is the usual cause?
8. A CAPA has effectiveness_result pending. What happens when someone tries to close it?
9. Why must the action priority test vectors be read from the printed handbook by a second person?
10. The dashboard shows CAPA on-time closure 4 of 5, and your hand count of the seed is 3 of 5. What do you change?
11. How do closed records from the old eQMS arrive?
12. How do real records reach production?