Chapter 1 · Sessions 1–2
What the old CMMS holds, and the tables on one asset tree
Before anything is built, you find out what the old maintenance system holds, what it costs and what people work around, and you map the first area's assets onto the platform's one equipment tree. Then one prompt adds the module's fifteen tables, with the tests that try to break them and a made-up history whose reliability figures you can check by hand, and you try them on the development project before the pipeline takes them to production.
30 min5 stepsSessions 1 and 215 cmms_ tablesabout 7.5 hours hands-on across six sessions
By the end of this chapter you can
- Inventory the old CMMS from its own reports and bills: assets, work orders, PM plans, parts, users and cost, inventing nothing.
- Map the first area's assets onto the spine's equipment, with a criticality agreed with the planner, so there is never a second asset tree.
- Add the cmms_ tables with one prompt, prove them on the development project, and let the pipeline apply them to production.
Check your names once. Every prompt, command and address below uses them.
Saved with your progress. Every prompt, command and address in the course now uses these names. Change them any time from Your names at the top of the page.
What Maintenance replaces
The module runs maintenance from a request to a reliability figure: one asset register on the shared ISA-95 hierarchy, work orders closed with ISO 14224 failure codes [2], preventive maintenance on calendar, meter and condition triggers, spares through the inventory ledger, calibration, offline work on a technician's phone, and the measures that prove the programme works. It replaces CMMS and EAM tools; the module library names IBM Maximo, Rockwell Fiix, UpKeep, MaintainX, Limble, Fluke eMaint, SAP PM and HxGN EAM [5].
| Standard | Used in this module for |
|---|---|
| ISO 55000/55001/55002 [1] | Asset management: criticality, lifecycle cost, the line from objectives to work |
| ISO 14224:2016 [2] | Equipment classes and failure mode, cause, mechanism coding |
| EN 13306:2017 | Maintenance terms: corrective, preventive, condition-based, predictive |
| EN 15341:2019 and SMRP metrics [3] | PM compliance, schedule compliance, MTBF, MTTR, backlog, cost as % of replacement value |
| ISO 17359 | Condition monitoring guidelines, for condition triggers |
| ISO 10012 and ISO/IEC 17025 | Calibration traceability |
| OSHA 29 CFR 1910.147 [4] | Control of hazardous energy (lockout/tagout) for maintenance work |
| MIMOSA CCOM / OIIE | Asset information exchange, as an integration reference |
Session 1: Inventory the old CMMS from its own reports and bills
40 minutesWhy
The module must replace what the old system really holds and does, not what its brochure says. Its own reports give the counts (assets, open work orders, PM plans, parts, users), its bill gives the cost, and fifteen minutes with a technician and the planner give what people work around. Claude Code writes it up in minutes, inventing nothing, so every figure can be traced when you claim a saving.
Do this
With read access to the old system, run its own reports and write down the counts as printed: assets, open and closed work orders in the last year, PM plans, parts, users. Read its bill on the vendor's own account page (amount, renewal date, number of seats) and its export page. Ask one technician and the planner what they work around (requests by text with a photo, work orders filled in from memory at the end of the day, a paper copy in a pocket, no signal in the plant). No names or phone numbers in your notes. Then:
cd ~/code/acme-platform && git switch main && git pull && claudeI am starting the Maintenance module (M05). It replaces our CMMS with the platform. Do not write any code in this session.
On a new branch m05/inventory, create docs/cmms-inventory.md from my notes below, with:
1. What the old system holds: assets, open work orders, closed work orders in the last year, PM plans, parts and users, each count exactly as I give it with the name of the report it came from.
2. How its asset list compares with our equipment table: the naming it uses, and examples where the same machine has different names.
3. What people work around, in their words (jobs, never names).
4. Cost: the bill amount, renewal date and seats exactly as I give them, and what export it offers (CSV, API, which objects).
Use only what is in my notes. Never fill in a price, a count, a date or a vendor feature I have not given you: write "unknown, ask <who>" instead. End with "Questions to settle".
Open a pull request titled "M05: CMMS inventory", wait for the checks, and tell me the result in plain words.
My notes:
<paste your notes here>You will see recreated screen
- Every count says which report it came from.
- Three names for one press: the reason Step 2 maps them onto one tree.
Check it worked
docs/cmms-inventory.md is in a pull request with every count from a named report, the cost copied from an invoice or marked with who to ask, the export it offers, and no person named.
If it goes wrong
Claude Code fills in a cost or a count
Say: Remove every figure I did not give you and write unknown, ask <who>. Agents fill empty places so a page looks finished; on our platform a report showed a revenue figure the customer never gave.
You have no read access to the old system
Ask the planner to run the four reports and send them to you, or sit with them while they do. Do not borrow anyone's login.
Session 1: Map the first area's assets onto the one tree, with criticality
25 minutesWhy
The import in Session 6 starts by matching each old asset to an equipment row; doing it now for the first area finds the duplicates, the scrapped machines and the assets that are really parts, while it is a conversation. Criticality decides what is planned first and which spares must never run out, so the planner and a production lead agree it, not Claude Code.
Do this
Export the old system's asset list for the first area to a private folder outside the repository. Read it with the planner and write, for each asset, its old id, its name, what it is on the floor, and a criticality (a: stops production or safety, b: slows it, c: neither). Then:
Read docs/cmms-inventory.md, docs/naming-standard.md and our equipment table's rows for site cle (from supabase/seed.sql and the migrations; do not connect to any project).
On a new branch m05/first-area, write docs/cmms/first-area.md, for someone who does not write code: a table with one row per asset of the first area from my notes below: old id, old name, our equipment code (or "not in equipment: ask"), criticality (a, b or c, as I give it), an ISO 14224 equipment class in plain words, whether it is maintainable, and a note. Flag every old asset that matches no equipment row, every two old assets that match one row, and every old asset that is really a part or a tool, under "Questions for the planner". Never invent an equipment code.
My notes:
<paste your asset notes: old id, old name, what it is, criticality>
Open a pull request titled "M05: first area mapped", wait for the checks, and show me the link.Settle the questions with the planner and a production lead, then:
The planner answered the questions in docs/cmms/first-area.md:
1. <their answer>
2. <their answer>
Update the file, add "Checked with the planner and the production lead on <today's date>" at the top, and push to the same pull request.You will see recreated screen
- One row per old asset; the equipment code comes from your table, never invented.
- The mismatches are the value of this step.
Check it worked
docs/cmms/first-area.md is merged with every old asset of the first area mapped to an equipment code or explained, each with a criticality agreed with the planner and a production lead.
Fastest path
Map only the first area now. The rest of the plant is mapped the same way in Session 5, when the import lists every asset it cannot match.
If it goes wrong
The planner wants to keep the old asset tree as it is
Show them the three names for one press from the inventory. The old ids are kept, as a reference on each profile, so nothing they search for is lost; but there is one tree.
Everything is criticality a
Ask: if this stopped for a shift, would we lose output or safety? Ranking by that question usually leaves a quarter as a.
The fifteen tables
The module library puts standard columns on every table: id, created_at, created_by, updated_at, updated_by, row_version, archived_at and ext, and a tenant_id; on your platform module tables carry site_id in place of tenant_id, so each keeps one simple access rule. The shared file docs/spine-map.md says which Foundation table plays each core_ name (equipment for core_equipment), the same for every module. The module has no asset list of its own: it points at the spine's core_equipment (your equipment table) and core_equipment_class, and at core_person, core_uom, core_data_tag, core_item, core_storage_location, core_reason_code, core_attachment and core_e_signature. Four links are soft (a uuid with no foreign key) because their modules may not be installed: permit_ref (M11), procedure_doc_ref (M06), inventory_txn_ref (M12) and impact_assessment_ref (M08).
| Table | One row is | Columns (req = required; {a, b} = only these values; → points to) |
|---|---|---|
| cmms_asset_profile | Maintenance attributes of one equipment row | equipment_id → core_equipment req, unique; criticality req {a, b, c}; criticality_score num; iso14224_class text; maintainable bool req; warranty_expires_at date; purchase_cost money; replacement_cost money; expected_life_years num; qr_code text; status req {in_service, standby, out_of_service, retired} |
| cmms_craft | A trade with its rate and capacity | code text req, unique; name text req; hourly_rate money; capacity_hours_per_week num |
| cmms_job_plan | A reusable procedure | code text req, unique; name text req; equipment_class_id → core_equipment_class; craft_id → cmms_craft; est_hours num; loto_required bool req; permit_types json; safety_notes text; procedure_doc_ref (soft link) |
| cmms_job_plan_task | An ordered task, maybe a measurement | job_plan_id → cmms_job_plan req; seq int req; description text req; measurement_required bool; uom_id → core_uom; lsl num; usl num |
| cmms_meter | A runtime, cycle or condition meter | equipment_id → core_equipment req; name text req; uom_id → core_uom; data_tag_id → core_data_tag; reading_type req {cumulative, gauge}; alert_low num; alert_high num |
| cmms_meter_reading | One reading | meter_id → cmms_meter req; value num req; read_at ts req; source req {manual, tag, import}; read_by → core_person |
| cmms_pm_schedule | A preventive maintenance trigger | code text req, unique; equipment_id → core_equipment req; job_plan_id → cmms_job_plan req; trigger req {calendar, meter, condition, hybrid}; interval_value num; interval_unit {day, week, month, year, hour, cycle, unit}; meter_id → cmms_meter; meter_interval num; condition_rule json; lead_days int; floating bool req; next_due_at ts; next_due_meter num; last_completed_at ts; active bool req |
| cmms_work_request | A request from anyone | request_no text req, unique; equipment_id → core_equipment; location_text text; description text req; requested_by → core_person req; priority_suggested int; source req {mobile, qr, shift_log, form, scada, email, portal}; status req {new, accepted, rejected, converted, duplicate}; work_order_id → cmms_work_order; photo_attachment_id → core_attachment |
| cmms_work_order | A maintenance work order | wo_number text req, unique; equipment_id → core_equipment req; wo_type req {corrective, preventive, predictive, inspection, calibration, project, safety, improvement}; priority int req; status req {draft, awaiting_approval, approved, planned, scheduled, in_progress, on_hold, completed, closed, cancelled}; hold_reason_code_id → core_reason_code; pm_schedule_id → cmms_pm_schedule; job_plan_id → cmms_job_plan; requested_at, required_by, scheduled_start, scheduled_end, actual_start, actual_end ts; equipment_down bool; downtime_min num; assigned_craft_id → cmms_craft; assigned_to → core_person; failure_mode_id, failure_cause_id, failure_mechanism_id, remedy_id → cmms_failure_code; completion_notes text; permit_ref (soft link); completion_signature_id → core_e_signature |
| cmms_wo_task | A task line with its result | work_order_id → cmms_work_order req; seq int req; description text req; result {pass, fail, done, not_done, not_applicable}; measured_value num; done_by → core_person; done_at ts |
| cmms_wo_labor | Labour booked to a work order | work_order_id → cmms_work_order req; person_id → core_person req; craft_id → cmms_craft; started_at ts; ended_at ts; hours num req; rate money; is_overtime bool |
| cmms_wo_part | Parts planned and used | work_order_id → cmms_work_order req; item_id → core_item req; qty_planned qty; qty_used qty; storage_location_id → core_storage_location; unit_cost money; inventory_txn_ref (soft link) |
| cmms_failure_code | One ISO 14224 code for a class | code_type req {mode, cause, mechanism, remedy}; equipment_class_id → core_equipment_class; code text req; name text req; iso14224_ref text; active bool req |
| cmms_spare_part_link | A spare part of one asset | equipment_id → core_equipment req; item_id → core_item req; qty_installed qty; critical_spare bool req; min_qty qty; max_qty qty; reorder_point qty |
| cmms_calibration_record | One calibration, as found and as left | equipment_id → core_equipment req; work_order_id → cmms_work_order; procedure_doc_ref (soft link); due_at date; performed_at ts; performed_by → core_person; reference_standard_id → core_equipment; as_found json; as_left json; tolerance json; result req {pass, fail, adjusted_pass, out_of_tolerance}; certificate_attachment_id → core_attachment; impact_assessment_ref (soft link) |
Session 2: Check the spine, and the inventory ledger, before adding to them
10 minutesWhy
Fifteen tables point at a dozen shared ones, and parts must move through an inventory ledger, never by changing a number in a maintenance table. If Claude Code cannot find these it will invent its own, starting with a second asset tree. A read-only report first shows what exists, what plays the role, and what is missing.
Do this
Read docs/spine-map.md (if another module made it), docs/SCHEMA-PLAN.md, docs/naming-standard.md, docs/matrix.json, docs/cmms/first-area.md and every file in supabase/migrations. Do not change anything.
Maintenance (M05) needs these shared ("spine") tables and helpers. For each one: exists (file and line), exists under another name (which table plays the role, for example our equipment table for core_equipment), or missing:
core_equipment, core_equipment_class, core_person, core_site, core_uom, core_data_tag, core_item, core_storage_location, core_reason_code, core_attachment, core_e_signature, core_number_sequence, core_notification, core_event_outbox, core_action_item, core_audit_log, and a trigger that sets updated_at, updated_by and row_version.
Also: is there an inventory ledger (M12's inv_ tables) that records every issue and return of a part as a movement? If not, plan a minimal one: inv_inventory_transaction (item, location, quantity, type issue or return, work order reference, who, when) and a balance per item and location computed from it, never stored by hand.
Finish with a short plan: the rows M05 adds to docs/spine-map.md, one spine migration that adds only what is missing and reuses the rest, and how our equipment table's status maps to the profile's four statuses. Our module tables carry site_id in place of tenant_id.You will see recreated screen
- One tree: the profile hangs on your equipment rows.
- Only these are new.
- A ledger, so a part's balance is always the sum of its movements.
Check it worked
Every spine name is marked exists, exists as, or missing; the plan reuses your equipment table, and parts move through a ledger whose balance is computed, never typed.
If it goes wrong
The plan creates a cmms_asset or cmms_location table
Say: No asset tree in the module. Every asset is a row of our equipment table; cmms_asset_profile adds maintenance attributes one for one. The module library names a drifting second tree as its first pitfall.
The plan stores a stock quantity on cmms_spare_part_link and changes it
Say: Stock moves only as ledger transactions; the balance is computed from them. Never change a quantity by hand.
Session 2: One prompt: the spine pieces, the cmms_ tables, their tests and the seed
25 minutesWhy
The tables, the tests that try to break them and the made-up history in one pull request means the proof arrives with the change. The seed's failure history is chosen so its reliability figures can be worked out on paper: 8,000 operating hours and four failures give an MTBF of 2,000 hours; four repairs of 3, 5, 4 and 8 hours give an MTTR of 5 hours. Session 4 checks the dashboard against them.
Do this
Read docs/cmms/first-area.md, docs/naming-standard.md, docs/matrix.json and the spine plan you just gave me.
On a new branch m05/schema:
1. A spine migration (npx supabase migration new m05_spine) with only the missing pieces and the minimal ledger if planned, each with the standard columns (id uuid primary key default gen_random_uuid(), created_at, created_by, updated_at, updated_by, row_version, archived_at, ext jsonb) and site_id in place of tenant_id, reusing our existing tables where they play the role. Every function has set search_path = ''. Add M05's rows to docs/spine-map.md (create it if missing).
2. The module migration (npx supabase migration new m05_cmms_tables): the fifteen tables with the standard columns, a site_id and every column below. req means not null; {a, b} is a check constraint; → is a foreign key; money is numeric(14,2); qty is numeric; "equipment" means our equipment table.
cmms_asset_profile: equipment_id → equipment req unique, criticality req {a, b, c}, criticality_score numeric, iso14224_class text, maintainable bool req, warranty_expires_at date, purchase_cost money, replacement_cost money, expected_life_years numeric, qr_code text, status req {in_service, standby, out_of_service, retired}
cmms_craft: code text req unique, name text req, hourly_rate money, capacity_hours_per_week numeric
cmms_job_plan: code text req unique, name text req, equipment_class_id → core_equipment_class, craft_id → cmms_craft, est_hours numeric, loto_required bool req, permit_types jsonb, safety_notes text, procedure_doc_ref uuid (soft link, no foreign key)
cmms_job_plan_task: job_plan_id → cmms_job_plan req, seq int req, description text req, measurement_required bool, uom_id → core_uom, lsl numeric, usl numeric
cmms_meter: equipment_id → equipment req, name text req, uom_id → core_uom, data_tag_id → core_data_tag, reading_type req {cumulative, gauge}, alert_low numeric, alert_high numeric
cmms_meter_reading: meter_id → cmms_meter req, value numeric req, read_at timestamptz req, source req {manual, tag, import}, read_by → person
cmms_pm_schedule: code text req unique, equipment_id → equipment req, job_plan_id → cmms_job_plan req, trigger req {calendar, meter, condition, hybrid}, interval_value numeric, interval_unit {day, week, month, year, hour, cycle, unit}, meter_id → cmms_meter, meter_interval numeric, condition_rule jsonb, lead_days int, floating bool req, next_due_at timestamptz, next_due_meter numeric, last_completed_at timestamptz, active bool req
cmms_work_request: request_no text req unique (from core_number_sequence), equipment_id → equipment, location_text text, description text req, requested_by → person req, priority_suggested int, source req {mobile, qr, shift_log, form, scada, email, portal}, status req {new, accepted, rejected, converted, duplicate}, work_order_id → cmms_work_order, photo_attachment_id → core_attachment
cmms_work_order: wo_number text req unique (from core_number_sequence), equipment_id → equipment req, wo_type req {corrective, preventive, predictive, inspection, calibration, project, safety, improvement}, priority int req, status req {draft, awaiting_approval, approved, planned, scheduled, in_progress, on_hold, completed, closed, cancelled}, hold_reason_code_id → core_reason_code, pm_schedule_id → cmms_pm_schedule, job_plan_id → cmms_job_plan, requested_at, required_by, scheduled_start, scheduled_end, actual_start, actual_end timestamptz, equipment_down bool, downtime_min numeric, assigned_craft_id → cmms_craft, assigned_to → person, failure_mode_id, failure_cause_id, failure_mechanism_id, remedy_id → cmms_failure_code, completion_notes text, permit_ref uuid (soft link), completion_signature_id → core_e_signature
cmms_wo_task: work_order_id → cmms_work_order req, seq int req, description text req, result {pass, fail, done, not_done, not_applicable}, measured_value numeric, done_by → person, done_at timestamptz
cmms_wo_labor: work_order_id → cmms_work_order req, person_id → person req, craft_id → cmms_craft, started_at timestamptz, ended_at timestamptz, hours numeric req, rate money, is_overtime bool
cmms_wo_part: work_order_id → cmms_work_order req, item_id → core_item req, qty_planned qty, qty_used qty, storage_location_id → core_storage_location, unit_cost money, inventory_txn_ref uuid (soft link)
cmms_failure_code: code_type req {mode, cause, mechanism, remedy}, equipment_class_id → core_equipment_class, code text req, name text req, iso14224_ref text, active bool req
cmms_spare_part_link: equipment_id → equipment req, item_id → core_item req, qty_installed qty, critical_spare bool req, min_qty qty, max_qty qty, reorder_point qty
cmms_calibration_record: equipment_id → equipment req, work_order_id → cmms_work_order, procedure_doc_ref uuid (soft link), due_at date, performed_at timestamptz, performed_by → person, reference_standard_id → equipment, as_found jsonb, as_left jsonb, tolerance jsonb, result req {pass, fail, adjusted_pass, out_of_tolerance}, certificate_attachment_id → core_attachment, impact_assessment_ref uuid (soft link)
Every table: row-level security on with no policies yet, the update and audit triggers, an index on every foreign key. A partial unique index on cmms_work_order (pm_schedule_id) where status is not completed, closed or cancelled, so a PM schedule can never have two open work orders.
3. Add every new table to docs/matrix.json with no rights yet.
4. pgTAP tests in supabase/tests/m05_schema.test.sql: every new table exists with a primary key and row-level security on; a criticality of x, a work order type outside the list, a second profile for one equipment row, a work order with no equipment, and a second open work order for one PM schedule are each refused.
5. Made-up data in supabase/seeds/m05.sql, listed under [db.seed] sql_paths in supabase/config.toml, marked SYNTHETIC, shifted onto today from one moment read once at the start, and safe to run twice: profiles on three presses (criticality a, b, c); crafts mechanical and electrical with a rate and weekly capacity; job plan JP-PRESS-PM with four tasks (one a measurement with limits), loto_required false, and job plan JP-CLUTCH with loto_required true; three failure modes, causes, mechanisms and remedies for the press class; a running-hours meter on the first press reading 0 a year ago and 8000 now; a cycle counter on the second press with no readings; a 30-day calendar PM on the first press and a 500-cycle meter PM on the second (next_due_meter 500); and four closed corrective work orders on the first press with repairs of 3, 5, 4 and 8 hours (equipment_down, downtime 180, 300, 240, 480 minutes), each with all four failure codes, two sharing one failure mode.
The hand-worked example, with fixed dates, goes in tests/fixtures/m05-reliability.json (the running-hours readings 0 and 8000 and the same four repairs), not in the seed. Add a test that loads the fixture and checks MTBF 2000 hours and MTTR 5 hours.
6. Do not connect to or change any Supabase project, and do not run supabase db push.
Push, open a pull request titled "M05: cmms tables", wait for every check, and tell me in plain words: the tables added, the tests run and the fixture's MTBF and MTTR. If a check fails, fix it and wait again before reporting. End with the exact commands I must type myself to try this on the development project.You will see recreated screen
- Spine first: its earlier time makes it run first everywhere.
- One profile per equipment row, and the database itself refuses a second open PM order.
- The figures you check by hand in Session 4.
Check it worked
Pull request M05: cmms tables is green on GitHub, and the summary gives MTBF 2000 hours and MTTR 5 hours from the fixture.
Fastest path
"Wait for every check and fix it before reporting" saves a round trip: Claude Code reads the failure while you do something else.
If it goes wrong
CI fails: relation "core_equipment_class" does not exist
The module migration ran before the spine migration. Say: Give the spine migration a timestamp before the module migration on this branch, re-run the tests and push.
The failure is one text column
Say: Four keys, failure_mode_id, failure_cause_id, failure_mechanism_id and remedy_id, each to cmms_failure_code, as listed. Free-text closeout notes are the module library's second pitfall: no Pareto, no bad actors.
The seed uses fixed dates
Say: Count every time back from one moment read once at the start of the seed. We hit this: a seed with fixed dates was ten days old a week later, and every recent panel was blank.
Claude Code says green, GitHub says red
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.
Session 2: Try it on the development project yourself, then merge
15 minutesWhy
A merge applies migrations to production automatically (Foundation Session 11), so the last place to catch a problem is before it. Applying the branch to the development project yourself shows the tables build on a database that already holds your equipment rows. Only a person does this, with the password from the password manager.
Do this
In a terminal, not inside Claude Code:
cd ~/code/acme-platform && git fetch && git switch m05/schema && git pullnpx supabase link --project-ref tsrqponmlkjihgfedcbaType the development project's database password from the password manager. Check, then apply the migrations and the seed. --include-seed is for the first time a seed file is added; after that, reload made-up data with npm run seed:dev. Never supabase db reset on a project.
npx supabase migration listnpx supabase db push --include-seedhttps://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor
The development project's Table Editor: cmms_asset_profile has three rows on your presses; cmms_work_order has the four closed repairs.
Owner two (sam@acme.com) approves; merge. The deploy pipeline applies the migrations to production:
https://github.com/acme-ops/acme-platform/actions
The deploy run for the merge: green, two migrations applied.
You will see recreated screen
- Two new files, on your branch only.
- Check you linked tsrqponmlkjihgfedcba, the development project. If it lists files you do not expect, answer n.
You will see recreated screen
Applying migration 20261102094000_m05_spine.sql... Applying migration 20261102094500_m05_cmms_tables.sql... Finished supabase db push.
- The pipeline, after review, changed production; no person ran db push there.
Check it worked
The development project has the cmms_ tables and the SYNTHETIC rows from supabase/seeds/m05.sql; the deploy run is green; production's Table Editor (https://supabase.com/dashboard/project/abcdefghijklmnopqrst/editor) shows the cmms_ tables, empty.
If it goes wrong
db push: Remote migration versions not found in local migrations directory
The development project has a migration this branch does not, often another module's branch tried there. Do not force anything. In Claude Code: supabase db push on the development project says remote versions are not in the local directory. Tell me which versions differ and which branch each came from, without changing any project.
The deploy run fails on the migration
Good: the pipeline stopped before the code went live. Do not fix it in the dashboard. In Claude Code: The deploy failed applying the m05 migrations. Show me the error and write the fix as a new migration on a new branch. Our production once fell nine migrations behind main because nothing applied them.
The seed fails with a duplicate key
Every seed must be safe to run twice. Say: supabase/seeds/m05.sql failed with a duplicate key when run again. Make it safe to run twice and add a test that runs it twice. Then reload with npm run seed:dev. Never use supabase db reset to get round it.
Knowledge check
Where does a press's maintenance information live?
Knowledge check
Why are the seed's four repairs 3, 5, 4 and 8 hours over 8,000 operating hours?
References
- ISO 55001:2014 Asset management: management systems, requirements. https://www.iso.org/standard/55089.html
- ISO 14224:2016 Collection and exchange of reliability and maintenance data for equipment. https://www.iso.org/standard/64076.html
- SMRP: Society for Maintenance and Reliability Professionals. https://smrp.org/
- OSHA: 29 CFR 1910.147, The control of hazardous energy (lockout/tagout). https://www.osha.gov/laws-regs/regulations/standardnumber/1910/1910.147
- Limble: Fiix alternatives and core CMMS features. https://limblecmms.com/?p=26572
- Accendo Reliability: setting up the asset hierarchy (ISO 14224 levels). https://accendoreliability.com/setup-asset-hierarchy/
- Supabase CLI reference: supabase db push. https://supabase.com/docs/reference/cli/supabase-db-push
Chapter 2 · Session 3
Who may do what, and the screens
Rights to requests, work orders, plans and costs are decided once, in the role matrix, and the rules, the route list and the tests are generated from it. Then Claude Code builds the request screen behind a QR label, the technician's offline work screen, the planner's week and the reliability dashboard, and a technician and the planner try them.
25 min4 stepsSession 35 roles + machine accounts20 work orders offline
By the end of this chapter you can
- Add the module's roles, rights and screens to docs/matrix.json and regenerate the rules and tests.
- Have Claude Code build the screens with identity from the session, photos out of the project folders and costs hidden from those who do not need them.
- Prove the technician's offline screen syncs 20 completed work orders without loss, and watch a technician and the planner use the screens.
Rights start from nothing
Every role starts with no rights. Nobody deletes: a work order is cancelled, never removed, and a closed order never changes. Costs (rates, purchase and replacement costs) are read only by those who need them. Rights are enforced row by row by the database [1].
| Role (a job) | What they do |
|---|---|
| requester (anyone signed in) | Raise a request from a QR label or a phone, with a photo; see their own requests |
| technician | See work assigned to them; start, record tasks, measurements, labour and parts used; complete with a signature; offline |
| planner | Triage requests, plan and schedule work, job plans, PM schedules, crafts, spares; read costs |
| supervisor | Approve work, review failure coding, close or send back completed work, never their own |
| reliability engineer | Read everything at the site, failure codes, reliability views; propose PM interval changes |
| machine accounts | PM generator (makes PM work orders); meter feed (writes tag readings, via the plant connector) |
| Screen | Address | Who may open it |
|---|---|---|
| Request (behind each QR label) | /maintenance/request | anyone signed in |
| Technician's work, offline | /maintenance/work | technician |
| Planner's week | /maintenance/schedule | planner |
| Triage and closeout queue | /maintenance/queue | planner, supervisor |
| Reliability dashboard | /maintenance/reliability | reliability engineer, planner, supervisor |
| Sync (the technician's queue) | /api/maintenance/sync | technician |
Session 3: The module's rows in the matrix, and the rules generated from them
20 minutesWhy
One reviewed line in the matrix decides each right, and the database rules, the route guard and the tests all follow from it. Testing in both directions, and reading a row back after every allowed change, catches the mistakes we hit most: a role that can do too much, and an update that reports success and changes nothing.
Do this
Read docs/matrix.json, scripts/gen-policies.mjs, lib/access/routes.ts and docs/access-review.md. Never edit a generated file by hand.
On a new branch m05/access, add Maintenance to the matrix:
- Roles (jobs), reusing ours where they fit: requester (any signed-in person), technician, planner, supervisor, reliability engineer; machine accounts with named jobs only: PM generator (runs inside the database as a pg_cron job, so it never signs in) and meter feed (signs in with its own password, set by a person and listed by name in docs/KEYS.md; never the service role key).
- Rights, starting from nothing:
requester: insert cmms_work_request (requested_by from the session) with a photo; read their own requests.
technician: read work orders assigned to them and their tasks, job plans and spare links; update their own work order's status from scheduled to in_progress, on_hold (with a reason) and completed; insert tasks results, labour and parts used on their own work orders; insert their own core_e_signature; insert manual meter readings. No cost columns.
planner: triage requests; insert and update work orders up to scheduled; job plans, PM schedules, crafts, spare links; read costs.
supervisor: approve work orders; review failure coding; set completed work to closed, or back to in_progress with a comment; never on a work order assigned to them.
reliability engineer: read everything in the module at the site, including costs; insert and update failure codes.
PM generator: insert preventive work orders and update cmms_pm_schedule's next due fields. Meter feed: insert cmms_meter_reading with source tag.
Nobody deletes. A closed work order never changes.
- Screens: /maintenance/request, /maintenance/work, /maintenance/schedule, /maintenance/queue, /maintenance/reliability, and /api/maintenance/sync (technician).
Run scripts/gen-policies.mjs and scripts/gen-routes.mjs, then add to supabase/tests/access.test.sql one allowed and one refused test for every new cell, and: a technician cannot read cost columns; a technician cannot update another technician's work order; a requester cannot open /maintenance/work; nobody closes a work order assigned to them; another site sees nothing; for every role that updates a row, read it back and check it really changed.
Push, open a pull request titled "M05: who may do what", wait for every check, and tell me the result in plain words, quoting the new sections of docs/access-review.md.You will see recreated screen
- Rights by job, with the scope in the same line.
- A machine account is a role too, with the narrowest rights.
Check it worked
The pull request is green; docs/access-review.md has a section for each new role and machine account; the tests include cost, own-order, cross-site and read-back tests.
If it goes wrong
A technician's Complete says success but the status stays in_progress
An update only finds rows the role can read, and the changed row must still pass the read rule; we hit this building the module courses. Say: Make the technician's read rule cover their work order before and after completion, regenerate, and add a test that reads the row back.
A technician can see rates in the work screen
Column rights are easy to miss. Say: Serve technicians a view without cost columns, or column grants without them, regenerate, and add a test that a technician's read returns no cost column.
A check fails that names a generated list
The generated files are older than the matrix. Say: Open the failed check's log, run the command it names to regenerate, commit, and show me what changed.
Session 3: The request screen, the planner's week and the reliability dashboard
25 minutesWhy
A request that takes more than a minute to raise goes back to a text message with a photo. A QR label on each machine opens the request already pointing at it. Who raised it must come from the session on the server, and the photo must go to Supabase Storage, because the app's folders cannot be written on Vercel and anything in public/ can be opened by anyone.
Do this
Before writing any page or route, read the guides in node_modules/next/dist/docs/ for routing, server actions and proxy.ts in our version of Next.js, and our operator-screen rules from Session 12.
On a new branch m05/screens, build against the development data:
1. /maintenance/request?eq=<equipment code>: opened from a QR label, the machine already filled in; a description, a photo (private Supabase Storage bucket, never public/ or a project folder) and Send. Without eq, choose the machine from a list. Afterwards the requester sees their request's number and status.
2. A printable QR label page for every profile: machine code, name and the QR, pointing at https://acme-platform.vercel.app/maintenance/request?eq=<code>. The QR leads to sign-in like every page; it is not a public link.
3. /maintenance/schedule: the planner's week, work orders by craft against each craft's capacity_hours_per_week, overload shown in red.
4. /maintenance/queue: new requests to triage (accept, reject with a reason, mark duplicate, convert to a work order) and completed work to review.
5. /maintenance/reliability: laid out now with "No data" panels; Session 4 fills them from views.
Who is signed in comes from the session on the server, never from the page. Everything goes through proxy.ts and the generated lib/access/routes.ts. Playwright tests at 360 and 390 px for each role that may open each screen, a refused test for each role that may not, and a signed-out test that each lands on sign-in.
Push, open a pull request titled "M05: screens", wait for every check and the Vercel preview, and tell me the preview link and what each test proved.You will see recreated screen
- Words, not codes: coding happens at closeout.
- The photo goes to the private bucket.
- A number the requester can quote.
Check it worked
The pull request is green; a QR label from the preview opens the request screen for its machine after sign-in; a photo sent in the preview is in the Storage bucket, not the repository.
If it goes wrong
Photos save in development and vanish on the preview
The code wrote into a project folder, read-only on Vercel; we hit this when the maintenance register wrote where the server could not. Say: Store every photo in the private Supabase Storage bucket and add a test that fails if code writes into the project folders.
The QR opens the request without sign-in
Say: The request page is behind proxy.ts like every page; a QR label only fills in the machine. Add a signed-out test. A public page is a door for anyone with a phone at the fence.
Claude Code writes middleware.ts
This version of Next.js calls it proxy.ts. Say: Read node_modules/next/dist/docs/ on proxy.ts, use our proxy.ts, and delete middleware.ts.
Session 3: The technician's offline work screen, and the 20-order test
25 minutesWhy
Technicians work where the signal is worst: inside guards, behind presses, in the basement. The work screen must keep their jobs on the phone and send what they did when the signal returns, once each. The definition of done asks for 20 work orders completed offline to sync without loss, and we have had a save that said "created" and was later gone, so the tests are shown failing first.
Do this
On a new branch m05/work, build /maintenance/work, reusing the outbox from Session 12:
- On opening, it keeps the technician's assigned work orders with their tasks, limits and job plan on the phone (IndexedDB).
- Start, each task's result and measurement (flagged at once if outside lsl and usl), labour (start and end), parts used, and Complete with a signature (password confirmed again when back online) each go into the queue with an id made on the phone and the work order's row_version. The screen shows how many are waiting.
- /api/maintenance/sync applies each queued change in one transaction with on conflict (id) do nothing, takes the person from the session, keeps the phone's times and stamps the server's, and refuses a change whose row_version is stale (someone changed the order meanwhile), showing it on the phone. A refused change stays in the queue, visible.
- scripts/make-batch.mjs creates 20 synthetic scheduled work orders on JP-PRESS-PM for the test technician on the development project only (refusing any other project), and writes their 20 completions in the queue's format; a test-only button loads them into the queue and must not exist when VERCEL_ENV is production, read in one place only.
Playwright tests with the browser offline: complete three orders, close and reopen, the queue still shows them; go online, each order completed exactly once with its tasks, labour and times; send again, nothing changes; a stale change is refused and shown. Show each test failing with the on conflict line removed, then passing.
Push, open a pull request titled "M05: offline work screen", wait for every check, and tell me the result in plain words.You will see recreated screen
| # | Task | Result |
|---|---|---|
| 1 | Isolate and lock out | done |
| 2 | Clutch air pressure (5.5–6.5 bar) | 6.1 |
| 3 | Lubricate slide gibs | done |
- Nothing is lost while the count is on screen.
- A measurement outside its limits is flagged at once.
- Completion is signed; the server stamps its own time.
Check it worked
The pull request is green, and the summary says the tests failed with the safety line removed and passed with it.
If it goes wrong
The screen says "Completed" but the order is still in progress on the server
Say: Count a change as sent only when the sync route answered with its id; otherwise keep it in the queue and say so. Add a test with the route switched off. A button that claims success while nothing happens is worse than an error.
A planner rescheduled an order the technician was completing offline, and one change was lost
We hit this: a save said "Created" and a minute later the record was gone. Say: Refuse a change whose row_version is stale, keep it in the queue, and show both versions to the technician.
The test-only button appears on the live site
Say: Make it refuse to exist when VERCEL_ENV is production, read that flag in one place, and add a test that fails if any other file reads it. On our platform a demo switch left on made every visitor an administrator.
Session 3: Try it with a technician and the planner
20 minutesWhy
A screen that passes every test can still be wrong for a technician with greasy gloves inside a guard, or a planner who plans the week on a Friday afternoon. Twenty minutes watching each, without explaining, finds what the tests cannot.
Do this
https://github.com/acme-ops/acme-platform/pulls
Open the M05 screens and work screen pull requests: Vercel's comment on each has the preview link.
Print one QR label from the preview and stick it on a machine in the first area. On a real phone, scan it and send a request. Switch to airplane mode, complete a SYNTHETIC work order, reconnect and watch it arrive. Then give the phone to a technician and the schedule to the planner. Say nothing; write down every place either stops or asks. Then:
Here are my notes from a technician and the planner trying the M05 screens:
<paste your notes>
Write each as a one-line change request in docs/m05/try-out.md, marked screen, wording, or rule. Make the screen and wording changes on this branch with their tests; list the rule changes for me to decide. Push, wait for the checks, and tell me what changed.Owner two approves each pull request; merge in order: access, screens, work screen.
You will see recreated screen
| Craft | Planned | Capacity | |
|---|---|---|---|
| mechanical | 86 h | 80 h | over by 6 h |
| electrical | 31 h | 40 h |
- Overload shown, not hidden.
- Backlog in crew-weeks, the module library's measure.
Check it worked
A request from a QR label arrived; a work order completed in airplane mode arrived once; docs/m05/try-out.md lists what the technician and planner hit; the three pull requests are merged.
If it goes wrong
The preview link answers 401
That is Vercel's preview protection, not your code. Sign in to Vercel on the phone, or use Vercel's Share button.
The QR label will not scan in the press shop
Print it larger, on a matt label, and away from oil. Test it at the distance a person stands from the machine.
Knowledge check
A technician opens a work order. Which columns may they see?
Knowledge check
Why does each queued change carry the work order's row_version?
References
- Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
- Supabase Docs: Storage access control. https://supabase.com/docs/guides/storage/security/access-control
- MDN: IndexedDB API. https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
- Playwright: BrowserContext.setOffline. https://playwright.dev/docs/api/class-browsercontext#browser-context-set-offline
Chapter 3 · Session 4
The workflow, from request to reliability figure
A request is triaged into a work order that moves through ten statuses, cannot start without a permit reference when lockout is required, and cannot close without its four failure codes. Preventive maintenance is generated from calendar, meter and condition triggers, exactly once per crossing. Parts move through the ledger, calibrations record as found and as left, and the reliability measures must match a calculation you make yourself.
25 min4 stepsSession 410 statusesMTBF and MTTR by hand
By the end of this chapter you can
- Enforce the work order lifecycle in the database, with the lockout guard at the start and failure coding at the end.
- Generate preventive work from calendar, meter and condition triggers, one order per crossing, floating where work runs late.
- Move parts through the ledger, record calibrations with an out-of-tolerance trigger, and check the reliability views against a hand calculation.
Two guards: lockout at the start, coding at the end
Work that needs lockout/tagout, the control of hazardous energy under OSHA 1910.147 [2], cannot move to in_progress without a permit or lockout reference; the module library enforces it in the database when M11 is installed, and this build records the reference even without it. At the end, a corrective order cannot close without its failure mode, cause, mechanism and remedy from the ISO 14224 lists for its equipment class [1], reviewed by a supervisor.
Session 4: Requests become work orders; the lifecycle and its two guards
25 minutesWhy
The statuses are where maintenance gets lost: work started before isolation, work closed with "fixed it" and nothing else. Putting the allowed moves and the two guards in the database means no screen, import or agent can skip them. The second pitfall the module library names is free-text closeout with no failure coding; the guard at closeout prevents it.
Do this
On a new branch m05/lifecycle:
1. Triage: the planner accepts a request (converting it to a corrective work order linked both ways, number from core_number_sequence), rejects it with a reason, or marks it a duplicate of another; the requester is told each time (core_notification).
2. A trigger allows only these status moves on cmms_work_order: draft → awaiting_approval → approved → planned → scheduled → in_progress; in_progress ↔ on_hold (on_hold needs hold_reason_code_id); in_progress → completed (needs actual_start, actual_end and completion_signature_id); completed → closed (by a supervisor not assigned to it) or back to in_progress with a comment; any status before completed → cancelled with a reason. A closed order never changes.
3. Lockout guard: an order whose job plan has loto_required true cannot move to in_progress without permit_ref; when M11 is installed, permit_ref must point at an active permit.
4. Closeout guard: a corrective order cannot move to closed without failure_mode_id, failure_cause_id, failure_mechanism_id and remedy_id, each of the right code_type and for the equipment's class; the supervisor's queue shows the four codes beside the technician's notes for review.
5. A trigger writes cmms.work_request.created, cmms.work_order.status_changed and cmms.work_order.completed into core_event_outbox.
pgTAP tests for every allowed move and a refused example of each guard. Show the closeout test failing without the guard, then passing.
Push, open a pull request titled "M05: work order lifecycle", wait for every check, and tell me the result in plain words.Try it on the development project as in Step 5, then prove the closeout guard yourself:
https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new
The development project's SQL editor: paste the text below and Run. It must fail.
-- Development project only. Must be refused: a corrective order closed without its failure codes.
update public.cmms_work_order set status = 'closed', failure_mode_id = null
where wo_type = 'corrective' and status = 'completed';You will see recreated screen
| Key | Code |
|---|---|
| Failure mode | Low output (LOO) |
| Cause | Wear |
| Mechanism | Leakage |
| Remedy | Replace seal |
- Four keys from the press class's lists: countable in a Pareto.
- Closed by a supervisor who was not assigned to it.
Check it worked
The update in the development SQL editor is refused; the lifecycle tests are green and the closeout test was shown red without the guard.
If it goes wrong
Technicians pick "other" for every code
The lists are too long or wrong for your presses. With the reliability engineer, cut each list to what your class really fails by, from the last year's history, and add the change as a new migration of codes. Review the coding weekly for a month.
An urgent repair cannot start: no permit reference
That is the guard working. The permit is issued by the people who own lockout (M11, or your paper permit); record its number. Never weaken the guard to get a job started.
Session 4: Preventive maintenance: one order per crossing, with a 90-day forecast
25 minutesWhy
The first definition-of-done test is that a meter reading crossing a threshold generates exactly one PM work order. Meter feeds repeat readings and the engine runs every few minutes, so without a database rule a single crossing makes three orders. The third pitfall the module library names is fixed dates when work runs late; floating schedules count from completion instead.
Do this
On a new branch m05/pm:
1. A function cmms_generate_pm(), run every 15 minutes by pg_cron (Supabase Cron) as the PM generator: for each active schedule, calendar: due when now() + lead_days reaches next_due_at; meter: due when the latest reading reaches next_due_meter; condition: due when condition_rule holds on the meter or tag; hybrid: whichever comes first. It inserts one preventive work order with the job plan's tasks copied in, relying on the partial unique index on pm_schedule_id (insert ... on conflict do nothing), and writes cmms.pm.generated to core_event_outbox only when a row was really inserted.
2. On completion of a PM order: floating schedules set next_due_at from actual_end (or next_due_meter from the reading at completion); fixed ones from the previous due date; last_completed_at is set.
3. Meter readings: manual on the work screen, or source tag from the plant connector via the meter feed account; a reading outside alert_low or alert_high raises a work request with source scada.
4. A view cmms_pm_forecast (security_invoker = true) of every PM due in the next 90 days, for the planner's week.
Tests: a reading crossing 500 cycles makes exactly one order; the same reading again, a higher reading and three runs of the function still make one; completing it 10 days late moves a floating schedule 30 days from completion and a fixed one 30 days from the due date; the forecast lists the seed's two schedules.
Push, open a pull request titled "M05: PM engine", wait for every check, and tell me the result in plain words.Try it on the development project, merge after owner two approves, and check the job is scheduled in production:
https://supabase.com/dashboard/project/abcdefghijklmnopqrst/integrations/cron/jobs
Production: Integrations, Cron. The PM job is listed, every 15 minutes, with its last run.
You will see recreated screen
- The partial unique index, not the code's care, keeps it to one.
- Floating and fixed, exactly as drawn above.
Check it worked
The tests show one order per crossing and the floating and fixed dates as drawn; the PM job is listed in production's Cron page after the merge.
If it goes wrong
Three PM orders for one crossing
Say: Insert PM orders with on conflict do nothing against the partial unique index on pm_schedule_id, and announce cmms.pm.generated only when a row was inserted. Test three engine runs.
PMs pile up after a late month
The schedules are fixed. With the planner, decide which tasks are tied to time since the last service (floating: lubrication, filters) and which to the calendar (fixed: statutory inspections), and set each schedule's floating flag.
Session 4: Parts through the ledger, and calibration as found and as left
20 minutesWhy
A spare's count changed by hand in a maintenance table is how stores and maintenance end up with two different numbers. Every issue and return is a ledger movement, and the balance is computed. Calibration needs both readings: as found says whether product measured since the last calibration may be wrong, so an out-of-tolerance result must open an impact assessment.
Do this
On a new branch m05/parts-calibration:
1. Parts: planning a part on a work order sets qty_planned; issuing it writes an issue movement to the inventory ledger (M12, or our minimal ledger) and stores its id in inventory_txn_ref; a return writes a return movement. qty_used comes from the movements. The balance per item and location is computed from the ledger; a balance below reorder_point on a cmms_spare_part_link raises one notification to the planner, critical spares first.
2. Calibration: a calibration work order records as_found, as_left and tolerance (JSON per point), the reference standard (an equipment row) and the certificate; the result is computed: pass if as found is in tolerance, adjusted_pass if as found was out but as left is in, out_of_tolerance if as left is out. Any as found outside tolerance writes cmms.calibration.out_of_tolerance to core_event_outbox and opens an impact assessment: in M08 if installed (impact_assessment_ref), otherwise a core_action_item for the quality lead listing what was measured with the instrument since its last good calibration.
Tests: issuing 2 and returning 1 leaves qty_used 1 and the balance down by 1; a balance below reorder point notifies once; as found out and as left in gives adjusted_pass and one impact assessment; the result cannot be typed by hand.
Push, open a pull request titled "M05: parts and calibration", wait for every check, and tell me the result in plain words.You will see recreated screen
| Point | As found | As left | Tolerance |
|---|---|---|---|
| 50 mm | 50.012 | 50.002 | ± 0.005 |
| 100 mm | 100.009 | 100.003 | ± 0.005 |
- Both readings kept: as left proves the gauge is good now, as found says whether it was good before.
- Computed, not chosen, and the quality lead is told what to check.
Check it worked
The tests are green: parts move only as ledger movements, the reorder notice comes once, and an out-of-tolerance as found opens exactly one impact assessment.
If it goes wrong
Stores and maintenance show different counts
Something changed a quantity outside the ledger. Say: Find every place that writes a stock quantity directly, replace it with a ledger movement, and add a test that fails on any direct write.
Every calibration comes back pass
Check the result is computed from as found, not as left. Say: Show me the rule that sets result, and test a case where as found is out and as left is in.
| Measure | Definition | On the fixture |
|---|---|---|
| MTBF | Operating time ÷ number of failures, per asset or class | 8,000 h ÷ 4 = 2,000 h |
| MTTR | Total repair time ÷ number of repairs | (3 + 5 + 4 + 8) h ÷ 4 = 5 h |
| PM compliance | PM orders completed within their window ÷ PM orders due | From the PM history, once there is one |
| Schedule compliance | Scheduled hours worked as scheduled ÷ scheduled hours | From the planner's week |
| Planned vs reactive | Planned maintenance hours ÷ total maintenance hours | From labour |
| Backlog | Estimated hours of ready backlog ÷ weekly craft capacity | In crew-weeks |
| Cost as % of RAV | Maintenance cost ÷ replacement asset value | From labour, parts and profiles |
Session 4: The reliability views, checked against your own calculation
20 minutesWhy
The definition of done asks that MTBF and MTTR on the made-up history match a spreadsheet calculation. A measure nobody can reproduce is a measure nobody should trust; we have shipped a chart that drew twelve hard-coded points and called them "In control". Every panel says where its number comes from and shows "No data" rather than a number nobody measured.
Do this
First, work MTBF and MTTR out yourself in a spreadsheet from the fixture: four closed repairs and the running-hours readings, with fixed dates:
https://github.com/acme-ops/acme-platform/blob/main/tests/fixtures/m05-reliability.json
The hand-worked example on GitHub: actual_start and actual_end of each repair, and the meter readings.
On a new branch m05/reliability, create views with security_invoker = true and fill /maintenance/reliability from them: cmms_v_mtbf and cmms_v_mttr per asset and class; cmms_v_pm_compliance; cmms_v_schedule_compliance; cmms_v_planned_reactive; cmms_v_backlog in crew-weeks; cmms_v_cost_rav; cmms_v_bad_actor (assets ranked by failures and downtime); cmms_v_failure_pareto by class and failure mode. Use the definitions in the module library: MTBF = operating time from the running-hours meter ÷ failures; MTTR = sum of actual_end − actual_start ÷ repairs. Each panel says which view and definition it uses, and shows "No data" when there is none, never 0 for unknown. Add a test on tests/fixtures/m05-reliability.json expecting MTBF 2000 hours and MTTR 5 hours for the first press, and the shared failure mode first in the Pareto. Push, open a pull request titled "M05: reliability", wait for every check and the preview, and tell me the figures the dashboard shows on the development data.You will see recreated screen
| Failure mode (press) | Failures |
|---|---|
| Low output | 2 |
| Abnormal noise | 1 |
| Fail to start | 1 |
- The same as your spreadsheet.
- Repair time from actual start and end, not from downtime.
- No PM history yet: says so, never 0.
Check it worked
Your spreadsheet and the dashboard agree exactly: MTBF 2,000 hours and MTTR 5 hours for the first press; the shared failure mode leads the Pareto. Then merge.
Fastest path
Calculate first, then read the dashboard: reading it first makes it too easy to calculate your way to its answer.
If it goes wrong
The dashboard says MTTR 6.3 hours
Fix the view, not the spreadsheet. Say: MTTR shows 6.3; my calculation from actual_start and actual_end is 5.0. Show me the rows and the formula you used. Usually downtime minutes were used instead of repair time, or a cancelled order was counted.
The test expects figures the fixture never makes
We found this in reviews of five Academy modules. Say: For every figure this test expects, show me the fixture rows that create it. Fix the fixture, not the test.
A view shows another site's work orders
A view runs with its owner's rights unless security_invoker is on. Say: Recreate every cmms_v_ view with security_invoker = true and test a reader from another site.
Knowledge check
A meter reading crosses 500 cycles, then the feed repeats it and the engine runs three times. How many PM work orders are made?
Knowledge check
A 30-day PM due on day 30 is done on day 40. On a floating schedule, when is it next due?
References
- ISO 14224:2016 Collection and exchange of reliability and maintenance data for equipment. https://www.iso.org/standard/64076.html
- OSHA: 29 CFR 1910.147, The control of hazardous energy (lockout/tagout). https://www.osha.gov/laws-regs/regulations/standardnumber/1910/1910.147
- ISO/IEC 17025:2017 General requirements for the competence of testing and calibration laboratories. https://www.iso.org/standard/66912.html
- Supabase Docs: Cron. https://supabase.com/docs/guides/cron
- PostgreSQL Documentation: Partial indexes. https://www.postgresql.org/docs/current/indexes-partial.html
- Fabrico: ISO 14224 failure taxonomy codes. https://www.fabrico.io/blog/iso-14224-failure-taxonomy-codes/
Chapter 4 · Sessions 5–6
Move the old CMMS in, and switch it off
The old system's assets are matched to equipment rows first, then its PM plans, open work and parts are moved, and its closed work orders arrive as history. The import is rehearsed on the development project, then run into production through the pipeline with counts that must match. You run old and new side by side, prove 20 work orders offline on a real phone, cut over on a written date, and cancel the old subscription with the saving from real invoices.
25 min4 stepsSessions 5 and 6Assets matched firstCounts must match
By the end of this chapter you can
- Build the CMMS import as reviewed code that matches assets to equipment first and never creates a second tree, and rehearse it on the development project.
- Prove the module side by side for a week and on a real phone with 20 work orders offline.
- Import the old data into production through the pipeline after a backup, cut over, and record the saving.
The module library gives the order: export assets, PMs, work orders and parts (Fiix, MaintainX, Limble and UpKeep offer CSV or API export [3]); map asset ids to spine equipment codes first; then import closed work orders as history. History is evidence: closed orders arrive closed and cannot change, with their dates, and are never counted as new work. Open orders and active PM plans arrive as live work for the planner to confirm.
| Key or secret | What it unlocks | Where it lives | Who holds it | Never |
|---|---|---|---|---|
| Meter feed's password | The machine account that writes tag meter readings, nothing else | Where the plant connector runs (Session 20), set by a person; listed by name in docs/KEYS.md | pat@acme.com, sam@acme.com | Never the service role key; never in a chat or a file |
| Old CMMS login or API token | Taking the export from the old system | The old system; the export goes to a private folder | The person taking the export | Never given to Claude Code, never stored in the repository |
Session 5: Build the import, and rehearse it on the development project
35 minutesWhy
An import that creates equipment rows for anything it cannot match is a second asset tree by the back door. This one matches each old asset to an equipment row first, and lists every asset it cannot match instead. Building it as reviewed code, run from main by a workflow with an insert-only account, means real records reach production only through the pipeline, never through a laptop or a chat; a rehearsal with a copy IT approved in writing finds the mapping problems first.
Do this
Take the export yourself from the old system's own export page, into a private folder outside the repository. Claude Code never reads it. Give it the first line of each file only, the column names:
We will move the old CMMS in. The export files stay outside the repository and you will not read them. The first line of each, the column names only:
assets: <first line of the assets export>
pm plans: <first line of the pm plans export>
work orders: <first line of the work orders export>
parts: <first line of the parts export>
On a new branch m05/import:
1. scripts/import-m05.mjs, which reads the export files in this format and in this order: (a) assets: matches each old asset to our equipment row by code, using docs/cmms/first-area.md's mapping and the same rule elsewhere, and creates its cmms_asset_profile with the old id in ext.legacy_id; it never creates an equipment row; (b) PM plans: to cmms_pm_schedule on matched equipment, a job plan per distinct procedure, active false until the planner confirms; (c) work orders: closed ones as cmms_work_order with status closed, their dates, tasks, labour and parts used, ext.origin 'import' and the old number in ext.legacy_number, failure text in completion_notes and codes only where they map exactly; open ones as approved, for the planner; (d) parts: spare part links on matched equipment, and opening stock as one ledger movement per item and location. Every imported row carries ext.origin 'import'. Rows it cannot match are not imported but listed with the reason. It prints each file's sha256 and the counts: rows, records it would create, rows skipped. In dry-run mode it writes nothing.
2. A migration that creates this module's import account: a database role import_m05 that can log in, with insert only on cmms_asset_profile, cmms_job_plan, cmms_pm_schedule, cmms_work_order, cmms_wo_task, cmms_wo_labor, cmms_wo_part, cmms_spare_part_link and the ledger and on an insert-only table import_log (module, file, sha256, counts, run_at, run_by), read on the private Storage bucket imports, and nothing else: no update, no delete, never the service role key. Imported closed orders are protected by the closed-order trigger. A file whose sha256 is already in import_log is refused.
3. .github/workflows/import-m05.yml, started only by hand from main (workflow_dispatch), with inputs target (development or production), file (its path in the bucket imports) and apply (default false). It downloads the file from the target project's bucket, signs in as import_m05 with a password a person stores as a GitHub secret (IMPORT_M05_PASSWORD_DEV and IMPORT_M05_PASSWORD_PROD, listed by name in docs/KEYS.md), and runs the script. For production with apply true it refuses unless docs/imports/m05-approved.md on main lists this file's sha256 and expected counts, and it fails on any count mismatch. It never prints a row of the export.
4. Tests on a made-up ten-row file per export (SYNTHETIC values): a dry run writes nothing; apply creates the expected counts; the same file again is refused; an unknown asset is listed and no equipment row is created; an imported closed order cannot change; import_m05 cannot update or delete anything.
Do not run the workflow and do not set any password. Push, open a pull request titled "M05: import", wait for every check, and tell me the result in plain words, with the secrets I must create myself.Try it on the development project and merge it, as in Step 5. Then a person creates the import account's password in the password manager, sets it on each project in the SQL editor, and types the same value as the GitHub secret. Nobody pastes it into Claude Code or a file.
-- Typed by a person, once per project. The password comes from the password manager.
alter role import_m05 with login password '<from the password manager>';https://github.com/acme-ops/acme-platform/settings/secrets/actions
Add IMPORT_M05_PASSWORD_DEV and IMPORT_M05_PASSWORD_PROD: paste the value only, never NAME=value.
| Key or secret | What it unlocks | Where it lives | Who holds it | Never |
|---|---|---|---|---|
| import_m05 password (one per project) | Inserting imported records into this module's tables, nothing else | GitHub Actions secrets, and the password manager | pat@acme.com, sam@acme.com | Never in a chat, a file or a log; set to NOLOGIN at cut-over |
The rehearsal uses a copy of the export that IT has approved in writing for the development project, redacted where it holds personal, injury or pay data. It is the only real data a development project ever holds, and it is removed the same day.
https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/storage/buckets
Development project, Storage: upload the approved copy to the private bucket imports.
https://github.com/acme-ops/acme-platform/actions/workflows/import-m05.yml
Run workflow from main: target development, the file's path, apply false. Read the counts; then again with apply true.
Open three imported work orders beside the same three in the old system: dates, tasks, labour and parts must match. Decide with the planner about every unmatched asset. Then, the same day, remove the rehearsal from the development project: delete the file from the bucket, and run:
-- Development project only, the same day: remove the rehearsal's real records.
delete from public.cmms_wo_task where work_order_id in (select id from public.cmms_work_order where ext->>'origin' = 'import');
delete from public.cmms_wo_labor where work_order_id in (select id from public.cmms_work_order where ext->>'origin' = 'import');
delete from public.cmms_wo_part where work_order_id in (select id from public.cmms_work_order where ext->>'origin' = 'import');
delete from public.cmms_work_order where ext->>'origin' = 'import';
delete from public.cmms_pm_schedule where ext->>'origin' = 'import';
delete from public.cmms_spare_part_link where ext->>'origin' = 'import';
delete from public.inv_inventory_transaction where ext->>'origin' = 'import'; -- or M12's ledger table
delete from public.cmms_asset_profile where ext ? 'legacy_id';
delete from public.import_log where module = 'm05';On a new branch m05/rehearsal, write docs/imports/m05-rehearsal.md: the date of IT's written approval and who gave it (a job, not a name), what was redacted, the rehearsal's counts and skipped rows from the run log below, the three records checked, and the date the copy was removed from the development project:
<paste the counts and the dates>
Open a pull request titled "M05: rehearsal record", wait for the checks, and show me the link.You will see recreated screen
assets 214 rows 198 profiles 16 skipped (no equipment row) pm plans 58 rows 55 schedules 3 skipped (asset skipped) work orders 3,940 rows 3,902 closed, 37 open, 1 skipped parts 611 rows 584 links, 584 opening movements sha256 per file printed above
- Every skipped row has a reason. Fix the mapping, or decide to leave them out, and write which.
- Read before you apply.
Check it worked
The import is merged; the import account's password is set on both projects and in GitHub secrets, by a person; the rehearsal ran dry, then applied, with every skipped row explained and no equipment row created; three work orders matched the old system; the copy was removed the same day and docs/imports/m05-rehearsal.md records it.
If it goes wrong
Claude Code asks to read the export "to get the mapping right"
Say no. Give it the column names and, if needed, a made-up row you write yourself. Real records reach the platform only through the import workflow.
IT will not approve a copy in writing
Then no real data goes to the development project. Rehearse with a made-up file in the same columns (Claude Code can write one from the header), and keep the first production run a dry run. Write the decision in docs/imports/m05-rehearsal.md.
The workflow cannot sign in as import_m05
The password on the project and the GitHub secret differ, or the secret holds NAME=value. Set both again from the password manager, value only. Never give the import account more rights to get past it.
Claude Code proposes creating equipment rows for unmatched assets
Say no: Never create equipment from the import. List them; I will decide with the planner, and any that are real get added to equipment through a reviewed migration.
Session 6: Run side by side, and prove 20 work orders offline on a real phone
30 minutes, after a week of running bothWhy
The module is ready to replace the old CMMS only when both handled the same week and every difference is explained. The definition of done also asks for 20 work orders completed offline to sync without loss, the test that matters most to a technician inside a guard with no signal.
Do this
For one week, the first area's work runs both ways: the old system stays the record, and the planner and technicians also work on the platform. At the end, count the old way from its own reports and read the same from the dashboard. Then:
On a new branch m05/cutover, write docs/cutover.md with a side-by-side table for the week of <dates>: requests raised, work orders completed, PM orders due and completed in their window, open backlog hours, one column from the old system's reports (named) and one from the platform:
Old system (<report names>): <your counts>
Explain every difference in one line, or mark it "not explained". Add the definition-of-done checks with the query and its result on production: no corrective order closed without four codes; no PM schedule with two open orders; every LOTO-required order that started has a permit reference. Then the cutover date, who tells the technicians and requesters, when the old system's QR labels and links come down, where the old exports are kept and by whom, and the way back: if the platform is down, a paper work order, entered within 24 hours with the reason. Do not change any data. Open a pull request titled "M05: side by side and cutover", wait for the checks, and show me the link.Then the 20-order test on a real phone, on the development preview: airplane mode; load the 20 synthetic completions with the test-only button; reconnect. In the development project all 20 must be completed exactly once, with their tasks, labour and times. Force a second send: still 20.
https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/editor
Count the batch's work orders with status completed: 20, not 19, not 40.
You will see recreated screen
- The QR labels caught the requests that used to arrive by text.
- The module's guards, proven on production by query.
Check it worked
docs/cutover.md has no "not explained" line; the checks pass on production; the phone test completed 20 of 20, once each.
If it goes wrong
The phone test completes 19, or 40
Do not cut over. Say: The 20-order offline test stored <n>. Find which change was lost or doubled from the queue ids, and add a test that would have caught it.
A difference cannot be explained
You are not ready. Run another week, and ask the planner to watch the work that differs.
Session 6: Import into production through the pipeline
20 minutesWhy
Real records go into production once, through reviewed code, after a backup, from a file whose fingerprint and counts owner two approved in the repository. The workflow refuses any other file and fails on any count mismatch, and the import account can only insert, so nothing already there can be changed by it.
Do this
https://github.com/acme-ops/acme-platform/actions
First, run the nightly backup workflow from Session 11 by hand (its Run workflow button) and wait for it to finish green.
https://supabase.com/dashboard/project/abcdefghijklmnopqrst/storage/buckets
Production, Storage: upload the full export to the private bucket imports.
https://github.com/acme-ops/acme-platform/actions/workflows/import-m05.yml
Run workflow from main: target production, the file's path, apply false. Copy the sha256 and the counts from the log.
On a new branch m05/import-approval, write docs/imports/m05-approved.md: today's date, the source (the old system's name and the export's date), and for each file its path, its sha256 and the expected counts exactly as in this dry-run log, with the skipped rows' reasons as a list, and the open work orders and PM plans that will arrive for the planner to confirm:
<paste the sha256 and counts from the run log>
Open a pull request titled "M05: approve the import", wait for the checks, and show me the link.The planner confirms the open work and PM plans; owner two approves; merge. Afterwards the planner activates each PM schedule after checking its next due date. Then run the workflow again from main: target production, the same file, apply true.
You will see recreated screen
profiles 198 · schedules 55 (inactive) · closed orders 3,902 · open 37 spare links 584 · opening movements 584 import_log: m05, 4 files
- The approval is a file on main that owner two approved.
- The same numbers, or the run fails.
Check it worked
The backup ran green first; docs/imports/m05-approved.md is on main; the production counts equal it; an imported closed order opens read-only and a change is refused; the planner has activated the PM schedules.
If it goes wrong
The workflow refuses: sha256 not in the approved file
The file in the bucket is not the one you approved, often a second export taken later. Do not edit the approved file to match. Upload the approved file, or dry-run the new one and approve it in a new pull request.
The run fails: counts do not match
Nothing was imported: the run is one transaction. Ask Claude Code: The m05 import failed on a count mismatch. Show me which count differs and why, from the log, without running anything.
The backup workflow has no Run workflow button
Say to Claude Code: Add workflow_dispatch to the nightly backup workflow so a person can run it before an import. Merge that first. A backup nobody has restored is only a hope: Foundation Session 23 drills the restore.
PM orders flood in the moment schedules are activated
Imported next due dates were in the past. Deactivate them, and with the planner set each schedule's next due date from its last completion, then activate them a few at a time.
Session 6: Cut over, and cancel the old CMMS
15 minutesWhy
Cutting over on the written date means nobody is unsure which system holds the work. The saving is real only when it comes from the old invoices and the vendor's own terms, so the subscription is cancelled after the data is safely imported, and the arithmetic is written down.
Do this
On the date: requesters and technicians are told, the old system's QR labels and links come down, the platform's labels go up on every machine of the area, and the planner plans the next week on the platform. Read the old vendor's cancellation terms on its own account page (notice period, renewal date, seats, how long you can still export). Then:
On a new branch m05/saving, add to docs/cutover.md: the old CMMS's bill, seats, renewal date and notice period exactly as I give them below, the date it is cancelled or ends, and the saving with its arithmetic: the old cost minus what the module adds to our running costs (none: it runs on the services we already pay for). Mark the area as cut over in docs/cmms-inventory.md with the date. Add a new migration that sets the import account import_m05 to NOLOGIN, now that the import is done.
Old bill and terms: <from your invoice and the vendor's account page>
Open a pull request titled "M05: saving", wait for the checks, and show me the link.You will see recreated screen
- Every figure points at the document it came from.
- One area cut over; others follow the same steps before the plan ends.
Check it worked
The first week's work was planned and done on the platform; docs/cutover.md has the saving with its arithmetic; the old CMMS is cancelled or its end date recorded; after the merge, import_m05 can no longer sign in.
If it goes wrong
Other areas still use the old system
Move them before the plan's end date, the same way: map their assets, rehearse, import. Write each area's date in docs/cmms-inventory.md.
Finance needs the old system's cost history
Keep the full exports in the agreed private place for as long as your records policy says, and note where in docs/cutover.md. The imported closed orders keep their labour and parts.
Knowledge check
The import finds an old asset that matches no equipment row. What does it do?
Knowledge check
How do the old system's closed work orders arrive?
References
- GitHub Docs: Manually running a workflow. https://docs.github.com/en/actions/managing-workflow-runs-and-deployments/managing-workflow-runs/manually-running-a-workflow
- Supabase Docs: Storage buckets. https://supabase.com/docs/guides/storage/buckets/fundamentals
- PostgreSQL Documentation: CREATE ROLE (LOGIN, NOLOGIN). https://www.postgresql.org/docs/current/sql-createrole.html
- GetApp: MaintainX against Limble (modules). https://www.getapp.ca/compare/117239/2049215/getmaintainx/vs/limble-cmms
- Supabase Docs: Database backups. https://supabase.com/docs/guides/platform/backups
Chapter 5 · 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
Maintenance (CMMS): Work Orders, Preventive Maintenance and Reliability on One Asset Tree
Element M05 complete · Learner
Your LMS records this completion. For the CivOps Foundation certificate, finish the Foundation Course at https://civops.io/learn.