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.
| Standard | Used 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 Tools | APQP, 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 Q10 | Pharmaceutical quality risk management and quality system |
| 21 CFR Part 11 and EU Annex 11 [4] | Electronic records and electronic signatures |
| AS9100D | Aerospace quality systems: nonconformance and first-article linkage |
Session 1: Count what the old eQMS holds and costs, from its own reports
60 minutesWhy
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.
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
- Every figure carries its source: an invoice, a report or a page. That is what makes it usable in Session 6.
- 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 says | On the stamping plant's platform | If you have nothing like it |
|---|---|---|
| core_site | sites | Never missing: Session 5 made it |
| core_item | parts | Never missing |
| core_lot | lots (with the lot_status view) | Never missing |
| core_equipment | equipment | Never missing |
| core_person | Supabase sign-in users with memberships | Add a people table that points at the sign-in user |
| core_party (suppliers and customers) | usually missing | Add it in the spine migration |
| core_uom, core_item_class | usually missing | Add them in the spine migration |
| core_e_signature, core_attachment, core_status_history, core_number_sequence, core_event_outbox, core_notification | usually missing | Add them in the spine migration: other modules need them too |
| tenant_id on every row | site_id on every row | Your platform serves one company; site_id is the scope the access rules of Session 8 use |
| uuid ids | the id type your first migration uses | Keep one id type across the platform |
Session 2: Map the spine, and add only what is missing
20 minutesWhy
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
cd ~/code/acme-platform && git switch main && git pull && claudeRead 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
- It read your actual migrations, not a guess at them.
- 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.
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.
| Table | Holds | Columns |
|---|---|---|
| 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 |
Session 2: One prompt: the eighteen tables, their rules and their tests
25 minutesWhy
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
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
- The column list is now the module's own section of the one shared map, so a later change can be checked against it.
- Every allowed-values list from the reference becomes a check the database enforces.
- 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.
Session 2: A small made-up seed, tried on the development project
20 minutesWhy
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
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.
cd ~/code/acme-platform && git fetch && git switch qms/tables && npx supabase link --project-ref tsrqponmlkjihgfedcbanpx supabase db push --include-seedhttps://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
- Read the list before answering y: only the files this branch adds.
You will see recreated screen
| event_no | event_type | severity | status |
|---|---|---|---|
| SYN-QE-0001 | ncr | major | closed |
| SYN-QE-0004 | ncr | minor | disposition |
| SYN-QE-0005 | scar | major | investigation |
| SYN-QE-0008 | audit_finding | minor | triage |
- SYN- numbers: made up, removable, never mistaken for real records.
- 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
- ISO 9001:2015, Quality management systems: requirements. https://www.iso.org/standard/62085.html
- ISO 13485:2016, Medical devices: quality management systems. https://www.iso.org/standard/59752.html
- eCFR: 21 CFR Part 820, Quality Management System Regulation. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-H/part-820
- eCFR: 21 CFR Part 11, Electronic records and electronic signatures. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-A/part-11
- Prezent: eQMS platforms for life sciences. https://www.prezent.ai/blog/qms-for-life-sciences
- SoftwareConnect: Veeva Vault QMS. https://softwareconnect.com/go/veeva-vault-qms-29564
- 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.
| Role | Scope | May | May never |
|---|---|---|---|
| Reporter | Own site | Raise an event, add photos, fix it while it is new | Read other people's events, place a hold |
| Quality engineer | Own site | Triage, place holds, open CAPAs, verify actions, plan audits, keep FMEAs and suppliers | Set a disposition, sign a release or closure |
| CAPA owner | Own CAPAs and the actions they own | Root cause, actions, effectiveness criteria | Verify their own action, close their own CAPA |
| Auditor | Assigned audits; never their home site | Record results, raise findings | Audit their own site |
| Approver | Own site | Sign dispositions, hold releases, closures, change approvals | Sign 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.
Session 3: The roles in the matrix, rules generated, refusals proven
35 minutesWhy
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
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
- The approver may touch only the signing columns, and never a record they reported, own or investigated.
- 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.
Session 3: The first three screens, one on each surface
40 minutesWhy
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
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.https://github.com/acme-ops/acme-platform/pulls
Open the pull request, then its Vercel preview, on your phone.
You will see recreated screen
- Picked from the spine, never typed: the lot must exist.
- Opens the phone camera. Test it with your thumb, standing up.
You will see recreated screen
| Record | Decision | Waiting |
|---|---|---|
| SYN-QE-0004 · NCR | Disposition: rework | 2 days |
| SYN-H-0002 · Hold | Release | 5 hours |
- 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
- ISO 9001:2015, Quality management systems: requirements. https://www.iso.org/standard/62085.html
- eCFR: 21 CFR Part 11, Electronic records and electronic signatures. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-A/part-11
- Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
- 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.
Session 4: Raise, triage, and a hold the database enforces
30 minutesWhy
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
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
- Red first: with the rule removed, the held lot moved. That shows the test can fail.
- 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.
Session 4: The signed decision, the CAPA and its effectiveness check
35 minutesWhy
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
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
- The meaning is part of the signature record, as Part 11 asks.
- Typed again at the moment of signing, never remembered by the page.
- The two-person rule, enforced by the database, shown in plain words.
You will see recreated screen
- 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
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.
Session 4: Action priority, the other workflows, and a dashboard that matches your count
35 minutesWhy
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:
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
- 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.
- 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
- ASQ: What is root cause analysis?. https://asq.org/quality-resources/root-cause-analysis
- AIAG: Quality Core Tools (APQP, CP, PPAP, FMEA, MSA, SPC). https://www.aiag.org/expertise-areas/quality/quality-core-tools
- AIAG: AIAG & VDA FMEA Handbook. https://www.aiag.org/training-and-resources/manuals/details/FMEAAV-1
- ASQ: The Plan-Do-Check-Act (PDCA) cycle. https://asq.org/quality-resources/pdca-cycle
- 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.
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 secret | What it unlocks | Where it lives | Who holds it | Never |
|---|---|---|---|---|
| qms_importer password (development) | Signing in as the insert-only import login on acme-platform-dev; listed by name in docs/KEYS.md | Password manager; GitHub secret QMS_IMPORTER_PASSWORD_DEV | pat@acme.com, sam@acme.com | Never 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.md | Password manager; GitHub secret QMS_IMPORTER_PASSWORD_PROD | pat@acme.com, sam@acme.com | Never on a laptop outside the password manager |
| The old eQMS export | Every quality record, with names | A private folder, then the private Storage bucket imports; its sha256 and counts in docs/imports/quality-approved.md | The quality manager | Never in the repository, a test, or a chat |
Session 5: The import, built and tested on a made-up export
35 minutesWhy
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.
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
- Six tests on a made-up export, including the ones that protect production.
- 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.
Session 5: Rehearse the import on the development project
30 minutesWhy
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):
shasum -a 256 ~/private/qms-export.zipOn 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:
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).
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.
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
| Kind | Approved | In export | Imported | Skipped |
|---|---|---|---|---|
| Events (open) | 38 | 38 | 38 | 0 |
| Events (closed) | 1,204 | 1,204 | 1,201 | 3 |
| CAPAs | 117 | 117 | 117 | 0 |
| Active holds | 4 | 4 | 4 | 0 |
- Green means it ran, and only because the export is the approved one: the counts decide.
- Approved, in the export and imported plus skipped must all agree, or the run fails.
- 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.
Session 6: A week side by side, compared one record at a time
30 minutes, after a week of parallel runningWhy
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:
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
| Measure | Old tool (Event Summary) | New module | Difference |
|---|---|---|---|
| Events raised | 23 | 23 | none |
| Events open | 41 | 41 | none |
| CAPAs overdue | 6 | 5 | 1: closed in new tool on Friday, old tool updated Monday |
| Active holds | 4 | 4 | none |
- Every difference has a reason in plain words.
- 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.
Session 6: The final import into production, through the pipeline
30 minutesWhy
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:
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.
https://github.com/acme-ops/acme-platform/settings/secrets/actions
New repository secret: QMS_IMPORTER_PASSWORD_PROD, the value only.
https://supabase.com/dashboard/project/abcdefghijklmnopqrst/storage/buckets
Production Storage: a private bucket named imports; upload the final export.
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
| Kind | Approved | In export | Imported | Skipped |
|---|---|---|---|---|
| Events (open) | 36 | 36 | 36 | 0 |
| Events (closed) | 1,231 | 1,231 | 1,231 | 0 |
| CAPAs | 119 | 119 | 119 | 0 |
| Active holds | 4 | 4 | 4 | 0 |
- Started by a person on GitHub, from main, for the approved file.
- The counts that go into docs/cutover.md.
- 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).
Session 6: Cut over, keep the history, and cancel with the saving written down
20 minutesWhy
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:
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
- Every figure points at an invoice or a stored file.
- 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.
Knowledge check
How do imported closed records keep their original signatures?
Knowledge check
Who starts the import into production, and how?
References
- GitHub Docs: Manually running a workflow. https://docs.github.com/en/actions/managing-workflow-runs/manually-running-a-workflow
- GitHub Docs: Using secrets in GitHub Actions. https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions
- Supabase Docs: Storage. https://supabase.com/docs/guides/storage
- Rajesh Kumar: top 10 QMS buyer criteria. https://www.rajeshkumar.xyz/blog/quality-management-systems-qms/
- 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
Your result
CivOps AI Academy
Quality Management: Events, CAPA, Audits, Change, Risk and Supplier Quality on One Record Model
Element M08 complete · Learner
Your LMS records this completion. For the CivOps Foundation certificate, finish the Foundation Course at https://civops.io/learn.