Skip to the lesson
CivOps AI Academy · M11Safety (EHS): Incidents, OSHA Records, Permits and Lockout/Tagout
0%

Chapter 1 · Sessions 1–2

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

Before anything is built, you find out what your EHS tool really holds and costs, from its own reports and bills. Then Claude Code adds the eleven ehs_ tables to your platform, with the injury details in one table only the EHS role can read, and you try them on the development project before they go anywhere near the plant's records.

30 min4 stepsAbout 7 hours hands-on across six sessions

By the end of this chapter you can

  • Inventory the EHS tool from its own reports, invoices and export page, with counts only and no health detail.
  • Classify three real records by the ehs_ tables that would hold them, and choose the first workflow to replace.
  • Have Claude Code check the spine, write the eleven tables with their tests, and try them on the development project yourself.

What the module replaces, and what it must never do

An EHS tool does three jobs: it takes reports of what went wrong or nearly did, it keeps the legal injury records, and it controls dangerous work. The module library names Intelex, Cority, Enablon, VelocityEHS, Sphera, Benchmark Gensuite, EHS Insight, Vector EHS and SafetyCulture as the tools it replaces [3]; yours may be a spreadsheet and a binder. The module rebuilds the core of those jobs on your own platform, in tables whose names start with ehs_.

Built in this moduleLeft for later, or to another module
Incidents and near misses, reported from a phone, anonymously if the reporter wishesInspection forms: module M01 (digital forms)
Investigations and corrective actions, ranked by the hierarchy of controlsSafety training records: module M07
The OSHA 300, 300A and 301 records and the injury rates, from recorded casesChemicals and safety data sheets, environmental permits and waste, management of change, contractors and visitors: eight more ehs_ tables, later
Risk assessments (JSA), permits to work and lockout/tagout that block the workEnterprise ESG reporting

Two mistakes sink EHS software, and the module's specification names both. The first is injury details in a table everyone can read: a body part and a diagnosis are health information about a named person. The second is a permit that does not stop the work it authorises: a record nobody is forced to check is paperwork. Every step below is arranged so neither can happen, and the tests prove it.

Two tiers of accessGeneral-access tables hold what happened, the investigation and the annual totals. Only the injury case table is limited to the EHS role, enforced by row-level security. Privacy cases show a substitute for the name on the 300 log. GENERAL ACCESSehs_incidentwhat happened, where, when, severityehs_investigationmethod, root causes, findingsehs_osha_annual_summaryhours, employees, certificationEHS ROLE ONLYehs_injury_caseperson, body part, treatment,outcome, days away and restricted,privacy case flag, OSHA case numberincident_idA person outside the EHS role reads the left side and is refused the right.On the 300 log a privacy case shows the words privacy case, not the worker's name.
Two tiers, decided in Session 2 and enforced from Session 3. What happened sits in tables a supervisor can read; who was hurt and how sits in one table only the EHS role can read.
Step 1

Session 1: Inventory the old tool from its own reports and bills

35 minutes

Why

You are about to replace a system people rely on for legal records. If you guess what it holds, the new module will quietly miss something, and you find out at an audit. Reading the counts from the tool's own reports, and the cost from its own invoice, gives you a list you can check the new module against in Session 6, and a saving you can prove.

Do this

Book 30 minutes with the person who looks after safety records. Open, in the old tool, its record counts (most tools have a report or a list with a total), its user list, its export page and, on the vendor's account page, the current invoice and renewal date. Injury records are health information: write down counts and categories only, never a name, body part, diagnosis or photo.

Terminal or PowerShell
cd ~/code/acme-platform && git switch main && git pull && claude
Paste into Claude Code
On a new branch ehs/inventory, write docs/ehs-inventory.md for me to fill in by hand. Do not invent any number, price or date: leave every value cell as "—" for me to complete from the old tool's own reports and invoices.

Sections:
1. Tools: a table with columns tool, owner (a job, not a name), how people sign in, users who can sign in, bill per year (as printed on the invoice), renewal date, notice period, what it exports, how long we can still export after cancelling.
2. Records: a table with one row per record type: incidents, near misses, injury and illness cases, investigations, corrective actions, observations and hazard reports, job safety analyses, permits to work, lockout procedures, lockout applications, OSHA 300 / 300A / 301 for each of the last five calendar years, chemicals and safety data sheets, environmental permits, management of change. Columns: count in the last 12 months, where it lives, the ehs_ table that will hold it (from the list below), who can read it today, who should.
   ehs_incident, ehs_injury_case, ehs_investigation, ehs_observation, ehs_risk_assessment, ehs_risk_step, ehs_permit, ehs_loto_procedure, ehs_isolation_point, ehs_loto_application, ehs_osha_annual_summary. Mark chemicals, environmental, change and contractor records as "later".
3. Who can see injury details today: one sentence.
4. Baseline: seconds and taps to report a near miss today, measured with a stopwatch.
5. Workarounds: one numbered line per thing people do around the tool (job, not name), so Session 6 can check each one is covered.
6. First workflow to replace, and why, in one sentence.

At the top, write: "Counts and categories only. No names, body parts, diagnoses or photos." Then open a pull request titled "EHS inventory" and show me the link.

Then fill in the cells on GitHub (open the file in the pull request, choose the pencil icon, and commit to the same branch). Time one worker who does not know the tool reporting a near miss on a phone, from taking the phone out to the receipt: that is your baseline.

You will see recreated screen

claude — acme-platform
⏺ Bash(git switch -c ehs/inventory)
⎿ Switched to a new branch 'ehs/inventory'
⏺ Write(docs/ehs-inventory.md)
+Counts and categories only. No names, body parts, diagnoses or photos.
+| Record type | Count, last 12 months | Where it lives | ehs_ table | Who reads it today | Who should |
+| Near misses | — | — | ehs_incident (near_miss) | — | — |
+| Injury and illness cases | — | — | ehs_injury_case | — | EHS role only |
1
⏺ Bash(gh pr create --title "EHS inventory")
⎿ https://github.com/acme-ops/acme-platform/pull/41
⏺ Pull request #41 adds docs/ehs-inventory.md with every value left as — for you to fill from the tool's reports and invoice. I have not guessed any count or price.
Claude Code writes the skeleton and leaves every value for you. Numbers you did not read from the tool have no place in it.
  1. Every cell is a dash: the numbers come from the tool, not from Claude Code. If you see a number you did not type, delete it.

Check it worked

docs/ehs-inventory.md is merged with every dash replaced by a value you read from the tool or its invoice (or "cannot see: ask "), the five years of OSHA logs located, the baseline time, and the workarounds listed.

Fastest path

Do the counts from the tool's own summary report rather than counting lists by hand; most EHS tools have one report with totals by type and year. If the invoice is with finance, write the cell as "ask finance" and carry on: the bill is not needed until Session 6.

If it goes wrong

Claude Code filled in counts or a price

Say: Remove every number you did not get from me. Leave them as —. An invented count in the inventory becomes a target the new module is checked against, which is worse than a blank.

The safety lead wants to send you the export file to "help"

Not yet, and never into a chat or the repository: it holds health information. Session 5 sets up where it is kept and who may open it. For now you need counts only.

The vendor's account page does not show the price

Write who can see it ("finance, ask for the last invoice") and the renewal date if you can. Never write a list price from the vendor's website as your cost: your contract may differ.

People list things the tool does that nobody wrote down

Good: that is what the workarounds list is for. When we moved a prototype to a real build, the agent carried over what it noticed and our audit found a 78% match, with ten items needing a person to decide. A numbered list now is what Session 6 checks against.

Step 2

Session 1: Classify three records, and choose the first workflow

25 minutes

Why

Classifying three real records against the tables is the cheapest test of the design: if a real record does not fit, you find out now, for the cost of a sentence. It also makes the health-information rule concrete before any table exists: you will see that an injury is two records, one anyone involved may read and one only the EHS role may.

Do this

With the safety lead, pick one near miss, one injury and one lockout record. Write only the date and a one-line description with no name. Then:

Paste into Claude Code, after replacing the <...> parts
Add a section "Three records, classified" to docs/ehs-inventory.md on the branch ehs/inventory. I will describe three records in categories only; do not ask for or write any name or health detail.

1. A near miss on <date>: <one line, no names>.
2. An injury on <date> that needed <first aid / medical treatment / days away>: <one line, no names, no body part>.
3. A lockout of <machine tag> on <date> for <job>.

For each, write: which ehs_ tables hold it (an injury is one ehs_incident for what happened, where and when, plus one ehs_injury_case for the person, the injury and the OSHA decision); who may read each table under the rule "only the EHS role reads ehs_injury_case"; and which of its fields are health information. Then add one line under "First workflow": incident reporting, because everyone uses it and it is where speed is measured, unless I tell you otherwise. Push to the same pull request.

