Skip to the lesson
CivOps AI Academy · M07Training Records and Competency: Skills, Qualification and the Live Skills Matrix
0%

Chapter 1 · Sessions 1 and 2

What the old records hold, and the tables that replace them

A certificate in a binder shows someone was once taught; it does not show that the person at the press today may run it. You start by writing down where training records live now, what the rules say and what the old tool costs, from real pages. Then one prompt adds the module's tables with the rules that keep a qualification honest, and you load a small team worked by hand as a test fixture.

25 min3 stepsSessions 1–2about 7 hours hands-on across six sessions

By the end of this chapter you can

  • Say the difference between trained and qualified, and the two pitfalls this module removes.
  • Inventory the old training records, the rules that set refresher intervals and the tool's bill, from real pages.
  • Have Claude Code check the spine and write the eight trn_ tables with their rules and tests, and keep the hand-counted team as a fixture.

Trained is not the same as qualified

Training records answer a question about the past: did this person finish this course? A qualification answers a question about now: may this person do this work today? They come apart in ordinary ways: a course finished but the practical never observed, a forklift licence that lapsed last week, a person who changed job. The module exists to keep the second question honest. It replaces learning-management and skills-matrix tools such as Cornerstone, Docebo, TalentLMS, LMS365, UL ComplianceWire, Vector LMS, AG5, Poka Skills, Workerbase and GembaDocs Skills Matrix [1][2].

The edge of the training moduleInside: skills and requirements, assignments by trigger, content delivery, on-the-job practical sign-off, qualification with expiry, the point-of-use check and the skills matrix. Outside: HR employment records (M21) and course authoring tools, which stay external; MES, CMMS and permits call the check. INSIDE TRAINING (M07)Skills and requirementsAssignments by triggerSCORM, xAPI, cmi5OJT and practical sign-offQualification and expiryPoint-of-use checkSkills matrix and gapsOUTSIDE THE MODULEHR employment recordsowned by M21Course authoring toolsimport packages; authoring stays externalMES, CMMS and permitscall the point-of-use check
The edge of the module. Inside: skills and requirements, assignments by trigger, content, practical sign-off, qualification with expiry, the point-of-use check and the matrix. Outside: HR employment records (M21) and course authoring tools.
StandardUsed for
ISO 9001:2015 clause 7.2 [3]Competence: determine it, ensure it, evaluate it, keep the evidence
ISO 13485 clause 6.2; 21 CFR 211.25 [4]Personnel qualification in regulated manufacturing
OSHA 1910.178(l), 1910.147(c)(7), NFPA 70E [5]Statutory training: forklifts, lockout and tagout, electrical safety
SCORM 1.2 and 2004, xAPI, cmi5Packaging and results of e-learning content
Competence as a cycleFour steps from ISO 9001 clause 7.2: determine the competence needed, ensure people have it, evaluate whether it is effective, and retain the evidence. A gap found when evaluating sends the cycle back to ensure. ISO 9001:2015 CLAUSE 7.2 · WHERE THE MODULE HOLDS EACH PARTDetermineSkills and requirementsper role, machine, taskEnsureCourses, OJT, assignmentswith due datesEvaluatePractical assessment,pass mark, expiryRetain evidenceCompletions, signatures,certificates, audit loggap found: assign more training
Competence as a cycle. Determine: skills and requirements. Ensure: courses, on-the-job training, assignments. Evaluate: practical assessment, pass mark, expiry. Retain evidence: completions, signatures, certificates.
CapabilityTierBuilt in these six sessions
Skills and requirements; assignments by trigger; practical assessment with two signatures; qualification with expiryMVPYes
Point-of-use check; live skills matrix by areaSTDYes
Content delivery (SCORM, xAPI and cmi5 player); instructor-led sessionsSTDDocuments, quizzes and video yes; the package player and sessions are optional later work
EffectivenessBICNot built
Step 1

Session 1: Inventory the old records, the rules and the bill

60 minutes

Why

The module must reproduce what the business relies on today, and the refresher intervals must come from the paragraph of the standard or procedure that sets them, not from a rule of thumb. Writing the inventory from the old tool's own reports, your invoices and the real rules gives Session 6 something to compare against, and choosing one area to start keeps the build tied to real people and machines.

Do this

Ask whoever keeps the training records (the old tool's administrator, HR, or the supervisor with the binder) for an hour. Training records name people: copy counts, skills and rules, never names.

Terminal or PowerShell
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
On a new branch training/inventory, create docs/training-inventory.md as an empty form for me to fill in. Do not invent any figure, price, interval or count: every cell starts as "not yet read".

Sections, each a table:
1. Where training records live today: the tool, spreadsheets, paper binders, certificates on a wall; who keeps each.
2. The tool: name, plan, users, bill, renewal date, notice period, export available, source (invoice or account page with its date).
3. Skills that need proof before work: skill, which job, machine or operation needs it, evidence (course, observed practical, exam, external certificate, read-and-understood), refresher interval, and the paragraph of the standard or procedure that sets it (for example OSHA 1910.178(l) for forklifts).
4. How training is triggered today: new hire, role change, revised procedure, refresher, corrective action; who notices; how long it takes.
5. The old tool's own figures for the last full month: assignments due, completed on time, late, overdue; people qualified per skill; items expiring in the next 30 days. Report name and date range for each.
6. What the export holds: completions, scores, dates, certificates with files, course codes, people identifiers.
7. Workarounds: people working on an expired licence, a supervisor's own spreadsheet, practicals never written down.
8. The first area to move, why, and its supervisor.

Add a line at the top: "Every number here comes from the tool's own reports, our invoices or the rule quoted. Never estimate. No personal names." Open a pull request titled "Training inventory" and show me the link.

Fill it in on GitHub with the records keeper. Take a ten-row export into a private folder outside the repository to fill in section 6, then delete it.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/training-inventory.md)
+Every number here comes from the tool's own reports, our invoices or the rule quoted. Never estimate. No personal names.
+## 3. Skills that need proof before work
+| Skill | Needed for | Evidence | Refresher | Rule (paragraph) |
+| not yet read | not yet read | not yet read | not yet read | not yet read |
1
⏺ Pull request #120 adds the empty inventory form with eight sections. I have not filled in any value or interval.2
Claude Code writes the form and stops; every value comes from you and the real pages.
  1. The rule column: every refresher interval cites the paragraph that sets it.
  2. Refuse "typical" intervals: your rules decide them.

You will see recreated screen

your training tool · Reports
DashboardAssignmentsComplianceCertificatesExport
Compliance · Press area · last month
Date range1–31 of last month1
2
MeasureValue
Assignments due42
Completed on time35
Overdue4
Certificates expiring in 30 days3
The old tool's compliance report for the stamping plant's press area, as you copy from it: report name, date range and the figure.
  1. The same date range is used in Session 6.
  2. Copy the figures exactly; Session 6 explains every difference.

Check it worked

Pull request Training inventory has every section filled in, each figure with its report and date range, each refresher interval with the rule that sets it, the bill from an invoice, and the first area chosen with its supervisor. No personal name appears. Owner two approves; merge.

Fastest path

Fill section 3 with the plant's EHS or quality lead in the room: they know which paragraph sets each interval, and that is the slowest thing to find alone.

If it goes wrong

Claude Code suggested typical refresher intervals

Say: Replace every interval with "not yet read". Intervals come from the rule we quote, not from typical practice.

Nobody can say which rule sets an interval

Write "no rule found" and who you asked. The interval is then a business decision, written down with the name of the person who made it.

The export identifies people by a national number

Write that down and do not copy it anywhere. The module needs no such number: Session 5 matches people by employee reference or work email.

The eight tables built here

Every table carries the standard columns id, site_id, created_at, created_by, updated_at, updated_by, row_version, archived_at and ext, and points at the tables docs/spine-map.md maps the spine names onto (core_person, core_job_role, core_equipment, core_attachment, core_e_signature) instead of keeping its own lists. site_id takes the place of the specification's tenant_id, so each table keeps one simple access rule. The other five tables of the specification (curricula, instructor-led sessions and attendance, and the xAPI record store) are later work, added as their own migration. An arrow is a foreign key; soft link is a plain uuid that names another module's row.

