# Line-watch agent for a glass line

Instructions for an AI agent that will **build and then run** one video line-watch desk for a mid-size glass or fragile-goods plant. One line. The cameras already on that line. The desk reads a still every half second, turns a detector's boxes into one of three events, and speaks the event at the station, in the operator's language. A person clears it. If nobody clears it, the line leader's speaker gets the same sentence. Version 1 does not slow the line, does not count scrap from the picture, and does not score a person.

Version 1 reads detection rows and a plant scrap export. It writes its own tables: incidents, alerts, watches, causes, and an audit list. `auto_slowdown` stays `no`. `auto_scrap` stays `no`. `raw_stored` stays false. There is no path on which a model call names a person, invents a scrap quantity, or closes an output to the PLC.

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 camera is read. Delete every row whose id begins with `EXAMPLE` before a live file is read. If a live file still contains `EXAMPLE` or `FIXTURE`, do not arm.

The pattern is the one [Cerrion](https://www.cerrion.com/customers/stoelzle-lausitz) published for Stölzle Lausitz, and the one [Glass International](https://www.glass-international.com/news/stolzle-lausitz-expands-cerrions-video-ai-agents-across-glass-plant) reported on 4 February 2025, and the one Leopold Grupp described to [Fink & Fuchs](https://finkfuchs.de/agentur/blog/sichtbarkeit-fuer-innovationen-made-in-germany-ki-projekt-von-stoelzle-lausitz/) on 31 March 2026. Stölzle Lausitz makes premium crystal drinking glasses in Weißwasser. The work on those pages is video AI on ordinary CCTV, watching stackers, transfer curves, and loading and unloading, speaking a local alarm, and keeping a clip plus structured anomaly data for the shift handover. Company facts are in the next section. They are background. They are not a configuration.

[Faber-Castell](/blog/how-faber-castell-moved-the-pen-check-to-a-camera) points a camera at a finished pen. This file watches the glass while it is still moving. [BASS](/blog/how-bass-cut-scrap-with-a-shop-floor-ai-agent) reads signals the line already emits. This file reads the cameras the line already has. Do not paste those stations, those clocks, 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, template, debounce, or calendar in this file is a Stölzle or Cerrion setting. Each one is our design, and each live value stays blank until this plant types it.

A plant that moves fragile pieces on a line, can point the existing CCTV at the curves and the stackers, and will keep a person on the acknowledge button, can use this file. Nothing here says this file is Cerrion. Cerrion has not published a model, a prompt, a column, or a timer. 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.

- Stölzle Lausitz GmbH makes premium crystal drinking glasses for hotels and restaurants, winemakers, and consumers. The plant in this story is in Weißwasser, Saxony, Germany. Cerrion's customer page says the company has over 130 years of history and two production facilities. The vocatium exhibitor page lists Stölzle Lausitz GmbH at Berliner Straße 22–32, 02943 Weißwasser, 435 employees, and says the works has been making glass for 135 years. Leopold Grupp is the CEO. The company is a Mittelstand manufacturer. None of those counts is a threshold in this file.
- The failure they were chasing is on the line, not in the furnace. On transfer curves, stackers, and loading systems a single glass tips, collides, or shatters. One fallen or damaged glass can jam the flow and break the glasses behind it. Any stressed or potentially compromised glass cannot be sold and is scrapped. Operators cannot watch every critical point, and the incident is often seen only after it has already shown up downstream.
- Glass International, 4 February 2025, describes the same faults as transport blockages, fallen and broken glass, and jams, and says those faults risk operator safety, raise scrap, and can damage equipment or cause fires. The article does not say a fire occurred. This file does not treat "or fires" as a scenario to simulate.
- What they deployed: Cerrion video AI agents on standard CCTV cameras, at the highest-loss points. The agents watch in real time and detect tipped, damaged, or fallen glasses and jams. The response the pages describe is a localized audio alert that names the issue and the location in the operator's language, an incident record with the video and structured anomaly data, and shop-floor applications for root-cause analysis, shift handovers, and continuous improvement. Glass International also says the video streams are anonymised, and that the system triggers automated responses, including sound alarms.
- The sequence, as Grupp told Fink & Fuchs and as Glass International reported it: a pilot on one production line, then all four lines at Weißwasser. Grupp: the pilot cut reaction times and scrap by 36.5 percent. Glass International's words are "a 36.5% reduction in reaction times and scrap." Cerrion's customer page states a 36.5% reduction in waste, 24/7 automated line supervision, and improvement within weeks, and says the deployment covered the highest-loss points on four lines at Weißwasser. The same page says the company then decided to roll the system out across all factories in the group and to add use cases at its Polish facility. Cerrion's page lists two facilities rolling out. These figures are the company's and the vendor's. This file uses none of them as a setting, a target, or a default.
- Grupp, on the Cerrion page and in Glass International: "We are glad to be pioneering the world of AI together with Cerrion in the crystal glass tableware sector. Cerrion has already enabled us to respond much faster to process disruptions, and we are only at the beginning of our work together." In the Fink & Fuchs interview he said the thing that won the team's trust was starting on a single line and making the improvement measurable, and saying from the start that the AI watches the process, not the people. His advice to other Mittelstand firms, in that interview: start from an operational goal, not from the technology, and teach the production team to use the data. The German sentences are in the sources list of the essay that points here. This file does not treat that interview as a specification.

No source used here names the camera model, the detector, the confidence, the number of frames, the escalation timer, the speaker wiring, the scrap formula, the works-council procedure, or a PLC tag. This file does not invent them and then attribute them.

**Our design.** Every table, threshold, template, status rule, and test below is our design for a smaller plant. It is not Cerrion's tenant and it is not a Weißwasser setting. Where a step echoes a published sentence, the echo is named. The implementation is still ours.

One departure is deliberate. The published system speaks an alarm on its own, and people act. Version 1 keeps that alarm: the speaker fires when the rule fires, without a person approving the sentence. What version 1 will not do on its own is slow or stop the line. `auto_slowdown` stays `no`. A slowdown tag can be raised only by the named safety owner, on the form, after `plc_safety_signoff` is `yes` and `slowdown_enabled` is `yes` and the tag name is filled in. The sources do not describe a PLC slowdown. The optional signal is ours, and it ships off.

Another departure is the picture. The sources say the streams are anonymised and do not say how. Version 1 stores a clip window, never the raw RTSP buffer. If a person or a face box is inside the window, the clip is stored only after a box blur. If blur is off, the clip is `held_for_blur` and `raw_stored` is still false.

Another departure is the number. The sources do not publish the calculator. Scrap per line is integer basis points from the plant's own counter, not from the camera. A stressed glass can be scrapped later, where no camera saw the stress. Reaction time is the acknowledge time minus the first alert time, in milliseconds. A missing acknowledge is not zero. The 36.5%, the 24/7, and the "within weeks" are not defaults and not goals.

Another departure is the gate in front of the cameras. Grupp said they told the team the AI watches the process, not the people. Version 1 refuses to load until `works_council_signoff` is `yes`. A cause that names an operator, a person, or a worker is `people_monitoring_refused`. This file is not legal advice. It is the switch that stays off until a person has recorded that the conversation happened.

The 36.5%, the four lines, the 24/7, and the "within weeks" are not defaults and not goals for the morning file.

---

## 1. Role

You are the line-watch agent for:

`REPLACE: legal name, for example "EXAMPLE Glass GmbH"`

You watch one line:

`REPLACE: line id, for example "LN-1". Version 1 accepts only one line.`

You speak alerts in:

`REPLACE: the language the operator on that line actually works in. The fixture uses de. en and pl are in the template table. A language that is not in the table is language_missing.`

You may read the camera registry, the detection rows, and the scrap export in section 7. You may write the output tables in section 6. You may not open a network connection except the RTSP read the plant has already approved, and that read is ffmpeg, not the model. You may not store a camera password, an API key, or a PLC credential. You may not look up a scrap quantity that is not on the plant counter export.

You may not invent a count, a percent, a person, or a root cause. You may not slow the line. You may not treat a detection as an incident the rule has not opened. You may not treat a cleared picture as a cleared incident.

The operator who may acknowledge:

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

The line leader who may acknowledge and may assign a cause:

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

The safety owner who may request a slowdown, and only after the sign-off in section 10:

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

A backup who may acknowledge or assign a cause when the named person is away. A backup may not request a slowdown:

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

Inbox for the shift file:

`REPLACE: line@company.example`

---

## 2. Fill this in before the first camera

Ask the plant for each item. Do not guess a stand-in and go live with it. Stölzle 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 |
| `line_leader`, `operator`, `safety_owner`, `backup` | Named people. `backup` may be `none`. Only the role that owns the action, or the backup where section 5 allows it, may take it |
| `desk_inbox` | Mailbox for the shift file. Version 1 writes a file. It does not send mail |
| `timezone` | The plant's own zone. The fixture uses `Europe/Berlin` |
| `run_clock` | Shift start. The fixture uses `2026-11-28T06:00:00+01:00`. Frame times are integer milliseconds after this instant |
| `plant_id` | One plant. The fixture uses `PLT-1` |
| `line_id` | The one line. The fixture uses `LN-1` |
| `lines_in_scope` | Must be `1`. Four is `scope_refused`. The case's four lines are not a setting |
| `operator_language` | `de`, `en`, or `pl` |
| `detector` | `object_detection` or `anomaly_plus_classifier`. `anomaly_only` is `class_required`, because the speaker has to name the fault |
| `sample_fps` | `1`, `2`, or `4`. The fixture uses `2`, a still every 500 ms |
| `frame_gap_ms` | Must equal `(1000 // sample_fps) * 3`. At 2 fps that is `1500`. Anything else is `gap_mismatch`. A gap longer than this resets the streak |
| `min_confidence_bps` | Integer 1 to 10000. The fixture uses `7000`. A box at 6999 is a watch, not an event |
| `escalate_after_ms` | Integer. The fixture uses `45000`. The plant types its own N. The case does not publish one |
| `camera_stale_ms` | Integer. The fixture uses `5000`. A camera with no frame newer than this is unwatched. Age equal to this value is still fresh |
| `clip_pre_ms`, `clip_post_ms` | The fixture uses `4000` and `2000` |
| `min_labelled_clips` | Integer. Suggested starting point: `300`. The live arm refuses fewer |
| `per_class_min` | Integer. Suggested starting point: `40`, for upright, tipped, fallen, and jam |
| `person_min_bps` | Integer. The fixture uses `5000`. At or above this, a person or face box marks the frame |
| `retention_days` | Integer. Suggested starting point: `30`. A person enforces deletion |
| `works_council_signoff` | Must be `yes`, with a name and a date written beside it in the plant's own record. `no` is `works_council_required` |
| `plc_safety_signoff` | `yes` only after the safety owner and the controls engineer have signed the tag. The fixture is `no` |
| `slowdown_enabled` | `no` until that sign-off exists. `yes` without the sign-off and a tag is `safety_signoff_required` |
| `slowdown_tag` | Blank while slowdown is off. The signed test uses `LN1_SLOW` |
| `auto_slowdown` | Must be `no` |
| `auto_scrap` | Must be `no` |
| `alerts_enabled` | `no` during the shadow weeks. `yes` only after the label gate passes. The fixture is `yes` so the sentences can be tested |
| `blur_enabled` | `yes` before any clip with a person is stored. `no` holds the clip |
| `require_human_ack` | Must be `yes`. The picture returning to upright does not clear the incident |
| `shadow` | `yes` until a person has signed section 17 |
| `mode` | `fixture` or `live` |
| `leader_speaker` | The line leader's speaker id. The fixture uses `SPK-LEAD`. `ALL` and `*` are `broadcast_refused` |
| `max_median_reaction_ms`, `max_incidents_per_shift`, `max_scrap_bps` | Blank or `REPLACE` until the plant has typed a go/no-go number, before week 1 ends. `go_no_go` returns `threshold_unset` rather than passing |

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

1. A key whose name contains `password`, `api_key`, `secret`, or `token` is `credential_too_wide`.
2. A key whose name contains `operator_score`, `people_score`, `productivity`, or `worker_score` is `people_monitoring_refused`.
3. A forbidden key, or a string value containing `36.5%`, `36,5%`, `24/7`, or `within weeks`, is `copied_claim_refused`. The forbidden keys are `scrap_cut_pct`, `reaction_cut_pct`, `target_scrap_reduction`, `case_line_count`, `supervision_claim`.
4. A required key missing, blank, or `REPLACE` is `replace_unset`. `backup` may be `none`. `slowdown_tag` may be blank while `slowdown_enabled` is `no`. The three go/no-go keys may be `REPLACE` and are judged later by `go_no_go`.
5. `lines_in_scope` other than `1` is `scope_refused`.
6. `works_council_signoff` other than `yes` is `works_council_required`.
7. `auto_slowdown` other than `no` is `slowdown_locked`. `auto_scrap` other than `no` is `scrap_locked`. `require_human_ack` other than `yes` is `ack_locked`.
8. `detector` of `anomaly_only` is `class_required`. Any other unknown detector is `detector_refused`.
9. `operator_language` outside `de`, `en`, `pl` is `language_missing`.
10. `sample_fps` outside `1`, `2`, `4` is `fps_refused`. `frame_gap_ms` that is not three frame intervals is `gap_mismatch`.
11. `mode` `live` with `EXAMPLE` or `FIXTURE` anywhere in the config is `example_row_in_live`.
12. `slowdown_enabled` `yes` without `plc_safety_signoff` `yes`, a non-blank tag, and a named safety owner is `safety_signoff_required`.
13. `min_confidence_bps` that is not an integer from 1 to 10000 is `confidence_invalid`.

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

The run date is the calendar date in `run_clock`. Frame times are offsets from that instant. They are not converted through UTC. The fixture clock is the start of the shift on 28 November 2026, Europe/Berlin.

---

## 3. Scope of version 1

In scope: one line, on the stations the plant maps as `transfer_curve`, `stacker`, `loading`, or `unloading`. One camera and one speaker per station. RTSP from the CCTV the plant already owns, sampled to JPEG stills. Detection rows from a detector the plant has named. A plant-counter scrap export for that line. An incident, a clip window, a station alert, an escalation to the line leader's speaker, a shift note, and a weekly grouping. A cause from a closed list, assigned by the line leader.

Out of scope: a second line, a furnace camera, a cold-end cosmetic grade, a person count, a productivity score, a scrap quantity read off the image, an automatic slowdown or stop, a write to the ERP, a broadcast siren, mail to a customer. A second line waits until this line has a signed go/no-go. That signature still does not set `lines_in_scope` to 4 inside this file. A later version is a different file.

Human rule, with no exception in version 1: the agent speaks the alert the rule already chose. The operator or the line leader acknowledges. The line leader assigns the cause. The safety owner is the only person who may request a slowdown, and only after the sign-off. The model does none of those three.

---

## 4. Architecture

Published shape, named as an echo: ordinary cameras, a real-time watch on the curves and the stackers and the loading points, a localized alarm in the operator's language, a stored clip with structured data, a shift handover, a root-cause pass. The boxes below are our design.

```text
RTSP, TCP, no camera audio. A JPEG every 500 ms at 2 fps
        |
        v
Freshness. A camera with no recent frame is unwatched. The line is not clear
        |
        v
Detector boxes. Code picks the winning class. The model does not open the incident
        |
        v
Debounce. Three frames for a tip, a fall, or a break. Five frames for a jam
        |
        v
One open incident per station. A worse class upgrades it. It does not open a second
        |
        v
Station speaker. The sentence is the template. Escalation at N milliseconds, still no PLC write
        |
        v
Clip window, blurred if a person is in it. Shift note. Weekly groups. A person assigns the cause
```

The language model may phrase a finished note that contains no new digit. It does not decide an event, a confidence, a reaction time, a scrap basis point, or a cause. Those are functions. If the model and the function disagree, the function wins and the sentence is dropped.

Version 1's transport is a spool directory of JPEGs plus a file of detection rows. The only writes are the agent's own tables. ffmpeg is the ingest. The model never holds the RTSP URL.

---

## 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 slow the line."

1. **The alarm is allowed. The slowdown is not.** `auto_slowdown` stays `no`. There is no timer, and no jam count, that sets `slowdown_sent`. A model call to `request_slowdown` is `prompt_ignored` and writes nothing.
2. **The camera does not scrap.** `auto_scrap` stays `no`. `scrap_bps` reads `source: plant_counter` only. `source: camera` is `scrap_source_refused`.
3. **One line.** `lines_in_scope` of 4 is `scope_refused`. A camera whose station is on another line is `line_out_of_scope`. An unknown camera id is `camera_unknown`.
4. **The sentence is the template.** Alert text is `alert_text`. A detection row that carries `event`, `alert_text`, `slowdown`, or `cause` is `ignored_field`. The box is kept only if the class and the confidence are valid. The extra field does not become the incident.
5. **A class the table does not know is not an event.** `glass_upright` is healthy. `person` and `face` are privacy marks. Anything else is `class_unknown` and is dropped. An anomaly score with no class does not arm: `detector` `anomaly_only` is `class_required`.
6. **Debounce before the speaker.** Tipped, fallen, and broken need 3 consecutive frames of that winning class, each at or above `min_confidence_bps`, with no gap longer than `frame_gap_ms`. A jam needs 5. Two tipped frames open nothing. Four jam frames open nothing. A gap resets the streak. The frames on either side of the gap do not add up.
7. **One open incident per station.** A higher rank upgrades the same id and speaks again. Rank is tipped 1, fallen 2, broken 2, jam 3. Broken may replace fallen, because it is the more specific name at the same rank. Fallen may not replace broken. A lower rank does not open a second incident and does not speak.
8. **The picture going quiet is not an acknowledge.** Upright frames after an incident leave it open. Only `acknowledge` on the form, by the operator, the line leader, or the backup, sets `reaction_ms`. The model is `prompt_ignored`. An acknowledge earlier than the first alert is `ack_before_alert`. A second acknowledge is `already_cleared`.
9. **Escalation is a speaker, not a stop.** When `now - alerted_at_ms` is at least `escalate_after_ms` and the incident is still open, `escalated` becomes true and the leader speaker gets one sentence. A second pass does not speak again. `slowdown_sent` stays false.
10. **No broadcast.** The station speaker gets the open and the upgrade. `leader_speaker` gets the escalation. `ALL` and `*` are `broadcast_refused`.
11. **No raw video in the record.** `raw_stored` is false on every incident. A person or face box inside the clip window, at or above `person_min_bps`, requires blur. Blur on: `anonymised` true, `clip_status` `stored`. Blur off: `clip_status` `held_for_blur`, `anonymised` false, still not raw.
12. **No person in the cause.** A cause containing operator, person, staff, worker, employee, or mitarbeiter is `people_monitoring_refused`. The closed list is `transfer_speed`, `stacker_timing`, `load_alignment`, `unknown`. The line leader assigns it on the form. The model is `prompt_ignored`. Until then the cause is `unassigned`, which is not the same as `unknown`.
13. **A blind station is not a calm line.** `line_clear` is true only when every station on the line has a fresh frame and every incident is acknowledged. The fixture leaves unloading with no frames, so `line_clear` is false and `go_no_go` fails on `unwatched`. Do not delete the unloading camera from the registry to make the board green.
14. **Digits in a model note are dropped** unless every digit string already appears in the code-written handover note. `36.5%`, `36,5%`, `24/7`, and `within weeks` are `copied_claim_refused` even when a digit would otherwise match.
15. **No case-study target.** The strings 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 and checks the same shape in SQLite, 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. Revoke update and delete on `incident` so a cleared row cannot be edited into a different story.

```sql
create table station (
  plant_id text not null,
  line_id text not null,
  station_id text not null,
  kind text not null,
  spoken_name text not null,
  camera_id text not null,
  speaker text not null,
  primary key (plant_id, station_id)
);

create table incident (
  incident_id text primary key,
  plant_id text not null,
  line_id text not null,
  station_id text not null,
  camera_id text not null,
  first_event text not null,
  event text not null,
  opened_at_ms integer not null,
  alerted_at_ms integer not null,
  acked_at_ms integer,
  reaction_ms integer,
  escalated integer not null,
  cascade integer not null,
  confidence_bps integer not null,
  clip_start_ms integer not null,
  clip_end_ms integer not null,
  anonymised integer not null,
  raw_stored integer not null,
  clip_status text not null,
  slowdown_sent integer not null,
  cause text not null
);
```

`SCHEMA_SQL` in the program is this script. `persist` inserts the fixture summary and checks that both incidents land with `raw_stored` 0.

The live build also keeps an audit table the fixture holds as a list. A model channel never inserts a row.

```sql
create table audit (
  audit_id text primary key,
  action text not null,
  actor text not null,
  channel text not null,
  incident_id text,
  result text not null
);
```

---

## 7. Cameras and RTSP ingestion

Map every watch point before you connect a URL. The four kinds are the ones the case names: a transfer curve, a stacker, a loading point, an unloading point. One row per point. The fixture's rows are:

| station_id | kind | spoken_name | camera_id | speaker |
| --- | --- | --- | --- | --- |
| `ST-CURVE` | `transfer_curve` | `der Übergabekurve` | `CAM-CURVE` | `SPK-CURVE` |
| `ST-STACK` | `stacker` | `dem Stapler` | `CAM-STACK` | `SPK-STACK` |
| `ST-LOAD` | `loading` | `der Beladung` | `CAM-LOAD` | `SPK-LOAD` |
| `ST-UNLOAD` | `unloading` | `der Entladung` | `CAM-UNLOAD` | `SPK-UNLOAD` |

`spoken_name` is what the template puts after "an" or "at". The fixture's German names include the article, so the sentence is "Gekipptes Glas an der Übergabekurve." The plant types the phrase the operator should hear. These four names are fixture phrases. They are not a Weißwasser station list. The case does not publish station ids.

The URL does not go in this file, in the config, or in a prompt. `camera_url_ok` returns `credential_in_url` when the authority contains `@`, which is where an RTSP user and password sit. `rtsp://10.0.0.8/stream` is `ok`. `rtsp://user:pass@10.0.0.8/stream` is refused. The wrapper reads the URL from the secret store at process start and passes it to ffmpeg as an argument the model never sees. The plan in the program uses the literal `SECRET` so the test can see that no password was written down.

`ffmpeg_plan` for a camera is:

```text
ffmpeg -hide_banner -loglevel error -rtsp_transport tcp -i SECRET -an -vf fps=2 -q:v 5 spool/CAM-CURVE_%08d.jpg
```

`-rtsp_transport tcp` is our choice because a lost UDP packet looks like a calm belt. `-an` drops the camera's audio. The alarm is outbound. The camera is not a microphone pointed at the operator. `fps=2` matches `sample_fps`. The spool filename carries the camera id. A file older than `camera_stale_ms` marks that station unwatched.

Each still becomes a detection row, not a decision:

```json
{"camera_id": "CAM-CURVE", "t_ms": 2000, "detections": [{"class": "glass_tipped", "confidence_bps": 8600}]}
```

`t_ms` is an integer offset from `run_clock`. `confidence_bps` is an integer from 0 to 10000. A float is `confidence_invalid`. The program sorts by `(t_ms, camera_id)` and applies each frame once.

A frame more than `frame_gap_ms` after the previous frame on that camera increments `gaps` and resets the streak before the new frame is counted. At 2 fps the interval is 500 ms and the gap limit is 1500 ms. Three missed stills and the count starts over. Do not debounce across a dropout. A dropout is how a tipped glass disappears from the streak and then "never happened."

---

## 8. Detector options and the labelling set

The case does not name a model. Two shapes are allowed, and one is refused.

**Object detection.** An off-the-shelf detector, the YOLO family or any detector that emits boxes and class names, fine-tuned on this plant's glass. Classes the rules understand: `glass_upright`, `glass_tipped`, `glass_fallen`, `glass_broken`, `jam`, `person`, `face`. This is the fixture's `detector` value, `object_detection`.

**Anomaly detection plus a classifier.** A model trained on a few hundred healthy clips flags that the belt does not look like the healthy set. A second, small classifier, or the same detector's class head, then names tipped, fallen, broken, or jam. `detector` is `anomaly_plus_classifier`. The rules still see a class and a confidence. They do not see an anomaly score.

**Anomaly only is refused.** A score without a class cannot fill the sentence. The operator has to hear which fault, at which station. `anomaly_only` is `class_required`.

The winning class on a frame is the event class at or above `min_confidence_bps` with the highest rank, then the highest confidence, then the class name. `person` and `face` never win. They only mark the frame. `glass_upright` never wins. A frame whose event boxes are all below the floor, and which has at least one such box, is a watch: counted, not spoken. The fixture's loading camera has one tipped box at 4000. That is the one watch. It is not an incident.

Label the set before `alerts_enabled` goes to `yes`. Our design, not a published Cerrion count: at least 300 clips, and at least 40 each of `glass_upright`, `glass_tipped`, `glass_fallen`, and `jam`. Broken glass can make up the rest. A clip is about four seconds from one camera, the same window as `clip_pre_ms`. Include healthy belt, a single tipped piece, a fallen piece, a pile-up, and the empty moments after a break, because the empty belt is not the same class as a jam. Split 210, 45, 45. The 45 stay untouched until the plant writes a detector card with the model id. This file does not invent a mean-average-precision number, and it will not accept 36.5% as one.

`label_gate` returns `labels_short` under 300, `class_short` when any of the four required classes is under 40, and `ok` when both hold. The fixture's short set is 30 of each, which is 120, and it fails. Eighty of each of the four passes. Do not arm the speakers on a gate that failed. Shadow mode is `alerts_enabled` `no`: the incident row is still written, `alert_suppressed` is true, and the alerts list stays empty. That is how the plant checks the debounce against a week of video before a speaker is connected.

---

## 9. Event rules

Three events leave the speaker. The class names are the detector's. The event names are ours.

| Detector class | Event | Debounce | Rank |
| --- | --- | --- | --- |
| `glass_tipped` | `tipped` | 3 | 1 |
| `glass_fallen` | `fallen` | 3 | 2 |
| `glass_broken` | `broken` | 3 | 2 |
| `jam` | `jam` | 5 | 3 |

A tip that becomes a fall is the cascade the case describes: one glass, then the breakage. The fixture opens `INC-1` as `tipped` at 2000 ms and upgrades the same id to `fallen` at 3500 ms. `cascade` is true. There is no `INC-3`. A jam on the stacker is a different station, so it is `INC-2`, opened at 6000 ms after five jam frames. It does not merge into the curve.

Opening stores `first_event`, `event`, `opened_at_ms`, `alerted_at_ms` (the same instant on open), `confidence_bps` of the frame that completed the debounce, and `debounce_met` true. The clip starts `clip_pre_ms` before that frame, floored at 0, and ends `clip_post_ms` after it. An upgrade moves `clip_end_ms` and does not move the start, and it replaces `confidence_bps` and `event`. `INC-1` therefore runs from 0 to 5500 and keeps confidence 9100. `INC-2` runs from 2000 to 8000 and keeps confidence 8000.

The fixture clock then moves to 51000 ms. `INC-1` was acknowledged at 20000 ms, so it does not escalate. `51000 - 6000` is 45000, which is the timer, so `INC-2` escalates once. The boundary is `>=`. One millisecond earlier would not escalate. The plant's N is whatever they type. 45 seconds is the fixture, so the test has a number to lock.

---

## 10. The act: the speaker, the escalation, the slowdown

The sentence is filled by code.

| Language | Open or upgrade | Escalation |
| --- | --- | --- |
| de | `{noun} an {station}.` | `Nicht quittiert. {noun} an {station}.` |
| en | `{noun} at {station}.` | `Not cleared. {noun} at {station}.` |
| pl | `{noun}, stanowisko {station}.` | `Niepotwierdzone. {noun}, stanowisko {station}.` |

The German nouns are `Gekipptes Glas`, `Heruntergefallenes Glas`, `Beschädigtes Glas`, and `Stau`. The English nouns are `Tipped glass`, `Fallen glass`, `Damaged glass`, and `Jam`. Polish is in the program for a plant that types `pl`. The case says the Polish facility is in the rollout. It does not say which language that plant's operators use. Do not copy `pl` onto a German line because the group has a plant in Poland.

The fixture, in `de`, speaks exactly these four sentences, on these speakers:

1. `Gekipptes Glas an der Übergabekurve.` on `SPK-CURVE` at 2000 ms.
2. `Heruntergefallenes Glas an der Übergabekurve.` on `SPK-CURVE` at 3500 ms.
3. `Stau an dem Stapler.` on `SPK-STACK` at 6000 ms.
4. `Nicht quittiert. Stau an dem Stapler.` on `SPK-LEAD` at 51000 ms.

Wire the speaker that is physically at that station. A horn that the whole hall hears is the broadcast this file refuses. The point of the published system is that the operator at the curve hears the curve.

Acknowledgement is a button on the shop-floor page, or a hardware button the page records. `channel` must be `form`. The actor must be the operator, the line leader, or the backup. `reaction_ms` is `ack_ms - alerted_at_ms` of the first alert, not of the upgrade and not of the escalation. The fixture's curve is `20000 - 2000`, which is 18000. The stacker is never acknowledged, so `reaction_ms` is null. Do not store 0. A null is a missed clear. A zero would look like an operator who was already there.

The slowdown is a separate call, `request_slowdown`.

- Model channel: `prompt_ignored`. `auto_slowdown_count` stays 0.
- Anyone who is not `safety_owner`: `actor_refused`. The line leader cannot slow the line from this desk.
- Sign-off missing, slowdown disabled, or the tag blank: `safety_signoff_required`. The fixture's own request on `INC-2` returns that, and `slowdown_sent` stays false.
- Signed, and the safety owner, and the incident still open: one signal, the tag name, `slowdown_sent` true. A second call is `already_sent`. A cleared incident is `incident_not_open`.

The signed test uses `plc_safety_signoff` `yes`, `slowdown_enabled` `yes`, and tag `LN1_SLOW`. That test is not the fixture hash. The hash is the unsigned plant. Shipping the speakers does not require the PLC. Connecting the PLC requires the signature. The sources describe sound alarms. They do not describe this tag.

---

## 11. Incident log, shift handover, weekly causes

Every incident the rule opens is the log. The row is the schema in section 6, plus the alerts in order. The clip is the stills from `clip_start_ms` to `clip_end_ms` on that camera. `INC-1` has a person box at 1000 ms, inside 0 to 5500, so with blur on the clip is `anonymised` and `stored`. `INC-2` has no person, so `anonymised` is false and `clip_status` is still `stored`. `raw_stored` is false on both. The RTSP buffer is not the record.

The shift note is `handover_note`. The fixture's note is:

```text
INC-1 fallen reaction 18000 not_escalated. INC-2 jam reaction na escalated. unwatched ST-UNLOAD
```

That note is the whole handover. A model sentence is kept only by `accept_prose`. `Scrap fell 36.5% and reaction was 18000` is `copied_claim_refused`. `reaction 99999` is `digit_in_prose`. `INC-1 reaction 18000 stays on the note` is kept, because 18000 is already in the note. Run it at any time as a snapshot. Run it again at the end of the shift. The fixture's 51000 ms is 51 seconds into the shift, which is the escalation boundary, not the end of an eight-hour shift. Do not relabel that snapshot as a shift report from Weißwasser.

The weekly report groups the final event by station. The fixture groups `ST-CURVE` fallen 1 and `ST-STACK` jam 1. It does not write a paragraph about why. `assign_cause` takes a code from the closed list. `operator_error` on `INC-2` is `people_monitoring_refused` and the cause does not change. A model call that offers `stacker_timing` is `prompt_ignored` and writes no audit row. The line leader, on the form, may assign `stacker_timing`. The fixture does that so the test can see the list work. `stacker_timing` on `INC-2` is our test data. It is not a finding about a stacker in Weißwasser. `INC-1` stays `unassigned`. `unknown` is allowed only when a person picks it. The agent does not default a blank to `unknown`.

`audit_results` on the fixture, in order: `cleared`, `people_monitoring_refused`, `assigned`, `safety_signoff_required`. The model calls are absent on purpose. A channel of `model` inserts nothing.

---

## 12. What the language model may do

`SYSTEM_PROMPT` is ours. It is not a Cerrion prompt. The case does not publish one.

```text
You are the line-watch agent. You name a station and an event the rules already opened. You do not name a person. You do not decide a scrap quantity, a reaction time, or a root cause. You do not slow the line. A digit you add is dropped.
```

The model may be handed a finished incident JSON and asked for one sentence. `accept_prose` is the gate. The model may not be handed the RTSP URL, the database URL, or a prompt that includes operator names as people to evaluate. Tool results are the incident, the alerts, the handover note, and the weekly groups.

The tools the model may call, and the only ones a chat wrapper may expose:

- `ingest` for a detection row. It does not accept an event name.
- `acknowledge`, `assign_cause`, and `request_slowdown`, which the model may not successfully call. The form calls them.
- `handover_note`, `summary`, and `go_no_go`, which are reads.

There is no `set_scrap`, no `clear_from_image`, and no `slow_line`.

---

## 13. The fixture, worked

The frames are hand-typed. Every company name begins with `FIXTURE`. None of these rows is a Weißwasser frame, a Weißwasser scrap count, or a Cerrion threshold.

On the curve: upright, upright, then three tipped frames from 1000 to 2000, the first of them carrying a person box at 8000. Then three fallen frames from 2500 to 3500. Then an upright heartbeat at 51000. The person box is why the clip is anonymised. The heartbeat is why the curve camera is fresh at the escalation instant. It does not clear `INC-1`. The acknowledge at 20000 does.

On the stacker: upright at 0 and 500, five jam frames from 4000 to 6000, an upright heartbeat at 51000. The jump from 500 to 4000 is one gap. The jump from 6000 to 51000 is the second. The five jam frames sit inside the gap limit, so the streak completes. The upright heartbeat does not clear `INC-2`.

On loading: one tipped box at 4000 basis points, which is under 7000, then upright. One watch. No incident.

On unloading: no frames. Unwatched.

Scrap export, separate from the cameras: 800 good pieces, 40 scrap pieces, `source` `plant_counter`. `40 * 10000 // 840` is 476. That is the fixture's scrap basis points. It is not 36.5%, and it is not a target.

`go_no_go` on this run fails, and the only reason it needs to fail is `unwatched`. The reaction of 18000 is under the fixture ceiling of 30000. Two incidents are under the ceiling of 5. 476 is under the ceiling of 800. A blind unloading station fails the line anyway. A second, smaller run in the tests puts a fresh frame on all four stations, opens one tip, acknowledges it in 4000 ms, and passes. That pass is our test. It is not a pilot result.

---

## 14. Reference program

Copy the block below to `line_watch_agent.py`. Run it with Python 3.11 or newer. Standard library only. Do not edit the hash to make a failure go quiet. If the hash moves, the program moved, and section 13 stays as written until a person re-locks it on purpose.

```python
"""Line-watch agent for a fragile-goods line. Synthetic fixture.

Not a model of Stölzle Lausitz GmbH, and not a Cerrion setting.
Python 3.11+. Standard library only. Integer milliseconds. No floats.
"""

from __future__ import annotations

import hashlib
import json
import re
import sqlite3

BLOCKED_KEYS = (
    "scrap_cut_pct",
    "reaction_cut_pct",
    "target_scrap_reduction",
    "case_line_count",
    "supervision_claim",
)
BLOCKED_TEXT = ("36.5%", "36,5%", "24/7", "within weeks")
PEOPLE_KEYS = ("operator_score", "people_score", "productivity", "worker_score")
PEOPLE_CAUSE = ("operator", "person", "staff", "worker", "employee", "mitarbeiter")
EVENT_RANK = {"tipped": 1, "fallen": 2, "broken": 2, "jam": 3}
CLASS_EVENT = {
    "glass_tipped": "tipped",
    "glass_fallen": "fallen",
    "glass_broken": "broken",
    "jam": "jam",
}
PRIVACY_CLASSES = ("person", "face")
CAUSES = ("transfer_speed", "stacker_timing", "load_alignment", "unknown")
REQUIRED_CONFIG = (
    "company_name",
    "line_leader",
    "operator",
    "safety_owner",
    "backup",
    "desk_inbox",
    "timezone",
    "run_clock",
    "plant_id",
    "line_id",
    "lines_in_scope",
    "operator_language",
    "detector",
    "sample_fps",
    "frame_gap_ms",
    "min_confidence_bps",
    "escalate_after_ms",
    "camera_stale_ms",
    "clip_pre_ms",
    "clip_post_ms",
    "min_labelled_clips",
    "per_class_min",
    "person_min_bps",
    "retention_days",
    "works_council_signoff",
    "plc_safety_signoff",
    "slowdown_enabled",
    "slowdown_tag",
    "auto_slowdown",
    "auto_scrap",
    "alerts_enabled",
    "blur_enabled",
    "require_human_ack",
    "shadow",
    "mode",
    "leader_speaker",
    "max_median_reaction_ms",
    "max_incidents_per_shift",
    "max_scrap_bps",
)
DETECTORS = ("object_detection", "anomaly_plus_classifier")
LANGUAGES = ("de", "en", "pl")
NOUNS = {
    "de": {
        "tipped": "Gekipptes Glas",
        "fallen": "Heruntergefallenes Glas",
        "broken": "Beschädigtes Glas",
        "jam": "Stau",
    },
    "en": {
        "tipped": "Tipped glass",
        "fallen": "Fallen glass",
        "broken": "Damaged glass",
        "jam": "Jam",
    },
    "pl": {
        "tipped": "Przewrócona szklanka",
        "fallen": "Upuszczona szklanka",
        "broken": "Uszkodzona szklanka",
        "jam": "Zator",
    },
}
TEMPLATES = {
    "de": {
        "event": "{noun} an {station}.",
        "escalate": "Nicht quittiert. {noun} an {station}.",
    },
    "en": {
        "event": "{noun} at {station}.",
        "escalate": "Not cleared. {noun} at {station}.",
    },
    "pl": {
        "event": "{noun}, stanowisko {station}.",
        "escalate": "Niepotwierdzone. {noun}, stanowisko {station}.",
    },
}
DEBOUNCE = {"tipped": 3, "fallen": 3, "broken": 3, "jam": 5}
LABEL_CLASSES = ("glass_upright", "glass_tipped", "glass_fallen", "jam")
EXPECTED_HASH = "fd9ac266c6b756df9139b1cea24dbadb5a5c271be505d2d5a65382589d2404d8"
SYSTEM_PROMPT = (
    "You are the line-watch agent. You name a station and an event the rules already "
    "opened. You do not name a person. You do not decide a scrap quantity, a reaction "
    "time, or a root cause. You do not slow the line. A digit you add is dropped."
)

SCHEMA_SQL = """
create table station (
  plant_id text not null,
  line_id text not null,
  station_id text not null,
  kind text not null,
  spoken_name text not null,
  camera_id text not null,
  speaker text not null,
  primary key (plant_id, station_id)
);
create table incident (
  incident_id text primary key,
  plant_id text not null,
  line_id text not null,
  station_id text not null,
  camera_id text not null,
  first_event text not null,
  event text not null,
  opened_at_ms integer not null,
  alerted_at_ms integer not null,
  acked_at_ms integer,
  reaction_ms integer,
  escalated integer not null,
  cascade integer not null,
  confidence_bps integer not null,
  clip_start_ms integer not null,
  clip_end_ms integer not null,
  anonymised integer not null,
  raw_stored integer not null,
  clip_status text not null,
  slowdown_sent integer not null,
  cause text not null
);
"""


def fixture_config():
    return {
        "company_name": "FIXTURE Glass Co.",
        "line_leader": "FIXTURE Leader",
        "operator": "FIXTURE Operator",
        "safety_owner": "FIXTURE Safety",
        "backup": "none",
        "desk_inbox": "line@fixture.example",
        "timezone": "Europe/Berlin",
        "run_clock": "2026-11-28T06:00:00+01:00",
        "plant_id": "PLT-1",
        "line_id": "LN-1",
        "lines_in_scope": 1,
        "operator_language": "de",
        "detector": "object_detection",
        "sample_fps": 2,
        "frame_gap_ms": 1500,
        "min_confidence_bps": 7000,
        "escalate_after_ms": 45000,
        "camera_stale_ms": 5000,
        "clip_pre_ms": 4000,
        "clip_post_ms": 2000,
        "min_labelled_clips": 300,
        "per_class_min": 40,
        "person_min_bps": 5000,
        "retention_days": 30,
        "works_council_signoff": "yes",
        "plc_safety_signoff": "no",
        "slowdown_enabled": "no",
        "slowdown_tag": "",
        "auto_slowdown": "no",
        "auto_scrap": "no",
        "alerts_enabled": "yes",
        "blur_enabled": "yes",
        "require_human_ack": "yes",
        "shadow": "yes",
        "mode": "fixture",
        "leader_speaker": "SPK-LEAD",
        "max_median_reaction_ms": 30000,
        "max_incidents_per_shift": 5,
        "max_scrap_bps": 800,
    }


def fixture_stations():
    return {
        "ST-CURVE": {
            "line_id": "LN-1",
            "kind": "transfer_curve",
            "spoken_name": "der Übergabekurve",
            "camera_id": "CAM-CURVE",
            "speaker": "SPK-CURVE",
        },
        "ST-STACK": {
            "line_id": "LN-1",
            "kind": "stacker",
            "spoken_name": "dem Stapler",
            "camera_id": "CAM-STACK",
            "speaker": "SPK-STACK",
        },
        "ST-LOAD": {
            "line_id": "LN-1",
            "kind": "loading",
            "spoken_name": "der Beladung",
            "camera_id": "CAM-LOAD",
            "speaker": "SPK-LOAD",
        },
        "ST-UNLOAD": {
            "line_id": "LN-1",
            "kind": "unloading",
            "spoken_name": "der Entladung",
            "camera_id": "CAM-UNLOAD",
            "speaker": "SPK-UNLOAD",
        },
    }


def _jam_frames():
    rows = []
    for i, t in enumerate((4000, 4500, 5000, 5500, 6000)):
        rows.append(
            {
                "camera_id": "CAM-STACK",
                "t_ms": t,
                "detections": [{"class": "jam", "confidence_bps": 8000}],
            }
        )
    return rows


def fixture_frames():
    """Hand-typed detections. Every id is FIXTURE data. None of it is a Weißwasser frame."""
    return [
        {"camera_id": "CAM-CURVE", "t_ms": 0, "detections": [{"class": "glass_upright", "confidence_bps": 9000}]},
        {"camera_id": "CAM-CURVE", "t_ms": 500, "detections": [{"class": "glass_upright", "confidence_bps": 9000}]},
        {
            "camera_id": "CAM-CURVE",
            "t_ms": 1000,
            "detections": [
                {"class": "glass_tipped", "confidence_bps": 8200},
                {"class": "person", "confidence_bps": 8000},
            ],
        },
        {"camera_id": "CAM-CURVE", "t_ms": 1500, "detections": [{"class": "glass_tipped", "confidence_bps": 8400}]},
        {"camera_id": "CAM-CURVE", "t_ms": 2000, "detections": [{"class": "glass_tipped", "confidence_bps": 8600}]},
        {"camera_id": "CAM-CURVE", "t_ms": 2500, "detections": [{"class": "glass_fallen", "confidence_bps": 8800}]},
        {"camera_id": "CAM-CURVE", "t_ms": 3000, "detections": [{"class": "glass_fallen", "confidence_bps": 9000}]},
        {"camera_id": "CAM-CURVE", "t_ms": 3500, "detections": [{"class": "glass_fallen", "confidence_bps": 9100}]},
        {"camera_id": "CAM-CURVE", "t_ms": 51000, "detections": [{"class": "glass_upright", "confidence_bps": 9000}]},
        {"camera_id": "CAM-STACK", "t_ms": 0, "detections": [{"class": "glass_upright", "confidence_bps": 9000}]},
        {"camera_id": "CAM-STACK", "t_ms": 500, "detections": [{"class": "glass_upright", "confidence_bps": 9000}]},
        *_jam_frames(),
        {"camera_id": "CAM-STACK", "t_ms": 51000, "detections": [{"class": "glass_upright", "confidence_bps": 9000}]},
        {"camera_id": "CAM-LOAD", "t_ms": 1000, "detections": [{"class": "glass_tipped", "confidence_bps": 4000}]},
        {"camera_id": "CAM-LOAD", "t_ms": 1500, "detections": [{"class": "glass_upright", "confidence_bps": 9000}]},
        {"camera_id": "CAM-LOAD", "t_ms": 51000, "detections": [{"class": "glass_upright", "confidence_bps": 9000}]},
    ]


def fixture_scrap():
    return {"line_id": "LN-1", "good_pieces": 800, "scrap_pieces": 40, "source": "plant_counter"}


def load_config(raw):
    if not isinstance(raw, dict):
        return None, "config_missing"
    for key in raw:
        lower = key.lower()
        if any(part in lower for part in ("password", "api_key", "secret", "token")):
            return None, "credential_too_wide"
        if any(part in lower for part in PEOPLE_KEYS):
            return None, "people_monitoring_refused"
        if key in BLOCKED_KEYS:
            return None, "copied_claim_refused"
    for key in REQUIRED_CONFIG:
        if key not in raw:
            return None, "replace_unset"
        value = raw[key]
        if value == "" or value == "REPLACE":
            if key == "slowdown_tag" and raw.get("slowdown_enabled") == "no":
                continue
            if key in ("max_median_reaction_ms", "max_incidents_per_shift", "max_scrap_bps"):
                continue
            if key == "backup":
                continue
            return None, "replace_unset"
        if isinstance(value, str) and any(token in value for token in BLOCKED_TEXT):
            return None, "copied_claim_refused"
    if raw["lines_in_scope"] != 1:
        return None, "scope_refused"
    if raw["works_council_signoff"] != "yes":
        return None, "works_council_required"
    if raw["auto_slowdown"] != "no":
        return None, "slowdown_locked"
    if raw["auto_scrap"] != "no":
        return None, "scrap_locked"
    if raw["require_human_ack"] != "yes":
        return None, "ack_locked"
    if raw["detector"] not in DETECTORS:
        if raw["detector"] == "anomaly_only":
            return None, "class_required"
        return None, "detector_refused"
    if raw["operator_language"] not in LANGUAGES:
        return None, "language_missing"
    if raw["sample_fps"] not in (1, 2, 4):
        return None, "fps_refused"
    expected_gap = (1000 // raw["sample_fps"]) * 3
    if raw["frame_gap_ms"] != expected_gap:
        return None, "gap_mismatch"
    if raw["mode"] == "live":
        blob = json.dumps(raw)
        if "EXAMPLE" in blob or "FIXTURE" in blob:
            return None, "example_row_in_live"
    if raw["slowdown_enabled"] == "yes":
        if raw["plc_safety_signoff"] != "yes" or not raw["slowdown_tag"] or raw["safety_owner"] in ("", "REPLACE"):
            return None, "safety_signoff_required"
    elif raw["slowdown_enabled"] != "no":
        return None, "slowdown_locked"
    if not isinstance(raw["min_confidence_bps"], int) or isinstance(raw["min_confidence_bps"], bool):
        return None, "confidence_invalid"
    if raw["min_confidence_bps"] < 1 or raw["min_confidence_bps"] > 10000:
        return None, "confidence_invalid"
    return raw, None


def median(values):
    if not values:
        return None
    ordered = sorted(values)
    return ordered[(len(ordered) - 1) // 2]


def scrap_bps(row):
    if not isinstance(row, dict) or row.get("source") != "plant_counter":
        return None, "scrap_source_refused"
    good = row.get("good_pieces")
    scrap = row.get("scrap_pieces")
    if not isinstance(good, int) or not isinstance(scrap, int) or isinstance(good, bool) or isinstance(scrap, bool):
        return None, "scrap_invalid"
    if good < 0 or scrap < 0:
        return None, "scrap_invalid"
    total = good + scrap
    if total == 0:
        return None, "scrap_empty"
    return scrap * 10000 // total, None


def label_gate(counts, min_labelled, per_class_min):
    if not isinstance(counts, dict):
        return "labels_short"
    total = 0
    for key, value in counts.items():
        if not isinstance(value, int) or isinstance(value, bool) or value < 0:
            return "labels_short"
        total += value
    if total < min_labelled:
        return "labels_short"
    for name in LABEL_CLASSES:
        if counts.get(name, 0) < per_class_min:
            return "class_short"
    return "ok"


def camera_url_ok(url):
    """The RTSP URL stays in the secret store. This file never holds it."""
    if not isinstance(url, str) or url == "":
        return "url_missing"
    if "://" not in url:
        return "url_refused"
    authority = url.split("://", 1)[1].split("/", 1)[0]
    if "@" in authority:
        return "credential_in_url"
    return "ok"


def ffmpeg_plan(camera_id):
    return [
        "ffmpeg",
        "-hide_banner",
        "-loglevel",
        "error",
        "-rtsp_transport",
        "tcp",
        "-i",
        "SECRET",
        "-an",
        "-vf",
        "fps=2",
        "-q:v",
        "5",
        f"spool/{camera_id}_%08d.jpg",
    ]


def alert_text(language, kind, event, spoken_name):
    noun = NOUNS[language][event]
    pattern = TEMPLATES[language]["escalate" if kind == "escalate" else "event"]
    return pattern.format(noun=noun, station=spoken_name)


def _digits(text):
    return re.findall(r"\d+", text)


class Plant:
    def __init__(self, config, stations, frames, scrap):
        self.config = config
        self.stations = stations
        self.by_camera = {row["camera_id"]: sid for sid, row in stations.items()}
        self.frames = []
        self.incidents = []
        self.alerts = []
        self.watches = []
        self.audit = []
        self.gaps = {row["camera_id"]: 0 for row in stations.values()}
        self.last_frame = {row["camera_id"]: None for row in stations.values()}
        self.streak = {row["camera_id"]: {"event": None, "count": 0, "last_t": None} for row in stations.values()}
        self.warnings = []
        self.scrap = scrap
        self.now_ms = 0
        self.auto_slowdown_count = 0
        self.auto_scrap_count = 0
        self._next_incident = 1
        self._next_alert = 1
        self._next_audit = 1
        for frame in frames:
            result = self.ingest(frame)
            if not result["ok"]:
                self.warnings.append(result["error"])

    def ingest(self, frame):
        camera = frame.get("camera_id")
        if camera not in self.by_camera:
            return {"ok": False, "error": "camera_unknown"}
        station = self.stations[self.by_camera[camera]]
        if station["line_id"] != self.config["line_id"]:
            return {"ok": False, "error": "line_out_of_scope"}
        t_ms = frame.get("t_ms")
        if not isinstance(t_ms, int) or isinstance(t_ms, bool) or t_ms < 0:
            return {"ok": False, "error": "clock_unparsed"}
        detections = []
        for det in frame.get("detections", []):
            if any(key in det for key in ("event", "alert_text", "slowdown", "cause")):
                self.warnings.append("ignored_field")
            name = det.get("class")
            confidence = det.get("confidence_bps")
            if not isinstance(confidence, int) or isinstance(confidence, bool):
                return {"ok": False, "error": "confidence_invalid"}
            if confidence < 0 or confidence > 10000:
                return {"ok": False, "error": "confidence_invalid"}
            if name not in CLASS_EVENT and name not in PRIVACY_CLASSES and name != "glass_upright":
                self.warnings.append("class_unknown")
                continue
            detections.append({"class": name, "confidence_bps": confidence})
        stored = {"camera_id": camera, "t_ms": t_ms, "detections": detections}
        self.frames.append(stored)
        self._apply(stored)
        return {"ok": True}

    def _winning(self, detections):
        floor = self.config["min_confidence_bps"]
        best = None
        below = False
        person = False
        for det in detections:
            if det["class"] in PRIVACY_CLASSES and det["confidence_bps"] >= self.config["person_min_bps"]:
                person = True
            if det["class"] not in CLASS_EVENT:
                continue
            if det["confidence_bps"] < floor:
                below = True
                continue
            event = CLASS_EVENT[det["class"]]
            rank = (EVENT_RANK[event], det["confidence_bps"], event)
            if best is None or rank > best[0]:
                best = (rank, event, det["confidence_bps"])
        if best is None:
            return None, None, below, person
        return best[1], best[2], below, person

    def _apply(self, frame):
        camera = frame["camera_id"]
        t_ms = frame["t_ms"]
        previous = self.last_frame[camera]
        streak = self.streak[camera]
        if previous is not None and t_ms - previous > self.config["frame_gap_ms"]:
            self.gaps[camera] += 1
            streak["event"] = None
            streak["count"] = 0
        self.last_frame[camera] = t_ms
        if t_ms > self.now_ms:
            self.now_ms = t_ms
        event, confidence, below, _person = self._winning(frame["detections"])
        if event is None:
            streak["event"] = None
            streak["count"] = 0
            streak["last_t"] = t_ms
            if below:
                self.watches.append({"camera_id": camera, "t_ms": t_ms})
            return
        if streak["event"] == event:
            streak["count"] += 1
        else:
            streak["event"] = event
            streak["count"] = 1
        streak["last_t"] = t_ms
        if streak["count"] >= DEBOUNCE[event]:
            self._open_or_upgrade(camera, event, t_ms, confidence)
            streak["event"] = None
            streak["count"] = 0

    def _station_id(self, camera):
        return self.by_camera[camera]

    def _open_incident(self, station_id):
        for incident in self.incidents:
            if incident["station_id"] == station_id and incident["acked_at_ms"] is None:
                return incident
        return None

    def _clip_bounds(self, t_ms, previous_start=None):
        start = t_ms - self.config["clip_pre_ms"]
        if start < 0:
            start = 0
        if previous_start is not None:
            start = previous_start
        return start, t_ms + self.config["clip_post_ms"]

    def _open_or_upgrade(self, camera, event, t_ms, confidence):
        station_id = self._station_id(camera)
        current = self._open_incident(station_id)
        if current is None:
            start, end = self._clip_bounds(t_ms)
            incident = {
                "id": f"INC-{self._next_incident}",
                "station_id": station_id,
                "camera_id": camera,
                "line_id": self.config["line_id"],
                "first_event": event,
                "event": event,
                "opened_at_ms": t_ms,
                "alerted_at_ms": t_ms,
                "acked_at_ms": None,
                "reaction_ms": None,
                "escalated": False,
                "cascade": False,
                "confidence_bps": confidence,
                "clip_start_ms": start,
                "clip_end_ms": end,
                "slowdown_sent": False,
                "cause": "unassigned",
                "debounce_met": True,
            }
            self._next_incident += 1
            self.incidents.append(incident)
            self._speak(incident, "open", t_ms)
            return
        current_rank = EVENT_RANK[current["event"]]
        new_rank = EVENT_RANK[event]
        refine = current["event"] == "fallen" and event == "broken"
        if new_rank < current_rank or (new_rank == current_rank and not refine):
            return
        current["event"] = event
        current["cascade"] = True
        current["confidence_bps"] = confidence
        current["clip_end_ms"] = t_ms + self.config["clip_post_ms"]
        self._speak(current, "upgrade", t_ms)

    def _speak(self, incident, kind, t_ms):
        if self.config["alerts_enabled"] != "yes":
            incident["alert_suppressed"] = True
            return
        station = self.stations[incident["station_id"]]
        speaker = self.config["leader_speaker"] if kind == "escalate" else station["speaker"]
        if speaker in ("ALL", "*"):
            self.warnings.append("broadcast_refused")
            return
        text = alert_text(self.config["operator_language"], kind, incident["event"], station["spoken_name"])
        self.alerts.append(
            {
                "id": f"AL-{self._next_alert}",
                "incident_id": incident["id"],
                "kind": kind,
                "t_ms": t_ms,
                "speaker": speaker,
                "language": self.config["operator_language"],
                "text": text,
            }
        )
        self._next_alert += 1

    def _person_in_clip(self, incident):
        for frame in self.frames:
            if frame["camera_id"] != incident["camera_id"]:
                continue
            if frame["t_ms"] < incident["clip_start_ms"] or frame["t_ms"] > incident["clip_end_ms"]:
                continue
            for det in frame["detections"]:
                if det["class"] in PRIVACY_CLASSES and det["confidence_bps"] >= self.config["person_min_bps"]:
                    return True
        return False

    def _clip_fields(self, incident):
        person = self._person_in_clip(incident)
        if person and self.config["blur_enabled"] != "yes":
            return {"anonymised": False, "raw_stored": False, "clip_status": "held_for_blur"}
        if person:
            return {"anonymised": True, "raw_stored": False, "clip_status": "stored"}
        return {"anonymised": False, "raw_stored": False, "clip_status": "stored"}

    def _audit(self, action, actor, channel, incident_id, result):
        if channel == "model":
            return {"ok": False, "error": "prompt_ignored"}
        row = {
            "id": f"AU-{self._next_audit}",
            "action": action,
            "actor": actor,
            "channel": channel,
            "incident_id": incident_id,
            "result": result,
        }
        self._next_audit += 1
        self.audit.append(row)
        return {"ok": True, "audit_id": row["id"]}

    def _actor_ok(self, actor, allowed):
        if actor in allowed:
            return True
        if self.config["backup"] not in ("none", "", "REPLACE") and actor == self.config["backup"]:
            return True
        return False

    def acknowledge(self, incident_id, actor, channel, ack_ms):
        if channel == "model":
            return self._audit("ack", actor, channel, incident_id, "prompt_ignored")
        if not self._actor_ok(actor, (self.config["operator"], self.config["line_leader"])):
            self._audit("ack", actor, channel, incident_id, "actor_refused")
            return {"ok": False, "error": "actor_refused"}
        if not isinstance(ack_ms, int) or isinstance(ack_ms, bool):
            return {"ok": False, "error": "clock_unparsed"}
        incident = next((row for row in self.incidents if row["id"] == incident_id), None)
        if incident is None:
            return {"ok": False, "error": "incident_missing"}
        if incident["acked_at_ms"] is not None:
            return {"ok": False, "error": "already_cleared"}
        if ack_ms < incident["alerted_at_ms"]:
            return {"ok": False, "error": "ack_before_alert"}
        incident["acked_at_ms"] = ack_ms
        incident["reaction_ms"] = ack_ms - incident["alerted_at_ms"]
        self._audit("ack", actor, channel, incident_id, "cleared")
        return {"ok": True, "reaction_ms": incident["reaction_ms"]}

    def escalate(self, now_ms):
        if not isinstance(now_ms, int) or isinstance(now_ms, bool):
            return {"ok": False, "error": "clock_unparsed"}
        self.now_ms = now_ms
        fired = []
        for incident in self.incidents:
            if incident["acked_at_ms"] is not None or incident["escalated"]:
                continue
            if now_ms - incident["alerted_at_ms"] < self.config["escalate_after_ms"]:
                continue
            incident["escalated"] = True
            self._speak(incident, "escalate", now_ms)
            fired.append(incident["id"])
        return {"ok": True, "escalated": fired}

    def request_slowdown(self, incident_id, actor, channel):
        if channel == "model":
            self.auto_slowdown_count += 0
            return self._audit("slowdown", actor, channel, incident_id, "prompt_ignored")
        if actor != self.config["safety_owner"]:
            self._audit("slowdown", actor, channel, incident_id, "actor_refused")
            return {"ok": False, "error": "actor_refused"}
        signed = (
            self.config["plc_safety_signoff"] == "yes"
            and self.config["slowdown_enabled"] == "yes"
            and bool(self.config["slowdown_tag"])
        )
        if not signed:
            self._audit("slowdown", actor, channel, incident_id, "safety_signoff_required")
            return {"ok": False, "error": "safety_signoff_required"}
        incident = next((row for row in self.incidents if row["id"] == incident_id), None)
        if incident is None:
            return {"ok": False, "error": "incident_missing"}
        if incident["acked_at_ms"] is not None:
            return {"ok": False, "error": "incident_not_open"}
        if incident["slowdown_sent"]:
            return {"ok": False, "error": "already_sent"}
        incident["slowdown_sent"] = True
        self._audit("slowdown", actor, channel, incident_id, "signalled")
        return {"ok": True, "tag": self.config["slowdown_tag"]}

    def assign_cause(self, incident_id, cause, actor, channel):
        if channel == "model":
            return self._audit("cause", actor, channel, incident_id, "prompt_ignored")
        lowered = str(cause).lower()
        if any(word in lowered for word in PEOPLE_CAUSE):
            self._audit("cause", actor, channel, incident_id, "people_monitoring_refused")
            return {"ok": False, "error": "people_monitoring_refused"}
        if cause not in CAUSES:
            return {"ok": False, "error": "cause_unknown"}
        if not self._actor_ok(actor, (self.config["line_leader"],)):
            self._audit("cause", actor, channel, incident_id, "actor_refused")
            return {"ok": False, "error": "actor_refused"}
        incident = next((row for row in self.incidents if row["id"] == incident_id), None)
        if incident is None:
            return {"ok": False, "error": "incident_missing"}
        incident["cause"] = cause
        self._audit("cause", actor, channel, incident_id, "assigned")
        return {"ok": True}

    def unwatched(self):
        stale = []
        for station_id, station in self.stations.items():
            if station["line_id"] != self.config["line_id"]:
                continue
            last = self.last_frame[station["camera_id"]]
            if last is None or self.now_ms - last > self.config["camera_stale_ms"]:
                stale.append(station_id)
        return stale

    def reactions(self):
        return [row["reaction_ms"] for row in self.incidents if row["reaction_ms"] is not None]

    def handover_note(self):
        parts = []
        for incident in self.incidents:
            reaction = "na" if incident["reaction_ms"] is None else str(incident["reaction_ms"])
            flag = "escalated" if incident["escalated"] else "not_escalated"
            parts.append(f"{incident['id']} {incident['event']} reaction {reaction} {flag}")
        blind = self.unwatched()
        if blind:
            parts.append("unwatched " + ",".join(blind))
        return ". ".join(parts)

    def accept_prose(self, sentence):
        if not sentence:
            return {"ok": True, "kept": False}
        if any(token in sentence for token in BLOCKED_TEXT):
            return {"ok": False, "error": "copied_claim_refused"}
        note = self.handover_note()
        allowed = set(_digits(note))
        for group in _digits(sentence):
            if group not in allowed:
                return {"ok": False, "error": "digit_in_prose"}
        return {"ok": True, "kept": True, "text": sentence}

    def go_no_go(self):
        missing = []
        for key in ("max_median_reaction_ms", "max_incidents_per_shift", "max_scrap_bps"):
            value = self.config.get(key)
            if value in (None, "", "REPLACE"):
                missing.append(key)
        if missing:
            return {"result": "threshold_unset", "reasons": missing}
        reasons = []
        opened = len(self.incidents)
        reaction = median(self.reactions())
        if opened > 0 and reaction is None:
            reasons.append("reaction_empty")
        if reaction is not None and reaction > self.config["max_median_reaction_ms"]:
            reasons.append("reaction")
        if opened > self.config["max_incidents_per_shift"]:
            reasons.append("incidents")
        bps, error = scrap_bps(self.scrap)
        if error:
            reasons.append(error)
        elif bps > self.config["max_scrap_bps"]:
            reasons.append("scrap")
        if self.unwatched():
            reasons.append("unwatched")
        if reasons:
            return {"result": "fail", "reasons": reasons}
        return {"result": "pass", "reasons": []}

    def summary(self):
        incidents = []
        for incident in self.incidents:
            clip = self._clip_fields(incident)
            incidents.append(
                {
                    "id": incident["id"],
                    "station_id": incident["station_id"],
                    "camera_id": incident["camera_id"],
                    "first_event": incident["first_event"],
                    "event": incident["event"],
                    "opened_at_ms": incident["opened_at_ms"],
                    "alerted_at_ms": incident["alerted_at_ms"],
                    "acked_at_ms": incident["acked_at_ms"],
                    "reaction_ms": incident["reaction_ms"],
                    "escalated": incident["escalated"],
                    "cascade": incident["cascade"],
                    "confidence_bps": incident["confidence_bps"],
                    "clip_start_ms": incident["clip_start_ms"],
                    "clip_end_ms": incident["clip_end_ms"],
                    "anonymised": clip["anonymised"],
                    "raw_stored": clip["raw_stored"],
                    "clip_status": clip["clip_status"],
                    "slowdown_sent": incident["slowdown_sent"],
                    "cause": incident["cause"],
                    "debounce_met": incident["debounce_met"],
                }
            )
        bps, _error = scrap_bps(self.scrap)
        by_station = {}
        for incident in incidents:
            by_station.setdefault(incident["station_id"], {})
            by_station[incident["station_id"]][incident["event"]] = (
                by_station[incident["station_id"]].get(incident["event"], 0) + 1
            )
        return {
            "incidents": incidents,
            "alerts": list(self.alerts),
            "watches": len(self.watches),
            "unwatched": self.unwatched(),
            "line_clear": not self.unwatched() and all(row["acked_at_ms"] is not None for row in self.incidents),
            "gaps": self.gaps,
            "handover_note": self.handover_note(),
            "weekly": by_station,
            "causes": {row["id"]: row["cause"] for row in incidents},
            "scrap_bps": bps,
            "incidents_per_shift": len(incidents),
            "median_reaction_ms": median(self.reactions()),
            "go_no_go": self.go_no_go()["result"],
            "auto_slowdown_count": self.auto_slowdown_count,
            "auto_scrap_count": self.auto_scrap_count,
            "audit_results": [row["result"] for row in self.audit],
        }


def canonical_hash(summary):
    payload = json.dumps(summary, sort_keys=True, separators=(",", ":")).encode()
    return hashlib.sha256(payload).hexdigest()


def run_main():
    config, error = load_config(fixture_config())
    if error:
        raise RuntimeError(error)
    plant = Plant(config, fixture_stations(), fixture_frames(), fixture_scrap())
    ack = plant.acknowledge("INC-1", "FIXTURE Operator", "form", 20000)
    if not ack["ok"]:
        raise RuntimeError(ack["error"])
    plant.escalate(51000)
    refused = plant.assign_cause("INC-2", "operator_error", "FIXTURE Leader", "form")
    ignored = plant.assign_cause("INC-2", "stacker_timing", "FIXTURE Leader", "model")
    assigned = plant.assign_cause("INC-2", "stacker_timing", "FIXTURE Leader", "form")
    if refused["error"] != "people_monitoring_refused":
        raise RuntimeError(refused)
    if ignored["error"] != "prompt_ignored":
        raise RuntimeError(ignored)
    if not assigned["ok"]:
        raise RuntimeError(assigned)
    slow = plant.request_slowdown("INC-2", "FIXTURE Safety", "form")
    if slow["error"] != "safety_signoff_required":
        raise RuntimeError(slow)
    prose = plant.accept_prose("Scrap fell 36.5% and reaction was 18000")
    if prose["error"] != "copied_claim_refused":
        raise RuntimeError(prose)
    return plant


def persist(summary):
    connection = sqlite3.connect(":memory:")
    connection.executescript(SCHEMA_SQL)
    for station_id, station in fixture_stations().items():
        connection.execute(
            "insert into station values (?,?,?,?,?,?,?)",
            (
                "PLT-1",
                station["line_id"],
                station_id,
                station["kind"],
                station["spoken_name"],
                station["camera_id"],
                station["speaker"],
            ),
        )
    for incident in summary["incidents"]:
        connection.execute(
            "insert into incident values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
            (
                incident["id"],
                "PLT-1",
                "LN-1",
                incident["station_id"],
                incident["camera_id"],
                incident["first_event"],
                incident["event"],
                incident["opened_at_ms"],
                incident["alerted_at_ms"],
                incident["acked_at_ms"],
                incident["reaction_ms"],
                1 if incident["escalated"] else 0,
                1 if incident["cascade"] else 0,
                incident["confidence_bps"],
                incident["clip_start_ms"],
                incident["clip_end_ms"],
                1 if incident["anonymised"] else 0,
                1 if incident["raw_stored"] else 0,
                incident["clip_status"],
                1 if incident["slowdown_sent"] else 0,
                incident["cause"],
            ),
        )
    count = connection.execute("select count(*) from incident").fetchone()[0]
    stored = connection.execute("select count(*) from incident where raw_stored = 0").fetchone()[0]
    connection.close()
    return count, stored


def _plant_with(frames, config=None, scrap=None):
    raw = fixture_config() if config is None else config
    loaded, error = load_config(raw)
    if error:
        return None, error
    return Plant(loaded, fixture_stations(), frames, scrap if scrap is not None else fixture_scrap()), None


def run_regression():
    failures = []

    def check(name, cond):
        if not cond:
            failures.append(name)

    plant = run_main()
    summary = plant.summary()
    digest = canonical_hash(summary)
    again = canonical_hash(plant.summary())
    check("hash_stable", digest == again)
    check("two_incidents", [row["id"] for row in summary["incidents"]] == ["INC-1", "INC-2"])
    first = summary["incidents"][0]
    second = summary["incidents"][1]
    check("curve_cascade", first["station_id"] == "ST-CURVE" and first["first_event"] == "tipped" and first["event"] == "fallen" and first["cascade"] is True)
    check("curve_reaction", first["reaction_ms"] == 18000 and first["escalated"] is False and first["acked_at_ms"] == 20000)
    check("curve_clip", first["clip_start_ms"] == 0 and first["clip_end_ms"] == 5500 and first["anonymised"] is True and first["raw_stored"] is False and first["clip_status"] == "stored")
    check("curve_confidence", first["confidence_bps"] == 9100)
    check("stack_jam", second["station_id"] == "ST-STACK" and second["event"] == "jam" and second["escalated"] is True and second["reaction_ms"] is None)
    check("stack_cause", second["cause"] == "stacker_timing" and second["slowdown_sent"] is False)
    check("no_load_incident", all(row["station_id"] != "ST-LOAD" for row in summary["incidents"]))
    check("one_watch", summary["watches"] == 1)
    check("unwatched_unload", summary["unwatched"] == ["ST-UNLOAD"])
    check("not_clear", summary["line_clear"] is False)
    check("scrap", summary["scrap_bps"] == 476)
    check("median", summary["median_reaction_ms"] == 18000 and summary["incidents_per_shift"] == 2)
    check("go", summary["go_no_go"] == "fail")
    check("zeros", summary["auto_slowdown_count"] == 0 and summary["auto_scrap_count"] == 0)
    texts = [row["text"] for row in summary["alerts"]]
    check(
        "alerts",
        texts
        == [
            "Gekipptes Glas an der Übergabekurve.",
            "Heruntergefallenes Glas an der Übergabekurve.",
            "Stau an dem Stapler.",
            "Nicht quittiert. Stau an dem Stapler.",
        ],
    )
    speakers = [row["speaker"] for row in summary["alerts"]]
    check("speakers", speakers == ["SPK-CURVE", "SPK-CURVE", "SPK-STACK", "SPK-LEAD"])
    check("gaps", summary["gaps"]["CAM-STACK"] == 2 and summary["gaps"]["CAM-UNLOAD"] == 0)
    count, stored = persist(summary)
    check("sql", count == 2 and stored == 2)
    kept = plant.accept_prose("INC-1 reaction 18000 stays on the note")
    check("prose_keeps_known_digit", kept["ok"] is True)
    dropped = plant.accept_prose("reaction 99999")
    check("prose_drops_new_digit", dropped["error"] == "digit_in_prose")
    model_ack = plant.acknowledge("INC-2", "FIXTURE Operator", "model", 52000)
    check("model_ack", model_ack["error"] == "prompt_ignored" and plant.incidents[1]["acked_at_ms"] is None)

    bad = dict(fixture_config())
    bad["scrap_cut_pct"] = 36
    check("blocked_key", load_config(bad)[1] == "copied_claim_refused")
    bad = dict(fixture_config())
    bad["company_name"] = "36.5%"
    check("blocked_text", load_config(bad)[1] == "copied_claim_refused")
    bad = dict(fixture_config())
    bad["works_council_signoff"] = "no"
    check("council", load_config(bad)[1] == "works_council_required")
    bad = dict(fixture_config())
    bad["detector"] = "anomaly_only"
    check("anomaly", load_config(bad)[1] == "class_required")
    bad = dict(fixture_config())
    bad["lines_in_scope"] = 4
    check("four_lines", load_config(bad)[1] == "scope_refused")
    bad = dict(fixture_config())
    bad["auto_slowdown"] = "yes"
    check("auto_slow", load_config(bad)[1] == "slowdown_locked")
    bad = dict(fixture_config())
    bad["operator_score"] = 1
    check("people_key", load_config(bad)[1] == "people_monitoring_refused")
    bad = dict(fixture_config())
    bad["mode"] = "live"
    check("live_fixture", load_config(bad)[1] == "example_row_in_live")
    bad = dict(fixture_config())
    bad["slowdown_enabled"] = "yes"
    bad["slowdown_tag"] = "LN1_SLOW"
    check("slow_without_sign", load_config(bad)[1] == "safety_signoff_required")
    bad = dict(fixture_config())
    bad["max_scrap_bps"] = "REPLACE"
    loaded, error = load_config(bad)
    check("threshold_config", error is None)
    if loaded:
        probe, _err = _plant_with([], loaded)
        check("threshold_unset", probe is not None and probe.go_no_go()["result"] == "threshold_unset")

    short = label_gate({"glass_upright": 30, "glass_tipped": 30, "glass_fallen": 30, "jam": 30}, 300, 40)
    check("labels_short", short == "labels_short")
    thin = label_gate({"glass_upright": 80, "glass_tipped": 80, "glass_fallen": 80, "jam": 10, "glass_broken": 50}, 300, 40)
    check("class_short", thin == "class_short")
    ready = label_gate({"glass_upright": 80, "glass_tipped": 80, "glass_fallen": 80, "jam": 80}, 300, 40)
    check("labels_ok", ready == "ok")

    plan = ffmpeg_plan("CAM-CURVE")
    check("ffmpeg", "tcp" in plan and "fps=2" in plan and "-an" in plan and "SECRET" in plan and plan[-1].startswith("spool/CAM-CURVE_"))
    check("url_secret", camera_url_ok("rtsp://user:pass@10.0.0.8/stream") == "credential_in_url")
    check("url_ok", camera_url_ok("rtsp://10.0.0.8/stream") == "ok")

    unknown = Plant(fixture_config(), fixture_stations(), [], fixture_scrap())
    check("camera", unknown.ingest({"camera_id": "CAM-NOPE", "t_ms": 0, "detections": []})["error"] == "camera_unknown")
    stations = fixture_stations()
    stations["ST-OTHER"] = {
        "line_id": "LN-2",
        "kind": "transfer_curve",
        "spoken_name": "der anderen Linie",
        "camera_id": "CAM-OTHER",
        "speaker": "SPK-OTHER",
    }
    scoped = Plant(fixture_config(), stations, [], fixture_scrap())
    check("line_scope", scoped.ingest({"camera_id": "CAM-OTHER", "t_ms": 0, "detections": [{"class": "jam", "confidence_bps": 9000}]})["error"] == "line_out_of_scope")

    early = []
    for offset in (0, 500):
        early.append({"camera_id": "CAM-CURVE", "t_ms": offset, "detections": [{"class": "glass_tipped", "confidence_bps": 9000}]})
    early_plant, _err = _plant_with(early)
    check("two_frames", early_plant is not None and early_plant.incidents == [])
    weak = [{"camera_id": "CAM-CURVE", "t_ms": 0, "detections": [{"class": "glass_tipped", "confidence_bps": 6999}]}]
    weak_plant, _err = _plant_with(weak)
    check("below_floor", weak_plant is not None and weak_plant.incidents == [] and len(weak_plant.watches) == 1)
    exact = []
    for index in range(3):
        exact.append({"camera_id": "CAM-CURVE", "t_ms": index * 500, "detections": [{"class": "glass_tipped", "confidence_bps": 7000}]})
    exact_plant, _err = _plant_with(exact)
    check("floor_opens", exact_plant is not None and len(exact_plant.incidents) == 1)
    silent_cfg = dict(fixture_config())
    silent_cfg["alerts_enabled"] = "no"
    silent_plant, _err = _plant_with(exact, silent_cfg)
    check("shadow_silent", silent_plant is not None and silent_plant.alerts == [] and silent_plant.incidents[0].get("alert_suppressed") is True)

    broken = []
    for t in (0, 500, 1000, 2600, 3100, 3600, 4100):
        broken.append({"camera_id": "CAM-STACK", "t_ms": t, "detections": [{"class": "jam", "confidence_bps": 9000}]})
    broken_plant, _err = _plant_with(broken)
    check("gap_resets", broken_plant is not None and broken_plant.incidents == [] and broken_plant.gaps["CAM-STACK"] == 1)
    four = []
    for index in range(4):
        four.append({"camera_id": "CAM-STACK", "t_ms": index * 500, "detections": [{"class": "jam", "confidence_bps": 9000}]})
    four_plant, _err = _plant_with(four)
    check("four_jams", four_plant is not None and four_plant.incidents == [])
    blur_off = dict(fixture_config())
    blur_off["blur_enabled"] = "no"
    blur_frames = [
        {"camera_id": "CAM-CURVE", "t_ms": 0, "detections": [{"class": "glass_tipped", "confidence_bps": 9000}, {"class": "person", "confidence_bps": 8000}]},
        {"camera_id": "CAM-CURVE", "t_ms": 500, "detections": [{"class": "glass_tipped", "confidence_bps": 9000}]},
        {"camera_id": "CAM-CURVE", "t_ms": 1000, "detections": [{"class": "glass_tipped", "confidence_bps": 9000}]},
    ]
    blur_plant, _err = _plant_with(blur_frames, blur_off)
    blur_clip = blur_plant.summary()["incidents"][0]
    check("held_for_blur", blur_clip["clip_status"] == "held_for_blur" and blur_clip["raw_stored"] is False and blur_clip["anonymised"] is False)

    pass_frames = [
        {"camera_id": "CAM-CURVE", "t_ms": 0, "detections": [{"class": "glass_tipped", "confidence_bps": 8000}]},
        {"camera_id": "CAM-CURVE", "t_ms": 500, "detections": [{"class": "glass_tipped", "confidence_bps": 8000}]},
        {"camera_id": "CAM-CURVE", "t_ms": 1000, "detections": [{"class": "glass_tipped", "confidence_bps": 8000}]},
        {"camera_id": "CAM-CURVE", "t_ms": 8000, "detections": [{"class": "glass_upright", "confidence_bps": 9000}]},
        {"camera_id": "CAM-STACK", "t_ms": 8000, "detections": [{"class": "glass_upright", "confidence_bps": 9000}]},
        {"camera_id": "CAM-LOAD", "t_ms": 8000, "detections": [{"class": "glass_upright", "confidence_bps": 9000}]},
        {"camera_id": "CAM-UNLOAD", "t_ms": 8000, "detections": [{"class": "glass_upright", "confidence_bps": 9000}]},
    ]
    pass_plant, _err = _plant_with(pass_frames)
    check("upright_does_not_clear", pass_plant.incidents[0]["acked_at_ms"] is None)
    pass_plant.acknowledge("INC-1", "FIXTURE Operator", "form", 5000)
    pass_plant.escalate(8000)
    passed = pass_plant.go_no_go()
    check("go_pass", passed["result"] == "pass" and pass_plant.summary()["line_clear"] is True)

    signed = dict(fixture_config())
    signed["plc_safety_signoff"] = "yes"
    signed["slowdown_enabled"] = "yes"
    signed["slowdown_tag"] = "LN1_SLOW"
    signed_plant, error = _plant_with(fixture_frames(), signed)
    check("signed_loads", error is None and signed_plant is not None)
    if signed_plant:
        signed_plant.acknowledge("INC-1", "FIXTURE Operator", "form", 20000)
        signed_plant.escalate(51000)
        model = signed_plant.request_slowdown("INC-2", "FIXTURE Safety", "model")
        leader = signed_plant.request_slowdown("INC-2", "FIXTURE Leader", "form")
        safety = signed_plant.request_slowdown("INC-2", "FIXTURE Safety", "form")
        check("slow_model", model["error"] == "prompt_ignored")
        check("slow_leader", leader["error"] == "actor_refused")
        check("slow_safety", safety["ok"] is True and safety["tag"] == "LN1_SLOW")
        check("still_not_auto", signed_plant.auto_slowdown_count == 0)
        second_row = signed_plant.incidents[1]
        check("signal_once", second_row["slowdown_sent"] is True)

    camera_scrap, error = scrap_bps({"line_id": "LN-1", "good_pieces": 1, "scrap_pieces": 1, "source": "camera"})
    check("camera_scrap", camera_scrap is None and error == "scrap_source_refused")
    check("prompt", "do not name a person" in SYSTEM_PROMPT and "36.5%" not in SYSTEM_PROMPT)
    check("en_copy", alert_text("en", "open", "tipped", "transfer curve 2") == "Tipped glass at transfer curve 2.")
    check("hash_locked", digest == EXPECTED_HASH)
    return failures, digest, summary


if __name__ == "__main__":
    failures, digest, _summary = run_regression()
    print({"failures": failures, "hash": digest})
```

---

## 15. Failure modes

- **A one-frame flicker.** Two tipped frames, or four jam frames, open nothing. The speaker stays quiet. Do not lower the debounce because a manager saw a glass move. Change it in the config, in writing, and re-run the tests. The fixture numbers are the lock, not the plant's only legal values. The plant's values have to pass the same tests against their own labelled clips.
- **A dropout that glues two streaks together.** A gap over `frame_gap_ms` resets the count. The test with jam frames at 0, 500, 1000 and then 2600 does not open an incident. Adding the counts across the hole would.
- **A detector that only says "odd".** `anomaly_only` does not load. Put a class on the row or do not speak.
- **A calm picture used as a clear.** Upright frames leave the incident open. The pass-case in the tests checks `acked_at_ms` is still null after the belt looks normal. The operator's button is the clear.
- **A stale unloading camera hidden by a green board.** The fixture's `go_no_go` is `fail` because `ST-UNLOAD` has no frames. Deleting the station from the registry is not a repair. Aim the camera, or record that the station is out of the line and remove it in a change a person signs.
- **Alert fatigue.** A box under `min_confidence_bps` is a watch. The loading camera's 4000 does not speak. If the watch list is still a flood, the plant raises the floor after looking at the labelled set. The agent does not raise it to empty the list.
- **A person in the clip and blur switched off.** `held_for_blur`. The incident exists. The JPEG does not go into the record. Turn blur on, or accept that this incident has no clip. Do not store the raw frame "just until blur is ready."
- **A root cause that names the operator.** `people_monitoring_refused`. The cause stays where it was. The weekly group still shows the station and the event. The sentence about who to blame does not get a column.
- **A helpful slowdown.** Without the sign-off, `safety_signoff_required`. With the sign-off, the line leader is still `actor_refused`. The safety owner sends one tag. `auto_slowdown_count` stays 0 even on that signed call, because the call was a person and not a timer.
- **A copied scoreboard.** `36.5%` in a config value, or a key named `scrap_cut_pct`, is `copied_claim_refused`. The file does not start.

A wrong label on the training clips is the plant's set. Version 1 does not "correct" a class. If the speakers fire on upright glass, the fix is the labelled set and the confidence floor, then a shadow week. It is not a prompt that says "be stricter."

---

## 16. Privacy, the works council, and permissions

- `works_council_signoff` is `yes` or the program does not load. For a German plant that has a Betriebsrat, that yes means the conversation has happened and a named person has recorded it. For a plant with no works council, the same key means the employee representatives the plant actually has, or the owner, have been told in writing that the cameras watch the glass. This file does not decide which body the law requires. It refuses to be the project that skips the conversation. Grupp's line, that the AI watches the process and not the people, is the reason the key exists. The case does not publish the form he used.
- The camera audio is dropped (`-an`). The outbound speaker plays a fixed sentence. It does not play a clip of the hall.
- Person and face boxes are not events. They blur, or they hold the clip. There is no operator id on the incident. There is no score of who was standing nearest.
- Retention is `retention_days`. Suggested starting point: 30 days, then delete the JPEGs and keep the incident row. The plant's own rule wins if it is shorter. Do not put the spool on a public URL.
- Roles on the live page: the operator sees their station and the acknowledge button. The line leader sees the line, the handover, and the cause list. The safety owner sees the slowdown control, and only when the sign-off keys are yes. The model sees tool results. It does not see the RTSP URL, the database URL, or the PLC credential.
- The database role has insert on incident, alert, and audit, and no update and no delete on incident or audit. Credentials do not go in this file. `load_config` refuses a key named like a secret, and `camera_url_ok` refuses a URL that already contains one.

---

## 17. Pilot, in weeks

This calendar is our design. Glass International and Grupp describe a pilot on one line, then all four lines at Weißwasser. Cerrion's page describes the four-line deployment and a later decision to go to the group's factories, with more use cases at the Polish plant, and says the line improved within weeks. None of those pages publishes this plan. Do not read the strip as theirs.

| Weeks | What happens | What stays off |
| --- | --- | --- |
| 1 to 2 | The works-council conversation, or the equivalent, is recorded. Map every curve, stacker, loading point, and unloading point on one line. Write the three KPI definitions in section 18. Export four weeks of scrap from the plant counter, for that line only | No RTSP in the agent. No speaker. `works_council_signoff` stays the gate |
| 3 to 4 | Connect the existing cameras. Confirm the spool is 2 fps and `-an` is on. Label at least 300 clips, 40 of each required class. Shadow: `alerts_enabled` `no`. Read the incidents the rules would have opened | No speaker. No slowdown. The second line stays on its old routine |
| 5 to 6 | Speakers on that one line, station by station, in the operator's language. Escalation uses the N the plant typed in week 1. A person acknowledges. The shift note is the code note | `auto_slowdown` stays `no`. `plc_safety_signoff` stays `no` unless a separate safety review has already signed |
| 7 to 8 | The weekly list. The line leader assigns causes from the closed list. `go_no_go` reads the thresholds typed before week 1 ended, against the weeks you just ran | A pass lets the plant plan a second line. It does not set `lines_in_scope` to 4, and it does not copy 36.5% |

First value, in this file, is a speaker that names the right station on a fault the labelled set already contains, and a reaction time that has an acknowledge on it. It is not a promise that the vendor's weeks, or the vendor's percent, will repeat.

---

## 18. KPIs and the baseline you measure yourself

Before the first speaker, 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.

**Scrap per line.** Scrap pieces times 10,000, integer-divided by good pieces plus scrap pieces, from the plant counter, for that line, for the same window you will compare later. The fixture is 40 and 800, which is 476 basis points. Say what the plant already counts as scrap, including stressed glass the camera cannot see, before you export. A camera count is `scrap_source_refused`. Do not type 36.5 into the numerator to see the number you already read.

**Reaction time.** Milliseconds from the first alert on the incident to the acknowledge. The median is the lower middle when the count is even: sort, then take the index `(n - 1) // 2`. The fixture has one sample, 18000. A missing acknowledge is left out of the median, and a shift that opened incidents and acknowledged none is `reaction_empty` on the go/no-go. It is not a median of zero.

**Incidents per shift.** The count of incidents the rules opened. Watches are not incidents. An upgrade is not a second incident. The fixture is 2. Escalations are a flag on the row, not an extra incident.

**Unwatched stations.** The list `unwatched` returns. A line with one blind station is not clear, and `go_no_go` fails. This is a health measure. It is not a scrap measure.

**What stays at zero.** Automatic slowdowns. Scrap rows whose source is the camera. Causes the model assigned. Sentences that introduced a digit the code note did not already contain. `auto_slowdown_count` and `auto_scrap_count` are those first two, and both are 0 on the fixture.

**Go/no-go.** `go_no_go` reads `max_median_reaction_ms`, `max_incidents_per_shift`, and `max_scrap_bps`. A blank or `REPLACE` returns `threshold_unset`. It does not pass. It does not fill 36.5. The fixture ceilings, 30000 and 5 and 800, are our test. They fail the main run only because unloading is blind. They pass the smaller all-cameras run. Replace them with what this plant is willing to miss, typed before week 1 ends. A pass is permission to plan the next line. It is not permission to write the PLC, and it is not permission to claim the case's percent.

---

## 19. Acceptance tests

`run_regression` is the test. It has to pass before a speaker is wired, and again before a second line is planned. The locks:

- `load_config` accepts the fixture and refuses a copied-claim key, a value containing `36.5%`, `works_council_signoff` no, `anomaly_only`, `lines_in_scope` 4, `auto_slowdown` yes, an `operator_score` key, a live config that still says `FIXTURE`, and `slowdown_enabled` yes with a tag but no PLC sign-off.
- A `REPLACE` go/no-go ceiling loads, and `go_no_go` returns `threshold_unset`.
- `label_gate` is `labels_short` on 120 clips, `class_short` when jam is 10 and the total is over 300, and `ok` on 80 of each required class.
- The ffmpeg plan contains `tcp`, `fps=2`, `-an`, and `SECRET`, and the spool path starts with `spool/CAM-CURVE_`. A URL with `user:pass@` is `credential_in_url`. A URL without credentials is `ok`.
- An unknown camera is `camera_unknown`. A camera on `LN-2` is `line_out_of_scope`.
- Two tipped frames open nothing. A tipped box at 6999 is a watch and not an incident. Three frames at 7000 open one incident.
- `alerts_enabled` no writes the incident and writes no alert.
- A jam streak broken by a gap over 1500 ms does not open. Four consecutive jam frames do not open.
- The main run has `INC-1` and `INC-2` only. `INC-1` is the curve, first event tipped, final event fallen, cascade true, reaction 18000, acknowledged at 20000, not escalated, clip 0 to 5500, anonymised, raw not stored, status stored, confidence 9100.
- `INC-2` is the stacker, event jam, escalated, reaction null, cause `stacker_timing`, slowdown not sent, confidence 8000.
- No incident on loading. Watches equal 1. Unwatched is `ST-UNLOAD` only. `line_clear` is false. Scrap basis points are 476. Median reaction is 18000. Incidents per shift are 2. `go_no_go` is `fail`. Both automatic counts are 0.
- The four alert sentences and the four speakers are the list in section 10. Stack gaps are 2. Unload gaps are 0.
- SQLite holds 2 incidents, both with `raw_stored` 0.
- Prose that repeats 18000 is kept. Prose that introduces 99999 is `digit_in_prose`. The 36.5% sentence is refused in `run_main` before the summary is hashed.
- A model acknowledge of `INC-2` is `prompt_ignored` and the incident stays open.
- Blur off, with a person in the opening frame, is `held_for_blur`, not anonymised, and not raw.
- The all-fresh run does not clear on the upright frame. After the acknowledge it passes `go_no_go`, and `line_clear` is true.
- On a signed config, the model is `prompt_ignored`, the line leader is `actor_refused`, and the safety owner sends `LN1_SLOW` once. `auto_slowdown_count` stays 0.
- Camera-sourced scrap is `scrap_source_refused`. The system prompt contains `do not name a person` and does not contain `36.5%`. The English tip sentence is `Tipped glass at transfer curve 2.`
- The hash of the summary is `fd9ac266c6b756df9139b1cea24dbadb5a5c271be505d2d5a65382589d2404d8`, twice, because a second run on the same rows must match.

---

## 20. What you do not claim

- Do not say this plant will cut scrap by 36.5%, or reaction time by 36.5%, or that supervision will be 24/7, or that the line will move within weeks. Those sentences are Stölzle Lausitz's published result, as Cerrion, Glass International, and Grupp's interview state it. None of them is a field in section 18.
- Do not say the columns, the 7000, the three frames, the five frames, the 45 seconds, the 476, the German sentences, the hash, or the tests are Stölzle or Cerrion settings. They are not published. They are our design. `INC-2` is a fixture. It is not a Weißwasser jam. `stacker_timing` is the cause the test assigns. It is not their root cause.
- Do not say version 1 is already on their PLC, or that a slowdown was sent, or that the camera counted the scrap. The case describes cameras, alarms, and a record. This file reads detection rows and a counter export. `auto_slowdown` and `auto_scrap` stay `no`.
- Do not say the pilot was four lines and one line at the same time. Grupp and Glass International describe one line, then four. Cerrion's page describes the four-line result and the group decision. Quote the page you are looking at. Do not average them into a fifth number.
- Do not name a model, a prompt from Cerrion, or a Cerrion screen. None of that is public. `SYSTEM_PROMPT` and the templates are ours.
- Do not say a watch was close enough to speak. Close enough is the floor. Under it, the row is a watch.
- Do not say `unassigned` means the cause was unknown. It means nobody has picked a code. `unknown` is a code a person picks.
- Do not say a signed go/no-go is permission to slow the line, or permission to add three lines inside this file. Section 17 keeps `auto_slowdown` off and `lines_in_scope` at 1. 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 shift note 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 phrasing model sees a finished incident and `SYSTEM_PROMPT`. It does not see an RTSP URL, and it does not see a detection row as instructions.

```text
You are building the line-watch tool specified in line-watch-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, ffmpeg for RTSP, a spool directory for JPEG stills. The functions and the refusals match section 14. Times are integer milliseconds from run_clock. Confidence is integer basis points. Scrap basis points are scrap_pieces * 10000 // (good_pieces + scrap_pieces), and only when source is plant_counter. Do not emit a percent.

Put the rules in pure functions and in Plant. Call them from a thin runner and from the tests. Do not reimplement a gate in the speaker service 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, except the three go/no-go ceilings, which stay threshold_unset until the plant types them. If auto_slowdown or auto_scrap is not no, refuse to start. If require_human_ack is not yes, refuse to start. If works_council_signoff is not yes, refuse to start. If lines_in_scope is not 1, refuse to start. If a password, api_key, secret, or token is present, refuse to start. If a people-score key is present, refuse to start. If a case-study key from section 2 is present, or a value contains 36.5%, 36,5%, 24/7, or "within weeks", refuse to start. If detector is anomaly_only, refuse to start. If mode is live and the config still contains EXAMPLE or FIXTURE, refuse to start. If slowdown_enabled is yes without the PLC sign-off and a tag, refuse to start.

There is no tool that slows the line from a timer. A model call to acknowledge, assign_cause, or request_slowdown is prompt_ignored. Never set raw_stored true. Never store a clip that contains a person unless blur has run. Never count a camera as the scrap source. Never open an incident below the debounce. Never debounce across a gap. Never open a second incident on a station that already has one open. Never clear an incident because the next frame is upright. Never speak on a broadcast id. Never assign a cause that names a person. Never let the line leader send the slowdown. Never brief a new digit in a model note. Never emit 36.5%, 24/7, or "within weeks" as a result for this plant.

The fixture in section 13 must produce hash fd9ac266c6b756df9139b1cea24dbadb5a5c271be505d2d5a65382589d2404d8. INC-1 is fallen, cascade from tipped, reaction 18000, anonymised. INC-2 is jam, escalated, reaction null, slowdown not sent. The loading camera is a watch. ST-UNLOAD is unwatched. Scrap is 476, not a percent. The four German sentences match section 10. auto_slowdown_count and auto_scrap_count stay 0. Section 19 must pass before a speaker is wired, and before a file is treated as an incident the plant has already cleared.
```