Ask the safety lead to read the pull request, then owner two approves and you merge.

You will see recreated screen

github.com/acme-ops/acme-platform/pull/41/files
ConversationCommitsFiles changed
docs/ehs-inventory.md
2. Injury, 2026-03-11, needed medical treatmentehs_incident (what happened, where, when): supervisor, EHS, manager. ehs_injury_case (person, treatment, outcome, recordable): EHS role only.1
3. Lockout of press P-04, 2026-04-02ehs_loto_application against ehs_loto_procedure for P-04 and its ehs_isolation_point rows. No health information.2
First workflow: incident reportingEveryone uses it; the baseline is 4 min 10 s and 14 taps today.3
The classification on GitHub, as the safety lead reads it. No name and no body part anywhere.
  1. One injury, two tables, two different audiences.
  2. The stamping plant's press P-04: yours will name your own machine.
  3. The baseline from Step 1 is the number Session 4 must beat.

Check it worked

The inventory on main has three records classified by table, each with who may read it, and a first workflow with a one-sentence reason the safety lead has read.

If it goes wrong

A record does not fit any of the eleven tables

Write it under "Not in this module" with where it should go (for example a chemical record: later; a training record: M07). Do not ask Claude Code to add a table for it yet: Session 2 builds only the eleven.

Someone typed a worker's name into the pull request

Edit the line out and commit. Then, because git keeps history, ask Claude Code: A personal name was committed in docs/ehs-inventory.md on this branch. Tell me how to remove it from the branch history before merge, without changing anything else. Do this before merging, while the branch is still yours.

Knowledge check

An injury is recorded in the module. Where does the body part go?

The eleven tables, column by column

These are the tables Session 2 builds, taken from the module's specification. Session 4 generates the OSHA records from them [1], and the injury-case rule follows the management-system idea of ISO 45001: records with an owner and a date, readable by the people who need them [2]. Every table also has the standard columns of the spine (id, site_id in place of the specification's tenant_id, created_at, created_by, updated_at, updated_by, row_version, archived_at, ext). req means required; values after a colon are the only ones allowed; an arrow is a link to another table. The prompt in Step 3 carries this list, so you do not copy it by hand.

The made-up rows the screens need are loaded by a seed file of their own, supabase/seeds/ehs.sql, with its dates shifted onto today, which Supabase runs after the migrations on a fresh database and on the development project [4]. The hand-worked year every later count is checked against has fixed dates, so it is a test fixture, tests/fixtures/ehs-osha-2025.json, not seed rows. The person, not Claude Code, loads the development project: supabase db push --include-seed the first time [5], npm run seed:dev after that.

TableOne row isColumns
ehs_incidentOne incident or near miss: what happened, where, when, how severe. Nothing about the bodyincident_no req unique; incident_type req: injury_illness, near_miss, property_damage, environmental_release, vehicle, fire, security, first_aid_only; occurred_at req; site_id → core_site req; area_equipment_id → core_equipment; location_text; description req; reported_by → core_person; reported_at req; anonymous; severity_actual req: none, minor, moderate, serious, major, fatal; severity_potential: minor … fatal; sif_potential; status req: reported, under_investigation, actions_open, closed; investigation_lead_id → core_person
ehs_injury_caseThe OSHA case for one injured person. EHS role onlyincident_id → ehs_incident req; person_id → core_person; non_employee_name; job_title; body_part; nature_of_injury; treatment: first_aid, medical_treatment, hospitalized, emergency_room; outcome req: death, days_away, restricted_or_transfer, other_recordable, not_recordable; recordable req; recordability_rationale (json); privacy_case req; osha_case_no; days_away; days_restricted; return_to_work_at
ehs_investigationOne investigation of an incidentincident_id req; method req: five_why, fishbone, causal_factor, taproot_style, other; timeline, root_causes, contributing_factors (json); findings; completed_at; approved_signature_id → core_e_signature
ehs_observationOne hazard, good catch or observed actobs_no req unique; obs_type req: safe_act, unsafe_act, unsafe_condition, hazard, good_catch; observed_at req; area_equipment_id; description req; observer_id; anonymous; risk_rating: low, medium, high, critical; status req: open, actioned, closed
ehs_risk_assessment and ehs_risk_stepA job safety analysis, and one step of itra_no req unique; ra_type req: jsa, jha, task, hira, ergonomic, chemical; title req; revision req; status req: draft, approved, due_review, superseded; review_due. Steps: step_no, task_step, hazard req; likelihood, severity req (1–5); risk_score; controls; control_type: elimination, substitution, engineering, administrative, ppe; residual_likelihood, residual_severity, residual_score
ehs_permitOne permit to workpermit_no req unique; permit_type req: hot_work, confined_space, line_break, electrical, working_at_height, excavation, general; work_order_ref (soft link); equipment_id; requested_by req; issuer_id; receiver_id; valid_from, valid_to req; status req: requested, approved, active, suspended, closed, cancelled, expired; hazards, precautions, gas_tests (json); issuer, receiver and close-out signature ids
ehs_loto_procedure and ehs_isolation_pointThe lockout procedure for one machine, and each isolation pointequipment_id req; procedure_doc_ref (soft link); revision req; energy_sources (json) req; last_annual_inspection; status req: draft, approved, superseded. Points: seq, energy_type req: electrical, pneumatic, hydraulic, mechanical, thermal, chemical, gravity, stored, radiation; device, isolation_method, verification_method req
ehs_loto_applicationThe locks on one machine for one jobloto_procedure_id req; permit_id; work_order_ref (soft link); applied_by, applied_at req; verified_by, verified_at; lock_ids (json); removed_by, removed_at; status req: applied, verified, removed
ehs_osha_annual_summaryOne site's year: the 300A totals' hours and headcountsite_id req; year req; avg_employees req; total_hours req; certified_by, certified_at; posted_at; ita_submitted_at. Unique per site and year
Step 3

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

35 minutes

Why

The module points at people, sites and machines it does not own. If Claude Code cannot find them, it invents a second people table, and from then on the platform has two answers to "who is this". Checking the spine first, and creating only what is truly missing in its own migration, keeps one truth. Writing the tests in the same pull request means the two module rules (injury details in one table, history never edited) are proved from the first day.

Do this

Paste into Claude Code
Read docs/SCHEMA-PLAN.md, docs/naming-standard.md and the migrations in supabase/migrations. Do not connect to any Supabase project.

On a new branch ehs/tables:

1. The spine. The EHS module needs: core_site, core_person, core_job_role, core_equipment, core_attachment, core_comment, core_action_item, core_approval, core_status_history, core_notification, core_number_sequence, core_event_outbox, core_e_signature (append-only), core_audit_log with a trigger function core_audit_row(), core_current_tenant() and core_touch_row(). For each one, tell me: exists under this name, exists under another name (for example sites for core_site, equipment for core_equipment), or missing. Never create a second table for something that exists under another name: use the existing one and write the mapping in the shared docs/spine-map.md, in its own section "M11 Safety (EHS)" (never a separate spine-map file). Module tables carry site_id in place of the specification's tenant_id, so core_current_tenant() is not created; write that in the section too. Create only what is missing, in its own migration (npx supabase migration new spine_for_ehs), with row-level security on and no policies.

2. In the same section of docs/spine-map.md, list these eleven tables and their columns, exactly as listed in element M11, chapter 1, with the spine table each one points at (no separate tables file): ehs_incident, ehs_injury_case, ehs_investigation, ehs_observation, ehs_risk_assessment, ehs_risk_step, ehs_permit, ehs_loto_procedure, ehs_isolation_point, ehs_loto_application, ehs_osha_annual_summary. I will paste the table from the element below this message if you need it.

3. npx supabase migration new ehs_tables, and in it create the eleven tables:
   - the standard columns (id, site_id not null references sites in place of tenant_id, created_at, created_by, updated_at, updated_by, row_version, archived_at, ext jsonb), an index on site_id, the core_touch_row() and core_audit_row() triggers;
   - required means not null; allowed values are check constraints; links are foreign keys to the spine (through docs/spine-map.md) and to each other;
   - work_order_ref and procedure_doc_ref are plain uuid columns with no foreign key (the tables they point at belong to other modules);
   - incident_no, obs_no, ra_no and permit_no unique per site; one ehs_osha_annual_summary row per site and year;
   - a function ehs_next_number(entity_key, site_id), security definer with set search_path = '', reading core_number_sequence;
   - a comment on ehs_injury_case: "Health information. EHS role only.";
   - row-level security on every table, no policies yet (Session 3 generates them from docs/matrix.json).