The thirteen trn_ tablesThirteen tables in four columns. An assignment points at a course; a completion points at an assignment; a curriculum course links a curriculum to a course; a role requirement points at a skill; an instructor-led attendance points at its session. A qualification links by basis to a completion, an assessment or an external certificate. trn_coursetrn_assignmenttrn_completiontrn_lrs_statementtrn_curriculum_coursetrn_curriculumtrn_practical_assessmenttrn_qualificationtrn_skilltrn_role_requirementtrn_external_certificatetrn_ilt_sessiontrn_ilt_attendancecourse_idassignment_idstatementcurriculumcourse_idskill_idsession_idbasisSolid arrow: foreign key, child to parent. Dashed: soft link by id (basis_id, lrs_statement_id).
The module's tables. A qualification links by its basis to the completion, assessment or certificate that earned it.
TableHoldsColumns (req = required)
trn_skillA skill or qualificationcode req, unique per site; name req; category req (operation, equipment, safety, quality, regulatory, soft, maintenance_craft); max_level int req; recert_months int; evidence_type req (course, ojt, exam, external_certificate, read_and_understood); active bool req
trn_role_requirementThe level a role, machine or operation needsjob_role_id → core_job_role; equipment_id → core_equipment; operation_ref soft link; skill_id req; required_level int req; mandatory bool req. At least one of the three targets set
trn_courseA learning object, versionedcode req, unique per site; title req; course_type req (scorm12, scorm2004, xapi, cmi5, video, document, quiz, ilt, ojt); version req; package_attachment_id; document_revision_ref soft link; duration_min; passing_score; grants_skill_id; grants_level; status req (draft, active, retired)
trn_assignmentTraining assigned to a personperson_id req; course_id req; reason req (new_hire, role_change, doc_revision, recertification, manual, corrective_action, regulatory); source_type; source_id; assigned_at req; due_at; status req (assigned, in_progress, completed, overdue, waived, cancelled); waived_by; waiver_reason
trn_completionCompletion evidenceassignment_id; person_id req; course_id req; completed_at req; score; passed bool req; trainer_id; evidence_attachment_id; signature_id → core_e_signature; lrs_statement_id
trn_practical_assessmentAn observed demonstrationperson_id req; skill_id req; target_level int req; checklist json req; result req (competent, not_yet_competent); assessor_id req; assessed_at req; trainee_signature_id; assessor_signature_id
trn_qualificationCurrent status per person and skillperson_id req; skill_id req; level int req; status req (in_training, qualified, expired, revoked, suspended); qualified_at; expires_at; basis_type req (completion, assessment, external, grandfathered); basis_id; revoked_reason
trn_external_certificateA licence or certificateperson_id req; name req; issuer; certificate_no; issued_at; expires_at; attachment_id → core_attachment; skill_id
Step 2

Session 2: Check the spine, then write the eight tables and their tests

40 minutes

Why

Completion and qualification records are regulated records in many plants: nothing is deleted, a signed assessment never changes, and a qualification cannot exceed what its evidence supports. Those are rules for the database, where every screen, import and later module meets them, with a test that tries to break each. Checking the spine first, and adding the missing pieces in their own migration, keeps the module's migration about training only.

Do this

Paste into Claude Code
Read docs/naming-standard.md, docs/SCHEMA-PLAN.md and every file in supabase/migrations. Change nothing yet.

Tell me which of our tables or functions plays each of these roles, and which are missing: core_person (with job_role_id, org_unit_id, is_active, email, employee_ref), core_job_role, core_org_unit (with manager_person_id), core_site, core_equipment, core_attachment, core_comment, core_approval, core_notification, core_event_outbox, core_e_signature (signer_id, meaning, record_type, record_id, record_hash, signed_at, auth_method, printed_name), core_audit_log with core_audit_row() and core_touch_row(). Where our Foundation tables already hold the same thing (sites, parts, lots, equipment, memberships), map the core_ name onto them; never a copy.

Then, on a new branch spine/training: add a section "M07 Training" to the one shared docs/spine-map.md (create it if no module has yet; never a separate training map): each core_ name and our table for it, and that the trn_ tables carry site_id (→ sites) in place of the specification's tenant_id. If anything is missing, one migration (npx supabase migration new spine_for_training) with only the missing pieces, row-level security on and forced, no policies, and pgTAP tests. Push, open a pull request titled "Spine for training", wait for every check, report in plain words, and stop.

When the spine is on main, paste the table list from this page into the next prompt:

Paste into Claude Code, then paste the table from this page where it says
On a new branch training/tables:

1. Create docs/trn-tables.md from the table list I paste below, exactly as written, and docs/training-rules.md with every rule in point 3.
2. Run npx supabase migration new training_tables and write the eight trn_ tables: the standard columns in docs/spine-map.md (site_id not null references sites, indexed, never tenant_id), timestamptz, required as not null, allowed values as check constraints, foreign keys only to the tables docs/spine-map.md names, to sites and to each other, soft links as plain uuid.
3. Rules: a requirement names at least one of job role, equipment or operation; one trn_qualification per person and skill (unique); a qualification's level is at most its skill's max_level (a trigger); an assignment is unique on person, course, source_type and source_id, so a retried trigger adds nothing; a practical assessment, once both signature ids are set, refuses any change; completions, assessments and certificates are never deleted, and a qualification is revoked or suspended with a reason, never deleted; core_audit_row() and core_touch_row() on every table; row-level security on and forced, no policies yet.
4. Add the eight tables to docs/matrix.json with empty cells.
5. pgTAP tests in supabase/tests/training.test.sql: every table exists with row-level security forced; a level above max_level, a requirement with no target, a second qualification for the same person and skill, a course type outside the list, the same trigger twice, and an edit of a signed assessment are each refused.
6. Do not connect to any Supabase project.

Push, open a pull request titled "Training tables", wait for every check, and report in plain words with the test counts.

The table list:
<paste the table "The eight tables built here" from element M07 here>

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase migration new training_tables)
⎿ Created new migration at supabase/migrations/20261116090000_training_tables.sql
1
⏺ Write(supabase/migrations/20261116090000_training_tables.sql)
+create unique index trn_assignment_once on public.trn_assignment
+ (site_id, person_id, course_id, source_type, source_id);
+create trigger trn_assessment_sealed before update on public.trn_practical_assessment
+ for each row when (old.assessor_signature_id is not null) execute function public.trn_refuse_change();
2
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 1m58s
⏺ Pull request #122 is green. 8 tables with row-level security forced and no policies. 39 tests passed, 7 of them refusals, including the same trigger twice and an edit to a signed assessment.3
The tables, the rules and the tests that try to break them, reported after GitHub's checks.
  1. Its timestamp puts it after the spine migration.
  2. A retried trigger adds nothing; a signed assessment cannot change.
  3. Check the counts in the checks tab too.

Check it worked

The M07 section is in docs/spine-map.md on main. Pull request Training tables is green on its latest commit; docs/training-rules.md lists every rule; owner two approves; merge, and the deploy workflow applies it to production.

Fastest path

Paste the table list into the prompt rather than describing it: the allowed values come through exactly and the review is a comparison.

If it goes wrong

Claude Code adds tenant_id, or puts the spine mapping in docs/trn-tables.md

Say: The trn_ tables carry site_id, never tenant_id, and the mapping lives only in the M07 section of docs/spine-map.md.

Claude Code added a column for date of birth or a national number

Say: Remove it. The module needs no such identifier; people are matched by employee_ref or work email.

CI fails on a fresh database with "relation does not exist"

Something exists only where it was clicked into being. Say: Rebuild from nothing with only supabase/migrations, name the missing object, and add it as a new migration; never edit an applied one.

After merging main, a rule or test you added has gone

A revert on main took it with no conflict. Say: List every schema change and test this branch added and confirm each is still there. If any disappeared, find the commit that removed it and tell me before changing anything.

A team worked by hand

The check and the matrix in Session 4 must give your answers, so a small press team is worked by hand first, as at 12:00 UTC on 1 June 2026. These fixed dates belong in a test fixture, tests/fixtures/training-cases.json; the seed for the screens, supabase/seeds/training.sql, is shifted onto today. Mandatory requirements on press 3: PRESS-OP level 2 (hands-on, evidence ojt, 24 months) and LOTO level 1 (course, 12 months). FORK (external certificate) is required on the forklift.

PersonPRESS-OPLOTO expiresFORKCheck on press 3
Operator 1level 2, qualified, to 2027-03-102026-09-10noneAllowed
Operator 2level 3, qualified, to 2027-01-152026-10-02qualified to 2027-02-12Allowed
Operator 3level 2, qualified, to 2026-06-212026-08-15noneAllowed (PRESS-OP expires within 30 days)
Operator 4level 2, status still qualified, expired 2026-05-312026-06-13noneDenied: expired, though no job has run
Operator 5level 1, in_training (course only)2026-11-20expired 2026-05-22Denied: level too low
Operator 6nonenonenoneDenied: no qualification

The figures as at that moment: training compliance on the six revised-procedure assignments (operators 1–4 on time, 5 late, 6 overdue) is 4 of 6; PRESS-OP has three people currently qualified; FORK is a single point of failure (operator 2 only); 2 items expire in the next 30 days (operator 3's PRESS-OP on 21 June, operator 4's LOTO on 13 June).

Step 3

Session 2: The hand-worked team as a fixture, made-up people as the seed, and a look on the development project

35 minutes

Why

The check that blocks unqualified work and the counts on the matrix need answers you trust before any code exists, and those answers need fixed dates. The screens need a team that looks current next month too. Keeping the fixture and the seed apart prevents the seed faults we hit: dates that age until nothing is "due this week", and later steps that expect counts the seed never made.

Do this

Paste into Claude Code, then paste the table from this page where it says
On a new branch training/seed:

1. Write tests/fixtures/training-cases.json with the press team exactly as in the table and paragraph I paste below: the as-at time 2026-06-01T12:00:00Z, the skills, the requirements on press 3 and the forklift, every qualification, certificate and assignment, and the expected answers (the check result and reason per person; compliance 4 of 6; PRESS-OP 3 qualified; FORK the only single point of failure; 2 expiring in 30 days). These are worked by hand: never change an expected value to pass a test.
2. Write supabase/seeds/training.sql and list it under [db.seed] sql_paths in supabase/config.toml (never append to supabase/seed.sql), with the Foundation seed's rules: the syn site, every date shifted onto today (read the clock once at seeding and keep every gap), names starting "SYNTHETIC · ", safe to run twice (on conflict do nothing on every unique key): a press team of six operators, an assessor, a trainer, a supervisor (the team's manager) and a training administrator; the four skills and their requirements; courses (a procedure document, a LOTO quiz, a press theory video, a press on-the-job course); assignments in every status; qualifications that include one expired with status still qualified, one in_training from a course only, and one expiring within 30 days; certificates with attachments; practical assessments with both signatures.
3. Write docs/trn-seed-counts.md with every count the seed makes, and supabase/tests/training-seed.test.sql asserting each one and that running the seed a second time changes no count.

Push, open a pull request titled "Training seed and check cases", wait for the checks, and report.

The hand-worked team:
<paste the table "A team worked by hand" and the paragraph after it from element M07>

When it is merged, apply the module and its made-up data to the development project yourself, with its database password from the password manager. The first time, --include-seed loads every seed file listed in config.toml, training.sql included; after a seed change, npm run seed:dev reloads them. Never reset the project. Production gets the migration from the deploy workflow, which never seeds it.

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

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

The development Table Editor. Check the project name says acme-platform-dev first.

You will see recreated screen

Terminal
$ npx supabase link --project-ref tsrqponmlkjihgfedcba
Finished supabase link.1
$ npx supabase db push --include-seed
Do you want to push these migrations to the remote database? • 20261116090000_training_tables.sql [Y/n] y
Seeding data from supabase/seeds/training.sql...
Finished supabase db push.2
db push on the development project applies exactly the merged migration.
  1. The development reference, never abcdefghijklmnopqrst.
  2. Production gets the same migration from the deploy workflow on merge, never the seed.

You will see recreated screen

supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor
trn_assignmenttrn_coursetrn_qualificationtrn_role_requirementtrn_skill
trn_qualification
1
personskilllevelstatusexpires_at
SYNTHETIC · Operator 1PRESS-OP2qualifiedin 9 months
SYNTHETIC · Operator 4PRESS-OP2qualifiedyesterday
SYNTHETIC · Operator 5PRESS-OP1in_training
The development project after the seed: a made-up press team with expiries around today.
  1. Operator 4 is the nightly-batch pitfall in one row: status qualified, expiry passed. The check in Session 4 must deny them.

Check it worked

The fixture holds your hand count unchanged; the seed-count test is green; on the development project the migrations match main and the Table Editor shows SYNTHETIC people with expiries around today.

If it goes wrong

db push lists the live project

Answer n. You are linked to abcdefghijklmnopqrst. Link to tsrqponmlkjihgfedcba; production gets migrations only from the deploy workflow.

A month later nothing is "expiring in 30 days"

The seed has fixed dates. Say: Move every seeded date by one offset taken from the moment of seeding, reading the clock once, and test that the seed still has one expiry in the next 30 days. Our seeded data was 10.9 days old eleven days later.

A later step expects a count the seed does not make

Fix the seed, not the check, then reload it with npm run seed:dev: List every count a later step or test expects and show the seed line that makes it.

Knowledge check

An operator finished the press theory video and passed its quiz. PRESS-OP's evidence type is ojt. What may the record show?

Knowledge check

Why is the hand-worked press team a test fixture rather than seed data?

References

  1. AG5: skills matrix software. https://www.ag5.com/skills-matrix-software/
  2. Poka: skills management. https://www.poka.io/en/skills-management/
  3. ISO 9001:2015 Quality management systems: requirements (clause 7.2, competence). https://www.iso.org/standard/62085.html
  4. eCFR: Title 21, Part 211 (211.25, personnel qualifications). https://www.ecfr.gov/current/title-21/chapter-I/subchapter-C/part-211
  5. OSHA: 29 CFR 1910.178, Powered industrial trucks (paragraph (l), operator training). https://www.osha.gov/laws-regs/regulations/standardnumber/1910/1910.178

Chapter 2 · Session 3

Who may teach, assess, assign and read

Access is decided once, in the role matrix, and the database rules, the page list and the access tests are generated from it. This chapter adds the training roles and four machine logins, walks every right the later sessions need, and builds the phone screens an operator, an assessor and a supervisor use.

25 min3 stepsSession 34 roles, 4 machine logins

By the end of this chapter you can

  • Write the training roles and machine logins into docs/matrix.json, with the rules that involve two people.
  • Walk every right Sessions 4 to 6 ask for, in docs/rights-walk.md, before a step is refused.
  • Build My training, Start a task, Assess and the supervisor's matrix, and try them as each demo login on a phone.

Roles and machine logins

Role or loginScopeWritesNever
Trainee (every signed-in person)Own rowsOwn self-paced completions (the server decides passed); own assignment progress; own signaturesGrant themselves a qualification; see anyone else's record
TrainerSiteInstructor-led and on-the-job completions with trainer_id themselvesAssess the practical they taught, in the same sitting
AssessorSitePractical assessments with the checklist; their own signatureAssess themselves; assess above their own level
SupervisorOwn team (core_org_unit.manager_person_id)Manual assignments; waivers with a reason (not regulatory); suspend a qualificationRevoke; waive their own assignment
Training administratorSiteSkills, requirements, courses; revoke with a reason; grandfathered decisions, signedDelete anything
Assignment engine (login)Events and the clockAssignments from triggers; overdue status; notificationsCompletions or qualifications
Qualification service (login)EvidenceQualifications from a basis it re-reads; expiry housekeepingAnything a caller hands it unchecked
Qualification checker (login)Read onlyNothing: it answers allow or denyAny write
Importer (login, insert-only, Sessions 5–6 only)Imported rowsInserts imported completions and certificates with original dates; set to NOLOGIN at cut-overUpdates, deletes, qualifications; anything after cut-over
Step 4

Session 3: Put the roles in the matrix, walk every right, and generate the rules

35 minutes

Why

Every rule and page is generated from docs/matrix.json, so a right missing there is refused in the middle of Session 4, when the temptation is to widen a rule by hand. Walking every insert, update and read the later sessions perform, now, and writing the cell for each in docs/rights-walk.md, finds the gaps while they cost one line. The generated tests then prove each role is allowed what it needs and refused what it must not have.

Do this

Paste into Claude Code, then paste the role table above after it
Read docs/matrix.json, scripts/gen-policies.mjs, docs/access-review.md, docs/trn-tables.md and docs/training-rules.md. On a new branch training/access:

1. Add the roles trainee, trainer, assessor, supervisor and training_admin, and the machine logins trn_assigner, trn_qualifier, trn_checker and trn_importer, with the cells in the table I paste below. Nobody gets delete. Every insert that returns its new row needs the matching read. Add the restrictive rules: nobody signs both sides of one assessment; an assessor never assesses themselves or above the level they hold; a supervisor never waives their own assignment; a regulatory assignment is never waived; trn_checker writes nothing; trn_importer inserts only rows with ext.imported true.
2. Write docs/rights-walk.md: one line per insert, update and read that Sessions 4, 5 and 6 of the training module perform (session and step, who acts, table, action, the cell that allows it), with every line with no cell at the top under "Gaps". Stop and show me the gaps.

Agree the gaps with the training administrator. The usual ones: the assessor's route inserting the on-the-job completion after the second signature, the qualification service reading signatures, the engine reading core_org_unit to find the supervisor. Then:

Paste into Claude Code
Add the cells for the gaps we agreed. Run node scripts/gen-policies.mjs for the policy migration (never a hand-written policy) and the access tests (one allowed and one refused per cell, plus the cross-site test). In a separate migration create the logins trn_assigner, trn_qualifier, trn_checker and trn_importer (insert-only) with NOLOGIN, no BYPASSRLS, owning nothing; I set passwords myself. Add tests for every restrictive rule, each giving one person both jobs, and a test that runs every line of docs/rights-walk.md as its role against the seed and checks the row really changed. Update docs/access-review.md. Push, open a pull request titled "Training access", wait for every check, and report with the allowed and refused counts.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/rights-walk.md)
+## Gaps (no cell yet)
+- S4 step 9 · assessor route · insert · trn_completion (ojt, after both signatures)
+- S4 step 9 · trn_qualifier · read · core_e_signature (to compare the two fingerprints)
+- S4 step 8 · trn_assigner · read · core_org_unit.manager_person_id (the supervisor to notify)
1
> Add the cells for the gaps we agreed. ...
⏺ Bash(node scripts/gen-policies.mjs)
⎿ Wrote supabase/migrations/20261118100000_policies.sql (52 policies, 9 roles, 6 restrictive)
2
⏺ Pull request #125 is green. 104 access tests, 6 two-person tests refused, and 58 rights-walk lines each allowed and really changing the row. trn_checker has no write anywhere.3
The walk stops at the gaps; the generated rules come after you agree them.
  1. Gaps found before any step needs them.
  2. Generated from the matrix, never hand-written.
  3. The checker can only read: it answers, it never changes anything.

