Chapter 1 · Sessions 1–2
What the old tool holds, and the tables that replace it
A manufacturing execution system (MES) makes the plan happen on the floor and writes down what really happened. Session 1 finds out what yours does and costs, from its own reports and bills. Session 2 adds the fifteen mes_ tables to your Foundation platform, keyed to the equipment, items, lots and people you already have, with the tests that prove the database refuses bad rows.
30 minAbout 7 hours hands-on across six sessionsSessions 1–2: 5 steps15 tables
By the end of this chapter you can
- Inventory the MES you pay for today from its own reports and bill, and run three tests on it in numbers.
- Map the module onto your Foundation spine so it never builds a second equipment list.
- Have Claude Code write the fifteen tables, the course's rules, the tests, a seed shifted onto today and the hand-worked shift as a test fixture in one pull request, and try them on the development project yourself.
Execute, enforce, record
An MES defines how products are made, dispatches orders to work centres, guides operators step by step, checks materials and qualifications, collects data from machines and people, builds the genealogy of every lot, captures downtime and OEE, and reports performance to the ERP. Three verbs cover it: execute the work, enforce the rules while it is done, and record what happened in a form nobody can quietly change. Tools in this class include Rockwell Plex and FactoryTalk ProductionCentre, Siemens Opcenter Execution, Critical Manufacturing, AVEVA MES, Dassault DELMIA Apriso, Parsec TrakSYS, Tulip and Sepasoft on Ignition.
ISA-95, published internationally as IEC 62264, divides a manufacturer into levels [1][2]. The ERP is at Level 4 and the machines and their controls are below. The MES sits at Level 3: it takes the schedule from above, turns it into work on the floor, and sends what was done back up. The standard's five parts give the object models (Parts 1 and 2), the Level 3 activity model (Part 3), the information flows (Part 4) and the business-to-manufacturing transactions (Part 5) [3].
The MESA model lists eleven functions an MES covers: resource allocation, scheduling, dispatching, document control, data collection, labour, quality, process management, maintenance, genealogy and performance analysis [4]. It is a checklist, not a design: Session 1 uses it to find out which of the eleven your plant does today, with what, and who does them.
| Standard | What the module takes from it |
|---|---|
| ISA-95 / IEC 62264 Parts 1 to 5 | Equipment and material models, the Level 3 activity model, information flows, B2M transactions |
| MESA-11 | The eleven-function checklist for Session 1's inventory |
| B2MML (MESA) | The message shapes for the ERP exchange in Session 4 |
| ISA-88 / IEC 61512 | Batch recipes: procedure, unit procedure, operation, phase; master and control recipes |
| ISO 22400-2 | OEE, availability, effectiveness, quality ratio, on one time base |
| ISA-TR88.00.02 (PackML) | The machine state model the module maps to its nine states |
| OPC UA (IEC 62541), Eclipse Sparkplug B | How machine values reach the tag registry |
| 21 CFR 211.188, 211.192; 21 CFR 820; 21 CFR Part 11 | Batch and device history records and electronic signatures, where regulated |
Session 1: Inventory the MES you pay for, from its own reports and bill
35 minutesWhy
The module must replace something real, not a guess. A number you read from the tool's own report or invoice can be checked by anyone; a number from memory is the first thing a finance lead or an auditor will knock down, and every later saving rests on it. Writing the inventory into the repository also gives Claude Code the facts it needs in Session 2 instead of inventing them.
Do this
First, on the floor and in the tool, gather: one routing (printout or screenshot), one finished order with its history, the tool's lot trace report if it has one, and its account or billing page. Ask the supervisor before you copy anything, and leave operator and customer names out of everything you save. Then:
cd ~/code/acme-platform && git switch main && git pull && claudeOn a new branch mes/inventory, create docs/mes-inventory.md for Acme Bottling, site Cleveland (cle), as a form I will fill in from the old MES's own reports and invoices. Do not invent any number, name or price: where I have not given one, write "not known: ask <role>".
Sections:
1. Every place production is recorded on the line I choose (MES, ERP shop-floor screens, historian or HMI, spreadsheets, whiteboard, paper traveller, label printer): who enters, who reads, how often.
2. Paid tools: name, owner, named users, how people sign in, the amount and what it covers as printed on the invoice, renewal date, notice period, which exports it gives (routings, orders, genealogy) and how long history stays readable after cancelling.
3. The equipment tree in ISA-95 words (site, area, work centre, work unit), with the tool's code and our Foundation equipment code side by side, so any machine with two names stands out.
4. Materials: raw, intermediate, finished, consumable, packaging; which are lot-controlled; how a lot number is made; where lots are split, mixed or reworked.
5. The eleven MESA functions, one row each: who does it today (tool, person, paper), and where it will live: this module (resource allocation, dispatching, data collection, labour, process management, genealogy, performance analysis), M03 (scheduling), M05 (maintenance), M06 (document control), M08 or M09 (quality).
6. Counts, each with the report it came from: active routings, operations, parameters with limits, orders a week, lots a week, years of genealogy kept.
7. Interfaces: ERP messages each way; how machine values arrive (OPC UA, MQTT Sparkplug B, Ignition, typing); printers, scales, file drops.
8. Three tests (I will run them): trace, OEE, interlock.
9. Workarounds, in the users' own words.
10. The first scope: one line or two to five work centres in one area, one or two products, and why.
Then ask me for each section in turn and write my answers in. Open a pull request titled "MES inventory" when I say it is complete.You will see recreated screen
- Prices and counts start as "not known": a gap you can see is better than a figure nobody can trace.
- Two codes for one press: this is the second equipment list the module must not build. Note both.
Check it worked
docs/mes-inventory.md has every section filled from a report, an invoice or a named person, and each number says where it came from. Nothing reads like an estimate.
Fastest path
Fill sections 2 and 6 from the vendor's account page and the tool's standard reports in one sitting: they are where most "not known" answers come from, and one hour with the right login saves a week of emails.
If it goes wrong
Claude Code fills in a price or a user count I never gave it
Say: Remove every number I did not give you and write "not known: ask <role>" instead. Every number in this file must name its source. An invented figure in an inventory becomes an invented saving in Session 6.
I cannot see the bill
Write who can (finance, IT purchasing) and ask them for the invoice and the contract's renewal and notice clauses. Do not guess: the saving in Session 6 is calculated from this invoice.
The tool has no trace or OEE report
That is a finding. Write "not measured" and how long the manual way takes; the three tests below measure it.
Session 1: Run three tests on today's system, and choose the first scope
25 minutesWhy
The module's definition of done is three tests: trace a lot in under a second, stop an unqualified operator, and match OEE to a hand calculation. Running the same three on the old way today gives you the baseline the new way must beat, in numbers, and shows the people on the floor what the change is for.
Do this
Trace test. Pick a finished lot from last month; time how long it takes to list every raw-material lot in it, then pick one raw lot and time listing every finished lot that used it. Note anything that needed a phone call.
OEE test. Pick one machine and one shift; work out OEE by hand from the stop log and counts (share of planned time it ran × speed against ideal × share of good units). Compare with the tool's figure, write which time base the tool uses, and whether stops of a minute or two are recorded at all.
Interlock test. Ask what stops an operator without the training from starting an operation, a lot on hold from being used, and a step done out of order. Write the answers word for word, including "nothing" and "the supervisor remembers".
Add the three test results I give you below to section 8 of docs/mes-inventory.md, as numbers with units and the source of each, and the first scope to section 10. Then open the pull request "MES inventory", wait for the checks to finish, and tell me the result in plain words.
Trace test: <paste>
OEE test: <paste>
Interlock test: <paste>
First scope and why: <paste>Have the supervisor and the process engineer read the scope in the pull request; owner two approves and it merges.
You will see recreated screen
| Test | Today | Source |
|---|---|---|
| Trace back, lot FG-2291 | 47 min, 2 phone calls | Trace report + stores |
| OEE, press 4, 3 Sept day shift | Tool 81%; by hand 74% | Stop log, counter |
| Expired qualification | Nothing stops it | Supervisor |
- Numbers with units and a source. A tool figure that differs from the hand figure usually means a different time base.
- The scope names people who have read it.
Check it worked
docs/mes-inventory.md is merged on main, with the three tests in numbers, a bill and renewal date for each paid tool, and the first scope read by the supervisor and the process engineer.
If it goes wrong
The tool's OEE and my hand OEE differ
Do not pick one. Write both and the tool's time base (whole shift, or shift less breaks). Session 4 fixes one time base for every figure, and Session 6 compares against your hand figure, not the tool's.
Claude Code says the checks passed but the pull request shows a red check
Say: The check on the pull request is red. Run gh pr checks, read the failed log, fix it and wait for green before you report. We trust the check on GitHub, never the summary. A documentation-only change usually fails on the name check (Session 4): the log says which name.
Fifteen tables on your spine
How production is stored decides what you can ever ask of it. Five tables say how a product is made, three say which order is made where and how well, and seven keep what happened. The module has no item master, machine list, lot table or people table of its own: its keys go to the shared spine tables the module library calls core_item, core_equipment, core_lot, core_person and core_shift_instance, and to core_e_signature, core_uom, core_data_tag, core_reason_code, core_attachment, core_site and core_serial_unit. Some already exist in your Foundation under another name: your equipment table is the spine's core_equipment. Step 3 writes that map, so nothing is built twice.
Every table also has the module library's standard columns, with site_id in place of the library's tenant_id: id, site_id, created_at, created_by, updated_at, updated_by, row_version, archived_at and ext. Types: text, int, num (decimal), qty (a quantity, kept with its unit in a uom_id column), bool, ts (timestamp with time zone), uuid and json (jsonb). An arrow is a foreign key, req means required, and a list after a colon is the allowed values.
Definitions: how a product is made
| Table | Holds | Columns |
|---|---|---|
| mes_product_definition | A routing or master recipe header, with revision and effectivity | code text req, unique; item_id → core_item req; revision text req; process_type text req: discrete, batch, continuous or mixed; status text req: draft, approved, effective, superseded or obsolete; effective_from ts; effective_to ts; approved_signature_id → core_e_signature |
| mes_operation_definition | An operation (or ISA-88 unit procedure, operation or phase) within a definition | product_definition_id → mes_product_definition req; seq int req; code text req; name text req; work_center_id → core_equipment req; isa88_level text: none, unit_procedure, operation or phase; std_setup_min num; std_cycle_sec num; std_crew num; instruction_doc_ref uuid (soft link to M06's doc_controlled_document); required_skill_ref uuid (soft link to M07's trn_skill); quality_gate bool |
| mes_operation_step | A guided step: instruction, check, data entry, scan, signature | operation_definition_id → mes_operation_definition req; step_no int req; step_type text req: instruction, check, data_entry, material_scan, signature, timer or equipment_check; text text req; media_attachment_id → core_attachment; requires_verification bool; parameter_key text |
| mes_operation_parameter | A process parameter with limits, captured automatically or by hand | operation_definition_id → mes_operation_definition req; key text req; name text req; data_tag_id → core_data_tag; uom_id → core_uom; target num; lsl num; usl num; capture text req: auto, manual or both; critical bool |
| mes_operation_material | The bill of materials for one operation: inputs, outputs and by-products | operation_definition_id → mes_operation_definition req; item_id → core_item req; qty_per qty req; uom_id → core_uom req; direction text req: input, output or byproduct; consumption text req: scan, backflush or manual; scrap_factor num |
Orders, runs and performance
| Table | Holds | Columns |
|---|---|---|
| mes_production_order | An order to produce, from the ERP, MRP, a scheduler or by hand | order_no text req, unique; item_id → core_item req; product_definition_id → mes_product_definition req; site_id → core_site req; qty_planned qty req; uom_id → core_uom req; due_at ts; priority int; status text req: planned, released, in_progress, on_hold, completed, closed or cancelled; source text req: erp, mrp, aps or manual; external_ref text; output_lot_id → core_lot |
| mes_operation_run | One operation of one order on one piece of equipment | production_order_id → mes_production_order req; operation_definition_id → mes_operation_definition req; equipment_id → core_equipment; status text req: pending, ready, running, paused, complete or skipped; started_at ts; ended_at ts; qty_good qty; qty_scrap qty; qty_rework qty; lead_operator_id → core_person; shift_instance_id → core_shift_instance |
| mes_shift_performance | ISO 22400 performance for one piece of equipment and one shift, calculated | equipment_id → core_equipment req; shift_instance_id → core_shift_instance req; planned_busy_min num; actual_run_min num; ideal_cycle_sec num; total_count qty; good_count qty; availability num; performance num; quality num; oee num |
Records: what happened
| Table | Holds | Columns |
|---|---|---|
| mes_step_record | The electronic batch or device history record of a step, with performer and verifier | operation_run_id → mes_operation_run req; operation_step_id → mes_operation_step req; entry json; performed_by → core_person req; performed_at ts req; verified_by → core_person; verified_at ts; performer_signature_id → core_e_signature; verifier_signature_id → core_e_signature; deviation_ref uuid (soft link to M08's qms_quality_event) |
| mes_parameter_value | A captured value with its specification evaluation | operation_run_id → mes_operation_run req; operation_parameter_id → mes_operation_parameter req; value_num num; value_text text; captured_at ts req; captured_by → core_person; source text req: tag or manual; in_spec bool |
| mes_material_consumption | Material consumed from a lot into a run | operation_run_id → mes_operation_run req; item_id → core_item req; lot_id → core_lot; serial_unit_id → core_serial_unit; qty qty req; uom_id → core_uom req; consumed_at ts req; consumed_by → core_person; verified_by_scan bool |
| mes_material_production | A lot or serial produced by a run | operation_run_id → mes_operation_run req; item_id → core_item req; lot_id → core_lot; serial_unit_id → core_serial_unit; qty qty req; uom_id → core_uom req; produced_at ts req |
| mes_labor_record | Labour time against a run | person_id → core_person req; operation_run_id → mes_operation_run; activity text req: direct, setup, indirect, training or break; started_at ts req; ended_at ts |
| mes_equipment_state_event | A state interval for one piece of equipment, with a reason | equipment_id → core_equipment req; state text req: running, idle, starved, blocked, planned_down, unplanned_down, changeover, micro_stop or offline; started_at ts req; ended_at ts; reason_code_id → core_reason_code; source text req: tag, manual or inferred; operation_run_id → mes_operation_run |
| mes_production_count | A count increment, good and reject, by equipment and time | equipment_id → core_equipment req; operation_run_id → mes_operation_run; ts ts req; good qty req; reject qty; source text req: tag or manual |
Three links are soft on purpose: instruction_doc_ref, required_skill_ref and deviation_ref are plain uuid columns with no foreign key, because the modules that own those tables (M06, M07, M08) may not be installed yet.
Rules this course adds
A routing is a promise about how a product is made, so a change is a new revision, never an edit: draft, then approved with a signature, then effective on a date (the earlier effective revision becomes superseded), then never changed. An order records the definition it was made against, so a year later you can show exactly how a lot was made. For regulated batch production the US rules ask for a master record and a batch record showing each step done and checked [5]; for devices, a device history record [6].
- One item has at most one effective definition at a time (a partial unique index: a uniqueness rule for rows meeting a condition).
- One piece of equipment has at most one open state event (no ended_at), so it is never in two states at once.
- One run per order and operation; one operation per definition and seq; one step per operation and step_no; one performance row per equipment and shift.
- lsl is not above usl; ended_at is not before started_at; a run's good, scrap and rework are not negative.
- Counts and consumptions may be negative, because that is how they are corrected: a row with the opposite sign that names the row it corrects and has a comment giving the reason.
Session 2: Map the module onto your spine, before any table
15 minutesWhy
The module library names spine tables (core_equipment, core_lot and twenty more) that your Foundation may already hold under its own names, or may not have yet. Building them blind is how a plant ends up with two equipment lists and two lot tables that drift apart. A written map, checked by you, makes Claude Code extend what exists and create only what is missing, in a separate spine migration that merges first.
Do this
Read docs/SCHEMA-PLAN.md, docs/naming-standard.md, docs/matrix.json and every file in supabase/migrations. Do not write any SQL yet.
On a new branch mes/spine, add a section "M04 MES" to the shared docs/spine-map.md (create the file if it does not exist yet; never a separate docs/mes-spine-map.md or tables file). Put in it first the text between the lines below, then, for each spine table or function the module needs (core_site, core_equipment with parent_id and isa95_level, core_item with item_type, lot_controlled, serial_controlled and base_uom_id, core_uom, core_lot with lot_no, item_id, status, qty_initial, uom_id, origin_type and origin_id, core_lot_genealogy with parent_lot_id, child_lot_id, qty, uom_id, relation, event_type, event_id and occurred_at, core_serial_unit, core_data_tag, core_calendar, core_shift_definition, core_shift_instance, core_person, core_job_role, core_org_unit, core_reason_code, core_attachment, core_e_signature, core_approval, core_comment, core_status_history, core_action_item, core_event_outbox, core_audit_log with core_audit_row(), core_block_mutation(), core_touch_row(), core_current_tenant()), say one of: "we have it as <our table>, missing columns: ...", or "missing". Also the three tables of other modules the interlocks read: trn_skill and trn_qualification (M07) and cmms_calibration_record (M05).
Rules: never plan a second table for something we already have (our equipment table IS core_equipment); add missing columns to the existing table instead. Module tables carry site_id in place of the module library's tenant_id, so core_current_tenant() is not created; say so in the section, and how site_id maps to the way our access rules scope rows today. End the section with "Questions for me". Open a pull request titled "MES spine map" and show me the link.
----- docs/spine-map.md, section M04 MES -----
# The module's fifteen tables (from module library M04)
Standard columns on every table: id, site_id (in place of the library's tenant_id), created_at, created_by, updated_at, updated_by, row_version, archived_at, ext.
Types: text, int, num (decimal), qty (quantity, with its unit in uom_id), bool, ts (timestamptz), uuid, json (jsonb). "req" = not null. A list after a colon = the only allowed values. "→" = foreign key. Soft links are uuid with no foreign key.
## mes_product_definition
A routing or master recipe header, with revision and effectivity.
- code text req, unique
- item_id → core_item req
- revision text req
- process_type text req: discrete, batch, continuous or mixed
- status text req: draft, approved, effective, superseded or obsolete
- effective_from ts
- effective_to ts
- approved_signature_id → core_e_signature
## mes_operation_definition
An operation (or ISA-88 unit procedure, operation or phase) within a definition.
- product_definition_id → mes_product_definition req
- seq int req
- code text req
- name text req
- work_center_id → core_equipment req
- isa88_level text: none, unit_procedure, operation or phase
- std_setup_min num
- std_cycle_sec num
- std_crew num
- instruction_doc_ref uuid (soft link to M06's doc_controlled_document)
- required_skill_ref uuid (soft link to M07's trn_skill)
- quality_gate bool
## mes_operation_step
A guided step: instruction, check, data entry, scan, signature.
- operation_definition_id → mes_operation_definition req
- step_no int req
- step_type text req: instruction, check, data_entry, material_scan, signature, timer or equipment_check
- text text req
- media_attachment_id → core_attachment
- requires_verification bool
- parameter_key text
## mes_operation_parameter
A process parameter with limits, captured automatically or by hand.
- operation_definition_id → mes_operation_definition req
- key text req
- name text req
- data_tag_id → core_data_tag
- uom_id → core_uom
- target num
- lsl num
- usl num
- capture text req: auto, manual or both
- critical bool
## mes_operation_material
The bill of materials for one operation: inputs, outputs and by-products.
- operation_definition_id → mes_operation_definition req
- item_id → core_item req
- qty_per qty req
- uom_id → core_uom req
- direction text req: input, output or byproduct
- consumption text req: scan, backflush or manual
- scrap_factor num
## mes_production_order
An order to produce, from the ERP, MRP, a scheduler or by hand.
- order_no text req, unique
- item_id → core_item req
- product_definition_id → mes_product_definition req
- site_id → core_site req
- qty_planned qty req
- uom_id → core_uom req
- due_at ts
- priority int
- status text req: planned, released, in_progress, on_hold, completed, closed or cancelled
- source text req: erp, mrp, aps or manual
- external_ref text
- output_lot_id → core_lot
## mes_operation_run
One operation of one order on one piece of equipment.
- production_order_id → mes_production_order req
- operation_definition_id → mes_operation_definition req
- equipment_id → core_equipment
- status text req: pending, ready, running, paused, complete or skipped
- started_at ts
- ended_at ts
- qty_good qty
- qty_scrap qty
- qty_rework qty
- lead_operator_id → core_person
- shift_instance_id → core_shift_instance
## mes_shift_performance
ISO 22400 performance for one piece of equipment and one shift, calculated.
- equipment_id → core_equipment req
- shift_instance_id → core_shift_instance req
- planned_busy_min num
- actual_run_min num
- ideal_cycle_sec num
- total_count qty
- good_count qty
- availability num
- performance num
- quality num
- oee num
## mes_step_record
The electronic batch or device history record of a step, with performer and verifier.
- operation_run_id → mes_operation_run req
- operation_step_id → mes_operation_step req
- entry json
- performed_by → core_person req
- performed_at ts req
- verified_by → core_person
- verified_at ts
- performer_signature_id → core_e_signature
- verifier_signature_id → core_e_signature
- deviation_ref uuid (soft link to M08's qms_quality_event)
## mes_parameter_value
A captured value with its specification evaluation.
- operation_run_id → mes_operation_run req
- operation_parameter_id → mes_operation_parameter req
- value_num num
- value_text text
- captured_at ts req
- captured_by → core_person
- source text req: tag or manual
- in_spec bool
## mes_material_consumption
Material consumed from a lot into a run.
- operation_run_id → mes_operation_run req
- item_id → core_item req
- lot_id → core_lot
- serial_unit_id → core_serial_unit
- qty qty req
- uom_id → core_uom req
- consumed_at ts req
- consumed_by → core_person
- verified_by_scan bool
## mes_material_production
A lot or serial produced by a run.
- operation_run_id → mes_operation_run req
- item_id → core_item req
- lot_id → core_lot
- serial_unit_id → core_serial_unit
- qty qty req
- uom_id → core_uom req
- produced_at ts req
## mes_labor_record
Labour time against a run.
- person_id → core_person req
- operation_run_id → mes_operation_run
- activity text req: direct, setup, indirect, training or break
- started_at ts req
- ended_at ts
## mes_equipment_state_event
A state interval for one piece of equipment, with a reason.
- equipment_id → core_equipment req
- state text req: running, idle, starved, blocked, planned_down, unplanned_down, changeover, micro_stop or offline
- started_at ts req
- ended_at ts
- reason_code_id → core_reason_code
- source text req: tag, manual or inferred
- operation_run_id → mes_operation_run
## mes_production_count
A count increment, good and reject, by equipment and time.
- equipment_id → core_equipment req
- operation_run_id → mes_operation_run
- ts ts req
- good qty req
- reject qty
- source text req: tag or manual
----- end -----Read the map. For each line marked "we have it as", ask yourself: is it really the same thing? Answer the questions, then:
My answers to the questions in the M04 section of docs/spine-map.md: <paste>.
Now write ONE spine migration on this branch (npx supabase migration new mes_spine) that adds only what the map says is missing: missing columns on our existing tables, and missing core_ tables and functions with exactly the columns the module library lists, using create table if not exists. trn_skill, trn_qualification and cmms_calibration_record go in a second migration named for the module that will own them, without the foreign key from cmms_calibration_record to cmms_work_order. Row-level security on for every new table, no policies (they come from docs/matrix.json in Session 3). Add pgTAP tests that each new table exists with RLS on. Push, wait for the schema check, and tell me the result in plain words.You will see recreated screen
- Extend, do not duplicate: your equipment table gains two columns instead of a second machine list appearing.
- Questions about meaning are yours to answer: Claude Code must not guess a status mapping.
Check it worked
The pull request "MES spine map" is green, the M04 section of docs/spine-map.md has no open questions, and no new table duplicates one you had (no core_equipment beside equipment, no core_lot beside lots).
Fastest path
The table list goes into the shared spine map inside the same prompt, so Claude Code reads the module's columns from a file instead of from memory. That one paste saves the round trips where it guesses a column name.
If it goes wrong
The map plans core_equipment as a new table although we have equipment
Say: Our equipment table is core_equipment. Remove the new table from the plan and add the missing columns to equipment instead. This is the module's first pitfall, caught before it costs anything.
CI fails with: column does not exist, on a fresh database
A column the code uses has no migration. Say: Rebuild from nothing using only supabase/migrations, run supabase db diff, and write any missing change as a new migration, never by editing an old one. We hit exactly this: a merged change added ten columns and no migration, and it only worked on one machine.
Claude Code adds access policies to the new tables
Say: Remove every policy. Access comes from docs/matrix.json through scripts/gen-policies.mjs in Session 3.
Session 2: One prompt: the fifteen tables, the rules, the tests and the seed
30 minutesWhy
Writing the tables, the rules, the tests that try to break them and the seed in one pull request means the proof arrives with the change. The seed is small, with its dates shifted onto today so the screens always show a recent shift, and the hand-worked shift is kept on its fixed dates as a test fixture: Session 4 checks OEE, traces and refusals against exact numbers, and a seed that later steps do not agree with costs hours of chasing counts that were never there.
Do this
After the spine pull request has merged:
Read the M04 section of docs/spine-map.md and docs/naming-standard.md. Use our table names from the map wherever the module library says core_...
On a new branch mes/tables:
1. npx supabase migration new mes_tables. Create the fifteen mes_ tables exactly as the M04 section of docs/spine-map.md lists them: every column, type, required flag and allowed value (allowed values as check constraints). Foreign keys only to spine tables and to each other. Every table: an index on its scope column, row-level security on with no policies, the touch trigger, and the audit trigger so each insert, update and delete lands in the audit log.
2. Add the course's rules: a partial unique index for one effective definition per item; one open state event per equipment; unique (production_order_id, operation_definition_id) on runs, (product_definition_id, seq) on operations, (operation_definition_id, step_no) on steps, (equipment_id, shift_instance_id) on performance; checks lsl <= usl, ended_at >= started_at on runs, state events and labour, and qty_good, qty_scrap, qty_rework >= 0 on runs. No sign check on counts or consumptions: corrections are rows with the opposite sign.
3. The append-only rule: core_block_mutation() refuses update and delete on mes_production_count, mes_material_consumption, mes_material_production and mes_parameter_value, and on mes_step_record for every column except verified_by, verified_at and verifier_signature_id.
4. pgTAP tests in supabase/tests/mes_schema.test.sql: every mes_ table exists with RLS on; a query over information_schema proves every foreign key from a mes_ table points to a spine table or a mes_ table; and the database refuses a process_type outside the list, a second effective definition for one item, a state event that ends before it starts, lsl above usl, a duplicate order_no, and an update of a consumption row.
5. The seed, exactly as I give it in the next message, in supabase/seeds/mes.sql, listed under [db.seed] sql_paths in supabase/config.toml after supabase/seed.sql. Never appended to supabase/seed.sql, never in a migration. Check .github/workflows/deploy.yml never uses --include-seed.
6. A test that loads the seed and checks the row counts I give in the next message, and that running the seed twice leaves the same counts.
7. The hand-worked shift as a test fixture, not seed rows: tests/fixtures/mes-shift-2026-03-02.json, with CELL-B's state events and counts of Mon 2 Mar 2026 on their fixed dates, the 45-second ideal cycle, the genealogy links, and the answers Session 4 checks (availability 0.8667, performance 0.9000, quality 0.9615, OEE 0.7500; four lots forward from RAW-L1).
Do not connect to or change any live project. Do not push to main. Then wait for my next message.The seed for the MES module, marked SYNTHETIC and safe to run twice (fixed ids, inserted with on conflict do nothing). Dates are shifted onto today: the dates below are the reference week, and the seed moves the shift instances, runs, state events, counts, order due dates, the qualification expiry and the calibration date by the same whole number of weeks, worked out from current_date, so that Mon 2 Mar 2026 lands on the most recent Monday before today. Weekdays and every number stay the same; definition effective dates and the calibration due date (31 Dec 2030) stay as written. Every row is made up and carries ext synthetic true; history rows also carry ext imported_from "seed". No real names.
Places and people: under our site cle: equipment AREA-1 and AREA-2 (isa95_level area), CELL-A "Cutting" and CELL-B "Forming press" (work_center, parent AREA-1). Calendar with shift DAY-1 06:00–14:00 Mon–Fri, paid_break_min 30, and two shift instances, Fri 27 Feb 2026 and Mon 2 Mar 2026, supervisor SUP-1. Units EA, KG, MM, BAR. Items RM-STRIP (raw_material, KG, lot-controlled), WIP-BLANK (intermediate, EA, lot-controlled), FG-BRACKET (finished_good, EA, lot-controlled), CON-OIL (consumable, KG, not lot-controlled). Reason codes DT-JAM Press jam, DT-WAIT Waiting for blanks, DT-BREAK Break (domain downtime; planned false, false, true), CH-PRODUCT Product changeover (domain change, planned true). People OPR-1, OPR-2, OPR-3, SUP-1, SUP-2, PLN-1, ENG-1, QA-1 (display names like "SYNTHETIC · Operator One"); teams Area 1 (all but SUP-2) and Area 2 (SUP-2). Tags on CELL-B: State, GoodCount, RejectCount (mqtt_sparkplug) and FormPressure (opc_ua, float, BAR), 1000 ms. trn_skill SK-CUT and SK-FORM. trn_qualification: OPR-1 SK-CUT and SK-FORM level 2 qualified, no expiry; OPR-2 SK-CUT level 2 qualified, SK-FORM level 1 in_training; OPR-3 SK-CUT level 2 qualified, expires 31 Jan 2026. cmms_calibration_record for CELL-A and CELL-B, performed 16 Feb 2026, due 31 Dec 2030, result pass.
Definitions (imported_from seed): two signatures by QA-1 (meaning approved). RT-BRACKET-A revision A, superseded, effective 1 Jan 2025 to 31 Dec 2025, header only. RT-BRACKET-B revision B, effective from 1 Jan 2026, item FG-BRACKET, discrete. OP10 Cut blanks (seq 1, CELL-A, setup 20 min, cycle 30 s, crew 1, skill SK-CUT, no gate); OP20 Form bracket (seq 2, CELL-B, setup 30, cycle 45 s, crew 1, skill SK-FORM, quality_gate true). Steps OP10: 1 equipment_check "Check the blade guard", 2 material_scan "Scan the steel strip lot", 3 data_entry "Measure the cut length" (cut_length_mm), 4 signature (requires verification). OP20: 1 instruction "Load the blank", 2 material_scan "Scan the blank lot", 3 equipment_check "Die clean, guard closed", 4 data_entry "Review the pressure readings" (form_pressure_bar), 5 signature (requires verification). Parameters cut_length_mm (MM, target 120.0, lsl 119.5, usl 120.5, manual, critical) and form_pressure_bar (BAR, 120, 110, 130, auto, tag FormPressure, critical). Materials per 1 EA: OP10 in RM-STRIP 2 KG scan, out WIP-BLANK 1 EA manual; OP20 in WIP-BLANK 1 EA scan, in CON-OIL 0.01 KG backflush, out FG-BRACKET 1 EA manual.
History (imported_from seed): lots RAW-L1 and RAW-L2 (RM-STRIP, released, 1000 KG), RAW-L3 (RM-STRIP, on_hold, 500 KG), PO-0900-OP10 (40 EA), PO-0900-OP20 (38), PO-0901-OP10 (30), PO-0901-OP20 (30), released. Orders: PO-0900 (40, closed), PO-0901 (30, closed), PO-1001 (100, planned, manual, priority 1, due 5 Mar 2026 17:00), PO-1002 (50, planned, erp, ERP-1002, priority 2, due 6 Mar 2026 17:00). Runs complete on 27 Feb by OPR-1: R1 PO-0900 OP10 CELL-A 40/0; R2 PO-0900 OP20 CELL-B 38/2; R3 PO-0901 OP10 30/0; R4 PO-0901 OP20 30/0. Consumptions (scanned): R1 RAW-L1 80 KG; R2 PO-0900-OP10 40 EA; R3 RAW-L1 60 KG; R4 PO-0901-OP10 30 EA. One production per run. Genealogy consumed_into: RAW-L1→PO-0900-OP10 80 KG; PO-0900-OP10→PO-0900-OP20 40 EA; RAW-L1→PO-0901-OP10 60 KG; PO-0901-OP10→PO-0901-OP20 30 EA. CELL-B on 2 Mar, source tag: 06:00–06:30 changeover (CH-PRODUCT), 06:30–09:30 running, 09:30–09:45 unplanned_down (DT-JAM), 09:45–11:45 running, 11:45–12:15 planned_down (DT-BREAK), 12:15–13:45 running, 13:45–14:00 starved (DT-WAIT). Counts with no run: 09:30 good 225 reject 9; 11:45 150/6; 13:45 75/3.
Row counts the test must check: definitions 2, operations 2, steps 9, parameters 2, materials 5, orders 4, runs 4, consumptions 4, productions 4, state events 7, counts 3; every other mes_ table 0.
Now push, open a pull request titled "MES tables", wait for every check, and tell me the result in plain words. If a check fails, fix it and wait again before reporting.You will see recreated screen
- The migration file: dated, so files run in order. Production gets it from the deploy pipeline when this merges (Session 11), never by hand.
- A rule from the course in the table itself: it holds for every screen, import and agent.
- The test for pitfall 1: no foreign key from a mes_ table points anywhere but the spine.
Check it worked
Pull request MES tables is green on GitHub, its summary gives the test count and the seed row counts, the seed sits in supabase/seeds/mes.sql (not in a migration, not in supabase/seed.sql), and tests/fixtures/mes-shift-2026-03-02.json is in the pull request.
Fastest path
Two messages, sent one after the other, replace a dozen exchanges: the first sets every rule, the second gives the seed and the counts the test must prove. "Wait for every check and fix before reporting" saves another round trip.
If it goes wrong
A later step says "you should see 4 orders" and the seed has 3
The seed and the steps disagree. Say: List every count any later step or test expects and show the seed line that creates each. Fix the seed, not the check. Reviews of five Academy modules found exactly this fault.
Claude Code reports the tests pass, but CI is red
Say: Show me the exact command, its exit code and the last 20 lines of its output, and the failed log of the check on GitHub. A summary is a claim; the check on GitHub is the evidence.
Claude Code proposes to loosen a check (for example drop lsl <= usl) to get green
Say: Never edit, skip or loosen a test or a rule to make something pass. Explain why you think it is wrong and stop. The failing rule is usually right and the seed wrong.
After merging main into the branch, a column or test you added has gone
Say: I just merged main. List every schema change and test this branch added and confirm each is still there. If any disappeared, find the commit that removed it and tell me before changing anything. A revert on main once silently took a schema change with it.
Session 2: Try it on the development project yourself, then predict the numbers
20 minutesWhy
CI proves the files build a database from nothing; the development project proves they apply on top of a real, already-migrated Foundation with its seed. You run it, in your own terminal, because changing a database is kept for a person. Production then gets the same migration from the deploy pipeline when the pull request merges, never by hand. Writing your predictions before any code runs makes Session 4's checks honest.
Do this
In a terminal, not inside Claude Code. The password is in the password manager under Supabase: acme-platform-dev database password:
cd ~/code/acme-platform && git fetch && git switch mes/tablesnpx supabase link --project-ref tsrqponmlkjihgfedcbacat supabase/.temp/project-refIt must print tsrqponmlkjihgfedcba, the development project. If it prints abcdefghijklmnopqrst, stop: that is production. Then:
npx supabase db push --include-seedPush the seed with the migrations only this first time. After that, to reload the made-up rows, you run npm run seed:dev yourself (Claude Code may not). The screens in this element show the seed loaded in the week of 2 March 2026, so its Monday shift is 2 March; yours is the most recent Monday.
https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new
The development project's SQL editor. Paste the query below and press Run.
select 'orders' t, count(*) from mes_production_order union all
select 'runs', count(*) from mes_operation_run union all
select 'state events', count(*) from mes_equipment_state_event union all
select 'counts', count(*) from mes_production_count;Then write docs/mes-seed.md by hand, before you read any code: OEE for CELL-B on the seed's Monday shift (2 March in the fixture) with the sums written out (planned busy time, run time, availability, performance with the 45-second ideal cycle, quality, product), the lots forward from RAW-L1 and backward from PO-0901-OP20 with depths, and whether OPR-1, OPR-2 and OPR-3 may start OP10 and OP20, and why. Commit it to the pull request; owner two approves and it merges.
You will see recreated screen
- The development project. Production's reference is different; check every time.
- Only the new files. If it lists one you do not expect, answer n and ask why.
You will see recreated screen
| t | count |
|---|---|
| orders | 4 |
| runs | 4 |
| state events | 7 |
| counts | 3 |
- The same numbers the seed test proves in CI.
Check it worked
The query shows orders 4, runs 4, state events 7, counts 3 on acme-platform-dev; docs/mes-seed.md holds your sums; the pull request is merged and the deploy pipeline has applied the migration to production (its run is green on the Actions tab).
If it goes wrong
db push says: Remote migration versions not found in local migrations directory
The development project has a migration your branch does not, often from another branch you tried earlier. Do not force anything. In Claude Code: db push on the development project reports remote versions not in the local directory. List which versions differ and which branch each came from, without changing any project.
The migration changed in review after I pushed it to the development project
Do not rebuild the project. Ask Claude Code: The development project has the earlier version of this migration. Write a new migration that brings it to the reviewed version; never edit an applied migration. Push it to the development project yourself, then run npm run seed:dev to reload the made-up rows.
A page later fails on the live site with "column does not exist"
The migration merged but production did not get it. Open the deploy workflow run on GitHub's Actions tab and read why. Our live database once fell nine migrations behind main; the Session 11 pipeline and its daily freshness check exist so that never happens silently.
Knowledge check
Where does the MES sit in ISA-95?
Knowledge check
Your Foundation already has an equipment table. What does the module do with work centres?
References
- ISA: ISA-95 standard, Enterprise-Control System Integration. https://www.isa.org/standards-and-publications/isa-standards/isa-95-standard
- Siemens: ISA-95 framework and layers. https://www.siemens.com/en-us/technology/isa-95-framework-layers/
- Automation World: the five parts of ISA-95. https://www.automationworld.com/products/software/article/13309288/the-five-parts-of-isa-95
- SYMESTIC: the 11 core MES functions (MESA-11). https://www.symestic.com/en-us/what-is/mesa-11
- eCFR: 21 CFR Part 211, current good manufacturing practice for finished pharmaceuticals (batch records, 211.188 and 211.192). https://www.ecfr.gov/current/title-21/chapter-I/subchapter-C/part-211
- eCFR: 21 CFR Part 820, Quality Management System Regulation. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-H/part-820
- 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
Production access is decided once, in docs/matrix.json, and the database rules, the route guard and the menus are generated from it. Then Claude Code builds the screens: a dispatch list and a guided run on the operator's phone, downtime reasons, and the views for the supervisor, the engineers and quality.
20 minSession 3: 2 steps5 roles, 4 machine accounts7 screens
By the end of this chapter you can
- Add the module's roles, machine accounts, tables, screens and routes to docs/matrix.json and regenerate the access rules.
- Walk Sessions 4 to 6 against the matrix so no later step is refused.
- Have Claude Code build the seven screens and test them on a phone, signed out and as each role.
The roles, as jobs
| Role | Scope | May | May not |
|---|---|---|---|
| Operator | Own area | Read the area's runs and definitions; claim a ready run; record steps, values, scans, own signature (performed); open a downtime and give it a reason; manual counts for own run | Verify a step; release an order; touch definitions; delete anything |
| Supervisor | Own area | Everything the operator reads; verify a step someone else performed (verified); reasons and manual counts and states; hold an order | Verify their own step; see another area (SUP-2 sees nothing of AREA-1) |
| Planner | Whole site | Create planned orders; release them (creates the runs and one outbox event) | Run operations; change definitions |
| Process engineer | Whole site | Write definitions, operations, steps, parameters and materials while draft; make an approved revision effective | Approve their own definition |
| Quality engineer | Whole site | Approve a definition with a signature; review runs by exception; close an order | Edit a definition |
| Tag collector (machine) | Site | Insert counts, states and values with source tag; close an open state | Read orders or people |
| Performance job (machine) | Site | Read states, counts and definitions; write one performance row per equipment and shift | Anything else |
| ERP publisher (machine) | Site | Read outbox rows whose type starts with mes.; set published_at, attempts, last_error | Read any other table |
| Importer (machine) | Site | Insert definitions, open orders and history with ext imported_from (Sessions 5–6) | Read step records; write the outbox |
Nobody gets delete. Corrections are new rows. Two facts about how Postgres applies row-level security shape the cells [1]: an update finds rows only through the role's read rule, so a role that updates a row must also read it, and the changed row must still pass that read rule; and an insert that returns its new row needs the read right too. The interlock triggers in Session 4 run as the operator, so the operator must read their own qualifications and the area's calibration records, or every start is refused, or worse, the check finds nothing to check.
| Key or secret | What it unlocks | Where it lives | Who holds it | Never |
|---|---|---|---|---|
| MES_TAG_COLLECTOR_KEY | Lets a machine or the simulator post counts, states and values to /api/mes/tags | Vercel environment variables (Preview and Production, different values); company password manager | pat@acme.com and sam@acme.com | In the repository, Claude Code, a chat or a screenshot |
| MES_ERP_PUBLISHER_KEY | Lets the publisher read mes. outbox rows and mark them sent | Vercel (Preview, Production); password manager | pat@acme.com and sam@acme.com | Shared with the ERP team |
| MES_IMPORT_DB_PASSWORD | Lets the import-mes workflow sign in as mes_import, insert only, with imported_from (Session 6) | GitHub Actions secret, typed by a person; password manager | pat@acme.com | In Vercel or any file; usable after cut-over (mes_import is set to NOLOGIN) |
Session 3: The roles, rights and machine accounts into the matrix
35 minutesWhy
Access decided once in the matrix and generated everywhere cannot drift: the database, the routes and the menus all say the same thing. Walking every later step against the matrix now is what stops Session 4 failing with a refusal halfway through a run, or worse, an update that reports success and changes nothing because the role could not read the row.
Do this
Read docs/matrix.json, the M04 section of docs/spine-map.md, scripts/gen-policies.mjs and docs/access-review.md.
On a new branch mes/access, add to docs/matrix.json, starting every cell blank and adding only what the job needs:
- roles operator, supervisor (scope own area: a run is in an area through its operation's work_center_id, walking parent_id up to the area equipment, which must match the area on the person's team), planner, process engineer, quality engineer (whole site), with exactly the rights in element M04 chapter 2's table, which I paste below;
- machine accounts tag collector, performance job, ERP publisher, importer (the database role mes_import, used only by the import workflow in Session 6), each its own sign-in, with only the rights in the same table;
- the seven screens /mes/dispatch, /mes/run/[id], /mes/downtime, /mes/performance, /mes/definitions, /mes/review, /mes/trace and the routes /api/mes/release, run, scan, step, downtime, definition, review, performance, trace, tags, outbox, each with the roles that may use it.
No delete for anyone. Every role that updates a table also reads it; every insert that returns its row has read; the operator reads their own trn_qualification, trn_skill and the area's cmms_calibration_record.
Then write docs/access-walk.md: one line per step of Sessions 4, 5 and 6 in element M04 (I paste the list below) giving the role or account, the table, the action and the matrix cell that allows it. Mark any step with no cell, and add the cell.
Run scripts/gen-policies.mjs and scripts/gen-routes.mjs (Session 9), so the policies migration, supabase/tests/access.test.sql and lib/access/routes.ts are regenerated. Add tests: SUP-2 reads no AREA-1 run; an operator cannot open /mes/definitions or verify a step; only the planner releases; the importer cannot read mes_step_record; the tag collector cannot read mes_production_order; nobody can delete from any mes_ table; and for each role that updates a table, the row really changed in the database afterwards. Push, open a pull request titled "MES access", wait for every check, and report.
<paste the role table and the step list>To act as a made-up person on the development project, one more prompt; it puts a helper in the seed, which never reaches production:
In the MES seed file only (never in a migration, never as a page or a switch in the app), add a function public.dev_act_as(email text, person_code text) that links the existing sign-in with that email to the made-up person with that code, and refuses unless that person row has ext synthetic true. Add a test that it refuses a person without the synthetic mark. Push to the same pull request.You will see recreated screen
- A verifier may change only three columns. The importer has no right at all on step records.
- The walk catches the classic refusal: an update that needs a read right the role never had.
Check it worked
Pull request MES access is green; docs/access-walk.md has a cell for every line; docs/access-review.md shows a row for every role and machine account; the refused-role tests are in supabase/tests/access.test.sql.
If it goes wrong
A button later reports success but nothing changed
A role can update rows it cannot read, so the update matched nothing. Say: For each role that updates <table>, check its read policy covers the row before and after the change, and write a test that performs the change and checks the row really changed. We met this in three modules.
Claude Code proposes the service_role key for the machine routes "to keep it simple"
Refuse: Each machine account is its own sign-in with only its matrix rights. Never use service_role in a route. A route on that key skips every policy, and every test you wrote stops meaning anything.
A check called something like routes or access fails though nothing looks wrong
It compares a generated list with the code. Say: Open the failed log, tell me which generated file it compares against, regenerate it, commit, and show me what changed in the list. If the list shows a new unprotected route, stop.
Claude Code put dev_act_as in a migration or added an "act as" switch to the app
Say: Remove it. It lives only in the seed, which never runs in production. A demo switch once made every visitor an administrator in production.
Session 3: The screens, built and tried on a phone
40 minutesWhy
Operators judge the module by the run screen, with gloves on and a press running. Building the screens against the seed, then testing every one signed out, as each role and at phone width, catches the wrong person shown, a page that answers without sign-in, or a number nobody measured, before anyone on the floor sees it.
Do this
Read node_modules/next/dist/docs/ first: this version of Next.js differs from what you know, and request checks live in proxy.ts. Then read docs/matrix.json, lib/access/routes.ts and the screens from Foundation Sessions 12 to 15.
On a new branch mes/screens, build:
- /mes/dispatch: one card per released operation in the user's area, ordered by priority then due date (order, operation, work centre, quantity, due), Start only when the run is ready.
- /mes/run/[id]: one step at a time, targets at least 44 px: instruction, a scan box, a number box with its limits and an in-spec colour, a signature button (password typed again), Pause.
- /mes/downtime: the area's stops still needing a reason, newest first, reason codes of domain downtime; for a machine with no tag feed a counts box (good, reject) with source manual.
- /mes/performance: availability, performance, quality and OEE per shift and machine, and "No data" when there is none, never 0.
- /mes/definitions, /mes/review, /mes/trace for the engineers, quality and supervisors.
The server takes the person from the signed-in session, never from the page, and sets every time from its own clock. Every tap sends a row id made on the phone with crypto.randomUUID() and stays in the device outbox from Session 12 until confirmed; inserts use on conflict (id) do nothing, so a tap sent twice records once. Two people claiming the same ready run: the update includes the run's row_version, so the second is refused with "already started by someone else".
Tests: every screen and route signed out lands on sign-in; each role sees only its screens; a record made by OPR-1 says OPR-1 whoever the page claims; the same downtime start sent twice leaves one row; the screen-size check from Session 12 at 360 and 390 px. Push, open "MES screens", wait for every check including the preview, and report with the preview link.On the development project, act as the operator, then open the preview link from the pull request on your phone:
https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new
Run select public.dev_act_as('pat@acme.com', 'OPR-1'); in the development project's SQL editor. Change OPR-1 to SUP-1, PLN-1, ENG-1 or QA-1 to act as someone else.
Then sit an operator down with the run screen and a supervisor with the downtime screen. Do not explain. Write down every place each one stopped or asked a question, and give the list to Claude Code.
You will see recreated screen
- Made-up data says so. If a preview ever shows real plant data, stop and find out which project it reads.
- One card per released run in your area, by priority then due date.
- No Start until the previous operation is complete: the database enforces it too (Session 4).
Check it worked
Pull request MES screens is green; on the preview, OPR-1 sees AREA-1's cards and SUP-2 sees none; every screen passes at 360 and 390 px; you have the notes from one operator and one supervisor.
Fastest path
Asking for the signed-out, per-role and phone-width tests in the same prompt as the screens means the first preview you open has already been through them.
If it goes wrong
Every record says it was made by the same person, whoever is signed in
The page sent a name and the server trusted it. Say: Take the person from the signed-in session on the server and ignore what the page sends. Add a test that two different users each create a record and the recorded author is right.
The performance screen shows 0% or a figure for a shift with no data
Say: Show "No data" when a shift has no performance row, never 0 or a made-up value, and add a test per widget that renders it empty. A chart that drew twelve hard-coded points was once graded "In control" on 87 screens.
Two operators both started the same run
Two saves from the same starting copy. Say: Include row_version in the claim's WHERE clause so the second claim is refused with a clear message, and add a test that two claims from the same copy leave exactly one.
A page answers without sign-in
Stop. Say: List every /mes page and /api/mes route, call each signed out and show me the status code. Anything that is not a redirect to sign-in or 401 is a finding. A prior build had 376 of 449 route handlers with no guard at all.
Knowledge check
An operator's start is refused by the qualification interlock although they are qualified. The likeliest cause?
Knowledge check
How does the tag collector's route reach the database?
References
- Supabase Docs: Row Level Security. https://supabase.com/docs/guides/database/postgres/row-level-security
- Supabase Docs: Understanding API keys (service_role bypasses row-level security). https://supabase.com/docs/guides/api/api-keys
- PostgreSQL Documentation: Row Security Policies. https://www.postgresql.org/docs/current/ddl-rowsecurity.html
- W3C: Web Content Accessibility Guidelines (WCAG) 2.2. https://www.w3.org/TR/WCAG22/
Chapter 3 · Session 4
The workflow: interlocks, records, OEE and the ERP
An order is released, an operator runs it step by step, and from then on the database, not a memory or a poster, decides what is allowed. You run one order end to end on the preview, then check OEE and a trace against the sums you wrote by hand in Session 2.
30 minSession 4: 5 steps9 interlocksOEE 0.7500 on the seed
By the end of this chapter you can
- Have Claude Code write the rules page, the interlock triggers and the tests that try to break each one.
- Run PO-1001 end to end on a phone and see each refusal and each record.
- Check OEE, a trace and the ERP outbox against your own sums, and revise a routing the only safe way.
The interlocks
An interlock is a rule that must be satisfied before an action is allowed. The module puts them in the database as triggers, so no screen, route, import or agent can skip one; the route shows the rule's message. Imported history is the one exception, and it is keyed to who inserts, not to what a row says: a row marked ext imported_from skips the insert checks only when the importer account or the migration role inserts it.
| Interlock | The rule | The seeded case that proves it |
|---|---|---|
| Previous operation | The previous operation of the same order is complete | OP20 cannot start while OP10 is not complete |
| Qualification | The lead operator holds the required skill, qualified, not expired at the start | OPR-3 refused on OP10 (expired 31 Jan 2026); OPR-2 refused on OP20 (in_training); OPR-1 may start both |
| Calibration | The equipment's latest calibration is not due before the start and did not fail; no record, no requirement | A start dated 2031 is refused; one in 2026 is allowed |
| Lot status | A consumed lot is released | RAW-L3 is on_hold: the scan is refused and leaves no row |
| Bill of materials | The item is an input of this operation | WIP-BLANK cannot be consumed in OP10 |
| Scan and quantity | A scan-mode input was scanned, and a lot is never consumed past its initial quantity | RAW-L1 has 860 KG left: 900 more is refused |
| Step order | The previous step is recorded and the run is running | Step 3 before step 2 is refused |
| Completion | Every scan input consumed, every critical value captured, every out-of-spec critical value has a deviation, every signature step signed; all unmet conditions named in one message | Completing without the signature is refused |
| Verification | The verifier is not the performer | Setting a step's verifier to its performer is refused |
| Record | Statuses, in order | Who moves it |
|---|---|---|
| mes_production_order | planned, released, in_progress, completed, closed (also on_hold, cancelled) | Planner releases; first start; last run completes; quality closes |
| mes_operation_run | pending, ready, running, paused, complete (also skipped) | Release makes the first ready; completing one makes the next ready |
| mes_product_definition | draft, approved, effective, superseded (also obsolete) | Engineer drafts; quality approves with a signature; effective date supersedes the earlier one |
Session 4: The rules page, then one prompt for the interlocks and their tests
30 minutesWhy
A rule you can read on one page is a rule the supervisor and the process engineer can check before anything is built; the same page then tells Claude Code exactly what to enforce. Writing every interlock as a database trigger with a test that tries to break it means the refusal holds for the phone, an import and any future agent, and a later change that quietly removes it turns CI red.
Do this
On a new branch mes/workflow, write docs/mes-rules.md, one page, from element M04 chapter 3 (I paste its tables below): the nine interlocks with the exact message an operator sees for each; the status ladders and who moves them; lot numbering (order number, dash, operation code, e.g. PO-1001-OP10, status released); the PackML state map (Execute running; Idle, Complete idle; Held, Stopped, Aborted unplanned_down; Suspended starved, or blocked when the output is full; states ending in -ing keep the previous state; anything else offline; blocked, starved or unplanned_down under 2 minutes is micro_stop with no reason); the OEE time base (planned busy = shift minutes less planned_down; run = minutes running; availability = run ÷ planned busy; performance = ideal cycle of the definition effective when the shift started × total count ÷ run seconds; quality = good ÷ total; OEE = product of unrounded values); and that the module never writes to a machine.
Stop and show me the page. I will have the supervisor and the process engineer read it.When they have signed it off:
docs/mes-rules.md is signed off. Now, on the same branch, write the triggers and functions as new migrations:
1. Definitions: no change to operations, steps, parameters or materials unless the definition is draft; draft→approved only with approved_signature_id; approved→effective sets effective_from and supersedes the earlier effective revision with effective_to; planned→released only for an effective, signed definition, and release creates the runs (first ready, rest pending) and one mes.production_order.released outbox row.
2. The nine interlocks from docs/mes-rules.md, each naming every unmet condition in one message. Completion is one transaction: backflush first (while running), then counts, complete, the produced lot, genealogy only for lots with net consumption above zero, the next run ready, the outbox rows.
3. ext imported_from skips the signature, draft-only and insert checks only when current_user is the importer account or the migration role; from anyone else it is ignored.
4. mes_compute_shift_performance(equipment, shift): clips states to the shift, applies the time base, writes or updates the one row, writes mes.shift_summary.ready. mes_trace_forward(lot) and mes_trace_backward(lot): recursive, return lot, depth and the linking run, refuse to loop.
5. Tests in supabase/tests/mes_workflow.test.sql, the OEE and trace ones loading tests/fixtures/mes-shift-2026-03-02.json, each in a transaction it rolls back, setting the person the way the app does, and looking up the item's currently effective definition (so they survive revision C later): every seeded case in the interlock table; consuming RAW-L3 is still refused when OPR-1's insert carries imported_from; 120.5 in spec and 120.51 not; completion without a signature refused; update of a consumption refused; a scan sent twice leaves one row; OEE for CELL-B on 2 March gives 0.7500 and running it twice leaves one row; forward from RAW-L1 gives four lots.
For each new test, show it failing with its rule removed, then passing with it back. Push, open "MES workflow", wait for every check and report.You will see recreated screen
- The message the operator sees names the skill, not a database error.
- Red first: a test that cannot fail proves nothing.
Check it worked
docs/mes-rules.md is signed off by two people from the floor; pull request MES workflow is green; the summary shows each test failing before it passed, and OEE 0.7500 matching your hand sums.
Fastest path
"Show it failing with the rule removed" in the same prompt saves the day you find a test that was green all along because it could never fail.
If it goes wrong
A test checks that a word appears in a file, not that the database refuses
Say: For each test, tell me what behaviour it proves. Rewrite any test that only looks for a name to perform the action and check the refusal or the row.
OEE comes out 0.7517, not 0.7500
The function multiplied rounded factors (0.87 × 0.90 × 0.96). Say: Multiply unrounded values and round only for display.
A refused start says "permission denied for table trn_qualification"
The operator's read cell is missing. Add it to docs/matrix.json, regenerate, and never widen a key to get round it.
Claude Code goes round in circles on the same failing test
After the second identical failure say: Stop. Quote the error, what you tried, whether the cause is in our code or outside it, and what you need from me.
Session 4: Release PO-1001 and run OP10 on the phone
15 minutesWhy
Seeing the refusals and the records with your own eyes, on the screen the operator will use, is what lets you vouch for the module. Trying the held lot first shows that a refusal leaves nothing behind, which is why lot balances and the dispatch list stay true.
Do this
On the preview of pull request MES workflow (development project). In the dev SQL editor, act as each person in turn with select public.dev_act_as('pat@acme.com', '<code>');:
https://supabase.com/dashboard/project/tsrqponmlkjihgfedcba/sql/new
Act as PLN-1, then release PO-1001 on /mes/dispatch. Then act as OPR-1.
- As OPR-1, start OP10 on CELL-A. Step 1: record the guard check.
- Step 2: scan RAW-L3. See the refusal naming the hold. Then scan RAW-L2 for 200 KG.
- Step 3: enter 120.2: in spec. Step 4: sign by typing your password again.
- Complete with good 98, scrap 2.
On the development project, as a read-only check, tell me: PO-1001's status; its runs and their statuses; lot PO-1001-OP10 (quantity, status); the genealogy rows into it; the outbox rows for PO-1001; and whether any consumption row names RAW-L3. Use only select queries through the app's own access as QA-1.You will see recreated screen
- The trigger's own message, shown by the route. No consumption and no step record were saved.
- The scan and its step record are written together, or not at all.
You will see recreated screen
- Every record the run should leave, and the one it must not.
Check it worked
PO-1001 is in_progress, OP10 complete and OP20 ready, lot PO-1001-OP10 has 98 EA with one genealogy row from RAW-L2, and no row names RAW-L3.
If it goes wrong
The preview shows real plant data
Stop. Previews must use the development project (Session 11). In Claude Code: Which Supabase project does the preview environment use? Show me the variable names in Vercel's Preview environment, not their values. Fix it in Vercel yourself.
Start is refused with a calibration message on a 2026 date
Check the seeded calibration's due date is 31 Dec 2030. If the seed says otherwise, the seed is wrong, not the trigger.
Start works on one phone and is refused on another for the same run
Someone else claimed it first: the row_version check is working. The second phone should say so in words.
Session 4: Run OP20 with the tag simulator, the deviation and the signatures
20 minutesWhy
Counts and states arrive from machines, not from people, so the module must accept a repeated message without doubling anything and must turn short stops into micro-stops without asking anyone. The out-of-spec pressure then shows the completion rule at work: the run cannot close until someone records a deviation.
Do this
On the branch mes/workflow, write scripts/simulate-tags.mjs. It posts a fixed feed for CELL-B to the preview's /api/mes/tags with the key in MES_TAG_COLLECTOR_KEY (read from the environment, never printed), minutes counted from a required --start: minute 0 State Execute; pressure 118 at 10, 121 at 40, 135 at 90; GoodCount 40 and RejectCount 2 at 30, then Held for 40 s and back to Execute; GoodCount 70, RejectCount 3 at 50:40, then Stopped for 20 min and back to Execute; GoodCount 94, RejectCount 4 at 95:40, then Complete. Each message has a message_id; the route skips an id already stored and stores counter increments, not totals. Push and tell me the exact command for me to run.Make the key yourself and enter it in Vercel (Preview only for now); it never goes into Claude Code:
node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"https://vercel.com/acme-ops/acme-platform/settings/environment-variables
Add MES_TAG_COLLECTOR_KEY for Preview, paste the value only, and save it in the password manager. Redeploy the preview. Add the name to docs/KEYS.md.
npx vercel env pull .env.local --environment=preview && node --env-file=.env.local scripts/simulate-tags.mjs --start 2026-03-09T06:00Run it a second time with the same --start: nothing should change. Then, as OPR-1: start OP20, record step 1, scan PO-1001-OP10 for 98 EA, give the 20-minute stop the reason DT-JAM on /mes/downtime, record step 3, and try to complete. Open a deviation, record step 4 naming it, sign step 5, complete.
You will see recreated screen
- The 40-second Held became a micro_stop with no reason needed; the 20-minute Stopped needs one.
- The same message twice changes nothing: a phone on a weak signal cannot double a count either.
You will see recreated screen
- Every unmet condition in one message, and the backflush tried first was rolled back with it.
Check it worked
Three counts (good 40, 30, 24; reject 2, 1, 1), three values with only 135 out of spec and one mes.parameter.out_of_spec event, six state events with one micro_stop, and after the deviation and signature, lot PO-1001-OP20 with 94 EA and PO-1001 completed.
If it goes wrong
The simulator gets 401 or 403
Before changing the key, find out who refused it. Say: Show me the full response body and whether it came from our route, Vercel's preview protection or a proxy. A 401 from a preview address can be Vercel's own deployment protection, and behind a company proxy Node's fetch may need NODE_USE_ENV_PROXY=1.
Counts doubled after the second run
The route stored totals or did not check message_id. Say: A message whose message_id is stored must be skipped before the increment is taken; add a test that posts the same feed twice and expects the same rows.
The key appears in a log, the terminal output or a commit
Treat it as exposed: make a new one, replace it in Vercel and the password manager, and redeploy. Ask Claude Code to make the script never print it.
OEE on one time base, and the trace
ISO 22400-2 defines OEE as availability × performance (effectiveness) × quality ratio [1]. The danger is not the formula but mixing time bases, so nobody can reproduce the figure. The rules page fixes one base for every figure, and the function multiplies unrounded values: rounded first, 0.87 × 0.90 × 0.96 gives 0.7517, where the true product is 0.7500.
Session 4: Verify, review by exception, then check OEE and a trace
15 minutesWhy
Signed steps verified by a second person, and review by exception (a person reads only the runs with an out-of-spec value or a deviation) are what make the step records a batch or device history record. OEE and the trace are two of the module's three definition-of-done tests: they must match the sums you wrote before any code existed.
Do this
- As SUP-1, verify OP10 step 4 and OP20 step 5. As OPR-1, try to verify your own: refused.
- As QA-1, open /mes/review: OP10 is clean, OP20 is an exception. Approve OP10 in one action; open OP20, comment on the deviation, approve. PO-1001 becomes closed.
Read-only, on the development project: run mes_compute_shift_performance for CELL-B and the seed's Monday shift and show every column; then mes_trace_forward('RAW-L1') and mes_trace_backward('PO-1001-OP20') with depths, each with EXPLAIN ANALYZE and its execution time; then count core_lot_genealogy rows and consumption rows that name a lot. Compare the OEE figures with docs/mes-seed.md line by line.You will see recreated screen
- OEE to four places, from unrounded factors.
- Under one second with a large margin on the seed; Session 6 times it on real volume.
Check it worked
OEE 0.7500 for CELL-B on the seed's Monday shift, as in the fixture; four lots forward from RAW-L1, two backward from PO-1001-OP20, each under one second; PO-1001 closed; your own verification refused.
If it goes wrong
OEE differs from my sums
Find which time base differs: whole shift against shift less planned_down, or a stop counted in one list and not the other. Fix the sums or the function, and write which in docs/mes-rules.md.
The review queue shows a clean run as an exception, or the other way round
Every exception must be flagged in the record. Say: Show me the query behind the review queue and the flags on each run; a run with an out-of-spec value or a deviation must always be an exception.
Session 4: Send to the ERP through the outbox, and revise the routing
20 minutesWhy
A message sent from the middle of an operation can announce a lot that was never saved. Writing it to an outbox in the same transaction as the record, and sending it from there until the ERP answers, means either both exist or neither does, and a down ERP loses nothing. The revision proves the other promise: a routing in use is never edited, and old shifts keep the cycle time they ran on.
Do this
On mes/workflow: write scripts/erp-stub.mjs (listens on localhost:4010, appends each message to erp-received.jsonl and answers 200) and scripts/publish-outbox.mjs, which, as the ERP publisher (key MES_ERP_PUBLISHER_KEY from the environment, never printed), fetches unpublished mes. outbox rows from the preview's /api/mes/outbox, posts each as a B2MML-style JSON ProductionPerformance message carrying the event id, and marks it published; on failure it records attempts and last_error. A message is built from the outbox row's payload alone. Push and give me the commands.Add MES_ERP_PUBLISHER_KEY for Preview exactly as you did the tag key. Then run the publisher with the stub stopped (attempts and last_error fill in, nothing published), start the stub with node scripts/erp-stub.mjs in a second terminal, run it again (each message arrives once), and a third time (nothing new).
Revision test, on the development project, acting through the app as each person (I will switch with dev_act_as): as ENG-1 copy RT-BRACKET-B to RT-BRACKET-C revision C in draft with its operations, steps, parameters and materials (without imported_from), lower form_pressure_bar usl to 128 and OP20 std_cycle_sec to 40. Then tell me what to click as ENG-1 to try editing revision B, as QA-1 to approve C, as ENG-1 to make it effective, and as PLN-1 to release PO-1002 on B and then on C. Afterwards rerun mes_compute_shift_performance for CELL-B on the seed's Monday shift and show ideal_cycle_sec and oee.You will see recreated screen
- A refusal is reported, never a pretend success: nothing is marked published until the ERP answers.
- Run it again and nothing is sent twice.
You will see recreated screen
| Code | Rev | Status | Effective |
|---|---|---|---|
| RT-BRACKET-C | C | effective | today |
| RT-BRACKET-B | B | superseded | 1 Jan 2026 – today |
| RT-BRACKET-A | A | superseded | 2025 |
- One effective revision per item, enforced by the partial unique index.
- The draft-only trigger. CELL-B's 2 March OEE still uses 45 s and stays 0.7500.
Check it worked
Every outbox row is published once and the stub's file has one line per event; C is effective, B superseded, PO-1002 released on C, and the seed's Monday shift still shows ideal_cycle_sec 45 and oee 0.7500. The pull request is approved by owner two and merged.
If it goes wrong
The publisher marks events published while the stub is down
A stand-in that pretends is worse than none. Say: Mark published only after a 2xx answer; on any other outcome record attempts and last_error. Add a test with the receiver stopped.
The real ERP sits behind the plant firewall and every call times out
That is an IT question, not a failed test: the address must come from configuration with no public default, and an unreachable ERP reports "could not reach", not "failed". The connectivity design (Foundation Session 20) and the IT package (Session 21) say what IT approves.
Knowledge check
Why does an MES message to the ERP come from an outbox row written in the same transaction as the record?
Knowledge check
On CELL-B the shift is 480 minutes with 30 planned_down and 390 running. Availability is:
References
- ISO 22400-2:2014, Key performance indicators for manufacturing operations management. https://www.iso.org/standard/54497.html
- OPC Foundation: OPC UA. https://opcfoundation.org/about/opc-technologies/opc-ua/
- Eclipse Sparkplug specification. https://sparkplug.eclipse.org/
- eCFR: 21 CFR Part 11, Electronic records; electronic signatures. https://www.ecfr.gov/current/title-21/chapter-I/subchapter-A/part-11
- PostgreSQL Documentation: WITH queries (recursive). https://www.postgresql.org/docs/current/queries-with.html
Chapter 4 · Sessions 5–6
Move the records, prove it, switch the old tool off
MES history is rarely migrated whole. You bring the definitions, the open orders and the genealogy your traceability obligations need, rehearse on the development project with a copy IT has approved, then import into production through the import workflow, started from main, run both side by side for a week, cut over and cancel with the saving written from invoices.
25 minSessions 5–6: 4 stepsCounts must add upEnds with the module gate
By the end of this chapter you can
- Map an export, report every row that cannot be placed, and rehearse the import on the development project.
- Import into production through the import workflow, started from main against an approved sha256, and prove the counts and traces match the old tool.
- Run side by side, cut over with a rollback plan, and cancel the old tool with the saving from real invoices.
| Bring across | Leave in the export | Rule |
|---|---|---|
| Product definitions for the first scope | Obsolete routings | One effective revision per item; operations point to real work centres |
| Open orders: planned, released, on_hold | Orders half done | Finish or hold them in the old tool before cut-over; import as history |
| Genealogy for the last 12–24 months your obligations need | Older genealogy | Every link resolves to a real lot; no lot descends from itself |
Imported history (completed runs, consumptions, productions, genealogy) can never be changed afterwards; imported open orders and definitions follow the normal rules. An import sends nothing to the ERP, which already knows these orders. Where records are regulated, the retention period comes from your written procedure: the batch records of 21 CFR 211.188 and 211.192, or device history records under 21 CFR 820 [1].
Session 5: Read the export and write the mapping, writing nothing to any database
30 minutesWhy
An import that cannot account for every row is not finished, and the cheapest place to find an unmatched work centre or a lot that descends from itself is a report run before anything is written. Never creating equipment inside the import keeps one equipment list: a missing work centre is added by the person who owns the register.
Do this
Take the export yourself from the old tool's own export page, and keep it in a private company folder, never in the repository. If you have no MES, use the routing export from the ERP or the planners' spreadsheet.
I will describe the old MES export's files and columns below (no data). On a new branch mes/import:
1. Write docs/mes-mapping.md: old field → table and column; old work centre codes → our equipment codes; old statuses → ours (orders: planned, released, on_hold; routings: effective for the current revision, superseded for earlier); old units → our units; old lot numbers → lot_no. One effective revision per item.
2. Write scripts/import-mes.mjs with a --dry-run mode that reads the files from a path I give, applies the mapping, writes nothing, and reports per file: rows read, rows it would import, and every row it cannot place with the reason (work centre not found, item not found, unit not found, lot link to a missing lot, a lot that descends from itself, a second effective revision). It never creates equipment, items or people.
3. Two targets with the same code: --target dev asks for the development connection string with hidden input and refuses any host but tsrqponmlkjihgfedcba, and --undo <batch> removes only that batch's rows, on dev only; --target production refuses unless it runs inside the import-mes workflow in GitHub Actions, signed in as mes_import. Every row gets ext imported_from with the old tool's name and old id. Add the rule that refuses update or delete of imported history.
4. Tests on a made-up export of three routings, five orders and fifty lots, marked synthetic, including one bad row of each kind, and the count rule: rows read = imported + skipped, per file.
Push, open "MES import", wait for every check and report.
<paste the file names and their column headers, no data>node scripts/import-mes.mjs --dry-run --from ~/private/mes-exportYou will see recreated screen
- Fix the register or the mapping, never the import: the owner of the equipment register adds PRS-9.
- The three numbers the cut-over depends on, all zero.
Check it worked
The dry run shows zero unmatched work centres, zero unresolved lot links, zero loops and one effective revision per item; read = would-import + skipped for every file; docs/mes-import-report.md records the numbers and the months of genealogy you chose and why.
If it goes wrong
The export holds operator names
Keep names as text in ext only where a record needs them, and create no person rows for people who have left. Ask quality what the retention procedure requires.
Claude Code asks to read the export to "check the format"
Give it the column headers and a few made-up rows that have the same shape, never the real file. The real file stays in your private folder until IT approves the rehearsal.
Session 5: Rehearse the import on the development project with an approved copy
30 minutesWhy
The first import of real records should never be the one into production. A rehearsal on the development project, with a copy IT has approved, shows the counts, the traces and the time it takes, and the copy is deleted the same day, so real data does not linger where made-up data lives.
Do this
Get IT's written approval to load a copy into acme-platform-dev for one day, redacted where it holds personal data (operator names replaced by codes). With MES import merged, run the rehearsal yourself, pasting the development connection string when asked:
node scripts/import-mes.mjs --target dev --from ~/private/mes-exportRead-only, on the development project: for each imported table, the count of rows with ext imported_from, beside the numbers in docs/mes-import-report.md; the five resolve checks (no operation without a work centre, no genealogy link to a missing lot, no non-raw lot without a parent unless listed, no run without a definition, one effective revision per item); then mes_trace_backward for the three finished lots and mes_trace_forward for the two raw lots I name below, with EXPLAIN ANALYZE times. Lots: <paste>Compare each trace with the old tool's own trace report, lot by lot. Then remove the copy from the development project the same day with node scripts/import-mes.mjs --target dev --undo <batch id it printed>, which deletes only that batch's rows, and write the date in docs/mes-import-report.md.
You will see recreated screen
- Every number traced to the report.
- A finding on real volume the seed could never show. Fix it before production.
Check it worked
The rehearsal's counts match, the resolve checks pass, three lots trace backward and two forward identical to the old tool's reports in under one second each, and the copy was removed from the development project the same day, with the date in docs/mes-import-report.md.
If it goes wrong
A trace takes a second or more
Ask for the two indexes on the genealogy table as a separate spine migration (core_lot_genealogy is a spine table, never in the module's migration), merge it, and time again.
The rehearsal stopped half way when the connection dropped
It ran in one transaction per file, so a file is either in or not. Rerun it: rows already imported are found by their old id and skipped, and the counts must still add up.
Session 6: Import into production through the import workflow, and prove the counts
25 minutesWhy
Production gets the same code the rehearsal proved, run by a workflow a person starts from main, as the insert-only account mes_import, never by a person running SQL against the live database. A pull request that adds only docs/imports/mes-approved.md (each file's sha256 and expected counts, no data) is reviewed by owner two like any change, and the workflow refuses any other export and fails on any mismatch. mes_import is set to NOLOGIN at cut-over, so a forgotten password cannot write history later.
Do this
With MES import and the index migration merged (the pipeline has applied them; its run is green), upload the export files to a private Storage bucket named imports in the live project (Public bucket off), and work out each file's sha256 on your computer with shasum -a 256.
https://supabase.com/dashboard/project/abcdefghijklmnopqrst/storage/buckets
The live project's Storage: the private imports bucket.
On a new branch mes/import-prod:
1. Add docs/imports/mes-approved.md holding only the batch id, each export file name in the imports bucket with its sha256 (I give you the values), and the expected rows read, imported and skipped per file from the rehearsal (no data).
2. Add .github/workflows/import-mes.yml, started only by hand (workflow_dispatch) and refusing any branch but main: it downloads the export from the imports bucket, refuses it unless its sha256 and counts are in docs/imports/mes-approved.md on main, runs node scripts/import-mes.mjs --target production signed in as mes_import, and fails if any count differs. No GitHub environments or required reviewers: the reviewed pull request is the approval.
3. A migration creating the role mes_import: insert only on the tables the import writes, reading only the spine tables it matches against, never the service role key. I set its password myself and type it as the Actions secret MES_IMPORT_DB_PASSWORD; list it by name in docs/KEYS.md.
Push, open "MES import into production", wait for every check and report.Set mes_import's password yourself in the live project and type it at the repository's secrets page. Owner two approves; merge. Start the import yourself: Actions → import-mes → Run workflow, branch main. When it is green:
Read-only, as QA-1 on production: the same counts, resolve checks and traces as the rehearsal, against docs/mes-import-report.md, and write the results into docs/cutover.md on a new branch mes/cutover. Do not change any data.You will see recreated screen
| File | Read | Imported | Skipped |
|---|---|---|---|
| routings.csv | 214 | 211 | 3 (listed) |
| orders.csv | 37 | 37 | 0 |
| genealogy.csv | 18,402 | 18,402 | 0 |
- An export whose sha256 or counts are not in the approved file is refused before anything is written.
- Read = imported + skipped, file by file. A count that differs fails the run.
Check it worked
The import-mes run, started from main, is green: the sha256 matched docs/imports/mes-approved.md and rows read = imported + skipped for every file; docs/cutover.md shows the resolve checks passing and the traces matching the old tool.
If it goes wrong
Production reports a column or table missing at import
The pipeline did not apply a migration. Open the deploy run on GitHub's Actions tab; do not apply anything by hand. The daily freshness check from Session 11 should also have flagged it.
The run refuses the export: sha256 not approved
The file in the bucket is not the one owner two approved. Upload the approved file again, or open a new pull request with the new sha256 and counts. Never change the workflow to skip the check.
Someone suggests running the import SQL straight against production to save time
No. Production changes come through the pipeline and the import workflow, so every row has its imported_from mark, its audit entry and the mes_import identity.
Session 6: A week side by side, then cut over and cancel with the saving from invoices
60 minutes, after a weekWhy
A week of both systems on the same orders, with the numbers compared to a hand count, is the evidence that the new way records what the old way did. Cancelling only after the cut-over works and the full export is stored, with the saving worked from real invoices, is what makes the figure something finance can sign.
Do this
For one week, on the chosen line the new screens are the record and the supervisor keeps the old tool up to date for the same orders. Then:
On branch mes/cutover, add to docs/cutover.md, from numbers I give you and read-only queries on production through the app as QA-1:
1. The week side by side: orders completed, good and scrap per order, deviations, and for one machine and one shift the stop log and counts, old tool against platform, each with its source. Explain every difference or mark it unexplained.
2. My hand OEE for that shift (I paste the sums) against mes_shift_performance, to two decimals.
3. Three of the week's lots traced both ways in both systems, with the time in seconds.
4. The three kept rules, each as one query with its result: the interlock tests pass on the development project; an update or delete of a consumption, production, count or parameter row is refused; every signed step has a performer signature and a verifier who is not the performer.
5. The cut-over date and rollback plan: who tells the floor, when the old tool becomes read-only, how the ERP is switched (old interface off, the publisher pointed at the ERP), where the old export is kept, and the signal that makes us roll back.
6. The saving: the old cost from the invoice I paste, minus what the module costs to run on services we already pay for, with the arithmetic shown.
7. A migration that sets mes_import to NOLOGIN at cut-over, applied by the deploy workflow on merge.
Then update docs/mes-inventory.md: each MESA function marked replaced, moved to another module, kept elsewhere or out of scope, with the date. Open "MES cut-over", wait for checks, report.
<paste the week's numbers, the hand OEE sums and the invoice lines>On the cut-over date: point the publisher at the ERP (MES_ERP_PUBLISHER_KEY and the ERP address for Production, entered by you in Vercel), make the old tool read-only, and watch the first shift. Then cancel on the vendor's own account page, within its notice period, after the full export is stored in the company's storage.
You will see recreated screen
| Measure | Old tool | Platform | Hand |
|---|---|---|---|
| Good, PO-3112 | 1,940 | 1,940 | 1,940 |
| OEE, press 4, 18 Nov day | 81% | 0.74 | 0.74 |
| Trace back FG-3120 | 47 min | 0.6 s |
- The old tool's 81% used the whole shift as its base; the platform and the hand sum agree.
- From invoices, never estimates.
Check it worked
docs/cutover.md is merged with every difference explained, OEE matching your hand sum to two decimals, three traces with times, the three kept rules, the cut-over date and rollback plan, and the cancellation (or the date the plan ends) with the saving from invoices. At the end of the first shift: no stop without a reason, no run left running that should be complete, every outbox row published.
If it goes wrong
A difference between the old tool and the platform cannot be explained
You are not ready to cut over. Keep both running, find the cause (a time base, a stop counted in one list only, a manual count), fix it, and run another week if needed.
The first shift ends with outbox rows unpublished
Check the publisher's last_error. A 403 from the ERP side is often a proxy or a rate limit, not a wrong key: find out who refused before changing any key.
Finance asks whether the saving counts licences you still need
Only what you cancel counts. Anything still needed by another site or module stays in the inventory as kept elsewhere.
Knowledge check
Where do real MES records go first?
Knowledge check
When may the old MES be cancelled?
References
- eCFR: 21 CFR Part 211, subpart J, records and reports (batch production records). https://www.ecfr.gov/current/title-21/chapter-I/subchapter-C/part-211
- Supabase Docs: Database migrations. https://supabase.com/docs/guides/deployment/database-migrations
- Vercel Docs: Environment variables. https://vercel.com/docs/environment-variables
- SYMESTIC: the 11 core MES functions (MESA-11). https://www.symestic.com/en-us/what-is/mesa-11
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
Manufacturing Execution (MES): Routings, Interlocks, Genealogy and OEE on Your Own Spine
Element M04 complete · Learner
Your LMS records this completion. For the CivOps Foundation certificate, finish the Foundation Course at https://civops.io/learn.