4. pgTAP tests in supabase/tests/ehs.test.sql proving: the eleven tables exist with row-level security on; a bad incident_type, a bad permit status, a bad control_type and an injury case with no incident are each refused; ehs_incident has no column named body_part, nature_of_injury, treatment or diagnosis; no ehs_ table has a delete policy.

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

You will see recreated screen

claude — acme-platform
⏺ Read(supabase/migrations/20261016091500_create_first_tables.sql)
⎿ Read 96 lines
⏺ Spine check: core_site exists as sites, core_equipment as equipment (mapped in docs/spine-map.md). Missing: core_person, core_job_role, core_attachment, core_comment, core_action_item, core_approval, core_status_history, core_notification, core_number_sequence, core_event_outbox, core_e_signature, core_audit_log. I will create those in spine_for_ehs.1
⏺ Write(supabase/migrations/20261103101200_ehs_tables.sql)
+create table public.ehs_injury_case (
+ incident_id uuid not null references public.ehs_incident(id),
+ outcome text not null check (outcome in ('death','days_away',
+ 'restricted_or_transfer','other_recordable','not_recordable')),
+ privacy_case boolean not null default false, ...
+comment on table public.ehs_injury_case is 'Health information. EHS role only.';
2
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m04s clamps pass 1m12s
⏺ Pull request #43 is green: 2 migrations, 11 ehs_ tables, 38 tests passed, including 4 that try bad data and are refused and 1 that fails if ehs_incident ever gains an injury column.3
Claude Code reports the spine first, then writes the tables. Here the Foundation already had sites and equipment, so it used them.
  1. Mapped, not duplicated. If it proposes a second sites table, stop it.
  2. The restricted table, labelled in the database itself.
  3. The test that guards the first pitfall: it turns red if anyone adds a body-part column to the incident.

Check it worked

Pull request EHS tables is green on GitHub, docs/spine-map.md says what was mapped and what was created, and the summary names the test that guards ehs_incident against injury columns.

Fastest path

If Claude Code asks for the column list, paste the table from this chapter (select it on the page and copy) as your reply. One paste saves a dozen questions about allowed values.

If it goes wrong

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

The module migration ran before the spine migration, or the spine was made by clicking in the dashboard. Say: Make sure spine_for_ehs has an earlier timestamp than ehs_tables and creates everything the module points at. Rebuild from nothing and show me the check green. We merged a change once that worked on the developer's machine and failed everywhere else with "column does not exist"; the rebuild-from-nothing check is what catches it.

Claude Code added policies "so the tests can read the tables"

Say: Remove every policy. Policies come only from docs/matrix.json through scripts/gen-policies.mjs in Session 3. Tests that need to read use the test helpers for a signed-in role.

It reports green but GitHub shows a red check

Say: The check on the pull request is red. Run gh pr checks, read the failed log, fix the cause and wait for green before you report. We recorded a run that printed "npm: not found" and, minutes later, a summary claiming 1,326 tests passed. Trust the check, never the summary.

It wants to change an earlier Foundation migration to add a column

Say: Never edit an applied migration. Add the change as a new migration.

Step 4

Session 2: Seed made-up cases and try it on the development project

40 minutes

Why

Every later check in this module is a number you count by hand: four recordable cases, a TRIR of 3.2. Those hand counts have fixed dates, so they live in a test fixture that never changes; the seed gives the development project the same small set of rows shifted onto today, so the screens always have this year's records to show. Trying the migration and seed on the development project first, from your own terminal, shows you the tables in Supabase before the deploy workflow applies the migration to the live project on merge, and keeps made-up injuries out of production for good.

Do this

Paste into Claude Code
On the branch ehs/tables, add supabase/seeds/ehs.sql and list it after seed.sql under [db.seed] sql_paths in supabase/config.toml, so CI and the development project load it. Never append it to supabase/seed.sql. Never load it into production: check that .github/workflows/deploy.yml does not use --include-seed and tell me.

The seed is marked SYNTHETIC and safe to run twice: it replaces only its own rows, by fixed ids, and never touches a row it did not make. Its dates are shifted onto today: each is worked out from current_date and falls between 1 January of this year and today, so the same counts land in this year whenever it runs. At site cle, made-up people named Worker 01, Worker 02 ..., every visible name starting "SYNTHETIC · ":
- 12 ehs_incident: 6 near_miss, 1 property_damage, 1 first_aid_only, 4 injury_illness;
- 5 ehs_injury_case, one per injury and the first-aid one: first aid only (not_recordable, recordable false); medical treatment (other_recordable); 12 days away (days_away, days_away 12); 8 days restricted (restricted_or_transfer, days_restricted 8); a privacy case (privacy_case true, other_recordable);
- ehs_osha_annual_summary for this year: avg_employees 125, total_hours 250000;
- 12 ehs_observation, one a month, two rated high;
- one approved ehs_loto_procedure for press P-04 (revision A, last_annual_inspection 90 days before today) with three ehs_isolation_point rows: electrical, pneumatic, gravity;
- one draft ehs_risk_assessment (jsa, hot work on P-04) with three ehs_risk_step rows, and one ehs_permit (hot_work, requested).

Then, as a test fixture and not as seed rows, write the hand-worked year: tests/fixtures/ehs-osha-2025.json with the same 12 incidents and 5 cases on fixed dates in calendar year 2025, the 2025 summary (125 employees, 250,000 hours) and the expected totals: 4 recordable cases (1 days away, 1 restricted, 2 other recordable), 12 days away, 8 days restricted, TRIR 3.2, DART 1.6. Session 4's test loads it.

Add a pgTAP test that counts each of the seeded rows, and that running the seed twice leaves the same counts. Push, wait for the checks, and tell me the result.

When it is green, you (not Claude Code) load it into the development project from a terminal. The database password is in the password manager as Supabase: acme-platform-dev database password.

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

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

The development project's Table Editor: the eleven ehs_ tables, with the made-up rows.

This is the only time you push the seed with the migrations. From now on, to reload the made-up rows on the development project, you run npm run seed:dev yourself (Claude Code may not).

Owner two approves the pull request and you merge. The deploy workflow from Session 11 applies the two migrations to the live project; the seed stays out of it.

You will see recreated screen

Terminal
$ npx supabase projects list
LINKED | REFERENCE ID | NAME
● | tsrqponmlkjihgfedcba | acme-platform-dev1
| abcdefghijklmnopqrst | acme-platform-prod
$ npx supabase db push --include-seed
Do you want to push these migrations to the remote database? • 20261103101100_spine_for_ehs.sql • 20261103101200_ehs_tables.sql [Y/n] y2
Applying migration 20261103101200_ehs_tables.sql...
Seeding data from supabase/seed.sql, supabase/seeds/ehs.sql...
Finished supabase db push.
projects list marks the linked project with a dot: check it is the development project before you push.
  1. The dot is on acme-platform-dev. If it is on acme-platform-prod, stop and link the development project again.
  2. Only the two new migrations. Anything else listed: answer n and ask why.

You will see recreated screen

supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor
ehs_incidentehs_injury_caseehs_investigationehs_loto_procedureehs_observationehs_osha_annual_summaryehs_permit
ehs_incident
2
incident_noincident_typeoccurred_atseverity_actualreported_by
INC-2026-0001near_miss2026-01-14 06:40noneSYNTHETIC · Worker 03
INC-2026-0004injury_illness2026-03-02 22:15minorSYNTHETIC · Worker 07
The development project after the push: made-up incidents, marked as made up.
  1. Expected until Session 3: no policies, so nothing is readable through the app yet.
  2. No body part, no treatment: those columns do not exist on this table.

Check it worked

On the development project the ehs_ tables hold 12 incidents, 5 injury cases and one summary for this year of 250,000 hours, every name starting SYNTHETIC; tests/fixtures/ehs-osha-2025.json is in the pull request; after merge, the deploy workflow run on GitHub is green and the live project has the tables but none of the made-up rows.

If it goes wrong

The dot in projects list is on the live project

Do not push. Run npx supabase link --project-ref tsrqponmlkjihgfedcba again and re-check. Made-up injury cases in the live project would sit beside real ones and be counted in the real OSHA log.

A later step expects a count the seed does not make

Fix the seed, not the check. Reviews of five Academy modules found later steps written against counts the seed never created. Say: List every count a later step relies on and the seed line that makes it.

Someone asks for the seed in production "for the demo"

No. If a demo must ever run on the live site, every made-up row must say so, show a banner and come out with one command; that is a decision for the owners, not a shortcut. For this module, demos run on acme-platform-dev.

password authentication failed

Copy the development project's password again from the password manager (not the live project's). If it still fails, reset it in the development project's Database settings and save the new one in the password manager.