Check it worked

Pull request Training access is green; docs/rights-walk.md has no gap; no generated policy allows delete; docs/access-review.md shows every new role and login.

If it goes wrong

An insert works in the SQL editor but the route says it failed

The insert returns its new row and the role has no read on it. Add the read cell, regenerate, and test that the row really exists.

The assessor can assess themselves

The rule is a permissive cell, not restrictive. Say: Make it a restrictive policy and test it with one person as both trainee and assessor.

Claude Code edited a generated policy

Say: Revert it. Rights come only from docs/matrix.json through scripts/gen-policies.mjs.

The screens

ScreenForShows
/training/myTrainee (phone)Assignments with due dates, qualifications with expiry, certificates, assessments waiting for their signature
/training/startTrainee (phone)Choose a machine: allowed, or blocked with the reason in words and who to ask
/training/assessAssessor (phone)Pick person, skill and level; the checklist one step at a time with large targets; sign
/training/recordTrainerRecord an on-the-job or classroom completion
/training/matrixSupervisor, administratorSkills across, people down, live; gaps, single points of failure, expiries
/training/adminAdministratorSkills, requirements, courses, certificates to renew, grandfathered decisions
Step 5

Session 3: Build the phone screens and the supervisor's matrix

30 minutes

Why

Operators and assessors use this module at the press, on a phone, often with gloves. Building the screens against the seed with the access rules already in place means each person sees only their own record from the first day. Adding the pages to the matrix keeps the sign-in guard denying everything it was not told about, and a blocked operator who sees why, and who to ask, is the difference between a rule people follow and one they work around.

Do this

Paste into Claude Code
Before writing any page, read the routing and proxy guides in node_modules/next/dist/docs/ (this Next.js version differs from older guides; request checks live in proxy.ts) and lib/access/routes.ts.

On a new branch training/screens:
1. Add /training/my, /training/start, /training/assess, /training/record, /training/matrix and /training/admin to the screens section of docs/matrix.json with the roles from element M07 chapter 2, and regenerate lib/access/routes.ts with node scripts/gen-routes.mjs, as Session 9 does. Do not edit proxy.ts or routes.ts by hand.
2. Build them against the seed in their simplest form. Status and expiry are said in words ("expires in 12 days", "expired yesterday"), never colour alone. A figure with nothing behind it shows "No data", never 0. The person on every record comes from the signed-in session on the server.
3. Foundation phone rules: 44 px targets, 16 px fields, 15 px text, no sideways scroll at 360 and 390 px, contrast 4.5:1.
4. Screen tests at phone size: signed out, every page goes to sign-in; each role opens its pages and is refused the others; a trainee sees only their own record.

Push, open a pull request titled "Training screens", wait for the checks and the Vercel preview, and give me the preview address.

You will see recreated screen

acme-platform-git-training-screens-acme-ops.vercel.app/training/my
My training · SYNTHETIC · Operator 3
PRESS-OP level 2 · qualifiedexpires in 20 days · renew by practical assessment1
Read: Press setup procedure, revision 3due in 4 days · read and sign
LOTO level 1 · qualifiedexpires in 2 months
Start a task2
My training on the preview at phone width, for a made-up operator.
  1. Expiry in words, with what renews it.
  2. The check itself is built in Session 4; here the button opens the page.

Check it worked

On the preview, signed out, every training page goes to sign-in; each demo role opens its pages on a phone with nothing scrolling sideways; the screen tests are green.

If it goes wrong

A page compiles but a link goes nowhere

Test by visiting: Start the production build, sign in as each role, visit every page and link, and report each 404, error page and console error.

The matrix shows 0 for a skill nobody holds

Say: Show "No one qualified" in words, never a bare 0 that could be read as a count of zero required.

Every completion says the same author

Say: Take the person from the signed-in session on the server and ignore what the page sends; test with two users.

Step 6

Session 3: Demo logins on the development project, and a trial at the press

20 minutes

Why

Tests prove the rules; people prove the screens. One demo login per role on the development project lets you, an operator and an assessor use the module as each role will, with made-up data only. Watching them on their own phones, without explaining, finds the screens that would be skipped on a busy shift.

Do this

On the development project, create users with Create new user and Auto confirm user: operator.test, assessor.test, trainer.test, supervisor.test and admin.test, all @example.com, each password generated and kept in the password manager.

Open

https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/auth/users

Authentication, Users, on acme-platform-dev.

Paste into Claude Code
Write supabase/snippets/trn-demo-logins.sql for me to run in the development SQL editor. Do not run it. It finds the five demo users by email and links each to the seeded person of the same role (operator.test is Operator 3), with a membership at the seeded site. It refuses to run if core_person holds anyone in the seeded team whose name does not start "SYNTHETIC · ". Open a pull request titled "Training demo logins" and wait for the checks.

After it merges, run it in the development SQL editor. Sign in on the preview as each role. Then hand an operator and an assessor a phone signed in as the demo logins, and watch them open My training and Assess without help; write down where each stops.

You will see recreated screen

acme-platform-git-training-screens-acme-ops.vercel.app/training/assess
PRESS-OP level 2 · SYNTHETIC · Operator 5
Step 3 of 8 · mandatoryChecks the die is clamped before the first stroke1
Observed
Note
Next step2
Assess on the preview as assessor.test: one checklist step at a time, large targets, the mandatory steps marked.
  1. Mandatory steps decide the result; the server, not the phone, sets competent.
  2. Large targets: usable with gloves.

Check it worked

Each demo login sees exactly its role's pages on the preview; you have written notes from the operator's and assessor's trial, each fixed or decided.

If it goes wrong

The user waits for a confirmation email

You used Invite. Delete it and use Create new user with Auto confirm user: example.com addresses receive nothing.

The snippet refuses: people not marked SYNTHETIC

Good: it found real people. Check you are in acme-platform-dev. Real records go there only with IT's written approval (Session 5).

Knowledge check

Who may sign as assessor on an operator's PRESS-OP level 2 practical?

Knowledge check

What does the qualification checker login write?

References

  1. PostgreSQL Documentation: Row Security Policies (permissive and restrictive). https://www.postgresql.org/docs/current/ddl-rowsecurity.html
  2. eCFR: Title 21, Part 11, Electronic records; electronic signatures. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-A/part-11
  3. W3C: Web Content Accessibility Guidelines (WCAG) 2.2. https://www.w3.org/TR/WCAG22/

Chapter 3 · Session 4

The workflow: from trigger to the check at the moment of use

One session builds the module's working life: an event creates the assignment, a person completes it and the server decides the pass, an assessor and the trainee sign a practical, the qualification service grants only what the evidence supports, and a check called by other modules denies a person whose qualification expired one minute ago. The matrix reads the same live rows. You type the keys; Claude Code builds and proves the rest.

35 min4 stepsSession 4denies at the minute of expiry

By the end of this chapter you can

  • Set the machine logins' passwords yourself and list them by name in docs/KEYS.md.
  • Have Claude Code build trigger assignments, completions, dual-signed assessments and the qualification rules, each tested.
  • Prove the check denies at the moment of expiry and the matrix counts change at once, against your hand count.
Key or secretWhat it unlocksWhere it livesWho holds itNever
trn_assigner, trn_qualifier, trn_checker passwordsThe machine logins of the assignment engine, the qualification service and the checkPassword manager; set in each project's SQL editor; inside the connection strings in VercelOwner one and owner twoPasted into Claude Code, a chat or a file
TRN_ASSIGNER_DATABASE_URL, TRN_QUALIFIER_DATABASE_URL, TRN_CHECKER_DATABASE_URLConnections for those logins (Preview: development; Production: live)Vercel environment variablesOwnersCommitted, or used in the browser
TRN_CHECK_TOKENLets another module (MES, CMMS, permits) call the checkVercel environment variable, and the calling module's own settingsOwnersShown on a page or logged
Step 7

Session 4: Set the machine logins' passwords and the check token yourself

20 minutes

Why

Each machine part of the module writes or reads with its own narrow login, never the service key that skips every rule, and the check that other modules call must refuse callers without a token. These are secrets, so a person makes them and types them into the place that uses them; none goes into the repository, a chat or a prompt. Doing it before the code exists means the code is tested against the real arrangement from its first run.

Do this

Generate three passwords in the password manager (letters and digits only, so they need no encoding in an address). In the development SQL editor, type each in place of the angle brackets and run:

