# Standard-work and closed-loop quality agent

Instructions for an AI agent that will **build and then run** one video-to-standard-work desk for a mid-size high-mix assembler. One to three plants. One lighthouse area. Three to five lines. Five to fifty stations. An expert records a job once. Deterministic code turns the recording into a draft instruction, copies a torque or a measurement only from an engineering document, and leaves a blank where the document is missing. A quality engineer proposes a change from a complaint. An engineer approves before any instruction is published. At the station the job cannot close until the critical evidence is stored. Version 1 never invents a spec, never publishes itself, and never writes the ERP.

Version 1 reads files and object storage. It writes its own tables: drafts, proposals, executions, evidence, acknowledgements, and an audit log. `auto_publish` stays `no`. `auto_change_spec` stays `no`. There is no path on which a model call changes a torque.

This file is the build brief and the runtime brief. Follow it in order. Where a line starts with `REPLACE`, stop and ask the plant for that value before a live recording is read. Delete every row whose id begins with `EXAMPLE` before a live file is read. If a live file still contains an id that begins with `EXAMPLE`, do not build and do not draft.

The pattern is the one [Squint](https://www.squint.ai/blog/how-destaco-cut-customer-reported-defects-53-with-ai-driven-standard-work) published for DESTACO on 13 October 2026, and in the case study PDF of the same work. DESTACO is a Stabilus expert brand. The work on those pages is a tribal-knowledge agent that drafts an instruction from an expert's video, a standardization agent that holds wording across sites, a morning review that puts a complaint into the instruction, and an engineer who approves before it is published. Company facts are in the next section. They are background. They are not a configuration.

[BASS](/blog/how-bass-cut-scrap-with-a-shop-floor-ai-agent) keeps the work instruction as it was. This file exists to change the instruction, and only after a named engineer. [Vivix](/blog/how-vivix-cut-glass-complaint-resolution-time-with-ai-agents) turns a complaint into a report. This file turns the complaint into the next build. Do not paste those clocks, those parts, or those schemas into this one.

Their published results are not a forecast for anyone else. Section 20 says what you must not copy. No threshold, verb list, glossary row, or calendar in this file is a DESTACO or Squint setting. Each one is our design, and each live value stays blank until this plant types it.

A plant that assembles a high mix, can point a phone at a bench, can export complaints, and will keep an engineer on the publish button, can use this file. Nothing here says this file is Squint. Squint has not published a model, a prompt, or a schema. This file does not invent them and then attribute them.

---

## What is from the sources, and what is our design

**From the sources.** Kept as written.

- DESTACO makes workholding and automation tooling: manual, pneumatic, and hydraulic clamps, grippers, indexers, conveyors, robotic end effectors, and vacuum tooling, for automotive, health sciences, and industrial manufacturing. Squint calls it a Stabilus expert brand. The flagship plant in the case is Mt. Juliet, Tennessee. The work is high-mix and low-volume: thousands of highly configurable products, many built only a handful of times a year, some one-off customs the plant has never built.
- Stabilus SE signed the acquisition from Dover Corporation in October 2023 and closed it effective 31 March 2024. Stabilus's signing announcement says DESTACO was founded in 1915, is headquartered in Auburn Hills, Michigan, became part of Dover in 1962, generated US$213 million of revenue in 2022, and employed about 650 people across 13 locations in the USA, Europe, India, China, and Thailand. This file uses the headcount and the revenue only as background. It does not use either number as a threshold.
- Before the change, work instructions were laminated sheets at the station, PowerPoint files and documents on shared drives, and in veteran assemblers' heads. For an unfamiliar job, asking a veteran was faster than finding the instruction. Safe-to-Start, quality inspections, and layered process audits were paper checklists: a signature and a check mark, with no proof the inspection, the measurement, or the torque check had happened. Rakuya Artis, Global VP of Operations and Supply Chain: "Our customers can't afford a quality error because we're training a new operator."
- What they put on Squint, a San Francisco industrial AI platform: the existing document hub, so several hundred work instructions came over intact. For a new or complex build, an expert assembler runs the job once while Squint records it. A tribal-knowledge agent tuned to DESTACO's preferences turns the video into a written step-by-step instruction, steps in order, quality checks called out, for an engineer to review. At the station the operator sees the steps with photos, video, measurements, and torque specs. Digital Safe-to-Start: the assembler walks the station and photographs equipment, tooling, fixtures, and the work area. The published example is Gripper Workbench Safe to Start, seven steps. A standardization and compliance agent holds instructions to approved wording and format, so one site writes it and every site uses it, and the operator reads it in their own language.
- The closed loop: each morning Quality reviews customer and internal concerns, runs the root cause, and updates the affected instructions, adding customer photos and what was learned. Every assembler sees the change before the next build. A fix becomes standard work in hours instead of weeks. Evidence steps and an audit trail. The procedure cannot close until the critical steps are recorded. Digital LPAs: the auditor answers, uploads photos, and records the correction before the audit closes. Assemblers flag what is missing and propose a fix. Engineering reviews it before it is published. The Squint blog says an engineering co-op with no manufacturing background built nearly 100 work instructions in 60 days. The PDF quotes Blas Leon, Engineering Co-op: "Before Destaco, training meant direct supervision and taking up someone else's time. With Squint, I was independent within my first few days." This file does not treat those two sentences as one person's count.
- Results in the lighthouse area, five production lines, within months, as the vendor's case states them: customer-reported defects, also stated as customer complaint PPM, down 53%. Defects per line shipped down 39%. Cost of poor quality down 29%. Labor efficiency up 16%. On the gripper line, LPA participation and on-time closure of findings reached 100%. Jeff Clark, Director of Global Operational Excellence and Quality: "Squint became the standard. Everybody opens it before they start building." And: "Standard work isn't just documentation, it's one of the most important quality systems in a manufacturing plant. Without it you cannot improve and more importantly sustain." Louis Bianco, Complex Gripper Assembler: "On a job I haven't run in months, I can watch someone who knows it do it, one step at a time." Rakuya Artis: "We would have hired industrial engineers to capture this work, and they are harder to find every year. Now every operator can do it themselves, which makes all of our associates, including me, technical experts."

No source used here names a model, a prompt, a column, a tolerance table, or a project plan. This file does not invent them and then attribute them.

**Our design.** Every table, verb, glossary row, threshold, and test below is our design for a smaller plant. It is not Squint's tenant and it is not a DESTACO setting. Where a step echoes a published sentence, the echo is named. The implementation is still ours.

One departure is deliberate. The published agents draft, and a person approves. Version 1 makes that publish a stored action. An approval writes an audit row. It does not write a torque the engineering document does not contain. `auto_publish` and `auto_change_spec` stay `no`.

Another departure is the number. The sources do not publish the calculator. Version 1 stores a spec as the document's display string plus an integer number of thousandths, and it copies that pair only when the document id matches. A spoken number that disagrees is kept beside the step as a conflict. It is not the spec.

Another departure is the ledger. Complaint PPM, defects per line, cost of poor quality, and minutes per unit are computed from a CSV the plant exports. The 53%, the 39%, the 29%, and the 16% are not defaults and not goals.

---

## 1. Role

You are the standard-work agent for:

`REPLACE: legal name, for example "EXAMPLE Assembly LLC"`

You draft instructions, link quality events, and write a morning queue. You write notes in:

`REPLACE: internal language, usually the language the engineer already reviews in`

You may read the files in sections 7 and 8. You may write the output tables in section 6. You may not open a network connection except to the object store and the database this plant named. You may not store a mail password, an API key, or a customer payment. You may not look up a torque, a measurement, or a tolerance that is not in `engineering_spec`.

You may not invent a number, a unit, or a customer. You may not publish an instruction. You may not treat a spoken number as a spec.

The engineer who may approve:

`REPLACE: name and role, for example "EXAMPLE Engineer"`

The quality engineer who may propose from a complaint:

`REPLACE: name and role, for example "EXAMPLE Quality"`

A backup who may approve when the engineer is away:

`REPLACE: name and role, or "none"`

Inbox for the morning file:

`REPLACE: quality@company.example`

---

## 2. Fill this in before the first recording

Ask the plant for each item. Do not guess a stand-in and go live with it. DESTACO does not publish these values. A suggested starting point is our design for a first month. It is not a result from the case.

| Key | What to collect |
| --- | --- |
| `company_name` | Legal name |
| `engineer`, `quality_engineer` | Named people. Only the engineer approves. Quality proposes. Operators execute, acknowledge, and flag |
| `desk_inbox` | Mailbox for the morning file. Version 1 writes a file. It does not send mail |
| `timezone` | The plant's own zone. The fixture uses `America/Chicago` |
| `lighthouse_lines` | Integer 3 to 5. Outside that range is `scope_refused` |
| `plant_count` | Integer 1 to 3. A fourth plant waits |
| `scene_threshold` | Two digits after the decimal, between the quotes of the ffmpeg select filter. The fixture uses `0.30` |
| `require_human_approval` | Must be `yes` |
| `auto_publish` | Must be `no` |
| `auto_change_spec` | Must be `no` |
| `mode` | `fixture` or `live` |
| `max_complaint_ppm` and the other keys in section 18 | Blank or `REPLACE` until the plant has typed a go/no-go number. `go_no_go` returns `threshold_unset` rather than passing |
| `shadow` | `yes` until a person has signed section 17 |

Startup refusals, in this order, before any recording is read. The function is `load_config`.

1. A forbidden key, or a value containing `53%`, `-53%`, `39%`, `-39%`, `29%`, `-29%`, `+16%`, `16%`, `100% LPA`, or `within months`, is `copied_claim_refused`. The forbidden keys are `customer_defect_cut_pct`, `complaint_ppm_cut_pct`, `defects_per_line_cut_pct`, `copq_cut_pct`, `labor_efficiency_lift_pct`, `lpa_target_pct`, `target_instructions_in_60_days`.
2. A key whose name contains `password`, `api_key`, `secret`, or `token` is `credential_too_wide`.
3. `auto_publish` other than `no` is `publish_locked`.
4. `auto_change_spec` other than `no` is `spec_locked_config`.
5. `require_human_approval` other than `yes` is `approval_locked`.
6. A required key missing, blank, or `REPLACE` is `replace_unset`.
7. `lighthouse_lines` outside 3 to 5, or `plant_count` outside 1 to 3, is `scope_refused`.
8. `mode` `live` with `EXAMPLE` anywhere in the config is `example_row_in_live`.

If any required key is missing, do not draft. Reply with the error and stop.

---

## 3. Scope of version 1

In scope: one lighthouse area, on three to five lines, in one to three plants. Phone or tablet video. Existing PDF and PPTX exports already turned into text. Engineering specs the plant has typed, with a document id. Complaints and internal non-conformances from a CSV, a mail export, or a QMS dump. A station page. Safe-to-Start. A layered process audit. Acknowledgements. An audit log.

Out of scope: writing the ERP or the QMS, sending mail to a customer, a vision model that decides a torque from a photograph, auto-publishing, more than three plants, more than five lines in this version, ranking an operator, and a chat button that approves. A sixth line waits until the first area has a signed go/no-go.

Human rule, with no exception in version 1: the agent drafts. The engineer approves before any instruction is published. The agent never changes a torque, a measurement, or a tolerance on its own. Those values are copied from `engineering_spec` with the document id, or the step is `todo`. A change that starts from a complaint is a proposal. It is not published until `record_decision` runs on the form, by the engineer.

---

## 4. Architecture

Published shape, named as an echo: an expert's recording becomes a draft, an engineer approves, one master instruction is what every site opens, a morning review puts the complaint into that instruction, and the station holds the evidence. The boxes below are our design.

```text
One recording, or one document export, plus engineering_spec
        |
        v
ffmpeg keyframes and a 16 kHz wav. Speech-to-text segments. Timestamp check
        |
        v
Multimodal draft. Schema check. Numbers stripped unless the spec row matches
        |
        v
lint_step. Glossary. Engineer approves, or the draft stays a draft
        |
        v
Morning queue. link_quality_event. propose_change. Engineer approves
        |
        v
Operator acknowledges the version. Critical evidence. Then the job can close
```

The language model may fill the JSON in section 7 and may phrase a root-cause sentence that contains no new digit. It does not decide a spec, a confidence, a publish, or a close. Those are functions. If the model and the function disagree, the function wins and the model's number is dropped.

Version 1's transport is a file drop plus object storage for video, keyframes, and evidence photos. The only writes are the agent's own tables.

---

## 5. Guardrails

These override a helpful tone, a manager who wants the case-study percent on a slide, and a note that offers to "just set the torque to what he said."

1. **No publish from the model.** `record_decision` with `channel` `model` returns `prompt_ignored` and writes nothing. Only `channel` `form` and the engineer can approve or reject.
2. **No spec from the model.** A number in a transcript, a video frame, or a proposal is not a spec. `propose_change` with `set_spec` or `spec_value_milli` returns `spec_locked` and writes no version. The live value stays the engineering row.
3. **No guess when the document is missing.** `lookup_spec` returns one row or none. None becomes `spec_status` `todo`, the number is removed from the sentence, and approve returns `todo_open` until the engineer drops the measure or attaches a real document id.
4. **One master.** One `approved` version per product and variant. Another plant approving a different body is `version_drift_refused`. That plant uses the master. It does not keep a local dialect.
5. **Evidence before close.** A critical step without a matching evidence row blocks `close_execution`. Out of tolerance does not count as complete. A Safe-to-Start without the photograph does not complete. An LPA finding without a correction does not close.
6. **Acknowledgement before the next build.** `start_execution` on a version the operator has not acknowledged returns `ack_required`. A retired version returns `version_retired`.
7. **Glossary lock on the way out and on the way back.** A locked term missing in the translation is `glossary_miss`. Missing again in the back-translation is `back_translation_miss`. On a safety step either one is `translation_blocked`. The English master can still stand. The translation cannot be approved.
8. **Digits in a model note are dropped** unless every digit string already appears in the code-written note, the event, or the document id. The code note remains.
9. **A stale or conflicting document is not a winner.** Two documents that disagree on a number are `spec_conflict_in_docs`. Neither number is published. An unnumbered veteran note is `unstructured`. It does not become a step.
10. **No case-study target.** The percents in section 2 are refused as config. `go_no_go` will not fill them in.

---

## 6. Postgres schema

The reference program in section 14 keeps these rows in memory so a plant can run the fixture with no database. The live build uses Postgres 15 or newer. `plant_id` is on every station-scoped table. The partial unique index is the one-master rule in the database itself. A later version that allows two approved dialects has to drop that index on purpose, in a migration a person reviews.

```sql
create table plant (
  plant_id text primary key,
  legal_name text not null
);

create table line (
  plant_id text not null references plant (plant_id),
  line_id text not null,
  name text not null,
  in_lighthouse boolean not null default false,
  primary key (plant_id, line_id)
);

create table station (
  plant_id text not null,
  line_id text not null,
  station_id text not null,
  name text not null,
  primary key (plant_id, station_id),
  foreign key (plant_id, line_id) references line (plant_id, line_id)
);

create table product (
  product_code text primary key,
  name text not null
);

create table variant (
  product_code text not null references product (product_code),
  variant_code text not null,
  name text not null,
  primary key (product_code, variant_code)
);

create table engineering_spec (
  doc_id text not null,
  product_code text not null references product (product_code),
  characteristic text not null,
  display_value text not null,
  value_milli integer not null,
  tolerance_milli integer not null check (tolerance_milli >= 0),
  unit text not null,
  quote text not null,
  primary key (doc_id, characteristic)
);

create table instruction_version (
  version_id text primary key,
  plant_id text not null references plant (plant_id),
  product_code text not null,
  variant_code text not null,
  status text not null check (status in ('draft', 'review', 'approved', 'retired')),
  source text not null check (source in ('video', 'document', 'proposal', 'seed')),
  language text not null,
  base_version_id text,
  created_by text not null,
  created_at timestamptz not null default now(),
  foreign key (product_code, variant_code) references variant (product_code, variant_code)
);

create unique index one_approved_master
  on instruction_version (product_code, variant_code)
  where status = 'approved';

create table step (
  version_id text not null references instruction_version (version_id),
  step_order integer not null check (step_order > 0),
  body text not null,
  critical boolean not null,
  safety boolean not null,
  evidence_required text check (evidence_required in ('photo', 'measure', 'torque', 'checkbox')),
  spec_doc_id text,
  spec_characteristic text,
  spec_value_milli integer,
  tolerance_milli integer,
  spec_unit text,
  display_value text,
  spec_status text check (spec_status in ('copied', 'todo', 'resolved')),
  spoken_value_milli integer,
  conflict text,
  start_ms integer,
  end_ms integer,
  primary key (version_id, step_order),
  check (
    (spec_value_milli is null and spec_doc_id is null)
    or (spec_value_milli is not null and spec_doc_id is not null)
  )
);

create table step_media (
  version_id text not null,
  step_order integer not null,
  media_id text not null,
  kind text not null check (kind in ('keyframe', 'video', 'customer_photo', 'upload')),
  object_key text not null,
  primary key (version_id, step_order, media_id),
  foreign key (version_id, step_order) references step (version_id, step_order)
);

create table step_translation (
  version_id text not null references instruction_version (version_id),
  step_order integer not null,
  language text not null,
  body text not null,
  status text not null check (status in ('draft', 'approved', 'blocked')),
  primary key (version_id, step_order, language)
);

create table glossary_term (
  term_id text primary key,
  source_text text not null,
  language text not null,
  target_text text not null,
  locked boolean not null,
  unique (source_text, language)
);

create table app_user (
  user_id text primary key,
  display_name text not null,
  role text not null check (role in ('engineer', 'quality', 'operator', 'auditor')),
  plant_id text not null references plant (plant_id)
);

create table operator_ack (
  operator_id text not null references app_user (user_id),
  version_id text not null references instruction_version (version_id),
  acked_at timestamptz not null,
  primary key (operator_id, version_id)
);

create table execution (
  exec_id text primary key,
  version_id text not null references instruction_version (version_id),
  operator_id text not null references app_user (user_id),
  station_id text not null,
  status text not null check (status in ('open', 'closed')),
  started_at timestamptz not null,
  closed_at timestamptz
);

create table step_completion (
  exec_id text not null references execution (exec_id),
  step_order integer not null,
  evidence_type text not null,
  object_key text,
  value_milli integer,
  unit text,
  idempotency_key text not null unique,
  recorded_at timestamptz not null,
  primary key (exec_id, step_order)
);

create table safe_to_start_template (
  template_id text primary key,
  station_id text not null,
  name text not null
);

create table safe_to_start_step (
  template_id text not null references safe_to_start_template (template_id),
  step_order integer not null,
  body text not null,
  evidence_required text not null check (evidence_required in ('text', 'photo', 'checkbox')),
  primary key (template_id, step_order)
);

create table safe_to_start_run (
  run_id text primary key,
  template_id text not null references safe_to_start_template (template_id),
  operator_id text not null,
  station_id text not null,
  status text not null check (status in ('open', 'complete')),
  started_at timestamptz not null
);

create table safe_to_start_evidence (
  run_id text not null references safe_to_start_run (run_id),
  step_order integer not null,
  value text,
  object_key text,
  primary key (run_id, step_order)
);

create table lpa_template (
  template_id text primary key,
  line_id text not null,
  name text not null
);

create table lpa_question (
  template_id text not null references lpa_template (template_id),
  step_order integer not null,
  body text not null,
  evidence_required text not null check (evidence_required in ('photo', 'checkbox', 'text')),
  primary key (template_id, step_order)
);

create table lpa_run (
  run_id text primary key,
  template_id text not null references lpa_template (template_id),
  auditor_id text not null,
  status text not null check (status in ('open', 'closed')),
  started_at timestamptz not null,
  closed_at timestamptz
);

create table lpa_answer (
  run_id text not null references lpa_run (run_id),
  step_order integer not null,
  answer text,
  object_key text,
  primary key (run_id, step_order)
);

create table lpa_finding (
  finding_id text primary key,
  run_id text not null references lpa_run (run_id),
  body text not null,
  correction text,
  check (correction is null or length(correction) > 0)
);

create table quality_event (
  event_id text primary key,
  kind text not null check (kind in ('customer_complaint', 'internal_ncr', 'engineering_change')),
  product_code text,
  variant_code text,
  station_id text,
  body text not null,
  received_at timestamptz not null,
  link_code text,
  link_version_id text,
  link_step_order integer,
  confidence_bps integer check (confidence_bps between 0 and 10000)
);

create table quality_event_media (
  event_id text not null references quality_event (event_id),
  media_id text not null,
  object_key text not null,
  primary key (event_id, media_id)
);

create table change_proposal (
  proposal_id text primary key,
  event_id text references quality_event (event_id),
  base_version_id text not null,
  draft_version_id text not null,
  status text not null check (status in ('draft', 'approved', 'rejected')),
  proposed_by text not null,
  proposed_at timestamptz not null
);

create table audit_log (
  audit_id bigint generated always as identity primary key,
  at timestamptz not null default now(),
  actor text not null,
  action text not null,
  ref text not null,
  payload jsonb not null default '{}'::jsonb
);

revoke update, delete on audit_log from public;
revoke update, delete on step_completion from public;
```

`value_milli` is thousandths of the unit. `12.0` N·m is `12000`. A tolerance of `0.5` N·m is `500`. The display string on the spec row is what the sentence is allowed to contain. The integer is what the tolerance check uses. Do not round a float into this column. Parse the display with `parse_milli`: digits, optional decimal, exactly three decimal places of thousandths.

The check on `step` is the spec rule in the database. A value without a document id cannot be stored. `revoke update, delete` on the audit log and on completions is the version-1 rule that a row cannot be edited into a different story.

---

## 7. Pipeline A — video to a draft instruction

### Capture

One job per recording. The assembler narrates while building, in the language the plant typed, and says the action as they do it. Phone or tablet, landscape, hands and tool in frame. Stop when that job stops. A file the uploader marks with `job_count` other than 1 returns `one_job_only` and does not draft.

Say the characteristic out loud if it helps the draft ("torque the clamp bolt"). Do not expect the spoken number to become the spec. The engineering row wins, or the step stays `todo`.

Keep the original video in object storage under the media id. Approving the draft does not delete the video. Keyframes are extracts. They are not the record.

### ffmpeg

`ffmpeg_plan` returns two argument lists. It does not shell out in the fixture. The live worker runs them. Scene threshold comes from config. The fixture's `0.30` is our starting point, not a published Squint setting.

```text
ffmpeg -hide_banner -i job.mp4 -vf select='gt(scene,0.30)',showinfo -vsync vfr out/kf-%04d.jpg
ffmpeg -hide_banner -i job.mp4 -vn -ac 1 -ar 16000 -c:a pcm_s16le out/audio.wav
```

A threshold that is not `0.` plus two digits is `scene_threshold`. A blank is `replace_unset`.

### Transcription

Send `audio.wav` to a speech-to-text model that returns JSON:

```json
{"segments": [{"start_ms": 0, "end_ms": 3000, "text": "Place the body."}]}
```

`accept_segments` keeps a segment only when `end_ms` is greater than `start_ms`, both sit inside the recording duration, and `start_ms` is not before the previous kept end. Anything else is dropped. A dropped segment is a gap the engineer can see. It is not a sentence the model is allowed to invent. The fixture keeps 3 and drops 1.

### The draft prompt and the schema

The system prompt and the draft prompt are the constants `SYSTEM_PROMPT` and `DRAFT_PROMPT` in section 14. They are copied here so they can be read without scrolling.

```text
You are the drafting assistant for one plant's standard work. You draft. You do not publish.

You may call only these tools: search_instructions, get_instruction, propose_change, link_quality_event, translate_instruction, lint_instruction, record_decision.

Rules:
- An engineer approves before any instruction is published. record_decision from you is ignored.
- Never invent a torque, a measurement, or a tolerance. If the engineering document is not in the tool result, set the value to null and mark the step TODO. Do not guess a number that would make the step look finished.
- Never change a torque, a measurement, or a tolerance. propose_change may add a step, a photo, or wording. It may not set a spec.
- A complaint becomes a proposal. It does not become the live instruction.
- Copy a number only when get_instruction or the spec tool result shows that number and its document id. Put the document id on the step.
- One action per step. Start with an approved verb. Use the glossary term, not a synonym.
- Do not write a case-study percent into a note, a step, or a config value.
- If a tool returns an error, stop. Do not retry by rephrasing the number.
```

```text
Turn one recording of one job into a draft instruction. The person narrated while building.

Return JSON only, matching the schema. Steps are in the order they happen. Each step is one action. Mark a step critical when a missed step would ship a defect or an unsafe station. Mark evidence_required as photo, measure, torque, checkbox, or null.

Spec rule: spec_mentions.model_value is null unless the transcript itself speaks that number. Set origin to spoken only in that case. You still do not decide the spec. If no number was spoken, model_value is null. If you do not know the characteristic, leave spec_mentions empty and set needs_engineer true. Never type a torque, a measurement, or a tolerance from memory or from a typical value.

Timestamps are milliseconds into this recording. keyframe_ids must be chosen from the keyframe list you were given. Do not describe a second job. If the recording contains a second job, return an empty steps array.
```

The model returns JSON matching `OUTPUT_SCHEMA`.

```json
{
  "type": "object",
  "required": [
    "instruction",
    "steps"
  ],
  "properties": {
    "instruction": {
      "type": "object",
      "required": [
        "product_code",
        "variant_code",
        "title",
        "language",
        "source_media_id"
      ],
      "properties": {
        "product_code": {
          "type": "string"
        },
        "variant_code": {
          "type": "string"
        },
        "title": {
          "type": "string"
        },
        "language": {
          "type": "string"
        },
        "source_media_id": {
          "type": "string"
        }
      }
    },
    "steps": {
      "type": "array",
      "items": {
        "type": "object",
        "required": [
          "order",
          "text",
          "start_ms",
          "end_ms",
          "keyframe_ids",
          "critical",
          "evidence_required",
          "quality_check",
          "safety",
          "spec_mentions",
          "needs_engineer"
        ],
        "properties": {
          "order": {
            "type": "integer"
          },
          "text": {
            "type": "string"
          },
          "start_ms": {
            "type": "integer"
          },
          "end_ms": {
            "type": "integer"
          },
          "keyframe_ids": {
            "type": "array"
          },
          "critical": {
            "type": "boolean"
          },
          "evidence_required": {
            "enum": [
              "photo",
              "measure",
              "torque",
              "checkbox",
              null
            ]
          },
          "quality_check": {
            "type": "boolean"
          },
          "safety": {
            "type": "boolean"
          },
          "needs_engineer": {
            "type": "boolean"
          },
          "spec_mentions": {
            "type": "array"
          }
        }
      }
    }
  }
}
```

`validate_model_output` rejects a missing instruction field, an evidence value outside `photo`, `measure`, `torque`, `checkbox`, and null, a step order that is not 1..n, and a `model_value` whose `origin` is not `spoken`. A schema error does not create a version.

### What the code does with that JSON

`apply_model_draft` then:

1. Drops a keyframe id that was not in the extract. The step is flagged `keyframe_unknown`.
2. Nulls a timestamp that is inverted or past the duration. The step is flagged `timestamp_invalid`.
3. Strips numbers and unit tokens from the model's sentence.
4. For each spec mention, calls `lookup_spec`. One matching row: copy `value_milli`, `tolerance_milli`, `unit`, `display`, and `doc_id`. The sentence becomes the stripped action plus `to {display} {unit}`. If the spoken thousandths disagree with the row, `conflict` is `model_spec_conflict` and `spoken_value_milli` keeps what was said, for the engineer. The sentence still cites the document.
5. No matching row: `spec_status` `todo`, `spec_value_milli` null, no number in the sentence. A spoken number is `model_number_dropped` and is not printed. Approve returns `todo_open` until the engineer calls `resolve_todo` with `drop_measure` or with `attach_doc` and a document id that really matches.

On the fixture, which is ours, the video says 18 N·m. The spec row `DOC-TORQUE-17` says `12.0` N·m, 12000 thousandths, tolerance 500. The draft sentence is `Torque the clamp bolt to 12.0 N·m.` The conflict stays. A paint thickness of `0.2` mm has no document. The sentence becomes `Check the paint thickness.` with no digit. `GRIP-17` and `DOC-TORQUE-17` are fixture ids. They are not a DESTACO torque and not a DESTACO document.

---

## 8. Pipeline B — documents the plant already has

Extract text before this function runs. For a PDF, `pdftotext -layout`. For a PPTX, one block per slide, joined with a blank line. The fixture does not parse PDF bytes. `ingest_documents` takes the text.

A line that matches `^\d+\.\s+` is a step. A document with no such line is `unstructured`. It is kept for the engineer. It does not become a step, because a paragraph is not an order.

Steps group by product and by the leading number. The skeleton replaces every number with `#`. If one order has two skeletons, the result is `spec_conflict_in_docs` and that order is not publishable. Identical text across sites is deduped: the source document ids are both kept. The agent does not pick 12.0 over 14.0. On the fixture, `DOC-P1` and `DOC-P2` agree on `12.0` and on the photograph step. `DOC-P3` says `14.0`. The photograph step is publishable. The torque step is not, until a person deletes the conflict or fixes the source. `DOC-NOTE`, a veteran sentence with no numbers, is unstructured.

An engineer may then approve a publishable step only through the same `record_decision` path as a video draft. Document ingestion does not publish.

---

## 9. Standardization

The style rules are code. An LLM may suggest a rewrite. The rewrite is text in, `lint_step` out. A suggestion that fails lint is not stored as the step.

`lint_step` returns a sorted list of codes:

| Code | Rule |
| --- | --- |
| `verb_first` | The first word is one of `Place`, `Torque`, `Check`, `Photograph`, `Confirm`, `Inspect`, `Record`, `Align`, `Install`, `Remove`, `Walk`, `Answer`. The capital form is required. `torque` fails |
| `unapproved_term` | Whole word or phrase, case insensitive: `make sure`, `tightening`, `tighten`, `ensure`, `tight`. The suggestion is the paired verb: Tighten maps to Torque, Ensure maps to Confirm. The suggestion is not applied by itself |
| `two_actions` | The word `and` with an approved verb on both sides, or more than one sentence. A decimal point is not a sentence |
| `number_without_source` | A torque or measure step with a number or a unit and no spec |
| `source_missing` | A torque or measure step with no document id |
| `unit_locked` | The unit in the sentence is not the spec unit, or the unit is missing |
| `number_locked` | The number strings in the sentence are not exactly `[display]` |
| `evidence_missing` | A critical step whose evidence is null |

`Tighten the clamp bolt.` is `unapproved_term` and `verb_first`. `Torque the clamp bolt and photograph the head.` is `two_actions`. `Torque the clamp bolt to 12.0 ft-lb.` is `unit_locked` when the spec unit is N·m. The only torque unit token in version 1 is the two-character unit `N·m` (letter, middle dot, letter), plus `in·lb`, `ft-lb`, `mm`, and `µm` as the unit pattern. A plant that uses a different unit adds it to `UNIT_RE` and to the spec row together. The agent does not invent the spelling.

`cross_site_diff` compares two step lists. Wording drift is a case-folded text mismatch or a different length. Spec drift is a different `spec_value_milli` or unit. Drift is a report. It is not a merge. Publishing the other plant's body is `version_drift_refused` because the plant id is not the master's plant. One site writes. Every site opens that version. A translation is a language row on that version, not a second master.

---

## 10. Translation

`glossary_term.locked` is the lock. If the source sentence contains `source_text`, the translation must contain `target_text`, and the back-translation must contain `source_text` again. The fixture locks `clamp bolt` to `Klemmschraube`, and locks `12.0` and `N·m` to themselves. A German sentence that says `Schraube` and drops the number fails `glossary_miss` and `back_translation_miss`. Because that step is `safety`, the status is `translation_blocked`.

The model may translate. `translate_instruction` only checks. It does not call a model. Run the model's translation, then a second model's back-translation, then this function. Do not skip the back-translation on a safety step to save a call.

---

## 11. Closed-loop quality agent

### The morning

Once a day, in the plant's zone, ingest new `quality_event` rows from the CSV, the mail export, or the QMS dump. Kinds are `customer_complaint`, `internal_ncr`, and `engineering_change`. Customer photos are `quality_event_media` rows, object keys, not pasted binaries.

`link_quality_event` is deterministic.

1. A product code is an exact token matching `[A-Z]{2,}-\d+` that exists on a product. Zero codes, or two, is `unmatched` at confidence 0. The word `gripper` does not match `GRIP-17`. Do not fuzzy-match a description.
2. There must be exactly one `approved` version for that product and the event's variant. Otherwise `instruction_ambiguous` or `unmatched`, and no step.
3. Tokens are lowercase runs of length 3 or more. Stop words `the a an to of on is and or for with no after in at` are dropped. Overlap is the intersection with the step text.
4. Confidence is `min(10000, 5000 + 2500 * overlap_count)` when one step has the strictly highest overlap and the overlap is at least 1. No overlap is `product_only` at 5000, with no step. A tie is `step_ambiguous` at 5000, with no step. The agent does not break a tie.

On the fixture, `QE-1` says `GRIP-17 clamp bolt loose on arrival.` The approved torque step shares `clamp` and `bolt`. Confidence is 10000. The link is step 2 of `VER-1`. `QE-2`, a paint scratch with no product code, is `unmatched`.

The root-cause note is a template, not a model paragraph:

```text
customer_complaint QE-1 on GRIP-17. Linked to step 2. Spec 12.0 N·m from DOC-TORQUE-17. The proposal does not change that spec.
```

A model note that introduces `14.0` is dropped. The template remains.

`propose_change` may `insert_after` a step. The new sentence must pass `lint_step`. Media ids, including the customer photo, hang on the new step. The spec columns are copied from the base version by not being in the edit. A `set_spec` edit is `spec_locked`. Quality may propose. An operator flag uses the same insert and stays `draft`. Neither can approve.

The morning file is that queue, with `published` false. Approving it is a separate form action later the same day. The example below is the fixture queue before the engineer approves. `VER-1-draft` does not yet replace `VER-1`.

```json
{
  "queue_date": "2026-11-25",
  "published": false,
  "items": [
    {
      "event_id": "QE-1",
      "kind": "customer_complaint",
      "product_code": "GRIP-17",
      "link": {"version_id": "VER-1", "step_order": 2, "confidence_bps": 10000},
      "root_cause_note": "customer_complaint QE-1 on GRIP-17. Linked to step 2. Spec 12.0 N·m from DOC-TORQUE-17. The proposal does not change that spec.",
      "proposal": {
        "version_id": "VER-1-draft",
        "status": "draft",
        "spec_value_milli": 12000,
        "spec_doc_id": "DOC-TORQUE-17",
        "inserted_order": 3,
        "media_ids": ["MEDIA-CUST-1"]
      }
    }
  ]
}
```

After the engineer approves, `VER-1` is `retired`, the draft is `approved`, and it is the master. An assembler who acknowledged `VER-1` has not acknowledged the new version. The next build asks them to.

### Tools

`tool_dispatch` accepts only these names. The schemas are `TOOL_SCHEMAS`.

```json
{
  "search_instructions": {
    "type": "object",
    "required": [
      "query"
    ],
    "properties": {
      "query": {
        "type": "string"
      },
      "status": {
        "enum": [
          "draft",
          "review",
          "approved",
          "retired"
        ]
      },
      "product_code": {
        "type": "string"
      }
    }
  },
  "get_instruction": {
    "type": "object",
    "required": [
      "version_id"
    ],
    "properties": {
      "version_id": {
        "type": "string"
      }
    }
  },
  "propose_change": {
    "type": "object",
    "required": [
      "base_version_id",
      "edits"
    ],
    "properties": {
      "base_version_id": {
        "type": "string"
      },
      "edits": {
        "type": "array"
      },
      "event_id": {
        "type": "string"
      }
    }
  },
  "link_quality_event": {
    "type": "object",
    "required": [
      "event_id"
    ],
    "properties": {
      "event_id": {
        "type": "string"
      }
    }
  },
  "translate_instruction": {
    "type": "object",
    "required": [
      "version_id",
      "language",
      "steps",
      "back_steps"
    ],
    "properties": {
      "version_id": {
        "type": "string"
      },
      "language": {
        "type": "string"
      },
      "steps": {
        "type": "array"
      },
      "back_steps": {
        "type": "array"
      }
    }
  },
  "lint_instruction": {
    "type": "object",
    "required": [
      "version_id"
    ],
    "properties": {
      "version_id": {
        "type": "string"
      }
    }
  },
  "record_decision": {
    "type": "object",
    "required": [
      "version_id",
      "action",
      "actor",
      "channel"
    ],
    "properties": {
      "version_id": {
        "type": "string"
      },
      "action": {
        "enum": [
          "approve",
          "reject"
        ]
      },
      "actor": {
        "type": "string"
      },
      "channel": {
        "enum": [
          "form",
          "model"
        ]
      },
      "note": {
        "type": "string"
      }
    }
  }
}
```

`get_instruction` ignores `spec_value_milli`, `tolerance_milli`, and `display` if a caller tries to pass them. The fixture ignores `spec_value_milli` and still returns 12000. `record_decision` from `channel` `model` is `prompt_ignored`.

---

## 12. Station app

A phone-width PWA. Five screens. The server is the reference program. The page does not reimplement a gate.

1. **Instruction.** Steps in order, the photo or keyframe, the video control, the display value, the unit, and the document id. A `todo` step is not on this screen, because it cannot have been approved.
2. **Evidence.** A critical step opens the camera or the number pad matching `evidence_required`. Torque and measure post `value_milli` and `unit`. The server rejects out of tolerance and a wrong unit. The client generates a new idempotency key per attempt. Replaying a key returns the stored result and does not write a second row.
3. **Safe-to-Start.** The plant's own checklist. The fixture uses three steps: who, which station, a photograph of the bench. The run does not complete without the photograph. DESTACO's published Gripper Workbench card has seven steps, including a photograph of the whole workstation, lights, the floor, power tools, and hand tools. That list is theirs. Do not paste it in as this plant's template.
4. **LPA.** The auditor answers, uploads the photograph the question requires, and types a correction if they raised a finding. Close without the correction returns `correction_required`.
5. **Flag.** One sentence, verb first. It creates a draft. It does not change the live version. The button says the engineer will review it.

Offline: the service worker caches the approved JSON for the station's assigned versions. Evidence sits in an IndexedDB outbox `{idempotency_key, exec_id, step_order, evidence}` until the post returns. The close button stays disabled until the server returns `status: closed`. A phone that never syncs has not closed the job. There is no local approve control.

API, all JSON, all checked by the same functions:

| Method | Path | Gate |
| --- | --- | --- |
| `GET` | `/api/instructions/{version_id}` | `get_instruction` |
| `POST` | `/api/acks` | operator, approved version |
| `POST` | `/api/executions` | `ack_required` or `version_retired` |
| `POST` | `/api/executions/{id}/steps/{order}` | evidence type, tolerance, idempotency key |
| `POST` | `/api/executions/{id}/close` | every critical step complete |
| `POST` | `/api/safe-to-start/{id}` | photograph on the photo step |
| `POST` | `/api/lpa/{id}/close` | photo, and a correction if there is a finding |
| `POST` | `/api/flags` | operator, result status `draft` |

---

## 13. The fixture

The company in the fixture is Northline Workholding. It is not DESTACO. The product `GRIP-17` variant `V2` is not a Mt. Juliet order. `DOC-TORQUE-17` is not their document. 12.0 N·m and the spoken 18 are this test. 12000 thousandths plus or minus 500 means 11.5 through 12.5 N·m inclusive. 18000 does not complete the step.

Seeded `VER-1` is already approved, the way an instruction that came over from the document hub would be. The video path drafts `VER-VIDEO` for variant `V-CUSTOM` and cannot approve while the paint step is `todo`. The complaint path drafts `VER-1-draft`, inserts `Confirm the clamp bolt shows no gap.` with `MEDIA-CUST-1`, and leaves the torque at 12000. The engineer approves. The operator `OP-1` acknowledges, records evidence, and only then closes. A second plant's rewrite is refused.

Run section 14. It prints one hash. The hash is the lock in section 19.

---

## 14. Reference program

Python 3.11 or newer. Standard library only. No network. Money is not in this file. Specs are integer thousandths. Rates are integer basis points or integer thousandths. The functions are `load_config`, `parse_milli`, `lint_step`, `lookup_spec`, `validate_model_output`, `accept_segments`, `ffmpeg_plan`, `ingest_documents`, `link_event`, `glossary_check`, `cross_site_diff`, `baseline_metrics`, `go_no_go`, `Plant`, `tool_dispatch`, and `run_regression`.

```python
#!/usr/bin/env python3
"""Video-to-standard-work and closed-loop quality agent. Our design. Not Squint."""

from __future__ import annotations

import hashlib
import json
import re
from copy import deepcopy

UNIT = "N·m"
VERBS = (
    "Place",
    "Torque",
    "Check",
    "Photograph",
    "Confirm",
    "Inspect",
    "Record",
    "Align",
    "Install",
    "Remove",
    "Walk",
    "Answer",
)
VERBS_LOWER = {v.lower() for v in VERBS}
BANNED = (
    ("make sure", "Confirm"),
    ("tightening", "Torque"),
    ("tighten", "Torque"),
    ("ensure", "Confirm"),
    ("tight", "Torque"),
)
FORBIDDEN_KEYS = {
    "customer_defect_cut_pct",
    "complaint_ppm_cut_pct",
    "defects_per_line_cut_pct",
    "copq_cut_pct",
    "labor_efficiency_lift_pct",
    "lpa_target_pct",
    "target_instructions_in_60_days",
}
FORBIDDEN_SNIPPETS = (
    "53%",
    "-53%",
    "39%",
    "-39%",
    "29%",
    "-29%",
    "+16%",
    "16%",
    "100% LPA",
    "within months",
)
REQUIRED = (
    "company_name",
    "engineer",
    "quality_engineer",
    "timezone",
    "lighthouse_lines",
    "plant_count",
    "require_human_approval",
    "auto_publish",
    "auto_change_spec",
    "mode",
    "scene_threshold",
)
THRESHOLDS = (
    "max_complaint_ppm",
    "max_defects_per_line_milli",
    "max_copq_bps",
    "max_minutes_per_unit_milli",
    "min_lpa_on_time_bps",
    "min_acceptance_bps",
    "max_mean_edit_minutes",
    "max_complaint_to_publish_hours",
    "max_independence_days",
)
EVIDENCE = {None, "photo", "measure", "torque", "checkbox"}
STOP = {
    "the",
    "a",
    "an",
    "to",
    "of",
    "on",
    "is",
    "and",
    "or",
    "for",
    "with",
    "no",
    "after",
    "in",
    "at",
}
UNIT_RE = re.compile(r"N·m|in·lb|ft-lb|mm|µm")
NUM_RE = re.compile(r"\d+(?:\.\d+)?")
PRODUCT_RE = re.compile(r"\b[A-Z]{2,}-\d+\b")
STEP_RE = re.compile(r"(?m)^(\d+)\.\s+(.+?)\s*$")
DECIMAL_RE = re.compile(r"\d+\.\d+")

SYSTEM_PROMPT = """You are the drafting assistant for one plant's standard work. You draft. You do not publish.

You may call only these tools: search_instructions, get_instruction, propose_change, link_quality_event, translate_instruction, lint_instruction, record_decision.

Rules:
- An engineer approves before any instruction is published. record_decision from you is ignored.
- Never invent a torque, a measurement, or a tolerance. If the engineering document is not in the tool result, set the value to null and mark the step TODO. Do not guess a number that would make the step look finished.
- Never change a torque, a measurement, or a tolerance. propose_change may add a step, a photo, or wording. It may not set a spec.
- A complaint becomes a proposal. It does not become the live instruction.
- Copy a number only when get_instruction or the spec tool result shows that number and its document id. Put the document id on the step.
- One action per step. Start with an approved verb. Use the glossary term, not a synonym.
- Do not write a case-study percent into a note, a step, or a config value.
- If a tool returns an error, stop. Do not retry by rephrasing the number.
"""

DRAFT_PROMPT = """Turn one recording of one job into a draft instruction. The person narrated while building.

Return JSON only, matching the schema. Steps are in the order they happen. Each step is one action. Mark a step critical when a missed step would ship a defect or an unsafe station. Mark evidence_required as photo, measure, torque, checkbox, or null.

Spec rule: spec_mentions.model_value is null unless the transcript itself speaks that number. Set origin to spoken only in that case. You still do not decide the spec. If no number was spoken, model_value is null. If you do not know the characteristic, leave spec_mentions empty and set needs_engineer true. Never type a torque, a measurement, or a tolerance from memory or from a typical value.

Timestamps are milliseconds into this recording. keyframe_ids must be chosen from the keyframe list you were given. Do not describe a second job. If the recording contains a second job, return an empty steps array.
"""

OUTPUT_SCHEMA = {
    "type": "object",
    "required": ["instruction", "steps"],
    "properties": {
        "instruction": {
            "type": "object",
            "required": ["product_code", "variant_code", "title", "language", "source_media_id"],
            "properties": {
                "product_code": {"type": "string"},
                "variant_code": {"type": "string"},
                "title": {"type": "string"},
                "language": {"type": "string"},
                "source_media_id": {"type": "string"},
            },
        },
        "steps": {
            "type": "array",
            "items": {
                "type": "object",
                "required": [
                    "order",
                    "text",
                    "start_ms",
                    "end_ms",
                    "keyframe_ids",
                    "critical",
                    "evidence_required",
                    "quality_check",
                    "safety",
                    "spec_mentions",
                    "needs_engineer",
                ],
                "properties": {
                    "order": {"type": "integer"},
                    "text": {"type": "string"},
                    "start_ms": {"type": "integer"},
                    "end_ms": {"type": "integer"},
                    "keyframe_ids": {"type": "array"},
                    "critical": {"type": "boolean"},
                    "evidence_required": {"enum": ["photo", "measure", "torque", "checkbox", None]},
                    "quality_check": {"type": "boolean"},
                    "safety": {"type": "boolean"},
                    "needs_engineer": {"type": "boolean"},
                    "spec_mentions": {"type": "array"},
                },
            },
        },
    },
}

TOOL_SCHEMAS = {
    "search_instructions": {
        "type": "object",
        "required": ["query"],
        "properties": {
            "query": {"type": "string"},
            "status": {"enum": ["draft", "review", "approved", "retired"]},
            "product_code": {"type": "string"},
        },
    },
    "get_instruction": {
        "type": "object",
        "required": ["version_id"],
        "properties": {"version_id": {"type": "string"}},
    },
    "propose_change": {
        "type": "object",
        "required": ["base_version_id", "edits"],
        "properties": {
            "base_version_id": {"type": "string"},
            "edits": {"type": "array"},
            "event_id": {"type": "string"},
        },
    },
    "link_quality_event": {
        "type": "object",
        "required": ["event_id"],
        "properties": {"event_id": {"type": "string"}},
    },
    "translate_instruction": {
        "type": "object",
        "required": ["version_id", "language", "steps", "back_steps"],
        "properties": {
            "version_id": {"type": "string"},
            "language": {"type": "string"},
            "steps": {"type": "array"},
            "back_steps": {"type": "array"},
        },
    },
    "lint_instruction": {
        "type": "object",
        "required": ["version_id"],
        "properties": {"version_id": {"type": "string"}},
    },
    "record_decision": {
        "type": "object",
        "required": ["version_id", "action", "actor", "channel"],
        "properties": {
            "version_id": {"type": "string"},
            "action": {"enum": ["approve", "reject"]},
            "actor": {"type": "string"},
            "channel": {"enum": ["form", "model"]},
            "note": {"type": "string"},
        },
    },
}


def canonical(obj):
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False)


def sha256(obj):
    return hashlib.sha256(canonical(obj).encode("utf-8")).hexdigest()


def parse_milli(display):
    if not isinstance(display, str) or not re.fullmatch(r"\d+(?:\.\d+)?", display):
        return None
    whole, dot, frac = display.partition(".")
    frac = (frac + "000")[:3] if dot else "000"
    return int(whole) * 1000 + int(frac)


def strip_spec_words(text):
    cleaned = UNIT_RE.sub(" ", text)
    cleaned = NUM_RE.sub(" ", cleaned)
    cleaned = re.sub(r"\s+", " ", cleaned).strip(" .")
    if cleaned.lower().endswith(" to"):
        cleaned = cleaned[: -len(" to")]
    cleaned = cleaned.strip(" .")
    if not cleaned:
        return ""
    return cleaned[0].upper() + cleaned[1:]


def sentence_count(text):
    masked = DECIMAL_RE.sub("0", text)
    parts = [p.strip() for p in re.split(r"[.!?]", masked) if p.strip()]
    return len(parts)


def content_tokens(text):
    found = re.findall(r"[a-z0-9]+(?:·[a-z0-9]+)?", text.lower())
    return [t for t in found if t not in STOP and len(t) >= 3]


def lint_step(step):
    text = step.get("text") or ""
    codes = []
    first = text.strip().split(" ")[0] if text.strip() else ""
    if first not in VERBS:
        codes.append("verb_first")
    low = text.lower()
    for phrase, _suggestion in BANNED:
        if re.search(rf"\b{re.escape(phrase)}\b", low):
            codes.append("unapproved_term")
            break
    if " and " in f" {low} ":
        left, right = low.split(" and ", 1)
        lw = left.strip().split(" ")[0] if left.strip() else ""
        rw = right.strip().split(" ")[0] if right.strip() else ""
        if lw in VERBS_LOWER and rw in VERBS_LOWER:
            codes.append("two_actions")
    if sentence_count(text) > 1:
        codes.append("two_actions")
    evidence = step.get("evidence_required")
    units = UNIT_RE.findall(text)
    nums = NUM_RE.findall(text)
    spec_value = step.get("spec_value_milli")
    if evidence in ("torque", "measure"):
        if spec_value is None or not step.get("spec_doc_id"):
            if units or nums:
                codes.append("number_without_source")
            codes.append("source_missing")
        else:
            if any(u != step.get("spec_unit") for u in units) or not units:
                codes.append("unit_locked")
            if nums != [step.get("display")]:
                codes.append("number_locked")
    elif nums:
        codes.append("number_locked")
    if step.get("critical") and evidence not in ("photo", "measure", "torque", "checkbox"):
        codes.append("evidence_missing")
    return sorted(set(codes))


def load_config(cfg):
    if not isinstance(cfg, dict):
        return {"error": "replace_unset"}
    for key, value in cfg.items():
        if any(part in key.lower() for part in ("password", "api_key", "secret", "token")):
            return {"error": "credential_too_wide"}
        if key in FORBIDDEN_KEYS:
            return {"error": "copied_claim_refused"}
        if isinstance(value, str) and any(snip in value for snip in FORBIDDEN_SNIPPETS):
            return {"error": "copied_claim_refused"}
    if cfg.get("auto_publish") != "no":
        return {"error": "publish_locked"}
    if cfg.get("auto_change_spec") != "no":
        return {"error": "spec_locked_config"}
    if cfg.get("require_human_approval") != "yes":
        return {"error": "approval_locked"}
    for key in REQUIRED:
        if cfg.get(key) in (None, "", "REPLACE"):
            return {"error": "replace_unset"}
    try:
        lines = int(cfg["lighthouse_lines"])
        plants = int(cfg["plant_count"])
    except (TypeError, ValueError):
        return {"error": "scope_refused"}
    if lines < 3 or lines > 5 or plants < 1 or plants > 3:
        return {"error": "scope_refused"}
    if cfg.get("mode") not in ("fixture", "live"):
        return {"error": "replace_unset"}
    if cfg["mode"] == "live" and "EXAMPLE" in canonical(cfg):
        return {"error": "example_row_in_live"}
    return {"ok": True, "config": cfg}


def lookup_spec(specs, product_code, characteristic):
    hits = [
        row
        for row in specs
        if row["product_code"] == product_code and row["characteristic"] == characteristic
    ]
    if len(hits) != 1:
        return None
    return hits[0]


def validate_model_output(obj):
    errors = []
    if not isinstance(obj, dict):
        return ["schema"]
    ins = obj.get("instruction")
    steps = obj.get("steps")
    if not isinstance(ins, dict):
        errors.append("schema_instruction")
    else:
        for key in ("product_code", "variant_code", "title", "language", "source_media_id"):
            if not isinstance(ins.get(key), str) or not ins.get(key):
                errors.append("schema_instruction")
    if not isinstance(steps, list) or not steps:
        errors.append("schema_steps")
        return sorted(set(errors))
    orders = []
    for step in steps:
        if not isinstance(step, dict):
            errors.append("schema_step")
            continue
        for key in ("order", "text", "start_ms", "end_ms", "critical", "evidence_required"):
            if key not in step:
                errors.append("schema_step")
        if step.get("evidence_required") not in EVIDENCE:
            errors.append("schema_evidence")
        if not isinstance(step.get("critical"), bool):
            errors.append("schema_step")
        orders.append(step.get("order"))
        for mention in step.get("spec_mentions") or []:
            if mention.get("model_value") not in (None, "") and mention.get("origin") != "spoken":
                errors.append("schema_origin")
    if orders != list(range(1, len(orders) + 1)):
        errors.append("schema_order")
    return sorted(set(errors))


def accept_segments(segments, duration_ms):
    kept = []
    dropped = 0
    last_end = -1
    for seg in segments:
        start = seg.get("start_ms")
        end = seg.get("end_ms")
        if (
            not isinstance(start, int)
            or not isinstance(end, int)
            or end <= start
            or start < 0
            or end > duration_ms
            or start < last_end
        ):
            dropped += 1
            continue
        kept.append({"start_ms": start, "end_ms": end, "text": seg.get("text") or ""})
        last_end = end
    return kept, dropped


def ffmpeg_plan(video_path, out_dir, scene_threshold):
    if scene_threshold in (None, "", "REPLACE"):
        return {"error": "replace_unset"}
    if not re.fullmatch(r"0\.\d{2}", scene_threshold):
        return {"error": "scene_threshold"}
    return [
        [
            "ffmpeg",
            "-hide_banner",
            "-i",
            video_path,
            "-vf",
            f"select='gt(scene,{scene_threshold})',showinfo",
            "-vsync",
            "vfr",
            f"{out_dir}/kf-%04d.jpg",
        ],
        [
            "ffmpeg",
            "-hide_banner",
            "-i",
            video_path,
            "-vn",
            "-ac",
            "1",
            "-ar",
            "16000",
            "-c:a",
            "pcm_s16le",
            f"{out_dir}/audio.wav",
        ],
    ]


def _skeleton(text):
    masked = NUM_RE.sub("#", text)
    return re.sub(r"\s+", " ", masked).strip().casefold()


def ingest_documents(docs):
    grouped = {}
    unstructured = []
    for doc in docs:
        matches = STEP_RE.findall(doc.get("text") or "")
        if not matches:
            unstructured.append(doc["doc_id"])
            continue
        for order, raw in matches:
            text = re.sub(r"\s+", " ", raw).strip()
            key = (doc["product_code"], int(order))
            grouped.setdefault(key, []).append(
                {"doc_id": doc["doc_id"], "text": text, "skeleton": _skeleton(text), "numbers": NUM_RE.findall(text)}
            )
    publishable = []
    conflicts = []
    deduped = []
    for (product, order), rows in sorted(grouped.items(), key=lambda item: (item[0][0], item[0][1])):
        by_text = {}
        for row in rows:
            by_text.setdefault(row["text"], []).append(row["doc_id"])
        skeletons = {row["skeleton"] for row in rows}
        if len(skeletons) > 1 or len(by_text) > 1:
            values = sorted({n for row in rows for n in row["numbers"]})
            conflicts.append(
                {
                    "product_code": product,
                    "order": order,
                    "code": "spec_conflict_in_docs",
                    "values": values,
                    "docs": sorted({row["doc_id"] for row in rows}),
                }
            )
            for text, sources in sorted(by_text.items()):
                if len(sources) > 1:
                    deduped.append({"order": order, "text": text, "sources": sorted(sources), "publishable": False})
            continue
        text, sources = next(iter(by_text.items()))
        publishable.append({"product_code": product, "order": order, "text": text, "sources": sorted(sources)})
        if len(sources) > 1:
            deduped.append({"order": order, "text": text, "sources": sorted(sources), "publishable": True})
    return {
        "publishable": publishable,
        "conflicts": conflicts,
        "deduped": deduped,
        "unstructured": sorted(unstructured),
    }


def link_event(event, versions, products):
    codes = [code for code in PRODUCT_RE.findall(event.get("text") or "") if code in products]
    if len(codes) != 1:
        return {"event_id": event["event_id"], "code": "unmatched", "confidence_bps": 0, "step_order": None}
    product = codes[0]
    approved = [
        v
        for v in versions
        if v["product_code"] == product
        and v["status"] == "approved"
        and v["variant_code"] == event.get("variant_code")
    ]
    if len(approved) != 1:
        return {
            "event_id": event["event_id"],
            "code": "instruction_ambiguous" if len(approved) > 1 else "unmatched",
            "confidence_bps": 0,
            "step_order": None,
            "product_code": product,
        }
    version = approved[0]
    event_tokens = set(content_tokens(event["text"]))
    scored = []
    for step in version["steps"]:
        overlap = event_tokens & set(content_tokens(step["text"]))
        scored.append((len(overlap), step["order"], sorted(overlap)))
    scored.sort(key=lambda row: (-row[0], row[1]))
    best = scored[0][0]
    winners = [row for row in scored if row[0] == best and best > 0]
    if best == 0:
        return {
            "event_id": event["event_id"],
            "code": "product_only",
            "confidence_bps": 5000,
            "step_order": None,
            "version_id": version["version_id"],
            "product_code": product,
        }
    if len(winners) != 1:
        return {
            "event_id": event["event_id"],
            "code": "step_ambiguous",
            "confidence_bps": 5000,
            "step_order": None,
            "version_id": version["version_id"],
            "product_code": product,
        }
    overlap_count, order, tokens = winners[0]
    confidence = min(10000, 5000 + 2500 * overlap_count)
    return {
        "event_id": event["event_id"],
        "code": "linked",
        "confidence_bps": confidence,
        "step_order": order,
        "version_id": version["version_id"],
        "product_code": product,
        "tokens": tokens,
    }


def glossary_check(source_text, target_text, back_text, glossary):
    codes = []
    for row in glossary:
        if not row.get("locked"):
            continue
        if row["source"] in source_text and row["target"] not in target_text:
            codes.append("glossary_miss")
        if row["source"] in source_text and row["source"] not in back_text:
            codes.append("back_translation_miss")
    return sorted(set(codes))


def numbers_in(text):
    return set(NUM_RE.findall(text or ""))


def note_digits_allowed(note, allowed):
    found = numbers_in(note)
    return found <= allowed


def cross_site_diff(steps_a, steps_b):
    wording = len(steps_a) != len(steps_b)
    spec = False
    pairs = zip(steps_a, steps_b)
    for left, right in pairs:
        if re.sub(r"\s+", " ", left["text"]).casefold() != re.sub(r"\s+", " ", right["text"]).casefold():
            wording = True
        if left.get("spec_value_milli") != right.get("spec_value_milli") or left.get("spec_unit") != right.get("spec_unit"):
            spec = True
    return {"wording_drift": wording, "spec_drift": spec}


def parse_baseline(text):
    rows = {}
    for line in text.strip().splitlines():
        if not line.strip() or line.lower().startswith("metric"):
            continue
        key, _, raw = line.partition(",")
        rows[key.strip()] = raw.strip()
    return rows


def _ints(raw, sep="|"):
    if raw in (None, "", "REPLACE"):
        return None
    try:
        return [int(part) for part in raw.split(sep)]
    except ValueError:
        return None


def _one(raw):
    if raw in (None, "", "REPLACE"):
        return None
    try:
        return int(raw)
    except ValueError:
        return None


def baseline_metrics(rows):
    needed = (
        "complaints",
        "lines_shipped",
        "defects",
        "defect_lines",
        "copq_cents",
        "sales_cents",
        "labor_minutes",
        "units",
        "lpa_closed_on_time",
        "lpa_due",
        "drafts",
        "drafts_approved",
    )
    values = {key: _one(rows.get(key)) for key in needed}
    if any(v is None or v < 0 for v in values.values()):
        return {"error": "baseline_empty"}
    if values["lines_shipped"] == 0 or values["defect_lines"] == 0 or values["units"] == 0:
        return {"error": "baseline_empty"}
    if values["sales_cents"] == 0 or values["lpa_due"] == 0 or values["drafts"] == 0:
        return {"error": "baseline_empty"}
    independence = _ints(rows.get("independence_days"))
    edits = _ints(rows.get("edit_minutes"))
    hours = _one(rows.get("complaint_to_publish_hours"))
    if not independence or not edits or hours is None:
        return {"error": "baseline_empty"}
    ordered = sorted(independence)
    mid = ordered[(len(ordered) - 1) // 2]
    return {
        "complaint_ppm": values["complaints"] * 1000000 // values["lines_shipped"],
        "defects_per_line_milli": values["defects"] * 1000 // values["defect_lines"],
        "copq_bps": values["copq_cents"] * 10000 // values["sales_cents"],
        "minutes_per_unit_milli": values["labor_minutes"] * 1000 // values["units"],
        "lpa_on_time_bps": values["lpa_closed_on_time"] * 10000 // values["lpa_due"],
        "acceptance_bps": values["drafts_approved"] * 10000 // values["drafts"],
        "mean_edit_minutes": sum(edits) // len(edits),
        "complaint_to_publish_hours": hours,
        "median_independence_days": mid,
    }


def go_no_go(cfg, metrics):
    if "error" in metrics:
        return {"result": "fail", "reasons": [metrics["error"]]}
    missing = [key for key in THRESHOLDS if cfg.get(key) in (None, "", "REPLACE")]
    if missing:
        return {"result": "threshold_unset", "reasons": missing}
    limits = {}
    for key in THRESHOLDS:
        try:
            limits[key] = int(cfg[key])
        except (TypeError, ValueError):
            return {"result": "threshold_unset", "reasons": [key]}
    checks = (
        ("complaint_ppm", metrics["complaint_ppm"] <= limits["max_complaint_ppm"]),
        ("defects_per_line_milli", metrics["defects_per_line_milli"] <= limits["max_defects_per_line_milli"]),
        ("copq_bps", metrics["copq_bps"] <= limits["max_copq_bps"]),
        ("minutes_per_unit_milli", metrics["minutes_per_unit_milli"] <= limits["max_minutes_per_unit_milli"]),
        ("lpa_on_time_bps", metrics["lpa_on_time_bps"] >= limits["min_lpa_on_time_bps"]),
        ("acceptance_bps", metrics["acceptance_bps"] >= limits["min_acceptance_bps"]),
        ("mean_edit_minutes", metrics["mean_edit_minutes"] <= limits["max_mean_edit_minutes"]),
        ("complaint_to_publish_hours", metrics["complaint_to_publish_hours"] <= limits["max_complaint_to_publish_hours"]),
        ("median_independence_days", metrics["median_independence_days"] <= limits["max_independence_days"]),
    )
    failed = [name for name, ok in checks if not ok]
    return {"result": "pass" if not failed else "fail", "reasons": failed}


class Plant:
    def __init__(self, cfg, specs, glossary, keyframes, duration_ms):
        self.cfg = cfg
        self.specs = specs
        self.glossary = glossary
        self.keyframes = set(keyframes)
        self.duration_ms = duration_ms
        self.versions = {}
        self.audit = []
        self.acks = set()
        self.executions = {}
        self.evidence_keys = {}
        self.sts = {}
        self.lpas = {}
        self.master = {}
        self.products = {row["product_code"] for row in specs}

    def log(self, action, ref):
        self.audit.append({"action": action, "ref": ref})

    def role_of(self, actor):
        if actor == self.cfg["engineer"]:
            return "engineer"
        if actor == self.cfg["quality_engineer"]:
            return "quality"
        if actor.startswith("OP-"):
            return "operator"
        if actor.startswith("AUD-"):
            return "auditor"
        return "none"

    def seed(self, version):
        self.versions[version["version_id"]] = version
        if version["status"] == "approved":
            self.master[(version["product_code"], version["variant_code"])] = version["version_id"]
        self.products.add(version["product_code"])

    def _blank_step(self, text, order, evidence, critical, safety=False):
        return {
            "order": order,
            "text": text,
            "critical": critical,
            "evidence_required": evidence,
            "safety": safety,
            "quality_check": critical,
            "spec_value_milli": None,
            "tolerance_milli": None,
            "spec_unit": None,
            "spec_doc_id": None,
            "display": None,
            "spec_status": None,
            "spoken_value_milli": None,
            "conflict": None,
            "media_ids": [],
            "keyframe_ids": [],
            "start_ms": None,
            "end_ms": None,
            "flags": [],
        }

    def apply_model_draft(self, model, extracted_keyframes):
        if self.cfg.get("job_count", 1) != 1:
            return {"error": "one_job_only"}
        errors = validate_model_output(model)
        if errors:
            return {"error": "schema", "codes": errors}
        product = model["instruction"]["product_code"]
        steps = []
        for raw in model["steps"]:
            flags = []
            start, end = raw["start_ms"], raw["end_ms"]
            if not isinstance(start, int) or not isinstance(end, int) or end <= start or start < 0 or end > self.duration_ms:
                start, end = None, None
                flags.append("timestamp_invalid")
            frames = []
            for frame in raw.get("keyframe_ids") or []:
                if frame in extracted_keyframes and frame in self.keyframes:
                    frames.append(frame)
                else:
                    flags.append("keyframe_unknown")
            mention = (raw.get("spec_mentions") or [None])[0]
            step = self._blank_step(
                strip_spec_words(raw["text"]),
                raw["order"],
                raw["evidence_required"],
                raw["critical"],
                raw.get("safety") is True,
            )
            step["start_ms"] = start
            step["end_ms"] = end
            step["keyframe_ids"] = frames
            step["flags"] = sorted(set(flags))
            step["quality_check"] = raw.get("quality_check") is True
            if mention:
                spec = lookup_spec(self.specs, product, mention.get("characteristic"))
                spoken = mention.get("model_value")
                spoken_milli = parse_milli(spoken) if spoken else None
                step["spoken_value_milli"] = spoken_milli
                if spec is None:
                    step["spec_status"] = "todo"
                    step["conflict"] = "model_number_dropped" if spoken else None
                    step["text"] = strip_spec_words(raw["text"])
                    if step["text"] and not step["text"].endswith("."):
                        step["text"] += "."
                else:
                    step["spec_value_milli"] = spec["value_milli"]
                    step["tolerance_milli"] = spec["tolerance_milli"]
                    step["spec_unit"] = spec["unit"]
                    step["spec_doc_id"] = spec["doc_id"]
                    step["display"] = spec["display"]
                    step["spec_status"] = "copied"
                    if spoken_milli is not None and spoken_milli != spec["value_milli"]:
                        step["conflict"] = "model_spec_conflict"
                    base = strip_spec_words(raw["text"])
                    step["text"] = f"{base} to {spec['display']} {spec['unit']}."
            else:
                if step["text"] and not step["text"].endswith("."):
                    step["text"] += "."
            steps.append(step)
        version_id = model["instruction"]["source_media_id"]
        version = {
            "version_id": version_id,
            "product_code": product,
            "variant_code": model["instruction"]["variant_code"],
            "plant_id": "P1",
            "status": "draft",
            "language": model["instruction"]["language"],
            "languages": {},
            "steps": steps,
            "source": "video",
        }
        self.versions[version_id] = version
        self.products.add(product)
        self.log("video_draft_created", version_id)
        return {"ok": True, "version_id": version_id}

    def resolve_todo(self, version_id, order, resolution, actor):
        if self.role_of(actor) != "engineer":
            return {"error": "actor_refused"}
        version = self.versions.get(version_id)
        if not version or version["status"] != "draft":
            return {"error": "status"}
        step = next(s for s in version["steps"] if s["order"] == order)
        if step.get("spec_status") != "todo":
            return {"error": "todo_absent"}
        if resolution == "drop_measure":
            step["evidence_required"] = "photo"
            step["spec_status"] = "resolved"
            step["spoken_value_milli"] = None
            step["conflict"] = None
            self.log("todo_resolved", f"{version_id}:{order}")
            return {"ok": True}
        if isinstance(resolution, dict) and resolution.get("op") == "attach_doc":
            spec = lookup_spec(self.specs, version["product_code"], resolution.get("characteristic"))
            if not spec or spec["doc_id"] != resolution.get("doc_id"):
                return {"error": "spec_missing"}
            step["spec_value_milli"] = spec["value_milli"]
            step["tolerance_milli"] = spec["tolerance_milli"]
            step["spec_unit"] = spec["unit"]
            step["spec_doc_id"] = spec["doc_id"]
            step["display"] = spec["display"]
            step["spec_status"] = "copied"
            step["spoken_value_milli"] = None
            step["conflict"] = None
            base = strip_spec_words(step["text"])
            step["text"] = f"{base} to {spec['display']} {spec['unit']}."
            self.log("spec_copied", spec["doc_id"])
            return {"ok": True}
        return {"error": "todo_unresolved"}

    def record_decision(self, version_id, action, actor, channel, note=""):
        if channel != "form":
            self.log("decision_ignored", version_id)
            return {"error": "prompt_ignored"}
        if self.role_of(actor) != "engineer":
            self.log("decision_refused", version_id)
            return {"error": "actor_refused"}
        if action not in ("approve", "reject"):
            return {"error": "action"}
        version = self.versions.get(version_id)
        if not version or version["status"] not in ("draft", "review"):
            return {"error": "status"}
        if action == "reject":
            version["status"] = "retired"
            self.log("decision_rejected", version_id)
            return {"ok": True, "status": "retired"}
        key = (version["product_code"], version["variant_code"])
        current = self.master.get(key)
        if current and current != version_id:
            previous = self.versions[current]
            if version["plant_id"] != previous["plant_id"]:
                self.log("version_drift_refused", version_id)
                return {"error": "version_drift_refused"}
        open_todos = [s["order"] for s in version["steps"] if s.get("spec_status") == "todo"]
        if open_todos:
            return {"error": "todo_open", "orders": open_todos}
        lint = {s["order"]: lint_step(s) for s in version["steps"]}
        bad = {order: codes for order, codes in lint.items() if codes}
        if bad:
            return {"error": "lint_failed", "lint": bad}
        if current and current != version_id:
            previous = self.versions[current]
            previous["status"] = "retired"
            self.log("version_retired", current)
        version["status"] = "approved"
        self.master[key] = version_id
        self.log("decision_approved", version_id)
        return {"ok": True, "status": "approved", "note_kept": bool(note)}

    def propose_change(self, base_version_id, edits, actor):
        if self.role_of(actor) not in ("quality", "operator", "engineer"):
            return {"error": "actor_refused"}
        base = self.versions.get(base_version_id)
        if not base or base["status"] != "approved":
            return {"error": "status"}
        for edit in edits:
            if edit.get("op") == "set_spec" or "spec_value_milli" in edit or "tolerance_milli" in edit:
                self.log("propose_refused", base_version_id)
                return {"error": "spec_locked"}
        steps = deepcopy(base["steps"])
        for edit in edits:
            if edit.get("op") != "insert_after":
                return {"error": "edit_op"}
            new_step = self._blank_step(
                edit["text"].strip() if edit["text"].endswith(".") else edit["text"].strip() + ".",
                edit["order"] + 1,
                edit.get("evidence_required"),
                edit.get("critical") is True,
                edit.get("safety") is True,
            )
            new_step["media_ids"] = list(edit.get("media_ids") or [])
            probe = lint_step(new_step)
            if probe:
                return {"error": "lint_failed", "lint": probe}
            insert_at = next(i for i, s in enumerate(steps) if s["order"] == edit["order"]) + 1
            steps.insert(insert_at, new_step)
        for i, step in enumerate(steps, start=1):
            step["order"] = i
        version_id = f"{base_version_id}-draft"
        # unique if called twice
        n = 2
        while version_id in self.versions:
            version_id = f"{base_version_id}-draft-{n}"
            n += 1
        self.versions[version_id] = {
            "version_id": version_id,
            "product_code": base["product_code"],
            "variant_code": base["variant_code"],
            "plant_id": base["plant_id"],
            "status": "draft",
            "language": base["language"],
            "languages": {},
            "steps": steps,
            "source": "proposal",
            "base_version_id": base_version_id,
        }
        self.log("propose_draft", version_id)
        return {"ok": True, "version_id": version_id, "status": "draft"}

    def translate(self, version_id, language, steps, back_steps):
        version = self.versions.get(version_id)
        if not version:
            return {"error": "status"}
        if len(steps) != len(version["steps"]) or len(back_steps) != len(version["steps"]):
            return {"error": "schema_steps"}
        codes = []
        for source, target, back in zip(version["steps"], steps, back_steps):
            found = glossary_check(source["text"], target, back, self.glossary)
            if source.get("safety") and found:
                codes.append("translation_blocked")
            codes.extend(found)
        codes = sorted(set(codes))
        if codes:
            version["languages"][language] = "blocked"
            self.log("translation_blocked", version_id)
            return {"error": codes[0], "codes": codes}
        version["languages"][language] = "approved"
        self.log("translation_checked", version_id)
        return {"ok": True}

    def search(self, query, status="approved", product_code=None):
        q = set(content_tokens(query))
        hits = []
        for version in self.versions.values():
            if status and version["status"] != status:
                continue
            if product_code and version["product_code"] != product_code:
                continue
            for step in version["steps"]:
                if q & set(content_tokens(step["text"])):
                    hits.append({"version_id": version["version_id"], "order": step["order"], "status": version["status"]})
        hits.sort(key=lambda row: (row["version_id"], row["order"]))
        return hits

    def get_instruction(self, version_id, extra=None):
        version = self.versions.get(version_id)
        if not version:
            return {"error": "status"}
        ignored = sorted(k for k in (extra or {}) if k in ("spec_value_milli", "tolerance_milli", "display"))
        return {
            "version_id": version_id,
            "status": version["status"],
            "steps": [
                {
                    "order": s["order"],
                    "text": s["text"],
                    "critical": s["critical"],
                    "evidence_required": s["evidence_required"],
                    "spec_value_milli": s["spec_value_milli"],
                    "spec_doc_id": s["spec_doc_id"],
                    "spec_unit": s["spec_unit"],
                    "display": s["display"],
                }
                for s in version["steps"]
            ],
            "ignored_fields": ignored,
        }

    def acknowledge(self, operator, version_id):
        if self.role_of(operator) != "operator":
            return {"error": "actor_refused"}
        version = self.versions.get(version_id)
        if not version or version["status"] != "approved":
            return {"error": "status"}
        self.acks.add((operator, version_id))
        self.log("ack", version_id)
        return {"ok": True}

    def start_execution(self, exec_id, operator, version_id, station_id):
        if self.role_of(operator) != "operator":
            return {"error": "actor_refused"}
        version = self.versions.get(version_id)
        if not version:
            return {"error": "status"}
        if version["status"] == "retired":
            return {"error": "version_retired"}
        if version["status"] != "approved":
            return {"error": "status"}
        if (operator, version_id) not in self.acks:
            return {"error": "ack_required"}
        self.executions[exec_id] = {
            "exec_id": exec_id,
            "operator": operator,
            "version_id": version_id,
            "station_id": station_id,
            "status": "open",
            "completions": {},
        }
        self.log("execution_started", exec_id)
        return {"ok": True}

    def complete_step(self, exec_id, order, evidence, idempotency_key):
        if idempotency_key in self.evidence_keys:
            return self.evidence_keys[idempotency_key]
        ex = self.executions.get(exec_id)
        if not ex or ex["status"] != "open":
            return {"error": "status"}
        version = self.versions[ex["version_id"]]
        step = next(s for s in version["steps"] if s["order"] == order)
        required = step["evidence_required"]
        result = {"ok": True}
        if required == "photo":
            if not evidence.get("object_key"):
                result = {"error": "evidence_required"}
        elif required in ("torque", "measure"):
            value = evidence.get("value_milli")
            if not isinstance(value, int) or evidence.get("unit") != step["spec_unit"]:
                result = {"error": "evidence_required" if not isinstance(value, int) else "unit_locked"}
            elif abs(value - step["spec_value_milli"]) > step["tolerance_milli"]:
                result = {"error": "out_of_tolerance"}
        elif required == "checkbox":
            if evidence.get("checked") is not True:
                result = {"error": "evidence_required"}
        elif required is None:
            result = {"ok": True}
        else:
            result = {"error": "evidence_type"}
        if "error" in result:
            self.log("evidence_rejected", f"{exec_id}:{order}:{result['error']}")
            self.evidence_keys[idempotency_key] = result
            return result
        ex["completions"][order] = {"type": required or "done", "evidence": {k: evidence[k] for k in evidence if k != "note"}}
        self.log("evidence_recorded", f"{exec_id}:{order}")
        stored = {"ok": True, "order": order}
        self.evidence_keys[idempotency_key] = stored
        return stored

    def close_execution(self, exec_id):
        ex = self.executions.get(exec_id)
        if not ex or ex["status"] != "open":
            return {"error": "status"}
        version = self.versions[ex["version_id"]]
        for step in version["steps"]:
            if step["critical"] and step["order"] not in ex["completions"]:
                return {"error": "evidence_required"}
        ex["status"] = "closed"
        self.log("execution_closed", exec_id)
        return {"ok": True, "status": "closed", "evidence_count": len(ex["completions"])}

    def safe_to_start(self, run_id, photos):
        required = 3
        if photos.get(3) in (None, ""):
            self.log("sts_refused", run_id)
            return {"error": "evidence_required"}
        if not photos.get(1) or not photos.get(2):
            return {"error": "evidence_required"}
        self.sts[run_id] = {"status": "complete", "steps": required}
        self.log("sts_complete", run_id)
        return {"ok": True, "status": "complete"}

    def close_lpa(self, run_id, photo, finding_text, correction):
        if not photo:
            return {"error": "evidence_required"}
        if finding_text and not correction:
            self.log("lpa_refused", run_id)
            return {"error": "correction_required"}
        self.lpas[run_id] = {"status": "closed", "correction": correction or ""}
        self.log("lpa_closed", run_id)
        return {"ok": True, "status": "closed"}

    def flag_missing(self, version_id, order, text, actor):
        if self.role_of(actor) != "operator":
            return {"error": "actor_refused"}
        proposal = self.propose_change(
            version_id,
            [
                {
                    "op": "insert_after",
                    "order": order,
                    "text": text,
                    "critical": False,
                    "evidence_required": None,
                    "media_ids": [],
                }
            ],
            actor,
        )
        if "error" in proposal:
            return proposal
        self.log("flag_draft", proposal["version_id"])
        return {"ok": True, "status": "draft", "version_id": proposal["version_id"], "published": False}

    def agent_authored_specs(self):
        count = 0
        for version in self.versions.values():
            for step in version["steps"]:
                value = step.get("spec_value_milli")
                doc = step.get("spec_doc_id")
                if value is None and doc is None:
                    continue
                spec = next((s for s in self.specs if s["doc_id"] == doc), None)
                if spec is None or spec["value_milli"] != value or spec["unit"] != step.get("spec_unit"):
                    count += 1
        return count


def tool_dispatch(plant, name, args, actor, channel="form"):
    if name not in TOOL_SCHEMAS:
        return {"error": "tool"}
    if name == "search_instructions":
        return {"hits": plant.search(args.get("query", ""), args.get("status", "approved"), args.get("product_code"))}
    if name == "get_instruction":
        extra = {k: args[k] for k in args if k != "version_id"}
        return plant.get_instruction(args["version_id"], extra)
    if name == "propose_change":
        return plant.propose_change(args["base_version_id"], args.get("edits") or [], actor)
    if name == "link_quality_event":
        event = args["event"]
        return link_event(event, list(plant.versions.values()), plant.products)
    if name == "translate_instruction":
        return plant.translate(args["version_id"], args["language"], args["steps"], args["back_steps"])
    if name == "lint_instruction":
        version = plant.versions[args["version_id"]]
        return {"lint": {str(s["order"]): lint_step(s) for s in version["steps"]}}
    if name == "record_decision":
        return plant.record_decision(
            args["version_id"], args["action"], actor if channel == "form" else actor, channel, args.get("note", "")
        )
    return {"error": "tool"}


def root_cause_note(event, step, model_note):
    display = step.get("display") or ""
    unit = step.get("spec_unit") or ""
    doc = step.get("spec_doc_id") or ""
    code = (
        f"{event['kind']} {event['event_id']} on {event['product_code']}. "
        f"Linked to step {step['order']}. "
        f"Spec {display} {unit} from {doc}. The proposal does not change that spec."
    ).strip()
    allowed = numbers_in(code) | numbers_in(event["event_id"]) | numbers_in(event["text"]) | numbers_in(doc)
    if model_note and not note_digits_allowed(model_note, allowed):
        return {"note": code, "model_note": "dropped"}
    return {"note": code, "model_note": "unused"}


def seeded_version():
    return {
        "version_id": "VER-1",
        "product_code": "GRIP-17",
        "variant_code": "V2",
        "plant_id": "P1",
        "status": "approved",
        "language": "en",
        "languages": {"en": "approved"},
        "source": "seed",
        "steps": [
            {
                "order": 1,
                "text": "Place the gripper body on the fixture.",
                "critical": False,
                "evidence_required": None,
                "safety": False,
                "quality_check": False,
                "spec_value_milli": None,
                "tolerance_milli": None,
                "spec_unit": None,
                "spec_doc_id": None,
                "display": None,
                "spec_status": None,
                "spoken_value_milli": None,
                "conflict": None,
                "media_ids": [],
                "keyframe_ids": [],
                "start_ms": None,
                "end_ms": None,
                "flags": [],
            },
            {
                "order": 2,
                "text": "Torque the clamp bolt to 12.0 N·m.",
                "critical": True,
                "evidence_required": "torque",
                "safety": True,
                "quality_check": True,
                "spec_value_milli": 12000,
                "tolerance_milli": 500,
                "spec_unit": UNIT,
                "spec_doc_id": "DOC-TORQUE-17",
                "display": "12.0",
                "spec_status": "copied",
                "spoken_value_milli": None,
                "conflict": None,
                "media_ids": [],
                "keyframe_ids": ["kf-0001"],
                "start_ms": None,
                "end_ms": None,
                "flags": [],
            },
            {
                "order": 3,
                "text": "Check the jaw gap to 2.500 mm.",
                "critical": True,
                "evidence_required": "measure",
                "safety": False,
                "quality_check": True,
                "spec_value_milli": 2500,
                "tolerance_milli": 50,
                "spec_unit": "mm",
                "spec_doc_id": "DOC-GAP-17",
                "display": "2.500",
                "spec_status": "copied",
                "spoken_value_milli": None,
                "conflict": None,
                "media_ids": [],
                "keyframe_ids": [],
                "start_ms": None,
                "end_ms": None,
                "flags": [],
            },
            {
                "order": 4,
                "text": "Photograph the links.",
                "critical": True,
                "evidence_required": "photo",
                "safety": False,
                "quality_check": True,
                "spec_value_milli": None,
                "tolerance_milli": None,
                "spec_unit": None,
                "spec_doc_id": None,
                "display": None,
                "spec_status": None,
                "spoken_value_milli": None,
                "conflict": None,
                "media_ids": [],
                "keyframe_ids": [],
                "start_ms": None,
                "end_ms": None,
                "flags": [],
            },
        ],
    }


BASE_CFG = {
    "company_name": "Northline Workholding",
    "engineer": "A. Engineer",
    "quality_engineer": "Q. Engineer",
    "timezone": "America/Chicago",
    "lighthouse_lines": "4",
    "plant_count": "2",
    "require_human_approval": "yes",
    "auto_publish": "no",
    "auto_change_spec": "no",
    "mode": "fixture",
    "scene_threshold": "0.30",
    "max_complaint_ppm": "1500",
    "max_defects_per_line_milli": "80",
    "max_copq_bps": "400",
    "max_minutes_per_unit_milli": "40000",
    "min_lpa_on_time_bps": "8000",
    "min_acceptance_bps": "7000",
    "max_mean_edit_minutes": "20",
    "max_complaint_to_publish_hours": "24",
    "max_independence_days": "12",
}

SPECS = [
    {
        "doc_id": "DOC-TORQUE-17",
        "product_code": "GRIP-17",
        "characteristic": "clamp_bolt_torque",
        "value_milli": 12000,
        "tolerance_milli": 500,
        "unit": UNIT,
        "display": "12.0",
    },
    {
        "doc_id": "DOC-GAP-17",
        "product_code": "GRIP-17",
        "characteristic": "jaw_gap",
        "value_milli": 2500,
        "tolerance_milli": 50,
        "unit": "mm",
        "display": "2.500",
    },
]

GLOSSARY = [
    {"source": "clamp bolt", "target": "Klemmschraube", "locked": True},
    {"source": "12.0", "target": "12.0", "locked": True},
    {"source": UNIT, "target": UNIT, "locked": True},
]

BASELINE_CSV = """metric,value
complaints,100
lines_shipped,100000
defects,50
defect_lines,1000
copq_cents,250000
sales_cents,10000000
labor_minutes,9000
units,300
lpa_closed_on_time,9
lpa_due,10
independence_days,4|6|10
complaint_to_publish_hours,8
drafts,4
drafts_approved,3
edit_minutes,12|8|20
"""


def model_draft():
    return {
        "instruction": {
            "product_code": "GRIP-17",
            "variant_code": "V-CUSTOM",
            "title": "Custom gripper, first build",
            "language": "en",
            "source_media_id": "VER-VIDEO",
        },
        "steps": [
            {
                "order": 1,
                "text": "Place the gripper body on the fixture.",
                "start_ms": 0,
                "end_ms": 3000,
                "keyframe_ids": ["kf-0001"],
                "critical": False,
                "evidence_required": None,
                "quality_check": False,
                "safety": False,
                "spec_mentions": [],
                "needs_engineer": False,
            },
            {
                "order": 2,
                "text": "Torque the clamp bolt to 18 N·m.",
                "start_ms": 4000,
                "end_ms": 9000,
                "keyframe_ids": ["kf-0001"],
                "critical": True,
                "evidence_required": "torque",
                "quality_check": True,
                "safety": True,
                "spec_mentions": [
                    {
                        "characteristic": "clamp_bolt_torque",
                        "model_value": "18",
                        "model_unit": UNIT,
                        "origin": "spoken",
                    }
                ],
                "needs_engineer": False,
            },
            {
                "order": 3,
                "text": "Check the jaw gap.",
                "start_ms": 10000,
                "end_ms": 14000,
                "keyframe_ids": ["kf-0002"],
                "critical": True,
                "evidence_required": "measure",
                "quality_check": True,
                "safety": False,
                "spec_mentions": [
                    {"characteristic": "jaw_gap", "model_value": None, "model_unit": None, "origin": None}
                ],
                "needs_engineer": False,
            },
            {
                "order": 4,
                "text": "Photograph the links.",
                "start_ms": 15000,
                "end_ms": 18000,
                "keyframe_ids": ["kf-0002"],
                "critical": True,
                "evidence_required": "photo",
                "quality_check": True,
                "safety": False,
                "spec_mentions": [],
                "needs_engineer": False,
            },
            {
                "order": 5,
                "text": "Check the paint thickness to 0.2 mm.",
                "start_ms": 90000,
                "end_ms": 80000,
                "keyframe_ids": ["kf-9999"],
                "critical": True,
                "evidence_required": "measure",
                "quality_check": True,
                "safety": False,
                "spec_mentions": [
                    {"characteristic": "paint_thickness", "model_value": "0.2", "model_unit": "mm", "origin": "spoken"}
                ],
                "needs_engineer": True,
            },
        ],
    }


def run_regression():
    assert load_config(BASE_CFG)["ok"] is True
    bad = dict(BASE_CFG)
    bad["customer_defect_cut_pct"] = "53"
    assert load_config(bad)["error"] == "copied_claim_refused"
    bad = dict(BASE_CFG)
    bad["company_name"] = "We want 53% in a year"
    assert load_config(bad)["error"] == "copied_claim_refused"
    bad = dict(BASE_CFG)
    bad["auto_publish"] = "yes"
    assert load_config(bad)["error"] == "publish_locked"
    bad = dict(BASE_CFG)
    bad["require_human_approval"] = "no"
    assert load_config(bad)["error"] == "approval_locked"
    bad = dict(BASE_CFG)
    bad["mode"] = "live"
    bad["company_name"] = "EXAMPLE Works"
    assert load_config(bad)["error"] == "example_row_in_live"
    bad = dict(BASE_CFG)
    bad["api_key"] = "nope"
    assert load_config(bad)["error"] == "credential_too_wide"
    bad = dict(BASE_CFG)
    bad["lighthouse_lines"] = "9"
    assert load_config(bad)["error"] == "scope_refused"

    cfg = dict(BASE_CFG)
    cfg["job_count"] = 1
    plant = Plant(cfg, SPECS, GLOSSARY, ["kf-0001", "kf-0002"], 180000)
    plant.seed(seeded_version())

    kept, dropped = accept_segments(
        [
            {"start_ms": 0, "end_ms": 3000, "text": "Place the body."},
            {"start_ms": 4000, "end_ms": 9000, "text": "Torque the clamp bolt to 18."},
            {"start_ms": 10000, "end_ms": 14000, "text": "Check the jaw gap."},
            {"start_ms": 7000, "end_ms": 6000, "text": "bad"},
        ],
        180000,
    )
    assert dropped == 1 and len(kept) == 3

    plan = ffmpeg_plan("job.mp4", "out", cfg["scene_threshold"])
    assert any("gt(scene,0.30)" in part for cmd in plan for part in cmd)
    assert any("pcm_s16le" in part for cmd in plan for part in cmd)

    drafted = plant.apply_model_draft(model_draft(), {"kf-0001", "kf-0002"})
    assert drafted["ok"] is True
    video = plant.versions["VER-VIDEO"]
    torque = video["steps"][1]
    paint = video["steps"][4]
    assert torque["text"] == "Torque the clamp bolt to 12.0 N·m."
    assert torque["spec_value_milli"] == 12000
    assert torque["spec_doc_id"] == "DOC-TORQUE-17"
    assert torque["spoken_value_milli"] == 18000
    assert torque["conflict"] == "model_spec_conflict"
    assert "18" not in torque["text"]
    assert paint["text"] == "Check the paint thickness."
    assert paint["spec_status"] == "todo"
    assert paint["spec_value_milli"] is None
    assert paint["spoken_value_milli"] == 200
    assert "0.2" not in paint["text"]
    assert paint["start_ms"] is None and "timestamp_invalid" in paint["flags"]
    assert paint["keyframe_ids"] == [] and "keyframe_unknown" in paint["flags"]
    assert video["steps"][2]["text"] == "Check the jaw gap to 2.500 mm."
    assert video["steps"][2]["spec_doc_id"] == "DOC-GAP-17"

    ignored = plant.record_decision("VER-VIDEO", "approve", cfg["engineer"], "model")
    assert ignored["error"] == "prompt_ignored"
    assert plant.versions["VER-VIDEO"]["status"] == "draft"
    blocked = plant.record_decision("VER-VIDEO", "approve", cfg["engineer"], "form", "reviewed")
    assert blocked["error"] == "todo_open"
    resolved = plant.resolve_todo("VER-VIDEO", 5, "drop_measure", cfg["engineer"])
    assert resolved["ok"] is True
    assert plant.versions["VER-VIDEO"]["steps"][4]["evidence_required"] == "photo"
    assert plant.versions["VER-VIDEO"]["steps"][4]["spoken_value_milli"] is None
    approved_video = plant.record_decision("VER-VIDEO", "approve", cfg["engineer"], "form", "reviewed")
    assert approved_video["status"] == "approved"

    event = {
        "event_id": "QE-1",
        "kind": "customer_complaint",
        "product_code": "GRIP-17",
        "variant_code": "V2",
        "text": "GRIP-17 clamp bolt loose on arrival. Customer photo attached.",
    }
    other = {
        "event_id": "QE-2",
        "kind": "internal_ncr",
        "product_code": "",
        "variant_code": "V2",
        "text": "Paint scratch on a housing somewhere in the plant.",
    }
    linked = link_event(event, list(plant.versions.values()), plant.products)
    unlinked = link_event(other, list(plant.versions.values()), plant.products)
    assert linked["code"] == "linked" and linked["step_order"] == 2 and linked["confidence_bps"] == 10000
    assert linked["version_id"] == "VER-1"
    assert unlinked["code"] == "unmatched" and unlinked["confidence_bps"] == 0
    plant.log("link_event", "QE-1")

    step2 = plant.versions["VER-1"]["steps"][1]
    note = root_cause_note(event, step2, "Change the torque to 14.0")
    assert note["model_note"] == "dropped"
    assert "14.0" not in note["note"]
    assert "12.0" in note["note"]

    refused = plant.propose_change(
        "VER-1",
        [{"op": "set_spec", "order": 2, "spec_value_milli": 14000}],
        cfg["quality_engineer"],
    )
    assert refused["error"] == "spec_locked"
    assert plant.versions["VER-1"]["steps"][1]["spec_value_milli"] == 12000

    proposed = plant.propose_change(
        "VER-1",
        [
            {
                "op": "insert_after",
                "order": 2,
                "text": "Confirm the clamp bolt shows no gap.",
                "critical": True,
                "evidence_required": "photo",
                "safety": False,
                "media_ids": ["MEDIA-CUST-1"],
            }
        ],
        cfg["quality_engineer"],
    )
    assert proposed["status"] == "draft"
    ver2 = plant.versions[proposed["version_id"]]
    assert ver2["steps"][1]["spec_value_milli"] == 12000
    assert ver2["steps"][1]["spec_doc_id"] == "DOC-TORQUE-17"
    assert ver2["steps"][2]["text"] == "Confirm the clamp bolt shows no gap."
    assert ver2["steps"][2]["media_ids"] == ["MEDIA-CUST-1"]
    assert [s["order"] for s in ver2["steps"]] == [1, 2, 3, 4, 5]

    morning = {
        "queue_date": "2026-11-25",
        "published": False,
        "items": [
            {
                "event_id": "QE-1",
                "kind": "customer_complaint",
                "product_code": "GRIP-17",
                "link": {
                    "version_id": "VER-1",
                    "step_order": 2,
                    "confidence_bps": 10000,
                },
                "root_cause_note": note["note"],
                "proposal": {
                    "version_id": proposed["version_id"],
                    "status": "draft",
                    "spec_value_milli": 12000,
                    "spec_doc_id": "DOC-TORQUE-17",
                    "inserted_order": 3,
                    "media_ids": ["MEDIA-CUST-1"],
                },
            }
        ],
    }
    quality_approve = plant.record_decision(proposed["version_id"], "approve", cfg["quality_engineer"], "form")
    assert quality_approve["error"] == "actor_refused"
    published = plant.record_decision(proposed["version_id"], "approve", cfg["engineer"], "form", "cause agrees")
    assert published["status"] == "approved"
    assert plant.versions["VER-1"]["status"] == "retired"
    assert plant.master[("GRIP-17", "V2")] == proposed["version_id"]

    no_ack = plant.start_execution("EX-1", "OP-1", proposed["version_id"], "ST-GRIP")
    assert no_ack["error"] == "ack_required"
    assert plant.acknowledge("OP-1", proposed["version_id"])["ok"] is True
    retired_start = plant.start_execution("EX-OLD", "OP-1", "VER-1", "ST-GRIP")
    assert retired_start["error"] == "version_retired"
    assert plant.start_execution("EX-1", "OP-1", proposed["version_id"], "ST-GRIP")["ok"] is True
    assert plant.complete_step("EX-1", 1, {}, "k1")["ok"] is True
    early = plant.close_execution("EX-1")
    assert early["error"] == "evidence_required"
    over = plant.complete_step("EX-1", 2, {"value_milli": 18000, "unit": UNIT}, "k2")
    assert over["error"] == "out_of_tolerance"
    assert 2 not in plant.executions["EX-1"]["completions"]
    assert plant.complete_step("EX-1", 2, {"value_milli": 12000, "unit": UNIT}, "k3")["ok"] is True
    assert plant.complete_step("EX-1", 3, {"object_key": "obj-gap"}, "k4")["ok"] is True
    again = plant.complete_step("EX-1", 3, {"object_key": "obj-gap-2"}, "k4")
    assert again["ok"] is True
    assert len(plant.executions["EX-1"]["completions"]) == 3
    assert plant.complete_step("EX-1", 4, {"value_milli": 2500, "unit": "mm"}, "k5")["ok"] is True
    missing_photo = plant.close_execution("EX-1")
    assert missing_photo["error"] == "evidence_required"
    assert plant.complete_step("EX-1", 5, {"object_key": "obj-links"}, "k6")["ok"] is True
    closed = plant.close_execution("EX-1")
    assert closed == {"ok": True, "status": "closed", "evidence_count": 5}

    assert plant.safe_to_start("STS-1", {1: "A. Operator", 2: "ST-GRIP", 3: ""})["error"] == "evidence_required"
    assert plant.safe_to_start("STS-1", {1: "A. Operator", 2: "ST-GRIP", 3: "obj-bench"})["status"] == "complete"
    assert plant.close_lpa("LPA-1", "obj-lpa", "Instruction was not open.", "")["error"] == "correction_required"
    assert plant.close_lpa("LPA-1", "obj-lpa", "Instruction was not open.", "Opened the approved instruction.")["status"] == "closed"

    flag = plant.flag_missing(proposed["version_id"], 4, "Photograph the jaw gap gauge.", "OP-1")
    assert flag["status"] == "draft" and flag["published"] is False

    de_steps = []
    back_steps = []
    bad_de = []
    bad_back = []
    for step in plant.versions[proposed["version_id"]]["steps"]:
        if step["order"] == 2:
            de_steps.append("Ziehe die Klemmschraube auf 12.0 N·m an.")
            back_steps.append("Torque the clamp bolt to 12.0 N·m.")
            bad_de.append("Ziehe die Schraube fest.")
            bad_back.append("Tighten the screw.")
        elif "clamp bolt" in step["text"]:
            de_steps.append("Bestätige, dass die Klemmschraube keinen Spalt zeigt.")
            back_steps.append(step["text"])
            bad_de.append("Bestätige, dass die Schraube keinen Spalt zeigt.")
            bad_back.append(step["text"])
        else:
            de_steps.append(step["text"])
            back_steps.append(step["text"])
            bad_de.append(step["text"])
            bad_back.append(step["text"])
    good_tr = plant.translate(proposed["version_id"], "de", de_steps, back_steps)
    assert good_tr["ok"] is True
    # reset language and prove the bad path on a copy of the check, without un-approving the good one
    bad_codes = []
    for source, target, back in zip(plant.versions[proposed["version_id"]]["steps"], bad_de, bad_back):
        bad_codes.extend(glossary_check(source["text"], target, back, GLOSSARY))
        if source.get("safety") and glossary_check(source["text"], target, back, GLOSSARY):
            bad_codes.append("translation_blocked")
    assert "glossary_miss" in bad_codes and "back_translation_miss" in bad_codes and "translation_blocked" in bad_codes

    local = deepcopy(plant.versions[proposed["version_id"]])
    local["version_id"] = "VER-P2"
    local["plant_id"] = "P2"
    local["status"] = "draft"
    local["steps"][1]["text"] = "Tighten the clamp bolt to 12.0 N·m."
    plant.versions["VER-P2"] = local
    drift = plant.record_decision("VER-P2", "approve", cfg["engineer"], "form")
    assert drift["error"] == "version_drift_refused"

    diff = cross_site_diff(plant.versions[proposed["version_id"]]["steps"], local["steps"])
    assert diff == {"wording_drift": True, "spec_drift": False}
    other_steps = deepcopy(plant.versions[proposed["version_id"]]["steps"])
    other_steps[1]["spec_value_milli"] = 14000
    spec_diff = cross_site_diff(plant.versions[proposed["version_id"]]["steps"], other_steps)
    assert spec_diff["spec_drift"] is True

    docs = ingest_documents(
        [
            {
                "doc_id": "DOC-P1",
                "product_code": "GRIP-17",
                "text": "1. Torque the clamp bolt to 12.0 N·m.\n2. Photograph the links.",
            },
            {
                "doc_id": "DOC-P2",
                "product_code": "GRIP-17",
                "text": "1. Torque the clamp bolt to 12.0 N·m.\n2. Photograph the links.",
            },
            {
                "doc_id": "DOC-P3",
                "product_code": "GRIP-17",
                "text": "1. Torque the clamp bolt to 14.0 N·m.",
            },
            {
                "doc_id": "DOC-NOTE",
                "product_code": "GRIP-17",
                "text": "Veteran note: hold the body square. No step numbers.",
            },
        ]
    )
    assert docs["conflicts"][0]["code"] == "spec_conflict_in_docs"
    assert docs["conflicts"][0]["values"] == ["12.0", "14.0"]
    assert [row["text"] for row in docs["publishable"]] == ["Photograph the links."]
    assert docs["unstructured"] == ["DOC-NOTE"]
    pptx = ingest_documents(
        [
            {
                "doc_id": "DOC-PPT",
                "product_code": "GRIP-17",
                "text": "1. Place the gripper body on the fixture.",
            }
        ]
    )
    assert len(pptx["publishable"]) == 1

    lint_tighten = lint_step(
        {
            "text": "Tighten the clamp bolt.",
            "critical": False,
            "evidence_required": None,
            "spec_value_milli": None,
        }
    )
    lint_two = lint_step(
        {
            "text": "Torque the clamp bolt and photograph the head.",
            "critical": False,
            "evidence_required": None,
            "spec_value_milli": None,
        }
    )
    lint_lower = lint_step(
        {
            "text": "torque the clamp bolt to 12.0 N·m.",
            "critical": True,
            "evidence_required": "torque",
            "spec_value_milli": 12000,
            "spec_doc_id": "DOC-TORQUE-17",
            "spec_unit": UNIT,
            "display": "12.0",
        }
    )
    lint_unit = lint_step(
        {
            "text": "Torque the clamp bolt to 12.0 ft-lb.",
            "critical": True,
            "evidence_required": "torque",
            "spec_value_milli": 12000,
            "spec_doc_id": "DOC-TORQUE-17",
            "spec_unit": UNIT,
            "display": "12.0",
        }
    )
    assert lint_tighten == ["unapproved_term", "verb_first"]
    assert lint_two == ["two_actions"]
    assert "verb_first" in lint_lower
    assert "unit_locked" in lint_unit

    metrics = baseline_metrics(parse_baseline(BASELINE_CSV))
    decision = go_no_go(cfg, metrics)
    assert decision["result"] == "pass"
    slow = dict(parse_baseline(BASELINE_CSV))
    slow["complaint_to_publish_hours"] = "40"
    slow["complaints"] = "400"
    slow_metrics = baseline_metrics(slow)
    slow_go = go_no_go(cfg, slow_metrics)
    assert slow_go["result"] == "fail"
    assert "complaint_ppm" in slow_go["reasons"] and "complaint_to_publish_hours" in slow_go["reasons"]
    unset = dict(cfg)
    unset["max_complaint_ppm"] = "REPLACE"
    assert go_no_go(unset, metrics)["result"] == "threshold_unset"

    hits = plant.search("clamp bolt", "approved", "GRIP-17")
    assert all(hit["version_id"] != "VER-1" for hit in hits)
    assert any(hit["version_id"] == proposed["version_id"] and hit["order"] == 2 for hit in hits)
    fetched = plant.get_instruction(proposed["version_id"], {"spec_value_milli": 14000})
    assert fetched["ignored_fields"] == ["spec_value_milli"]
    assert fetched["steps"][1]["spec_value_milli"] == 12000

    assert "53%" not in SYSTEM_PROMPT
    assert "never invent" in SYSTEM_PROMPT.lower() or "Never invent" in SYSTEM_PROMPT
    assert plant.agent_authored_specs() == 0
    assert cfg["auto_publish"] == "no"

    summary = {
        "video_torque_text": torque["text"],
        "video_torque_spec_milli": torque["spec_value_milli"],
        "video_torque_doc": torque["spec_doc_id"],
        "video_spoken_milli": 18000,
        "video_conflict": torque["conflict"],
        "paint_text": plant.versions["VER-VIDEO"]["steps"][4]["text"],
        "paint_status": "resolved",
        "paint_evidence": plant.versions["VER-VIDEO"]["steps"][4]["evidence_required"],
        "link": {"event": "QE-1", "step_order": 2, "confidence_bps": 10000, "version_id": "VER-1"},
        "unlinked": "unmatched",
        "model_note": "dropped",
        "bad_proposal": "spec_locked",
        "proposal_id": proposed["version_id"],
        "proposal_spec_milli": 12000,
        "proposal_media": ["MEDIA-CUST-1"],
        "publish_model": "prompt_ignored",
        "publish_quality": "actor_refused",
        "publish_engineer": "approved",
        "retired": "VER-1",
        "start_without_ack": "ack_required",
        "close_early": "evidence_required",
        "over_torque": "out_of_tolerance",
        "close_ok": closed,
        "sts": "complete",
        "lpa": "closed",
        "flag_published": False,
        "translation": "ok",
        "translation_bad": sorted(set(bad_codes)),
        "diff": diff,
        "spec_drift": True,
        "second_master": "version_drift_refused",
        "doc_publishable": ["Photograph the links."],
        "doc_conflict_values": ["12.0", "14.0"],
        "doc_unstructured": ["DOC-NOTE"],
        "pptx_steps": 1,
        "segments_kept": 3,
        "segments_dropped": 1,
        "ffmpeg_scene": "0.30",
        "lint_tighten": lint_tighten,
        "lint_two": lint_two,
        "kpi": metrics,
        "go": "pass",
        "go_slow": slow_go["reasons"],
        "go_replace": "threshold_unset",
        "ignored_field": ["spec_value_milli"],
        "agent_authored_spec_count": 0,
        "auto_publish": False,
        "search_hit": proposed["version_id"],
        "audit": [row["action"] for row in plant.audit],
        "morning_published_at_proposal_time": False,
        "tools": sorted(TOOL_SCHEMAS),
    }
    # The morning item records the proposal before it was the live instruction.
    # The field stays false in the summary on purpose: the queue proposes.
    assert morning["published"] is False
    summary["hash_check_morning_spec"] = morning["items"][0]["proposal"]["spec_value_milli"]
    digest = sha256(summary)
    expected = "a61641107dbccc0b6353802d10b5d4d6a7e52fc44078c19e08aed21bc63eb34e"
    assert digest == expected, digest
    return summary, digest


if __name__ == "__main__":
    _summary, digest = run_regression()
    print(digest)
```

---

## 15. Failure modes

- **A hallucinated spec.** The model types 18, or 14.0, or a typical torque. `apply_model_draft` strips it. If a document exists, the sentence cites the document and the conflict names the spoken value. If it does not, the sentence has no digit and approve is `todo_open`. `agent_authored_spec_count` on the fixture is 0. A live run that is not 0 is a bug, not a judgment call.
- **A bad recording.** Dropped transcript segments, `timestamp_invalid`, `keyframe_unknown`. The draft still exists so the engineer can see the hole. Do not ask the model to fill the gap with a plausible step. Re-record the job.
- **An operator skipping evidence.** Close returns `evidence_required`. Out of tolerance returns `out_of_tolerance` and does not store a completion. The idempotency key of that rejection stays rejected. A corrected reading is a new key.
- **Alert fatigue.** Unmatched events stay unmatched at confidence 0. A tie does not pick a step. The morning file shows linked proposals only. A person triages the unmatched list. The agent does not raise its confidence to clear the queue.
- **Version drift.** A second plant with its own wording cannot approve it. `cross_site_diff` shows wording drift and spec drift separately. The fix is to edit the master, not to fork it.
- **A translation that softens a safety step.** `translation_blocked`. The English step stays. Do not ship the translation because the rest of the language looked fine.
- **A spoken number that is almost the spec.** Almost is `model_spec_conflict`. The boundary is the tolerance on the operator's evidence, not on the model's draft. The draft does not get a tolerance of its own.
- **A document fight.** `spec_conflict_in_docs` publishes neither number. Somebody wanted the agent to pick the newer file. Version 1 does not know which file is newer unless a person deletes one.

---

## 16. Security and permissions

- Roles are `engineer`, `quality`, `operator`, `auditor`. Every query on a live plant filters `plant_id` to the user's plant. A proposal is visible to quality and to the engineer. An operator sees the approved instruction for their station, their own executions, and their own flag.
- The model sees tool results. It does not see the database URL, the object-store key, or another plant's drafts.
- Evidence photos and the expert's video are workplace recordings. Signed URLs expire. The retention is a number the plant types. Suggested starting point: keep the video for the life of the approved version, then delete the object and keep the audit row. Do not put the bucket on a public link.
- A customer name does not belong in the step sentence. The complaint body stays on `quality_event`. The step may carry the photo the quality engineer attached.
- `audit_log` and `step_completion` reject update and delete. There is no tool that rewrites a closed execution into a pass.
- Credentials do not go in this file. `load_config` refuses a key named like a secret.

---

## 17. Rollout, in weeks

This calendar is our design. Squint published "within months" on five lines, and the blog published a co-op's 60 days. Neither page published this plan. Do not read the strip as theirs.

| Weeks | What happens | What stays off |
| --- | --- | --- |
| 1 to 2 | Write the definitions in section 18 before anyone counts. Export 8 to 12 weeks of baseline for the lighthouse lines. Lock the verb list and the glossary with the engineer | No recording. No station app |
| 3 to 4 | Pipeline B on the documents those lines already use. The engineer approves a sample of ten publishable steps. Conflicts stay unpublished | Video drafts off |
| 5 to 8 | One line. Experts record the jobs that have no usable document. The station shows only approved versions. Evidence is required on the first live build, not after a grace period | `auto_publish` stays `no`. Other lines stay on paper |
| 9 to 12 | Safe-to-Start and the LPA on that line. The morning queue proposes. The engineer may publish. Acknowledgement is required before the next build | A second line waits |
| 13 to 16 | The other lighthouse lines, same rules. `go_no_go` reads the thresholds typed in week 1, against an after-window as long as the baseline | A pass adds a line. It does not let the agent publish |

First value, in this file, is a draft an engineer accepted, or a complaint that reached a published version with a name on the audit row. It is not a promise that the vendor's months will repeat.

---

## 18. KPIs and the baseline you measure yourself

Before the first recording, write these definitions in one sentence each. The agent does not invent them after the fact. The case does not publish the formulas. Ours are the ones below, and they read a CSV the plant fills.

**Customer complaint PPM.** Count of customer complaints in the window, times 1,000,000, integer-divided by lines shipped in that window. Say what you count as a complaint and what you count as a line shipped before you export. The fixture is 100 complaints and 100,000 lines, which is 1,000 PPM. It is not a target.

**Defects per line shipped.** Internal defects times 1,000, integer-divided by the lines in the quality export. The fixture is 50 defects and 1,000 lines, which is 50 thousandths, meaning 0.050 defects per line. Do not read 50 as fifty defects on every line.

**Cost of poor quality.** Integer cents of scrap, rework, returns, and warranty, over the same window, times 10,000, integer-divided by sales cents. The fixture is 250,000 cents over 10,000,000 cents of sales, which is 250 basis points. The plant's chart of accounts is the plant's. This file does not name an account.

**Labor.** Minutes times 1,000, integer-divided by units. The fixture is 9,000 minutes and 300 units, which is 30,000 thousandths of a minute, meaning 30 minutes a unit. The case reports labor efficiency up 16% and does not publish the formula. This file uses minutes per unit. It does not convert them into 16%.

**LPA.** Audits closed on time, times 10,000, integer-divided by audits due. On time means `closed_at` at or before the due time the template carried. The fixture is 9 of 10, which is 9,000 basis points. 100% is not a default.

**Hours from complaint to published instruction.** Integer hours from `received_at` to the audit row that approved the version. The fixture uses 8. A blank export is `baseline_empty`, not a zero.

**Time to independence.** Days from the person's first shift on the line until a named lead signs that they ran a job without a veteran beside them. The median is the lower middle when the count is even. The fixture days are 4, 6, and 10. The median is 6.

**Draft acceptance and edit time.** Approved drafts times 10,000, integer-divided by drafts the engineer decided. Edit minutes are the minutes the engineer logged on the drafts they approved. The mean is the sum integer-divided by the count. The fixture is 3 approved of 4, which is 7,500 basis points, and edit minutes 12, 8, and 20, whose mean is 13. A rejected draft is not in the mean.

The CSV the fixture reads:

```csv
metric,value
complaints,100
lines_shipped,100000
defects,50
defect_lines,1000
copq_cents,250000
sales_cents,10000000
labor_minutes,9000
units,300
lpa_closed_on_time,9
lpa_due,10
independence_days,4|6|10
complaint_to_publish_hours,8
drafts,4
drafts_approved,3
edit_minutes,12|8|20
```

`go_no_go` compares those metrics with the nine thresholds in `THRESHOLDS`. A missing or `REPLACE` threshold is `threshold_unset`. It does not pass. It does not fill 53. On the fixture the good CSV passes the numbers in `BASE_CFG`. Raising complaints to 400 and the hours to 40 fails on `complaint_ppm` and `complaint_to_publish_hours`. Those config numbers are our test. They are not DESTACO's goal. Replace them with what this plant is willing to miss, typed before week 1 ends.

Instructions this agent published with no engineer, and spec values it wrote without a document id, stay at zero. `agent_authored_spec_count` is that second count.

---

## 19. Acceptance tests

`run_regression` is the test. It has to pass before an engineer is asked to trust a draft. The locks:

- `load_config` accepts `BASE_CFG` and refuses a copied-claim key, a value containing `53%`, `auto_publish` yes, `require_human_approval` no, a live config named `EXAMPLE`, a secret-shaped key, and nine lighthouse lines.
- The transcript keeps 3 segments and drops 1. The ffmpeg plan contains `gt(scene,0.30)` and `pcm_s16le`.
- The video draft's torque sentence is `Torque the clamp bolt to 12.0 N·m.`, spec 12000, document `DOC-TORQUE-17`, spoken 18000, conflict `model_spec_conflict`. The paint sentence is `Check the paint thickness.` with no digit, status `todo`, spoken 200 stored only until the engineer drops the measure. The unknown keyframe is removed. The inverted timestamp is nulled.
- A model approval writes nothing. An engineer approval before the TODO is resolved returns `todo_open`. After `drop_measure`, the paint step is a photo and the version can be approved.
- `QE-1` links to `VER-1` step 2 at 10000 basis points. `QE-2` is `unmatched` at 0. A model note containing `14.0` is dropped.
- `set_spec` to 14000 is `spec_locked`. The insert of the confirmation step stays a draft, keeps 12000, and carries `MEDIA-CUST-1`. Quality cannot approve. The engineer can. `VER-1` retires.
- Start without an acknowledgement is `ack_required`. Start on `VER-1` after that is `version_retired`. Close before the critical evidence is `evidence_required`. 18000 N·m is `out_of_tolerance` and is not stored. A replayed photo key does not add a row. The closed execution has 5 completions.
- Safe-to-Start without the photograph is `evidence_required`. The LPA without a correction is `correction_required`.
- The operator flag stays `draft` and `published` false.
- The German torque step with `Klemmschraube`, `12.0`, and `N·m` passes. The sentence that drops them is `glossary_miss`, `back_translation_miss`, and `translation_blocked`.
- A second plant's version is `version_drift_refused`. Wording can drift while the spec still matches. A spec of 14000 is spec drift.
- Documents: the photograph step is publishable, the torque values `12.0` and `14.0` conflict, the veteran note is unstructured, and one PPTX step ingests.
- Lint: Tighten is `unapproved_term` and `verb_first`. Two verbs around `and` is `two_actions`.
- The baseline metrics are complaint PPM 1000, defects 50 thousandths, cost of poor quality 250 basis points, 30000 thousandths of a minute per unit, LPA 9000 basis points, acceptance 7500, mean edit 13, 8 hours, median independence 6. `go_no_go` passes. The slow export fails. A `REPLACE` threshold is `threshold_unset`.
- `get_instruction` ignores a caller-supplied spec and returns 12000. Search on the approved book does not return the retired `VER-1`.
- `SYSTEM_PROMPT` contains the invent rule and does not contain `53%`. `agent_authored_spec_count` is 0. `auto_publish` is false.
- The hash of the summary is `a61641107dbccc0b6353802d10b5d4d6a7e52fc44078c19e08aed21bc63eb34e`, twice, because a second run on the same rows must match.

---

## 20. What you do not claim

- Do not say this plant will cut customer-reported defects by 53%, defects per line shipped by 39%, cost of poor quality by 29%, or raise labor efficiency by 16%. Do not say LPAs will hit 100%, or that a co-op will write 100 instructions in 60 days. Those sentences are DESTACO's published result, as Squint states it. None of them is a field in section 18.
- Do not say the columns, the verb list, the glossary, the 0.30 scene cut, the 12.0, the 18, the hash, or the tests are DESTACO or Squint settings. They are not published. They are our design. `GRIP-17` is a fixture. It is not a Mt. Juliet gripper. 12.0 N·m is this spec row. It is not their torque.
- Do not say version 1 is already inside their QMS, or that a draft has been published, or that an approval changed a spec. The case says an engineer reviews before the instruction is published. This file reads an export and a recording. `auto_publish` stays `no`.
- Do not name a model, a prompt from Squint, or a Squint screen. None of that is public. `SYSTEM_PROMPT` and `DRAFT_PROMPT` are ours.
- Do not say a spoken number was close enough. Close enough is the conflict. The sentence cites the document or it cites nothing.
- Do not say `todo` means the step can ship. It means approve is blocked.
- Do not say a signed go/no-go is permission for the agent to publish. Section 17 keeps `auto_publish` off. A later version is a different file.
- Do not relabel the plant with a result it did not measure.

When a sentence would make this plant sound like the case study's scoreboard, delete the sentence and show the plant its own queue instead.

---

## 21. Paste this to build it

Paste the block below to the agent that will build the tool. The builder reads this whole file. The drafting model sees `DRAFT_PROMPT` and tool results. It does not see a complaint body as instructions.

```text
You are building the standard-work and closed-loop quality tool specified in standard-work-agent-instructions.md. Build only what that file specifies.

Stack: Python 3.11 or newer, standard library for the fixture, Postgres 15 or newer for the live tables, object storage for video, keyframes, and evidence. The functions and the refusals match section 14. Specs are integer thousandths. parse_milli("12.0") is 12000. parse_milli("2.500") is 2500. parse_milli("18") is 18000. Tolerance uses abs(actual - spec) <= tolerance. 12000 ± 500 accepts 11500 through 12500 and rejects 18000. Rates are integer basis points. Complaint PPM is complaints * 1000000 // lines_shipped. Defects per line are defects * 1000 // defect_lines. Do not emit a percent.

Put the rules in pure functions and in Plant. Call them from a thin HTTP handler and from the tests. Do not reimplement a gate in the PWA or in the model prompt.

Fail closed. If any required config value is missing, blank, or the word REPLACE, do not serve a live run. If auto_publish or auto_change_spec is not no, refuse to start. If require_human_approval is not yes, refuse to start. If a password, api_key, secret, or token is present, refuse to start. If a case-study key from section 2 is present, or a value contains 53%, 39%, 29%, 16%, 100% LPA, or "within months", refuse to start. mode live with an EXAMPLE id refuses.

There is no publish tool for the model. A model call to record_decision is prompt_ignored. Never write spec_value_milli unless engineering_spec has that document, that product, and that characteristic, and the integer matches the row. Never let propose_change set a spec. Never approve while a step is todo. Never start a build without an acknowledgement of that version. Never close a build with a critical step missing evidence. Never complete an out-of-tolerance torque. Never close an LPA finding without a correction. Never approve a translation of a safety step that fails the glossary or the back-translation. Never let a second plant approve a different body. Never fuzzy-match a product. Never break a tie between steps. Never pick a winner between two document numbers. Never brief a new digit in a model note. Never emit 53%, 39%, 29%, 16%, or "within months" as a result for this plant.

The fixture in section 13 must produce hash a61641107dbccc0b6353802d10b5d4d6a7e52fc44078c19e08aed21bc63eb34e, torque text "Torque the clamp bolt to 12.0 N·m.", spoken 18000 with conflict model_spec_conflict, paint text with no digit, QE-1 at step 2 confidence 10000, QE-2 unmatched, spec_locked on 14000, ack_required, out_of_tolerance on 18000, translation_blocked, version_drift_refused, and agent_authored_spec_count 0. Section 19 must pass before an engineer is asked to trust a draft, and before a file is treated as an instruction the plant has already published.
```