Knowledge check

Where do you first try the module's migration and made-up cases?

References

  1. OSHA: Injury and illness recordkeeping and reporting requirements. https://www.osha.gov/recordkeeping
  2. ISO 45001:2018 Occupational health and safety management systems. https://www.iso.org/standard/63787.html
  3. EHS Insight: key features to look for in EHS software (a source of the module specification). https://www.ehsinsight.com/blog/key-features-to-look-for-in-ehs-software
  4. Supabase Docs: Seeding your database. https://supabase.com/docs/guides/local-development/seeding-your-database
  5. Supabase CLI reference: supabase db push. https://supabase.com/docs/reference/cli/supabase-db-push

Chapter 2 · Sessions 3–4

Who may do what, and the workflow end to end

The access rules come from the role matrix, so the one decision that matters most, only the EHS role reads injury cases, is written once and enforced by the database. Then the screens and the workflow: a report from a phone in under a minute, an investigation with ranked actions, OSHA records that match a form you filled in by hand, and a lockout that stops a work order starting.

40 min5 steps3 definition-of-done tests

By the end of this chapter you can

  • Add the module's roles, tables and screens to docs/matrix.json and regenerate the access rules and their tests.
  • Build the phone report, investigation and permit screens, and run the workflow from report to closed incident.
  • Generate the OSHA 300 and 300A from the hand-worked fixture and match them to a hand-completed form; prove a work order is refused until its lockout is verified.

The rights, as a matrix

The module's specification names one role, the EHS role. A plant needs five jobs around it. Four already exist in your Foundation roles; the fifth, the EHS specialist, is new. Read each cell as "this job may do this to this table". Nobody deletes: a correction is a new row or a status such as cancelled.

TableEveryone signed in (site worker)Maintenance (authorised employee)Supervisor (own area)EHS specialist (new)Manager
ehs_incidentReport; read ownReport; read ownRead; triageRead; write; closeRead
ehs_injury_caseNo rightNo rightNo rightRead; writeCounts only, through ehs_case_counts
ehs_investigationNo rightNo rightWrite, for non-injury incidents they leadRead; writeRead; approve
ehs_observationReport; read ownReport; read ownRead; rate riskRead; writeRead
ehs_risk_assessment, ehs_risk_stepRead approvedRead approvedDraftApproveRead
ehs_permitNo rightRequest; receive ownIssue, suspend, close (never their own)Cancel; expireRead
ehs_loto_procedure, ehs_isolation_pointRead approvedRead approvedReadWriteRead
ehs_loto_applicationNo rightApply, verify, remove own locksReadReadRead
ehs_osha_annual_summaryNo rightNo rightNo rightHours; posting datesCertify
Step 5

Session 3: Add the module to the role matrix and regenerate the access rules

35 minutes

Why

Writing the rights in docs/matrix.json, not in the screens, means the database refuses a row before any screen asks for it, so a new screen, an import or an agent cannot leak an injury case. Because scripts/gen-policies.mjs writes both the rules and one allowed and one refused test per cell, a right missing here shows up as a red test today, not as a refused worker on the floor in Session 4.

Do this

Paste into Claude Code, after pasting the matrix table where shown
Read docs/matrix.json, scripts/gen-policies.mjs and the M11 section of docs/spine-map.md.

On a new branch ehs/access:

1. Add a role ehs_specialist to docs/matrix.json. Map the module's jobs to the existing roles: site worker = every signed-in role, authorised employee = maintenance, supervisor = supervisor (scope: own area), manager = manager (scope: site). Add one cell per role and ehs_ table exactly as in this table (element M11, chapter 2), and no right that is not in it. No delete for anyone.
   <paste the matrix table from element M11, chapter 2 here>

2. Add the screens and routes with the roles that may open them: /ehs/report (everyone signed in), /ehs/investigate (supervisor, ehs_specialist, manager), /ehs/permits (maintenance, supervisor, ehs_specialist, manager), /ehs/osha (ehs_specialist only), /ehs/kpi (manager, ehs_specialist); routes under /api/ehs/ with the same roles.

3. Run node scripts/gen-policies.mjs to write the policy migration and supabase/tests/access.test.sql, and node scripts/gen-routes.mjs to write lib/access/routes.ts. Do not hand-edit generated files.

4. In a separate migration, write two security-definer functions with set search_path = '': ehs_case_counts(site_id, from_date, to_date), returning only counts from ehs_injury_case joined to ehs_incident.occurred_at (deaths, days_away_cases, restricted_cases, other_recordable_cases, recordable_cases, days_away_days, restricted_days), callable by ehs_specialist and manager at that site only; and ehs_notify_targets(site_id, area_id, include_manager), returning person ids only. Add two people in core_person with person_type system who can never sign in: "Anonymous reporter" and "EHS service".

5. Tests in supabase/tests/ehs_access.test.sql: as each of operator, maintenance, supervisor and manager, a select from ehs_injury_case returns no rows and an insert is refused, while ehs_specialist reads it; the manager gets numbers from ehs_case_counts and nothing else; a supervisor of another area cannot see this area's incident; a supervisor's triage update really changes the row; nobody can delete from any ehs_ table.

Push, open a pull request titled "EHS access", wait for every check, and tell me in plain words which role can do what to ehs_injury_case.

You will see recreated screen

claude — acme-platform
⏺ Write(docs/matrix.json)
+"ehs_injury_case": {
+ "ehs_specialist": { "read": "site", "insert": "site", "update": "site" }
+},
1
⏺ Bash(node scripts/gen-policies.mjs)
⎿ Wrote supabase/migrations/20261110090000_policies.sql (61 policies) Wrote supabase/tests/access.test.sql (122 tests)
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m31s clamps pass 1m10s
⏺ Pull request #47 is green. Only ehs_specialist can read or write ehs_injury_case; operator, maintenance, supervisor and manager get no rows and their inserts are refused (8 tests). The manager gets counts through ehs_case_counts only. 141 tests passed.2
The generator writes the rules and the tests; Claude Code adds only the two functions by hand.
  1. Only one role appears under ehs_injury_case. Any other role there is a leak of health information.
  2. Ask for this sentence every time: it is the rule in words you can check against the matrix.

Check it worked

Pull request EHS access is green; docs/matrix.json shows ehs_injury_case with one role; supabase/tests/access.test.sql was regenerated, not hand-written; docs/access-review.md shows the new role's row.

If it goes wrong

A supervisor's save says success and nothing changes

The read rule does not cover the row after the change. Say: For each role that updates ehs_ rows, check its read policy covers the row before and after the change, and add a test that the row really changed. We hit this across three modules: a test that checks only the response passes while nothing happened.

Claude Code proposes letting the supervisor read ehs_injury_case "to investigate properly"

No. Say: The supervisor investigates the event, not the injury. Keep ehs_injury_case for ehs_specialist only, as the matrix says. An injured person's right to a copy of their own 301 is met by the EHS specialist on request, not by opening the table.

The tests pass in the SQL editor, yet the app shows rows it should not

The app is connecting with a login that skips the rules (the database owner or the service_role key). Say: Show me which login each /api/ehs route uses. None may use service_role. The scheduler and the import sign in as their own accounts, with passwords a person sets and lists by name in docs/KEYS.md.

It edited supabase/tests/access.test.sql by hand to make a test pass

Say: Never edit a generated file or loosen a test to get green. Change docs/matrix.json and regenerate, or stop and tell me why the test is wrong.

Step 6

Session 3: Build the three screens, phone first

40 minutes

Why

A report that takes four minutes and asks for your name is a report that is not made. The phone screen is built for the person standing where it happened: five fields, a photo of the place (never of the injured person), and an anonymous switch. Building the investigation and permit screens in the same pull request lets you test the rights from Step 5 against real pages before the workflow exists.

Do this

Paste into Claude Code
Before writing any route or page, read the guide in node_modules/next/dist/docs/ for this version of Next.js (request middleware lives in proxy.ts). Read docs/matrix.json, lib/access/routes.ts and the M11 section of docs/spine-map.md.

On a new branch ehs/screens, build three screens against the development seed, using the operator-surface components from Session 12:

1. /ehs/report (every signed-in role), phone first: what happened (text); where (area, remembering the last one); what kind (near miss, someone hurt, property damage, hazard or good catch, other); a photo with the hint "photograph the place or the equipment, never the person"; an anonymous switch. "Hazard or good catch" writes ehs_observation; the others write ehs_incident. "Someone hurt" shows the site's emergency instruction and asks nothing about the body. The report's id is made on the phone with crypto.randomUUID(), the draft is saved after every answer, and it is sent through the Session 12 outbox with insert ... on conflict (id) do nothing, so a retry adds no second report. The person is taken from the signed-in session on the server, never from the page; anonymous reports are written as "Anonymous reporter".
2. /ehs/investigate (supervisor, ehs_specialist, manager): incidents by status with their lead and actions.
3. /ehs/permits (maintenance, supervisor, ehs_specialist, manager): permits in the area, and under each permit the isolation points of its machine's procedure in seq order.

Tests: each screen at 360 and 390 px wide with no sideways scroll and 44 px targets; signed out, each screen and /api/ehs route lands on sign-in; as an operator, /ehs/osha is refused; the same report sent twice makes one row.

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

Open the preview address on your phone. Sign in as a test operator and report a made-up near miss with a photo of a wall. Then time a colleague who has never seen the screen.

You will see recreated screen

https://acme-platform.vercel.app/ehs/report
Report
What kindNear miss ▾1
What happenedCoil end swung past the feeder when the clamp slipped
WherePress line 2 · P-04 ▾
Add a photo of the place or equipment
Report anonymously2
Send report
The report screen on a phone, as a worker sees it. Five answers and a photo; nothing about the body.
  1. Five kinds a worker understands; the database's eight types are worked out from them.
  2. Anonymous: the row names the Anonymous reporter, and nothing on the phone is kept that could name the reporter.
  3. The receipt number is the stopwatch's finish line.

Check it worked

On a phone, a colleague reports a near miss in under 60 seconds and gets a receipt number; the preview's tests are green; signed out, /ehs/report lands on sign-in.

Fastest path

Test on a real phone over the plant's Wi-Fi from the start. Most surprises (a slow photo upload, a keyboard covering the send button) only show there.

If it goes wrong

Every report shows the same reporter, whoever was signed in

The page is sending the reporter and the server trusts it. Say: Take the reporter from the signed-in session on the server and ignore anything the page sends. We found every record credited to one person this way.

A report sent on a weak signal appears twice

The id is made on the server, so the retry looks new. Say: Make the id on the phone with crypto.randomUUID() and insert with on conflict (id) do nothing; add a test that sends the same report twice.

A link on the permit screen opens a blank page

A link that compiles is not a link that works. Say: Sign in as each role on the preview, visit every page and link in /ehs, and list every 404 or error.

The screen works, but /api/ehs/report.json opens signed out

Say: Show me which paths proxy.ts skips. Every /api/ path must be checked whatever it ends with; add a signed-out test for an /api/ehs address ending in .json. On our platform, the gate skipped every path with a dot in it.

Knowledge check

Which role may read rows of ehs_injury_case?

The workflow, from report to closed

The life of an incidentAn incident moves through four statuses: reported, under_investigation, actions_open and closed. Severity decides who is notified at the first step. reportedAnyone, on a phoneanonymous if they wishunder_investigationA lead is namedteam, timeline, root causeactions_openCorrective actionsclassed by hierarchyclosedVerifiedevery action closedehs_incident.statusWho is told, and how fast, depends on the severity chosen at the first step.The sif_potential flag marks an event that could have been a serious injury or a fatality.
The life of an incident. Reported from a phone, triaged, investigated with a named lead, open while actions are open, closed only when every action is verified.

Corrective actions are ranked by the hierarchy of controls: remove the hazard, substitute it, engineer it out, change the procedure, and only last, protective equipment [4]. An investigation whose every action is "retrain" or "remind" is reaching for the weakest control; the screen asks the lead whether a stronger one was considered.

Step 7

Session 4: Report, triage, investigate and close with verified actions

25 minutes

Why

This is the workflow people will use every week, so it must be complete before anything clever is added: a report reaches the right people, someone owns the investigation, every action has an owner and a due date, and nobody verifies their own action. Asking for the whole flow in one prompt, with its tests, gets it built and proved in one pull request instead of five rounds of "and now add".

Do this

Paste into Claude Code
Read docs/ehs-rules.md if it exists; if not, create it first with: risk = likelihood x severity on 1–5 scales, green below 8, amber 8–14, red 15 or more; every report notifies the area supervisor and the EHS specialists, and a report whose actual or potential severity is serious, major or fatal also notifies the manager; a hazard rated high or critical notifies the EHS specialists.

On a new branch ehs/workflow, build the incident workflow behind the screens:
1. Report: incident_no from ehs_next_number; in one transaction insert ehs_incident (status reported; severity_actual none for a near miss, otherwise minor), the photo, a core_status_history row, an ehs.incident.reported row in core_event_outbox (ids, type and severity only) and an in-app core_notification for each id ehs_notify_targets returns.
2. Hazard: a hazard rated high or critical writes ehs.observation.high_risk to the outbox and notifies the EHS specialists.
3. Triage (supervisor): severity_potential, sif_potential, investigation_lead_id, status under_investigation.
4. Investigation: method, timeline, root_causes, contributing_factors, findings; completed_at submits it for the manager's approval with a core_e_signature whose record_hash is a hash of the findings.
5. Actions: core_action_item rows from the investigation, each with ext.control_type (elimination, substitution, engineering, administrative or ppe; refuse anything else); when every action is administrative or ppe, show "Was a stronger control considered?". The first action moves the incident to actions_open. Refuse verified_by equal to the action's owner. The incident closes only when every action is verified.

Tests for each rule, including: a notification only claims "sent" when the core_notification row exists; an anonymous report leaves reported_by, created_by and the core_audit_log actor as Anonymous reporter; an owner cannot verify their own action; an incident with an unverified action cannot close.

Push, open a pull request titled "EHS workflow", wait for the checks, and tell me the result.

On the preview, play each role in turn with the test accounts: report a near miss as an operator, triage it as the supervisor, investigate, approve as the manager, raise three actions and verify them as the EHS specialist.

You will see recreated screen

claude — acme-platform
☒ Report and hazard routes, one transaction each
☒ Triage, investigation, signature with record_hash
☒ Actions with control_type, verify-by-another, close rule
☒ Tests: 19 new
⏺ Bash(gh pr checks --watch)
⎿ schema / test pass 2m48s web / e2e pass 4m02s
⏺ Pull request #49 is green. One check failed first: verifying your own action was allowed. I added the refusal and the test now fails without it and passes with it.1
The workflow arrives with a test for every rule, including the two that stop people marking their own homework.
  1. "Fails without it, passes with it" is what a real test looks like. Ask for it whenever a summary just says "added a test".

Check it worked

On the preview, one made-up near miss goes from reported to closed with three actions verified by someone other than their owners, and core_status_history shows every step and who made it.

If it goes wrong

The screen says the supervisor was told, but nobody got anything

A stand-in is claiming success. Say: List every notification path. Each must write a core_notification row or refuse with a clear message; never report sent without the row. We had a "Send all" button that marked every message sent while nothing left the building.

Claude Code says the tests pass, and you are not sure they test anything

Say: For each new test, undo the rule it guards, run it and show me it fails, then restore the rule and show it passes. One of our checks was green for weeks because it could only ever answer yes.

After two tries it is still red with the same error

Say: Stop. Quote the error, say what you tried, and whether the cause is in our code or outside it. Retrying something refused for an outside reason never succeeds.

OSHA records and rates, checked by hand

29 CFR 1904 asks for three forms: the 300 log (one line per recordable case), the 300A annual summary (certified by a company executive and posted from 1 February to 30 April), and a 301 report per case [1]. Three questions decide whether a case is recordable, in order: work-related (1904.5), a new case (1904.6), and a general recording criterion such as days away, restricted work or medical treatment beyond first aid (1904.7) [2]. Privacy cases show "Privacy Case" on the 300 in place of the name (1904.29). Records are kept five years after the year they cover (1904.33).