Supabase SQL editor, development project, typed by you
alter role trn_assigner  with login password '<from the password manager>';
alter role trn_qualifier with login password '<from the password manager>';
alter role trn_checker   with login password '<from the password manager>';
Open

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

Development SQL editor. Repeat on acme-platform-prod with different passwords once the access migration is deployed there.

Generate the check token in your own terminal and save it straight into the password manager:

Terminal or PowerShell
openssl rand -hex 32

In Vercel add the three connection strings (the pooler address from each project's Connect panel, user trn_checker.tsrqponmlkjihgfedcba and so on, Preview for development and Production for live) and TRN_CHECK_TOKEN. Paste values only, no NAME=, no quotes.

Open

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

Vercel: Settings, Environment Variables.

Paste into Claude Code
Add to docs/KEYS.md, by name only, with what each unlocks, where it lives and who holds it: TRN_ASSIGNER_DATABASE_URL, TRN_QUALIFIER_DATABASE_URL, TRN_CHECKER_DATABASE_URL and TRN_CHECK_TOKEN. Add them to the start-up check from Session 10 so a missing or malformed one is named in the log without printing its value. Do not read any .env file. Open a pull request titled "Training keys" and wait for the checks.

You will see recreated screen

vercel.com/acme-ops/acme-platform/settings/environment-variables
Environment Variables
1
KeyEnvironmentsValue
TRN_ASSIGNER_DATABASE_URLPreview, Production (separate)••••••••
TRN_QUALIFIER_DATABASE_URLPreview, Production (separate)••••••••
TRN_CHECKER_DATABASE_URLPreview, Production (separate)••••••••
TRN_CHECK_TOKENPreview, Production (separate)••••••••
Vercel after this step: names visible, values hidden, Preview and Production kept apart.
  1. Never the same password in development and production.

Check it worked

Vercel lists the four variables for Preview and Production; the password manager holds the passwords and the token; docs/KEYS.md names them with no values; the start-up check test is green.

If it goes wrong

"Invalid URL", or the start-up check says a key is malformed

The value was pasted with quotes, NAME= or a space. Paste the value alone. A key can be present and still wrong: we once had a variable whose value was its own name.

"password authentication failed for user trn_checker"

Through the pooler the user name carries the project reference (trn_checker.tsrqponmlkjihgfedcba), and the password must be the one set in that project. Never switch to the service key to make it work.

Claude Code asks for the token to test the check

Refuse. Say: Test with a fake token in the test only; I set the real one in Vercel.

Triggers that create assignmentsSix sources feed trn_assignment: new hire, role change, document revision, recertification, corrective action, and manual or regulatory. An assignment ends as completed, overdue and escalated, or waived with a recorded reason. new_hirehr.job_assignment.changed, no previous rolerole_changehr.job_assignment.changed, previous role setdoc_revisiondoc.revision.effectiverecertificationa qualification nears expirycorrective_actionqms.capa_action.training_requiredmanual, regulatoryassigned by a supervisor or a ruletrn_assignmentperson_id, course_idreason, source_idassigned_at, due_atstatuscompletedoverdue: escalatewaived, reason kept
Triggers that create assignments. New hire, role change, document revision, recertification and corrective action feed trn_assignment; an assignment ends completed, overdue or waived with a reason.
How a package reports its resultSCORM 1.2 reports lesson status and a raw score. SCORM 2004 reports completion status, success status and a scaled score. xAPI and cmi5 send statements. The player turns these into a trn_completion row and a trn_lrs_statement row. SCORM 1.2 packagecmi.core.lesson_statuscmi.core.score.rawSCORM 2004 packagecmi.completion_statuscmi.success_statuscmi.score.scaledxAPI or cmi5 coursestatements: actor, verb, objectand a resultLMS player reads what the package reports, then writes one resulttrn_completioncompleted_at, score, passedthe server sets passedtrn_lrs_statementverb, object_id, resultstored_at, raw
What content reports. SCORM 1.2 a lesson status and raw score; SCORM 2004 completion, success and a scaled score; xAPI statements. Whatever reports, the server decides passed.
Step 8

Session 4: Assignments by trigger, and completions the server decides

35 minutes

Why

Nobody should have to remember to assign training: a revised procedure, a new hire or a corrective action creates the assignment with its reason and due date. A retried event must add nothing, or people get the same course twice. And the server, not the browser, decides whether a score passes, because a pass flag in a browser can be changed by anyone who opens its tools.

Do this

Paste into Claude Code
Read docs/training-rules.md, docs/rights-walk.md and docs/matrix.json. On a new branch training/assign:

1. Write in docs/training-rules.md the fields of the three consumed events (hr.job_assignment.changed: person_id, job_role_id, previous_job_role_id; doc.revision.effective: document_revision_ref, effective_at; qms.capa_action.training_required: person_ids, course_id, capa_ref) and the due days per reason, as settings.
2. Build the assignment job, connecting with TRN_ASSIGNER_DATABASE_URL: it reads those events from core_event_outbox and creates assignments with reason, source_type, source_id and due_at, relying on the unique index so a second run adds nothing. A test-only route /api/training/test/emit (administrator, refused in production) writes the three events, because the modules that publish them may not be installed.
3. The two clocks in the same job: an open assignment past due_at becomes overdue, with an in-app notification to the person and the supervisor; a qualification expiring within 30 days or already expired gets a recertification assignment for the course that grants the skill at the highest level, or is listed on /training/admin as a certificate to renew when no course grants it. In-app notifications only.
4. Completions on /training/my: a document is acknowledged by re-entering the password and creating a core_e_signature (meaning acknowledged, a record_hash of course, version, person and time); a quiz or video sends its score and the server compares it with passing_score and sets passed. Publish trn.assignment.created and trn.assignment.completed.
5. Tests: the three events create the right assignments and a second run adds none; an overdue assignment notifies once; a score below the pass mark stores passed false even when the page says passed. Show each test failing first.

Push, open a pull request titled "Training assignments", wait for every check, and report in plain words.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx vitest run tests/training-assign.test.ts)
⎿ ✓ doc.revision.effective → 5 assignments, due in 14 days ✓ second run → 0 new assignments ✓ score 70, pass mark 80, page says passed → stored passed false
1
⏺ Pull request #128 is green. Each test was shown failing with its rule removed. FORK has no course, so its expiry is listed on /training/admin as a certificate to renew.2
A retried trigger adds nothing, and the server, not the page, decides the pass.
  1. Three of the rules that keep the record honest.
  2. An external certificate cannot be renewed by a course: it goes to a person.

Check it worked

On the preview, the administrator emits a revised-procedure event; the operators get the assignment once; operator.test reads and signs it on a phone and the assignment shows completed.

If it goes wrong

The same course appears twice after a retry

The insert does not rely on the unique index. Say: Insert with on conflict do nothing on (person, course, source_type, source_id), and test two runs of the same event.

The test-only emit route answers in production

Stop and fix before merging. Say: Refuse /api/training/test/emit unless the environment is development or test, with a test that calls it as production.

A notification says sent and nobody saw it

In-app notifications are rows the screen shows; check the person's My training. If you later add email, count a send only when the provider returns an id.

A practical assessment with two signaturesFive steps: the trainee demonstrates, the assessor ticks the checklist, the result is competent or not yet competent, both sign, and a qualification is granted. A not yet competent result grants nothing and the person is assessed again. DemonstrateTrainee does the taskassessor observesChecklistAssessor ticks eachstep observedResultcompetent ornot_yet_competentDual signaturetrainee signsassessor signsQualificationlevel and expiry setevent publishedONE PRACTICAL ASSESSMENT, FROM DEMONSTRATION TO QUALIFICATIONnot_yet_competentno level granted: practise, then assess againEach attempt is its own row; a failed attempt is kept, never deleted.
A practical with two signatures. The trainee signs first (performed), the assessor last (verified); each signature holds a fingerprint of the content, and the record is sealed.
From evidence to a qualificationFour kinds of evidence, completion, assessment, external certificate and grandfathered, each become a basis for one trn_qualification row per person and skill. The row has a status: in training, qualified, expired, revoked or suspended. Course completedtrn_completion · passedPractical sign-offtrn_practical_assessmentExternal certificatetrn_external_certificateGrandfatheredaccepted from before the systemtrn_qualificationlevel, statusqualified_at, expires_atbasis_type, basis_idone row per person and skillin_trainingqualifiedexpiredrevokedsuspendedA course alone should not qualify a hands-on skill: it shows someone was taught, not that they can do the work.
From evidence to a qualification. A completion, an assessment, a certificate or a signed grandfathered decision is the basis of one row per person and skill.
Step 9

Session 4: The dual-signed practical, and qualifications only the evidence supports

40 minutes

Why

This is the first pitfall made impossible. A course for a hands-on skill grants level 1 at most, recorded as in training; only a practical observed by a qualified assessor and signed by both people makes someone qualified. The qualification service re-reads the evidence itself instead of trusting what a caller sends, and expiry is calculated from the date of the evidence, so an imported record can never move an expiry forward.

Do this

Paste into Claude Code
On a new branch training/qualify:

1. Assess: the assessor picks person, skill and target level and works through the checklist (each step: description, mandatory, observed, note). The server sets the result: competent only when every mandatory step is observed. Refuse an assessor who is the trainee or does not hold the skill above the target level (or at the top level when the target is the top level) at that moment.
2. Signatures: the trainee signs first (meaning performed), the assessor last (meaning verified), each re-entering their password; each core_e_signature holds a hash of the assessment's content. After the assessor's signature the assessor's route inserts the ojt completion. The assessment is then sealed.
3. /api/training/qualify, connecting with TRN_QUALIFIER_DATABASE_URL, given only a basis type and id; it re-reads everything. From a completion: the course's grants_level, except at most level 1 and status in_training for a skill whose evidence type is ojt. From an assessment: the target level, only if competent and both signatures hold the same hash. From a certificate: the skill's level until the certificate's own expiry, only for evidence type external_certificate. expires_at = qualified_at + recert_months, where qualified_at is the date of the evidence. Publish trn.qualification.granted.
4. Housekeeping: /api/training/jobs/expire moves lapsed rows to expired and publishes trn.qualification.expired, as a convenience for reports only.
5. Tests from tests/fixtures/training-cases.json: operator 5's course-only PRESS-OP stays level 1 in_training; a not_yet_competent assessment grants nothing; a signed assessment with a changed checklist answer is refused; an assessor below the target level is refused; an imported old completion keeps its old expiry. Show each failing first.

Push, open a pull request titled "Training qualifications", wait for every check, and report.

Then on the preview, on a phone: as assessor.test, assess operator 5 with one mandatory step unticked (not yet competent, nothing granted), then again with every mandatory step ticked; sign as operator.test, then as assessor.test; open the qualification row.

You will see recreated screen

acme-platform-git-training-qualify-acme-ops.vercel.app/training/assess/…
PRESS-OP level 2 · SYNTHETIC · Operator 5 · competent
Trainee signatureperformed · today 10:42 · fingerprint 9f3a…1
Assessor signatureverified · today 10:44 · fingerprint 9f3a…
The signed assessment on the preview: both signatures, the same fingerprint, and the record sealed.
  1. The same fingerprint on both: neither signed a different version of the checklist.
  2. Expiry from the skill's recert_months, from the date of the evidence.

Check it worked

The qualification tests are green with the fixture unchanged; on the preview, the unticked attempt granted nothing and the signed attempt granted level 2 with an expiry; an edit to the signed assessment is refused.

If it goes wrong

A course granted level 2 on a hands-on skill

Say: For a skill whose evidence type is ojt, a completion grants at most level 1 with status in_training; add the operator 5 case as a test. This is the pitfall the module exists to remove.

The qualify route trusts a level the page sends

Say: The route takes only a basis type and id and re-reads the evidence; ignore anything else in the request, with a test that sends a forged level.

An imported completion gets a fresh two-year expiry

qualified_at was set to today. Say: qualified_at is the date of the evidence; test an old completion keeps its old expiry.

The check at the moment of use

Other modules ask one question: is person X currently qualified for this machine or operation? A database function, trn_check_qualification(person_id, equipment_id, operation_ref), behind /api/training/check, answers allow or deny for each mandatory requirement with a reason in words. It denies when there is no qualification, the status is not qualified, the level is too low, the expiry is not later than the database clock at that moment, a required certificate has expired, or the person is not active, and it fails closed: when it cannot be sure, it says no.

The point-of-use qualification checkMES, CMMS and permits ask whether a person is qualified for a machine. The check reads requirements and qualifications, tests level and expiry against the database clock, and answers allow or deny with a reason. MES operationasks before the step startsCMMS work orderasks before it is assignedPermit to workasks before it is issuedIs this person qualified now?1 · requirements for the machine2 · the person's qualification3 · level at least the required4 · expires_at later than the clock5 · person is still activeAllowevery mandatory skill is currentDeny, with the reasonnames the missing or expired skilltrn_role_requirement + trn_qualificationRead at the moment of the request, from the database clock, never from a status set overnight.
The point-of-use check. MES, CMMS and permits ask; the check reads requirements and qualifications live and answers allow or deny with a reason.
Live check against a nightly statusA timeline from 12:00 to 04:00 drawn to scale. A qualification expires at 14:00. The live check denies from that moment. A status set by a nightly batch at 02:00 still shows qualified for twelve hours after it expired. EXAMPLE: A QUALIFICATION EXPIRES AT 14:00 AND A NIGHTLY BATCH RUNS AT 02:00Live check at the moment of usealloweddenied from the moment it expiresCached status set by a nightly batchqualifiedstill shown as qualified for 12 hours: expired, yet alloweddenied12:0014:0016:0018:0020:0022:0000:0002:0004:00At 14:01 the live check says no. The cached status says yes until 02:00: 12 hours of workby someone who is no longer qualified. The specification forbids it.
Live check against a nightly status. A qualification expires at 14:00; the live check denies from that moment, while a nightly status would allow until 02:00.
SQL sketch of the check
-- The heart of the check (Postgres). clock_timestamp() reads the real clock; now() stays fixed inside a transaction.
select r.skill_id, r.required_level, q.level,
       coalesce((q.status = 'qualified' and q.level >= r.required_level
                 and (q.expires_at is null or q.expires_at > clock_timestamp())), false) as allowed
from trn_role_requirement r
left join trn_qualification q
  on q.skill_id = r.skill_id and q.person_id = $1 and q.site_id = r.site_id
where r.equipment_id = $2 and r.mandatory and r.archived_at is null;
Step 10

Session 4: The check that denies at the minute of expiry, and the live matrix

40 minutes

Why

This is the second pitfall made impossible, and the specification's first test: the check must deny a person whose qualification expired one minute ago, with no job having run. Reading the expiry against the clock at the moment of the request is what protects the plant; the matrix reads the same live rows, so the supervisor and the press never disagree about who may work.

Do this

Paste into Claude Code
On a new branch training/check:

1. Write tests first, in supabase/tests/training-check.test.sql, building their own rows inside a transaction that is rolled back, with times from clock_timestamp() (never now(), never the seed's dates): expires_at one minute ago with status still qualified → denied; expires_at clock_timestamp() + 5 seconds → allowed, pg_sleep(6), → denied; status in_training, revoked, suspended, a level too low, a person not active, no qualification row, an expired required certificate → each denied with its reason. Then the fixture cases from tests/fixtures/training-cases.json as at 2026-06-01T12:00:00Z (operator 4 denied though status says qualified). Run them and show they fail with no function yet.
2. Write trn_check_qualification(person_id, equipment_id, operation_ref) and /api/training/check, connecting with TRN_CHECKER_DATABASE_URL and refusing callers without TRN_CHECK_TOKEN (constant-time compare). It fails closed.
3. /training/start on a phone: choose a machine; allowed, or blocked with the reason and who to ask; with no signal it says it cannot check and blocks.
4. The matrix and KPIs as functions taking an as-at time defaulting to clock_timestamp(), reading the live tables with the caller's rights: trn_matrix(org_unit_id, as_at) and trn_kpis(org_unit_id, as_at) (training compliance, coverage with N = 2, single points of failure, expiring in 30 days). Test them against the fixture: 4 of 6, PRESS-OP 3, FORK the only single point of failure, 2 expiring. A test grants a qualification and checks the next read shows it, with no job in between.

Push, open a pull request titled "Training check and matrix", wait for every check, and report in plain words.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase test db)
⎿ not ok 1 - expired one minute ago is denied # function trn_check_qualification does not exist
1
⏺ Bash(npx supabase test db)
⎿ ok 1 - expired one minute ago is denied (status still 'qualified') ok 2 - allowed at +5 s, denied after pg_sleep(6) ok 9 - fixture operator 4 denied: PRESS-OP expired 2026-05-31 ok 14 - kpis: compliance 4/6, single points of failure 1 (FORK), expiring 2
2
⏺ Pull request #131 is green. No expiry job ran in any test: the check reads the clock itself. The matrix shows a new qualification on the very next read.3
Red with no function, then green: the minute-of-expiry test is the specification's first definition-of-done item.
  1. Failing for the right reason.
  2. Your hand count, reproduced.
  3. The two pitfalls, closed with tests.

You will see recreated screen

acme-platform-git-training-check-acme-ops.vercel.app/training/start
Press 3
Ask your supervisor (SYNTHETIC · Supervisor) to book a practical assessment.
Choose another machine
Start a task on a phone as a blocked operator: the reason in words, and who to ask.
  1. The check's own reason, not a generic error.

Check it worked

The check tests are green with the fixture unchanged; on the preview a demo operator whose qualification expired is blocked with the reason; granting a qualification shows on /training/matrix on the next read.

If it goes wrong

The expiry test passes only after a job runs

The check reads the stored status. Say: The check must read expires_at against clock_timestamp() at the moment of the request; the expiry job is housekeeping only.

The "+5 seconds" test never turns to denied

now() is fixed inside a transaction. Say: Use clock_timestamp() for the row and the check.

