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 module | Left for later, or to another module |
|---|---|
| Incidents and near misses, reported from a phone, anonymously if the reporter wishes | Inspection forms: module M01 (digital forms) |
| Investigations and corrective actions, ranked by the hierarchy of controls | Safety training records: module M07 |
| The OSHA 300, 300A and 301 records and the injury rates, from recorded cases | Chemicals 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 work | Enterprise 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.
Session 1: Inventory the old tool from its own reports and bills
35 minutesWhy
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.
cd ~/code/acme-platform && git switch main && git pull && claudeOn 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
- 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
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.
Session 1: Classify three records, and choose the first workflow
25 minutesWhy
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:
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
- One injury, two tables, two different audiences.
- The stamping plant's press P-04: yours will name your own machine.
- 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.
| Table | One row is | Columns |
|---|---|---|
| ehs_incident | One incident or near miss: what happened, where, when, how severe. Nothing about the body | incident_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_case | The OSHA case for one injured person. EHS role only | incident_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_investigation | One investigation of an incident | incident_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_observation | One hazard, good catch or observed act | obs_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_step | A job safety analysis, and one step of it | ra_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_permit | One permit to work | permit_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_point | The lockout procedure for one machine, and each isolation point | equipment_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_application | The locks on one machine for one job | loto_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_summary | One site's year: the 300A totals' hours and headcount | site_id req; year req; avg_employees req; total_hours req; certified_by, certified_at; posted_at; ita_submitted_at. Unique per site and year |
Session 2: Check the spine, then write the eleven tables and their tests
35 minutesWhy
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
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
- Mapped, not duplicated. If it proposes a second sites table, stop it.
- The restricted table, labelled in the database itself.
- 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.
Session 2: Seed made-up cases and try it on the development project
40 minutesWhy
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
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.
cd ~/code/acme-platform && git fetch && git switch ehs/tables && git pullnpx supabase link --project-ref tsrqponmlkjihgfedcbanpx supabase projects listnpx supabase db push --include-seedhttps://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
- The dot is on acme-platform-dev. If it is on acme-platform-prod, stop and link the development project again.
- Only the two new migrations. Anything else listed: answer n and ask why.
You will see recreated screen
| incident_no | incident_type | occurred_at | severity_actual | reported_by |
|---|---|---|---|---|
| INC-2026-0001 | near_miss | 2026-01-14 06:40 | none | SYNTHETIC · Worker 03 |
| INC-2026-0004 | injury_illness | 2026-03-02 22:15 | minor | SYNTHETIC · Worker 07 |
- Expected until Session 3: no policies, so nothing is readable through the app yet.
- 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
- OSHA: Injury and illness recordkeeping and reporting requirements. https://www.osha.gov/recordkeeping
- ISO 45001:2018 Occupational health and safety management systems. https://www.iso.org/standard/63787.html
- 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
- Supabase Docs: Seeding your database. https://supabase.com/docs/guides/local-development/seeding-your-database
- 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.
| Table | Everyone signed in (site worker) | Maintenance (authorised employee) | Supervisor (own area) | EHS specialist (new) | Manager |
|---|---|---|---|---|---|
| ehs_incident | Report; read own | Report; read own | Read; triage | Read; write; close | Read |
| ehs_injury_case | No right | No right | No right | Read; write | Counts only, through ehs_case_counts |
| ehs_investigation | No right | No right | Write, for non-injury incidents they lead | Read; write | Read; approve |
| ehs_observation | Report; read own | Report; read own | Read; rate risk | Read; write | Read |
| ehs_risk_assessment, ehs_risk_step | Read approved | Read approved | Draft | Approve | Read |
| ehs_permit | No right | Request; receive own | Issue, suspend, close (never their own) | Cancel; expire | Read |
| ehs_loto_procedure, ehs_isolation_point | Read approved | Read approved | Read | Write | Read |
| ehs_loto_application | No right | Apply, verify, remove own locks | Read | Read | Read |
| ehs_osha_annual_summary | No right | No right | No right | Hours; posting dates | Certify |
Session 3: Add the module to the role matrix and regenerate the access rules
35 minutesWhy
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
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
- Only one role appears under ehs_injury_case. Any other role there is a leak of health information.
- 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.
Session 3: Build the three screens, phone first
40 minutesWhy
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
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
- Five kinds a worker understands; the database's eight types are worked out from them.
- Anonymous: the row names the Anonymous reporter, and nothing on the phone is kept that could name the reporter.
- 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
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.
Session 4: Report, triage, investigate and close with verified actions
25 minutesWhy
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
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
- "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).
| From the hand-worked 2025 fixture (this year's seed has the same cases) | By hand | What the platform must show |
|---|---|---|
| Recordable cases (300A total) | 4: one days away, one restricted, two other recordable | 4 |
| Days away / days restricted | 12 / 8 | 12 / 8 |
| TRIR = recordable x 200,000 / hours | 4 x 200,000 / 250,000 | 3.2 |
| DART = (days-away + restricted cases) x 200,000 / hours | 2 x 200,000 / 250,000 | 1.6 |
| Near-miss to injury ratio | 6 / 4 | 1.5 |
| Privacy case on the 300 | One line | "Privacy Case" in the name column |
Session 4: Decide recordability and generate the OSHA records, checked by hand
25 minutesWhy
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
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.
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
| Total | Platform | Your form |
|---|---|---|
| Deaths | 0 | 0 |
| Days-away cases | 1 | 1 |
| Restricted or transfer cases | 1 | 1 |
| Other recordable cases | 2 | 2 |
| Days away / restricted | 12 / 8 | 12 / 8 |
| Hours / average employees | 250,000 / 125 | 250,000 / 125 |
- Line by line, the platform against your pencil. One difference means the query is wrong.
- 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.
Session 4: Permits and lockout that block the work
30 minutesWhy
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
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
- The three behaviours, each a test.
- Red without the rule. A test that cannot fail proves nothing.
You will see recreated screen
- 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
- OSHA: Part 1904, Recording and reporting occupational injuries and illnesses. https://www.osha.gov/laws-regs/regulations/standardnumber/1904
- OSHA: 1904.7 General recording criteria. https://www.osha.gov/laws-regs/regulations/standardnumber/1904/1904.7
- Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
- NIOSH: Hierarchy of Controls. https://www.cdc.gov/niosh/hierarchy-of-controls/about/index.html
- 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 indocs/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.
Session 5: Write the import and rehearse it on the development project
45 minutesWhy
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.
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.
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:
node scripts/import-ehs.mjs --target dev --undo <batch id it printed>You will see recreated screen
- Hidden input, and a refusal for any other host: the script cannot write to production from your computer.
- 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.
Session 6: Import into production through the pipeline
30 minutesWhy
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.
https://supabase.com/dashboard/project/abcdefghijklmnopqrst/storage/buckets
The live project's Storage: the private imports bucket.
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.
https://github.com/acme-ops/acme-platform/actions
GitHub Actions: run import-ehs from main, then watch its counts.
You will see recreated screen
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
- 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.
Session 6: Side by side, cut over, and cancel the old tool
35 minutesWhy
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:
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
| Week of 2026-12-07 | Old way | Platform | Explanation |
|---|---|---|---|
| Near misses | 9 | 11 | 2 reported on the platform only (night shift, no tool login) |
| Permits issued | 4 | 4 | — |
| Lockouts applied / removed | 6 / 6 | 6 / 6 | — |
- More reports on the platform is a good difference, if you can explain it.
- The three definition-of-done tests, with their results.
- 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.
Knowledge check
Why are old injury cases imported with their original determinations?
References
- OSHA: 1904.33 Retention and updating. https://www.osha.gov/laws-regs/regulations/standardnumber/1904/1904.33
- OSHA: 1904.29 Forms (privacy concern cases). https://www.osha.gov/laws-regs/regulations/standardnumber/1904/1904.29
- Supabase Docs: Storage access control. https://supabase.com/docs/guides/storage/security/access-control
- 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
Your result
CivOps AI Academy
Safety (EHS): Incidents, OSHA Records, Permits and Lockout/Tagout
Element M11 complete · Learner
Your LMS records this completion. For the CivOps Foundation certificate, finish the Foundation Course at https://civops.io/learn.