The recordability wizardThree questions in order: is the case work-related, is it new, does it meet a general recording criterion. Three yeses make it recordable; any no makes it not recordable, with the reasoning kept. 1. Work-related?event or exposure at work2. New case?not a continuing one3. General criteria?at least one is metRecordablerecordable = truenononoehs_injury_case, one question at a timeNot recordablethe reasoning is still kept in recordability_rationaleGeneral criteria in 29 CFR 1904.7: death, days away from work, restricted work or job transfer,medical treatment beyond first aid, loss of consciousness, or a significant injury or illness diagnosed by a physician.
The recordability questions. Three yes answers make a case recordable; a no ends the check, and the reasoning is kept either way.
From the hand-worked 2025 fixture (this year's seed has the same cases)By handWhat the platform must show
Recordable cases (300A total)4: one days away, one restricted, two other recordable4
Days away / days restricted12 / 812 / 8
TRIR = recordable x 200,000 / hours4 x 200,000 / 250,0003.2
DART = (days-away + restricted cases) x 200,000 / hours2 x 200,000 / 250,0001.6
Near-miss to injury ratio6 / 41.5
Privacy case on the 300One line"Privacy Case" in the name column
Two rates on one scaleA base of 200,000 hours and an example site of 250,000 hours drawn to scale. Four recordable cases give a TRIR of 3.2 and two days-away, restricted or transfer cases give a DART rate of 1.6. Hours drawn to scale: 3.2 px = 1,000 hours200,000 hours: the base250,000 hours worked at the example site (made up)TRIRrecordable cases x 200,000 / hours4 x 200,000 / 250,000 = 3.2DART ratedays-away, restricted or transfer cases2 x 200,000 / 250,000 = 1.6A synthetic example for the lab, not a measurement of any business.
Two rates on one scale. The 200,000 hours are about 100 full-time workers for a year, so rates compare across sites of any size.
Step 8

Session 4: Decide recordability and generate the OSHA records, checked by hand

25 minutes

Why

The OSHA forms are legal records an executive signs. A total that is out by one is not a rounding problem; it is a false record. Filling in the 300A by hand from the five cases of the hand-worked 2025 fixture first gives you a number the platform must match exactly. If it does not, you fix the query, never the count.

Do this

Open

https://www.osha.gov/recordkeeping/forms

OSHA's recordkeeping forms: download a blank Form 300 and 300A (free). Fill them in by hand from the five cases in tests/fixtures/ehs-osha-2025.json, using the table above.

Paste into Claude Code
On a new branch ehs/osha, build /ehs/osha for ehs_specialist only:
1. The recordability wizard for an injury case: three questions in order (work-related 1904.5, new case 1904.6, general recording criteria 1904.7), each answer stored in recordability_rationale; it sets outcome, recordable, privacy_case, osha_case_no (from ehs_next_number, restarting each year), days_away, days_restricted, return_to_work_at, and the specialist signs with a core_e_signature. A no at any question ends the check and still stores the reasoning. When an outcome is death or an in-patient hospitalisation, show the reporting duty in 1904.39.
2. For a chosen year: the 300 log (job title from ehs_injury_case.job_title; "Privacy Case" in place of the name where privacy_case is true, and a separate confidential list of case numbers and names for this role only), a 301 per recordable case, and the 300A totals from the cases and ehs_osha_annual_summary. After the manager certifies (certified_by, certified_at), refuse changes to avg_employees and total_hours.
3. /ehs/kpi for manager and ehs_specialist: TRIR, DART, near-miss to injury ratio, action closure on time and observations per 100 employees per month, from ehs_case_counts and the other tables. A measure with no data shows "No data", never 0.
4. An "ITA file" button that writes the 300A totals and 300 case data in the columns OSHA's Injury Tracking Application lists. I will paste the column list from OSHA's ITA page; do not invent or rename any column. The file is generated on demand and never stored in the repository or in public/.

Test: load tests/fixtures/ehs-osha-2025.json and check that for 2025 the 300A equals its expected totals: 4 recordable cases, 12 days away, 8 days restricted; TRIR 3.2; DART 1.6; this year's 300A from the seed shows the same totals; the privacy case shows "Privacy Case"; the manager's /ehs/kpi works while a select from ehs_injury_case returns no rows. Push, open "EHS OSHA records", wait for the checks, and tell me.

You will see recreated screen

https://acme-platform.vercel.app/ehs/osha
OSHA 300A · Cleveland · this year (made-up)
1
TotalPlatformYour form
Deaths00
Days-away cases11
Restricted or transfer cases11
Other recordable cases22
Days away / restricted12 / 812 / 8
Hours / average employees250,000 / 125250,000 / 125
TRIR3.2
DART1.6
/ehs/osha on the preview for this year, from the seed, beside your hand-completed form of the 2025 fixture. The seed holds the same five cases, so every total must match exactly.
  1. Line by line, the platform against your pencil. One difference means the query is wrong.
  2. The privacy case is on the log, without the name.

Check it worked

The test that loads tests/fixtures/ehs-osha-2025.json is green and its 300A equals your hand-completed form in every box; on the preview, this year's 300A from the seed shows the same totals, the 300 shows one Privacy Case, and as the manager /ehs/kpi shows TRIR 3.2 and DART 1.6 while a direct select from ehs_injury_case returns nothing.

If it goes wrong

The platform says 5 recordable cases

The first-aid-only case was counted. Say: The 300A must count only cases where recordable is true. Fix the query, add a test with the first-aid case, and show me it fails before the fix. Never change the hand count to match.

A measure shows 0 where there is no data

Zero is a real reading; "nothing recorded" is not. Say: Every measure with no rows shows No data, with a test per widget. We had a control chart that said "In control" on 87 screens from twelve hard-coded points.

The KPI page for "the last 12 months" is empty

The seed's dates should be worked out from today. Say: Make every date in supabase/seeds/ehs.sql relative to current_date; keep fixed dates only in tests/fixtures/ehs-osha-2025.json. After the merge, run npm run seed:dev yourself. We hit this once: seeded data aged and every "recent" panel went blank.

Claude Code saved the ITA file into public/ so it can be downloaded

Stop and remove it: files in public/ are served to anyone and never pass the sign-in gate. We found customer emails sitting there. The file is made on request, behind /ehs/osha, and never stored.

Permits and lockout that stop the work

OSHA's control of hazardous energy standard, 1910.147, requires energy-control procedures, locks and tags, and a try-out that proves the energy is gone [5]. In the module, a lockout application is applied, then verified after the try-out, then removed. A permit is requested, approved by the issuer, activated by the receiver, and closed. The work order must not start while either is incomplete, and the refusal must be made by the database, at the moment the status changes: an event arrives afterwards and cannot refuse anything.

A work order held by its lockoutA work order cannot enter in_progress while its lockout application is not verified. The application moves from applied to verified, which opens the gate, and finally to removed. WORK ORDER (CMMS)Work order releasedplanned, ready to startGate: refuse in_progressuntil the lock status is verifiedin_progresswork may beginLOTO APPLICATION (ehs_loto_application.status)appliedlocks on, lock_ids recordedverifiedtry-out proves no energyremovedremoved_by, removed_atopens the gate
A work order held by its lockout. The gate refuses in_progress until the application is verified, and the permit is active.
Step 9

Session 4: Permits and lockout that block the work

30 minutes

Why

A permit the work order system ignores is advice. Putting the refusal in a database trigger on the work order means no screen, import or agent can start a job on a machine whose locks have not been tried out, including screens built after this one. Showing the refusal yourself, and showing the test fail when the trigger is removed, is the module's third definition-of-done test.

Do this

Paste into Claude Code
On a new branch ehs/permits:
1. Permit routes: the authorised employee requests (status requested, requested_by self); the supervisor of the area, who must be neither requester nor receiver, records hazards, precautions and gas_tests, signs and approves; the receiver activates only when any ehs_loto_application for the permit is verified and now is within valid_from and valid_to; the supervisor can suspend and resume with a comment; close-out is refused while locks are on. The daily scheduler (as EHS service) sets expired after valid_to. Events: ehs.loto.applied, ehs.loto.removed, ehs.permit.activated, ehs.permit.closed.
2. Lockout routes: apply (status applied, applied_by self, lock_ids), verify after the try-out (verified_by, verified_at), remove (only the person who applied, or the supervisor under the documented exception with a comment).
3. A cross-module migration, guarded by to_regclass so each part runs only when the other module's table exists: a before-update trigger on cmms_work_order (security definer, set search_path = '') that refuses a move to in_progress when the equipment has an approved ehs_loto_procedure and no verified ehs_loto_application for the work order, or when a permit linked to it is not active. The message names what is missing. If cmms_work_order does not exist (module M05 not built), create a throwaway table with id, equipment_id and status in the test only, never in a migration.
4. Tests: refused while the lock is applied; allowed once verified and the permit active; refused again with the permit suspended. Then remove the trigger, run the tests and show me they fail, and restore it.

Push, open "EHS permits and lockout", wait for the checks, and tell me the result, including the failing run.

On the preview, as maintenance, request a hot-work permit for P-04 and apply the locks; as the supervisor, approve it. Try to start the work order: it must be refused. Verify the locks, activate the permit, and start it again.

You will see recreated screen

claude — acme-platform
⏺ Bash(npx supabase test db)
⎿ ehs_permits.test.sql .. ok 1 - in_progress refused while lockout is applied ok 2 - in_progress allowed once verified and permit active ok 3 - in_progress refused while permit suspended
1
⏺ Bash(npx supabase test db # trigger removed)
⎿ not ok 1 - in_progress refused while lockout is applied not ok 3 - in_progress refused while permit suspended
2
⏺ Pull request #52 is green. With the trigger removed, 2 of 3 tests fail; restored, 3 of 3 pass. The refusal message reads: "Work order WO-2041 cannot start: lockout on P-04 is applied but not verified."
The proof the gate is real: red without the trigger, green with it.
  1. The three behaviours, each a test.
  2. Red without the rule. A test that cannot fail proves nothing.

You will see recreated screen

https://acme-platform.vercel.app/ehs/permits
WO-2041 · P-04 · hot work
Permit HW-0007approved (not active)
Lockoutapplied · 3 locks · not verified
Start work
The refusal as the technician sees it on the preview.
  1. The database refused, and the message says exactly what is missing.

Check it worked

You saw the work order refused while the lock was only applied, allowed once it was verified and the permit active, and refused again with the permit suspended; the pull request shows the tests failing without the trigger.

If it goes wrong

Claude Code made the check in the screen, not the database

Say: The refusal must be a trigger on the work order table, so every writer is refused. A check in the screen protects only that screen.

It suggests loosening the test because the throwaway work-order table differs from M05's

Say: Never loosen a test to get green. Make the throwaway table match the columns the trigger reads, and only in the test.

After merging main, your trigger or its test has gone

Someone reverted a batch on main and took your change with it, with no conflict. Say: List every schema change and test this branch added and confirm each is still present; if any vanished, find the commit that removed it.

Knowledge check

The platform's 300A says 5 recordable cases and your hand count says 4. What do you do?

Knowledge check

Where must the refusal "no start while the lockout is unverified" be made?

References

  1. OSHA: Part 1904, Recording and reporting occupational injuries and illnesses. https://www.osha.gov/laws-regs/regulations/standardnumber/1904
  2. OSHA: 1904.7 General recording criteria. https://www.osha.gov/laws-regs/regulations/standardnumber/1904/1904.7
  3. Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
  4. NIOSH: Hierarchy of Controls. https://www.cdc.gov/niosh/hierarchy-of-controls/about/index.html
  5. OSHA: 1910.147 The control of hazardous energy (lockout/tagout). https://www.osha.gov/laws-regs/regulations/standardnumber/1910/1910.147

Chapter 3 · Sessions 5–6

Move the records in, and retire the old tool

History comes across with its original decisions, because a five-year-old OSHA log must reproduce exactly as it was certified. You rehearse the import on the development project with a copy IT has approved, import into production through the pipeline, compare side by side, and cancel the old tool only when the numbers agree.

35 min3 stepsEnds with the module gate

By the end of this chapter you can

  • Write the import with Claude Code from column headings and made-up rows only, and rehearse it on the development project.
  • Import into production through the import-ehs workflow, started from main, against an approved sha256 and counts that must match.
  • Run old and new side by side, cut over, and record the saving from real invoices.

The rules for moving safety records

  • Original determinations. Every injury case keeps the outcome, recordable flag, privacy flag (1904.29 [2]), days and case number the old tool had. The import never re-runs the wizard on history: the logs must reproduce for five years after the year they cover (1904.33) [1].
  • Nobody pastes a row into Claude Code. It gets the column headings and three made-up rows in the same shape. The export holds health information.
  • Rehearse, then import. The rehearsal (Session 5) runs on acme-platform-dev with a copy IT has approved in writing, redacted of names and injury details, and is removed the same day, with the date recorded. Production is loaded only by .github/workflows/import-ehs.yml, started by a person from main, never from a laptop [4]: it reads the export from the private Storage bucket imports [3] and refuses any export whose sha256 and counts are not in docs/imports/ehs-approved.md, merged after owner two's approval.
  • No open permits move. A permit is a live authorisation: close or cancel every open permit in the old tool before cutover.
Step 10

Session 5: Write the import and rehearse it on the development project

45 minutes

Why

An import that runs once, on the day, against the live records is a bet. Writing it from headings and made-up rows keeps the health information out of Claude Code; rehearsing it on the development project with an approved copy shows you the counts, the unmatched people and the skipped rows while nothing real can be harmed. The script refusing any target but the development project from your computer is what stops a slip of the keyboard from writing into production.

Do this

The safety lead exports incidents, injury cases with their decisions, investigations, actions, observations and lockout procedures from the old tool, in their own account, into an encrypted folder only they and you can open. Ask IT to approve using a copy for the rehearsal on the development project, in writing, redacted: names replaced by codes, and body part, nature of injury and treatment blanked. Copy only the first line (the headings) of each file.

Paste into Claude Code, after adding the headings and made-up rows
On a new branch ehs/import, write scripts/import-ehs.mjs. You will never see the real export. Here are the headings of each file and three made-up rows in the same shape:
<paste the heading line of each file, and write three made-up rows under each, with made-up names>

The script:
1. Maps each file to ehs_incident, ehs_injury_case, ehs_investigation, ehs_observation, core_action_item, ehs_loto_procedure and ehs_isolation_point. Keeps the old incident, observation and case numbers unchanged; keeps occurred_at, reported_at and status; stores the old tool's id in ext.source_id, ext.imported true and ext.batch (a batch id it prints).
2. Copies outcome, recordable, privacy_case, days_away, days_restricted and return_to_work_at exactly, and stores the old tool's own words and decision date in recordability_rationale.original. Add a migration with a trigger that refuses any later change to recordability_rationale.original.
3. Lists every person, site and machine it cannot match to the spine and stops, so the people administrator can add them first (former employees inactive).
4. Moves each core_number_sequence past the highest imported number.
5. Prints, per file: rows read, imported, skipped (with the reason for each), and writes nothing of the data itself to the screen or a log.
6. --target dev asks for the development database connection string with hidden input and refuses any host that is not tsrqponmlkjihgfedcba. --target production refuses unless it runs inside the import-ehs workflow in GitHub Actions. --undo <batch> removes only that batch's rows, on dev only.
Tests in CI with the made-up rows: counts agree, determinations unchanged, numbering moved, a production run from a laptop refused. Push, open "EHS import", wait for the checks, and tell me.

When it is green, you run the rehearsal in your own terminal. Paste the connection string from the development project's Connect page when asked, with the password from the password manager; nothing shows as you paste.

Terminal or PowerShell
node scripts/import-ehs.mjs --target dev --file ~/secure/ehs-export/

Regenerate one year's 300 on the development project and compare it line by line with the old tool's (the redacted names apart). Then, the same day, remove the rehearsal batch and write the date you removed it in docs/ehs-import.md:

Terminal or PowerShell
node scripts/import-ehs.mjs --target dev --undo <batch id it printed>

You will see recreated screen

Terminal
$ node scripts/import-ehs.mjs --target dev --file ~/secure/ehs-export/
Development database connection string (hidden): 1
Target tsrqponmlkjihgfedcba (acme-platform-dev) · batch ehs-2026-11-24-a
incidents.csv read 1,284 imported 1,284 skipped 0
injury_cases.csv read 96 imported 96 skipped 0
actions.csv read 2,031 imported 2,029 skipped 2 (see skipped.txt: owner not in core_person)2
numbering: ehs_incident next 1,301 · ehs_observation next 4,410 · ehs_injury_case (2026) next 19
Original determinations unchanged on 96 of 96 cases.
The rehearsal's own report: counts only, no record shown.
  1. Hidden input, and a refusal for any other host: the script cannot write to production from your computer.
  2. Every skipped row has a reason. Fix the cause (here, two people to add) and run again until skipped is 0 or explained.

Check it worked

On the development project, imported plus skipped equals read for every file, every skip is explained in docs/ehs-import.md, one year's 300 matches the old tool's line by line, and the rehearsal batch was removed the same day, with the date recorded in docs/ehs-import.md.

If it goes wrong

The script stops with a list of unmatched people

That is it working. The Foundation people administrator adds them (former employees as inactive), then you run it again. Never let the import create people: two records for one person splits their history.

The regenerated 300 differs from the old tool's

The import re-decided something, or missed a privacy flag. Say: Compare the case that differs field by field with its row in the made-up test data shape, without reading the real file, and tell me which mapping is wrong. Never edit the case to match.

IT will not approve a copy on the development project

Rehearse with the made-up rows only, and do the first production import with the counts checked line by line in Step 11. Write IT's decision in docs/ehs-import.md.

A new incident gets a number that already exists

The numbering was not moved past the imports. Say: Set each core_number_sequence above the highest imported number and add a test that issues one new number of each kind and finds no duplicate.

Step 11

Session 6: Import into production through the pipeline

30 minutes

Why

Production holds the plant's legal records. Loading them from a laptop leaves no review, no record of who ran what, and nothing to stop a wrong file. A pull request that adds only docs/imports/ehs-approved.md (the export's sha256 and the expected counts, no data) is reviewed by owner two like any change; the import workflow, started by a person from main, refuses any export not listed there and fails if a count differs, so the import has the same governance as code.

Do this

Upload the export to a private storage bucket named imports in the live project (create it with Public bucket off). Only owners can see it.

Open

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

The live project's Storage: the private imports bucket.

Paste into Claude Code
On a new branch ehs/import-prod:
1. Add docs/imports/ehs-approved.md holding only: the batch id, each export file name in the imports bucket with its sha256, and the expected row counts per file from the rehearsal (no data). I give you the sha256 values; I worked them out on my computer with shasum -a 256.
2. Add .github/workflows/import-ehs.yml, started only by hand (workflow_dispatch) and refusing to run from any branch but main. It downloads the export from the private Storage bucket imports, refuses it unless its sha256 and counts are in docs/imports/ehs-approved.md on main, runs node scripts/import-ehs.mjs --target production signed in as ehs_import, and fails if any count differs. Do not use GitHub environments or required reviewers: the reviewed pull request is the approval.
3. A migration creating the role ehs_import: insert only on the tables the import writes, reading only the spine tables it matches against, moving core_number_sequence, no update or delete otherwise, never the service role key. I set its password myself and type it as the Actions secret EHS_IMPORT_DB_PASSWORD; list it by name in docs/KEYS.md. If the workflow needs any other secret that does not exist yet, stop and tell me its name.
Push, open "EHS import into production", and wait for the checks.

Set ehs_import's password yourself in the live project and type it at the repository's secrets page. Owner two reads docs/imports/ehs-approved.md and approves; merge. Then start the import yourself: Actions → import-ehs → Run workflow, branch main.

Open

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

GitHub Actions: run import-ehs from main, then watch its counts.

You will see recreated screen

github.com/acme-ops/acme-platform/actions
import-ehs · run by hand on main #53
export sha256 matches docs/imports/ehs-approved.md
incidents.csv      expected 1,284  imported 1,284  ok
injury_cases.csv   expected 96     imported 96     ok
actions.csv        expected 2,031  imported 2,031  ok
Original determinations unchanged: 96 of 96
The import run on GitHub, started by hand from main. It passes only if the export's sha256 and every count match docs/imports/ehs-approved.md as owner two approved it.
  1. A run that is red has written nothing: the import runs in one transaction per file and stops at the first mismatch.

Check it worked

The import-ehs run, started by hand from main, is green: the export's sha256 matched docs/imports/ehs-approved.md, its counts equal that file, and /ehs/osha regenerates the oldest retained year's 300 identical to the copy kept from the old tool.

If it goes wrong

The workflow fails with a secret that is empty

A secret that was never created reads as empty. Type it yourself at acme-ops/acme-platform/settings/secrets/actions" href="https://github.com/acme-ops/acme-platform/settings/secrets/actions" target="_blank" rel="noopener">the repository's secrets page (value only, no NAME=), list it in docs/KEYS.md, and re-run the job.

The run refuses the export: sha256 not approved

The file in the bucket is not the one owner two approved (exported again, or opened and saved by a spreadsheet). Upload the approved file again, or open a new pull request with the new sha256 and counts for owner two. Never change the workflow to skip the check.

Someone suggests running the script from a laptop "just this once"

The script refuses, by design. Every production change in this course goes through review and the pipeline; that is how you can answer later who loaded what, and when.

Step 12

Session 6: Side by side, cut over, and cancel the old tool

35 minutes

Why

A week of real reports in both systems, counted by hand from each, is the only proof the new way records everything the old way did. Writing the cutover date, the rollback and the saving from real invoices into one file means the decision to cancel can be checked by anyone, and nothing depends on memory.

Do this

A week before this session, start the side-by-side run: every report, observation, permit and lockout in one area goes into both the old way and the platform. Count the week by hand from each. Then:

Paste into Claude Code
On a new branch ehs/cutover, write docs/ehs-cutover.md for me to fill in, with no number invented:
1. The side-by-side week: a table of reports, near misses, observations, permits, lockouts applied and removed, actions opened and closed, with columns old way, platform, difference, explanation.
2. The three module proofs, each with the query or test and its result: only ehs_specialist reads ehs_injury_case (run the access tests); a work order is refused in_progress until its lockout is verified; an anonymous report names nobody in the row or in core_audit_log.
3. The phone test: three near misses reported in airplane mode, reconnected, and exactly three rows arrived; a second send of the same queue still three; a first-time reporter's time.
4. The workarounds from docs/ehs-inventory.md, each marked covered, not needed, or open.
5. Cutover: the date, who tells the floor, when the old links, posters and QR codes are replaced, confirmation that no permit is open in the old tool, the rollback plan, and who keeps the original export until when (five years after the end of the latest year it covers).
6. The saving: old bill from the invoice, minus what the module adds to the services we already pay for, as a sum I fill in.
7. A migration that sets ehs_import to NOLOGIN at cut-over, applied by the deploy workflow on merge.
Run the access tests and the lockout test now and write their results into section 2. Open "EHS cutover" and show me the link.

Fill in the numbers, then cut over on the date: replace the old links and QR codes with https://acme-platform.vercel.app/ehs/report. Read the old tool's cancellation terms on your own account page, cancel (or write the date the plan ends), and record the old bill from the invoice. Mark each record type in docs/ehs-inventory.md as replaced, retired or still on the old way.

You will see recreated screen

github.com/acme-ops/acme-platform/blob/main/docs/ehs-cutover.md
EHS cutover · Cleveland
1
Week of 2026-12-07Old wayPlatformExplanation
Near misses9112 reported on the platform only (night shift, no tool login)
Permits issued44—
Lockouts applied / removed6 / 66 / 6—
ProofsInjury case readable by ehs_specialist only (8 refusals pass). WO refused until lockout verified (3 of 3). Anonymous report names nobody.2
SavingOld tool, per the last invoice, minus the module's added running cost: written from invoices, not estimates.3
The cutover file, filled in. Every difference has an explanation; the saving comes from invoices.
  1. More reports on the platform is a good difference, if you can explain it.
  2. The three definition-of-done tests, with their results.
  3. Fill the sum from your own invoice; the course gives no figure.

Check it worked

docs/ehs-cutover.md is on main with every difference explained, the three proofs passing, the phone test counted, the cutover date and rollback written, the old tool cancelled (or its end date recorded) and the saving written from invoices.

If it goes wrong

A difference in the side-by-side week cannot be explained

You are not ready to cut over. Find the record in both systems by its number and date, and fix the cause before the date.

Asked whether an exposed injury record was ever seen, you cannot say

That needs request logs kept from before go-live. If an exposure is found, do not delete anything first: record what was reachable, from when, and preserve the evidence. We once could only answer "cannot determine" because no request log existed.

Cancelling early gives no refund

Leave the old tool until the paid period ends, read-only, and write that date. The export, not the subscription, is what you must keep.

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

Knowledge check

Why are old injury cases imported with their original determinations?

References

  1. OSHA: 1904.33 Retention and updating. https://www.osha.gov/laws-regs/regulations/standardnumber/1904/1904.33
  2. OSHA: 1904.29 Forms (privacy concern cases). https://www.osha.gov/laws-regs/regulations/standardnumber/1904/1904.29
  3. Supabase Docs: Storage access control. https://supabase.com/docs/guides/storage/security/access-control
  4. GitHub Docs: Events that trigger workflows. https://docs.github.com/en/actions/writing-workflows/choosing-when-your-workflow-runs/events-that-trigger-workflows

Chapter 4 · 12 questions · 80% passes

Final assessment

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

15 min12 questions≈ 15 minutesRetake allowed

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

1. What is a near miss?
2. What does the sif_potential flag mark?
3. Which corrective action is highest on the hierarchy of controls?
4. In what order are the three recordability questions asked?
5. A case is judged work-related and new, and the injury needed stitches. What is the likely result?
6. How long are OSHA injury and illness records kept?
7. Why is ehs_injury_case limited to the EHS role?
8. A site works 250,000 hours and has four recordable cases. What is its TRIR?
9. What happens when someone tries to start a work order while its lockout application is only applied?
10. Which signature activates a permit to work?
11. Where may the made-up seed of injury cases be loaded?
12. How are the old tool's records loaded into the live project?