The check allows when the database cannot be reached

Say: Fail closed: any error or timeout is a deny with the reason "cannot check", with a test.

The matrix and the check disagree

The matrix reads a snapshot. Say: Compute the matrix from the live tables at an as-at time defaulting to now, never from a stored status or an overnight snapshot.

Knowledge check

A qualification expired at 14:00 and the nightly job runs at 02:00. At 15:00 an operator tries to start the press. What does the check do?

Knowledge check

In the fixture, which skill is a single point of failure?

References

  1. PostgreSQL Documentation: Date/Time Functions (clock_timestamp and now). https://www.postgresql.org/docs/current/functions-datetime.html
  2. ADL: SCORM, Sharable Content Object Reference Model. https://adlnet.gov/past-projects/scorm/
  3. eCFR: Title 21, Part 11, Electronic records; electronic signatures. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-A/part-11
  4. OSHA: 29 CFR 1910.147, The control of hazardous energy (lockout/tagout). https://www.osha.gov/laws-regs/regulations/standardnumber/1910/1910.147

Chapter 4 · Sessions 5 and 6

Move the history in, prove it, switch the old tool off

Real training history arrives only at the end, and only after a rehearsal. Session 5 maps old course codes to skills and builds an import that keeps original dates and evidence, then rehearses it on the development project with a redacted copy IT has approved in writing, removed the same day. Session 6 imports into production only through the import workflow a person starts from main, with an export owner two approved, records signed grandfathered decisions, switches the importer off and cancels the old tool with the saving from invoices.

20 min4 stepsSessions 5–6ends with the module's gate

By the end of this chapter you can

  • Map legacy course codes to skills and levels, and build an import with a dry run that never grants more than the evidence supports.
  • Rehearse on the development project with a redacted, IT-approved copy, with counts that add up and expired items flagged at once, and remove it the same day.
  • Run the final import into production only through import-training.yml, record grandfathered decisions, set the importer to NOLOGIN, and record the saving.
Old recordArrives asRule
Completiontrn_completion with its original date, score and passedimported_from and legacy_id in ext; the old trainer's name as text
Certificate and its filetrn_external_certificate with core_attachmentOriginal issue and expiry dates; never extended
Legacy course codeA line in docs/legacy-map.csv: skill, level, whether it is evidence at allA classroom course for a hands-on skill maps to level 1 at most
PersonMatched to core_person by employee_ref, then emailNever created from a training record; unmatched people are listed
Years of experience with no signed practicalA grandfathered qualification, signed by the administrator, time-limitedDecided by people in Session 6, never by the import
Key or secretWhat it unlocksWhere it livesWho holds itNever
trn_importer passwordThe import's insert-only database loginPassword manager; set by a person in each project's SQL editor; inside the two secrets belowOwner one and owner twoKept after Session 6
TRN_IMPORT_DATABASE_URL_DEV, TRN_IMPORT_DATABASE_URL_PRODThe import workflow's connection to the development and the live projectGitHub Actions repository secrets, typed by a person; names in docs/KEYS.mdOwnersLeft in place after cut-over
Step 11

Session 5: Map the old codes to skills, and build an import with a dry run

40 minutes

Why

An import that grants more than the evidence supports would undo the whole module on its first day: a legacy classroom course for a hands-on skill is evidence of teaching, not of competence. Mapping every old code in a file people can read, and a dry run that lists unmatched people, unmapped codes, duplicates and unreadable dates before anything is written, keeps every decision visible. A legacy key makes a second run add nothing.

Do this

Read your private export beside docs/training-inventory.md and write docs/legacy-map.csv yourself, one line per old course code: skill code, level granted, course type, and whether it counts as evidence at all. Then:

Paste into Claude Code
On a new branch training/import:

1. Read docs/legacy-map.csv (written by me). Never change a mapping; list any code in the import that is not in it.
2. A new migration (never edit an applied one) with a unique index on ext.legacy_id for trn_completion and trn_external_certificate.
3. Write scripts/import-training.mjs, connecting as the insert-only trn_importer login with IMPORT_DATABASE_URL from the environment (never printed, never the service-role key). It reads the export (CSV and files); a dry run writes nothing and lists unmatched people (by employee_ref, then email), unmapped codes, duplicates and unreadable dates. A write inserts completions and certificates with original dates, scores and files, imported_from and legacy_id in ext (on conflict do nothing), then asks the qualification service for qualifications by the Session 4 rules, so a legacy course for an ojt skill grants level 1 in_training at most. It never creates a person and never writes a qualification itself. No deployed upload or import page.
4. Write .github/workflows/import-training.yml, started only by hand (workflow_dispatch) by a person, refusing any branch but main, with inputs target (development or production), file and mode (dry-run or write). It downloads the file from the private Storage bucket imports of the target project; computes its sha256; refuses the run unless that sha256, the target and the expected counts (completions, certificates, files) are listed in docs/imports/training-approved.md on main; runs the script; and fails if any count differs from the listed one. Secrets: repository secrets TRN_IMPORT_DATABASE_URL_DEV and TRN_IMPORT_DATABASE_URL_PROD, typed by me. No GitHub environments and no "required reviewers" (not available for private repositories on our plan): the reviewed pull request that adds the approved line is the approval. Counts in the job summary.
5. scripts/import-training-count.mjs <file>, which I run on my own computer: prints the sha256 and the counts, never any content; and scripts/import-training-redact.mjs <file> <out>, which I run for the rehearsal copy: replaces every person's name, email and employee reference with a consistent placeholder and drops any injury or medical note. docs/imports/training-approved.md: one heading per approved export with target, file name, sha256, expected counts, IT's approval reference and, for the rehearsal, the date it was removed. supabase/snippets/remove-training-rehearsal.sql, for me to run in the development SQL editor: removes only rows with ext.imported_from set (and the qualifications whose basis is one of them), prints the counts, refuses unless the database is acme-platform-dev. Add the secrets' names to docs/KEYS.md.
6. After a write, run the expiry housekeeping so anything already expired is flagged at once, and the recertification clock creates assignments or lists certificates to renew. Never move a date.
7. Tests with a ten-row fixture export: the dry run report; a second write adds nothing; a legacy classroom course for PRESS-OP gives level 1 in_training; an expired certificate is flagged; the importer cannot insert a qualification or update any row; the workflow refuses a file not listed and fails on a count mismatch.

Push, open a pull request titled "Training import", wait for every check, and report in plain words.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx vitest run tests/training-import.test.ts)
⎿ ✓ dry run: 1 person unmatched, 1 code unmapped (FL-REFRESH-OLD), 0 duplicates ✓ legacy PRESS-CLASS → PRESS-OP level 1, in_training ✓ second write: 0 inserted ✓ trn_importer insert into trn_qualification → refused
1
⏺ Pull request #134 is green. Every unmapped code and unmatched person is listed for you; nothing is guessed.2
The import never grants more than the evidence; it asks the qualification service, which applies the Session 4 rules.
  1. The first pitfall again, held by the same rule as live work.
  2. Decisions stay with people.

Check it worked

The pull request is green; docs/legacy-map.csv covers every code in your inventory or lists it as unmapped; the fixture's second write adds nothing.

If it goes wrong

Claude Code suggests mappings for codes you have not mapped

Say: Do not map anything yourself. List unmapped codes for me to decide.

The import creates people it cannot match

Say: Never create a person from a training record; list the unmatched for whoever keeps the people list.

Claude Code asks for the real export to test with

Refuse. Real records stay out of tests and chats; the ten-row fixture is for tests.

Claude Code builds an upload page, runs the import on merge, or adds a GitHub environment with required reviewers

Say: No import page, no import on merge, no environments: a person starts import-training.yml from main, reading the file from the private imports bucket, and the merged line in docs/imports/training-approved.md is the approval. Required reviewers are not available for private repositories on the Team plan.

Step 12

Session 5: Rehearse on the development project with an IT-approved copy

40 minutes

Why

The rehearsal shows real volumes and real oddities with production untouched: people who will not match, codes nobody can map, certificates already expired. Training records name people, so the copy goes into the development project only redacted, with IT's written approval, and comes out the same day with the date recorded. The list of people with years of experience and no signed practical is the main output: it is a decision for people, made in Session 6.

Do this

Ask IT in writing before any real record leaves the old tool:

Email to IT
Subject: Approval to rehearse the training records import on our development database

We plan to load an export of training completions and certificates (with their files) from
<old tool> into our development database (acme-platform-dev, Supabase, region us-east-2) for one
rehearsal on <date>, and delete it the same day. Names, emails and employee references are replaced
with placeholders, and any injury or medical note removed, before it is loaded.
Access: the two platform owners and the training administrator. Please confirm in writing.

When IT approves, on the rehearsal day: in your private folder run node scripts/import-training-redact.mjs on the export, then node scripts/import-training-count.mjs on the redacted copy. Record its sha256 and counts, with IT's approval reference, in docs/imports/training-approved.md through a pull request owner two approves and merges. Set trn_importer's password in the development SQL editor, type the repository secret TRN_IMPORT_DATABASE_URL_DEV (user trn_importer.tsrqponmlkjihgfedcba), and upload the redacted copy to the private bucket imports on the development project. Then start the workflow from main: dry run, fix the map, write, then write again: it must add nothing.

Open

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

Run workflow from main: target development, mode dry-run, then write, then write again.

Paste into Claude Code, then paste the old tool's figures
The rehearsal import has run on the development project. On a new branch training/rehearsal, write docs/training-import.md with: for each export file, rows in the export, rows imported, rows skipped and the reason for each skip (the numbers must add up exactly); certificates and qualifications already expired and expiring in the next 30 days; the people whose records show the work done for years with no signed practical (counts per skill, no names in the file). Read-only on the development project, compare trn_kpis for the area as at the end of last month with the old tool's figures I paste below, and leave a "Why" column for every difference. Open a pull request titled "Training rehearsal" and wait for the checks.

The old tool's figures:
<paste section 5 of docs/training-inventory.md>

The same day, when the Why column is filled: run supabase/snippets/remove-training-rehearsal.sql in the development SQL editor, delete the file from the bucket and your local copies, write the removal date in docs/imports/training-approved.md, reload the made-up data with npm run seed:dev, and tell IT in writing.

You will see recreated screen

github.com/acme-ops/acme-platform/actions/runs/…
import-training · target development · dry-run · from main · nothing written
1
CheckCount
Completions in file3,412
Certificates with files286
People not matched4
Codes not mapped2
Already expired19
The dry run's job summary: the file is the approved one, problems named, nothing written yet.
  1. Counts you will compare with the production run.
  2. Nothing is guessed.

Check it worked

IT's written approval is filed and the copy was redacted; every file's expected rows equal imported plus skipped with each skip explained; the second write added nothing; docs/training-import.md explains every difference from the old tool's figures and lists, by skill, the people who need a grandfathered decision or an assessment; the same day the development project holds no imported row and the removal date is in docs/imports/training-approved.md.

Fastest path

Do dry run, write and write-again from the Actions page in one sitting.

If it goes wrong

The new figures show fewer people qualified than the old tool

Usually right: course completions for hands-on skills now count as in training, and lapsed items show as expired. Write the reason per skill; never change the rules to match the old number.

The run refuses the file, or fails on a count

It is doing its job: the file is not the one owner two approved, or it changed. Run the count script on the uploaded file, record its sha256 and counts through a pull request, and run again. Never loosen the check.

"password authentication failed for user trn_importer"

The user name carries the project reference (trn_importer.tsrqponmlkjihgfedcba), and the password must be the development one.

Step 13

Session 6: The final import into production, grandfathered decisions, and the importer switched off

45 minutes

Why

Production holds the record that decides who may run a press, so the final import runs only through the same tested workflow as the rehearsal, started by you from main, with production's password typed by you and an export whose fingerprint and counts owner two approved in a merged pull request. People with long experience and no signed practical get a grandfathered decision signed by the administrator and limited in time, so they are assessed before it runs out. The importer is switched off straight after: a login that writes training history has no place once the move is done.

Do this

  • Write the cutover date, who tells the floor, the date after which a completion recorded only in the old tool is no longer accepted, and how long your rules say training records must be kept, in docs/cutover.md.
  • Set the old tool to read-only on the date.
  • Take the final export, run the count script on it, and record its sha256 and counts in docs/imports/training-approved.md through a pull request owner two approves and merges.
  • In the live SQL editor set trn_importer's password; type the repository secret TRN_IMPORT_DATABASE_URL_PROD (user trn_importer.abcdefghijklmnopqrst); upload the export to the private bucket imports on the live project.
  • Start the workflow from main: target production, dry-run; compare its counts with the rehearsal's; then write. It refuses an export not listed and fails on any count mismatch.
  • With the administrator and the supervisor, record each grandfathered decision on /training/admin: level, reason, an expiry no later than the date you can assess them, signed by the administrator.
Open

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

Run workflow from main: target production.

Then switch the importer off at cut-over:

Paste into Claude Code, then paste the live counts
The production import is done. On a new branch training/cutover: a migration (npx supabase migration new training_importer_off) that sets trn_importer to NOLOGIN, with a test that it cannot log in; remove trn_importer from docs/matrix.json and regenerate the rules with scripts/gen-policies.mjs; mark its lines in docs/rights-walk.md "retired" with today's date; mark TRN_IMPORT_DATABASE_URL_DEV and _PROD removed in docs/KEYS.md; and record in docs/cutover.md the production counts I paste below beside the rehearsal's. Then, read-only on production, check three imported people (one classroom course, one certificate, one expired item) and that the check denies the expired one. Open a pull request titled "Training cutover record" and wait for the checks.

Production counts:
<paste the count table from the production run's summary>

After it merges and the deploy workflow has applied the migration, delete both TRN_IMPORT_DATABASE_URL secrets on GitHub.

You will see recreated screen

https://acme-platform.vercel.app/training/admin
Grandfathered decision · PRESS-OP
Level2
ReasonOperated press 3 daily since 2019; no practical on record1
Expiresin 6 months2
Sign as training administrator (re-enter password)
A grandfathered decision on the live admin page: signed, with a reason and an expiry that forces an assessment.
  1. The reason is part of the record.
  2. An expiry is required: the person is assessed before it runs out.

Check it worked

The production run started from main with an approved export; its counts match the approved line and the rehearsal, with every skip explained; each grandfathered decision is signed with an expiry; trn_importer is NOLOGIN and its secrets are deleted; the check denies the expired imported person.

If it goes wrong

Production pages fail with "column does not exist"

A migration is merged but not applied. Check the deploy workflow's last run and the daily freshness check from Session 11; never run db push by hand. Our live database once fell nine migrations behind.

Someone asks to grandfather everyone at level 4 with no expiry

Refuse: a grandfathered level always has an expiry and a reason, and stops at what the person actually does. The point is to assess them before it runs out.

Step 14

Session 6: Retire the old tool, clear the last copies, and record the saving

25 minutes

Why

The module is finished when the old bill stops and the saving is a fact from invoices, and when the last copy of real training records outside production and the records store is gone from the imports bucket and your computer. The old tool's final export is kept for as long as your rules say training records must be kept, in the company's records store, not the repository.

Do this

Paste into Claude Code
On a new branch training/retired, update docs/training-inventory.md: mark each records location replaced or still in use, with today's date; and add to docs/cutover.md the saving: the old bill from the invoices (I will paste the figures), minus what the module adds to services we already pay for. Open a pull request titled "Training retired" and wait for the checks.
Open

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

Live Storage: delete the final export from the imports bucket once it is in the records store.

Store the old tool's final export in the records store for the retention period you wrote, read its cancellation terms, cancel or write the end date, and delete local copies.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/cutover.md)
+## Saving (from invoices)
+Old tool: <from the invoice, number and date>
+Module: no new service
+Final export kept in the records store until <date from our retention rule>.
1
⏺ Pull request #138 is green. 3 records locations replaced; the paper binder for the forklift licences is still in use and listed.2
The retirement record: what was replaced, the retention, and the saving from invoices.
  1. Every figure from an invoice; the retention date from your rule.
  2. Anything not replaced is written down.

Check it worked

The old tool is cancelled or has its end date written; the final export is in the records store with its retention date and gone from the bucket and local folders; docs/cutover.md records the saving from invoices.

If it goes wrong

Someone wants to keep the importer for late records

Late records are a new export: approved through docs/imports/training-approved.md, with the login switched on by a person for that one run and set to NOLOGIN again.

The vendor deletes data at cancellation before the retention period ends

That is why the final export is stored first. Check it opens, with its files, before you cancel.

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

Knowledge check

A legacy classroom course is the only record that someone can run press 3. What does the import give them for PRESS-OP?

Knowledge check

What must every grandfathered qualification have?

References

  1. GitHub Docs: Manually running a workflow. https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-workflow-runs/manually-running-a-workflow
  2. ISO 9001:2015 Quality management systems: requirements (clause 7.2, evidence of competence). https://www.iso.org/standard/62085.html
  3. Supabase Docs: Database migrations. https://supabase.com/docs/guides/deployment/database-migrations

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. What is the difference between a person who is trained and one who is qualified?
2. Which ISO 9001:2015 clause is the spine of the module?
3. Which of these is left to another module or tool?
4. What is a mandatory trn_role_requirement row attached to?
5. Which event makes the module assign the revised procedure to the people who must read it?
6. The assignment job runs twice after the same trigger. What should the second run do?
7. A SCORM 2004 package reports a scaled score of 0.7 and a pass mark of 80% is set. Who decides passed?
8. Which pair of fields does a SCORM 1.2 package report?
9. An assessment can only be competent when:
10. What may a completed course grant for a skill whose evidence type is ojt?
11. A qualification expired one minute ago and the nightly job has not run. What does the check return?
12. Final inspection is held by exactly one qualified person. How does the matrix treat it?