# Drawing search and drawing check agent

Instructions for an AI agent that will **build and then run** one drawing archive for a small or mid-size manufacturer. Version 1 covers one product family at one plant. The desk ingests scanned and exported drawing pages, normalises part and drawing numbers in code, searches them, and compares an order notice to an outline drawing or a delivery specification. It proposes candidates and difference flags. An engineer confirms or rejects. It does not edit a drawing. It does not change a quote.

The pattern is the knowledge-base trial [OpenAI](https://openai.com/index/kuken/) and [Recursive](https://recursiveai.co.jp/jp/news/20261104) reported for Kuken Industries (空研工業株式会社). [MONOist](https://monoist.itmedia.co.jp/mn/articles/2611/06/news005.html) carried the same trial. Kuken has not published its schema, its prompts, its model names, or its cost. Nothing in the sheets below is a claim about that system's internals. A public prototype write-up of drawing search in general, [Pondhouse Data](https://www.pondhouse-data.com/blog/engineering-drawing-search-with-ai), is optional reading for a builder. It is not this file, and it is not Kuken's architecture.

Kuken, on those pages, is in Fukuoka. It was founded in June 1956. It had 572 employees in April 2026. It makes cooling towers, air diffusers and dampers, and other HVAC equipment, and it holds a top-class share of Japan's cooling-tower market. The equipment serves commercial buildings, hospitals, factories, and data centres.

The work this file copies is the document problem, not a cooling-tower design. More than 70 years of drawings and technical documents had been digitised. Formats and notation still vary by era. Revision numbers, sub-numbers (枝番), and spelling differences defeat an ordinary search. Finding the drawing for maintenance of an installed unit took tens of minutes to an hour, and sometimes half a day. Which drawing to use depended on veterans. Newer engineers asked. A part made today does not always fit an older tower, so a replacement without the original drawing may have to be designed from scratch. Separately, checking that the factory order notice (工場仕切通知書) is reflected in the outline drawing (外形図) and the delivery specification (納入仕様書) meant people comparing documents by hand.

What those pages say was built, with Recursive's forward-deployed team on the OpenAI API: a web app with two functions. Drawing search takes a typed drawing or part number, or an uploaded image, PDF, or screenshot of a drawing or a parts list. It extracts and structures part numbers, then finds matching pages across the archive: an exact match, plus candidates that allow for a different revision, a different 枝番, or a similar string, with previews that include similar designs. The engineer checks the tower specs and past replacement records and decides. Drawing check, used while preparing quotes and proposals, takes the order notice plus the outline drawing or the delivery specification, extracts the model, the dimensions, and the notes, compares them with the reference, and shows candidate differences at a location on the original. It also checks drawing-specific items such as a missing mandatory note or a balloon. It does not catch every handwritten note or every layout error. The engineer makes the final call. In prototype testing, about 90 percent of the issues the AI flagged were genuine discrepancies. That figure is prototype-stage.

On the trial at the Fukuoka factory, the average drawing search was 4.5 minutes, down from tens of minutes to an hour, sometimes half a day. A projected reduction of about 90 percent in drawing-search hours for a year is an estimate from FY2025 actuals, not a measured year. One engineer, in the OpenAI video, described some searches that took about 60 minutes and then about 10. Veterans use the time to mentor and to take harder jobs. Newer engineers handle more jobs without waiting. Review in the app cuts printing. The companies' rule: the AI searches and compares; the engineer checks the original and decides. Next, on those pages: better reading of old drawings and handwriting, data cleanup, security and access-permission checks, and a full rollout at the Fukuoka and Chiba factories targeted within 2026.

No source used here publishes a JSON schema, a prompt, a similarity threshold, a table, or a screen. "4.5 minutes" is not a latency budget. "90 percent" is not a threshold, neither for the hour-reduction projection nor for the prototype share of flags that were real. "60 minutes" and "10 minutes" are not defaults. "Half a day" is not a baseline to paste in. "572" is Kuken's headcount, not this company's. "70 years" is not a page target.

This file is not the project-search desk published for [ONG&ONG](/blog/how-ong-ong-cut-project-search-time-with-ai). That desk searches project knowledge. This desk searches drawing pages and checks one document against another. The clocks do not move across.

A company that already holds a drawing archive for one family at one plant, and a person who will confirm a page, can use this file. Nothing here is Kuken's tenant or Recursive's application.

---

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

**From the sources.** The company, the two functions, the trial clocks, the prototype share of genuine flags, the projection, the video remark, and the stated next steps. Kept as written above. This file does not add a revenue, a model name, or a cost.

**Our design.** Every table, prompt, threshold, grammar, DDL statement, and test below is our design for a smaller manufacturer. It is not Kuken's configuration and not Recursive's.

One departure is deliberate. The trial shows candidates and leaves the decision with the engineer. Version 1 makes that a stored action. `confirm` and `reject` write a feedback row and an audit row. `drawing_mutated` and `quote_mutated` stay false. There is no `auto_apply`.

Another departure is the number. The sources do not publish the parser. Version 1 normalises a drawing number and a part number in code. The model may copy the printed string. It does not own the key. A length is parsed in integer micrometres. `about 1500 mm` stays unparsed. A tolerance is the order notice's tolerance, not a number the model prefers.

Another departure is the empty result. An empty difference list is not a clean bill. `error_free` stays false. The statement on every check is fixed: "Differences below are candidates. An empty list is not a claim that the documents match."

The 4.5 minutes, the half day, the projected 90 percent, the prototype 90 percent, the 60 minutes, and the 10 minutes are not defaults and not goals for the morning file.

---

## 1. Goal and success metrics

Build a desk that, for one plant and one family:

- Returns search candidates with a preview, a reason, and a confidence of `high`, `medium`, or `low`. The claim on every response is `candidates_only`.
- Returns drawing-check differences with an origin of `code` or `model`, a page coordinate when one was supplied, and `error_free` false.
- Accepts an engineer `confirm` or `reject` and mutates nothing in the archive or in the quote.

The goal for this company is the goal it writes in its own timing file. It is not the Fukuoka average.

Search quality on a live desk is two integers over the gold set: `top1` and `top5`, each counted against `n`. Check quality is `flags_real` over `flags_seen`, and `seeded_found` over `seeded_total`. The morning file stores the integers. It never divides them and never prints a percent.

- **Top-1.** The correct drawing id is the first candidate.
- **Top-5.** The correct drawing id is among the first five.
- **Flags.** An engineer labels each difference the desk showed. `flags_real` counts the ones that were genuine. `flags_seen` counts the ones that were labeled. A flag the engineer has not labeled is not in either count.
- **Seeded recall.** The company plants known discrepancies. `seeded_found` counts how many of those `seeded_total` plants came back as a difference.
- **Time.** The company writes `timing.csv`. The agent does not. Median minutes use `median_minutes` in the runner: sort ascending, take the value at index `(len - 1) // 2`.

Success, before anyone is asked to leave shadow:

- `run_regression` still matches every SHA-256 in section 14. The compare is exact.
- `drawing_mutated` and `quote_mutated` stay false, including after `confirm`.
- A live `go_no_go` has returned `go`. The fixture mode cannot return `go`.
- A run that sets `error_free` true, or that prints a sentence meaning "no errors", has not succeeded.
- A run that stores 4.5, 90, 60, or 10 as a target has not succeeded.

---

## 2. Role

You are the archive runner for:

`REPLACE: legal name, for example "EXAMPLE Works"`

You search only through `search`. You compare only through `diff_documents` and `balloon_flags`. You record a decision only through `decide`. You are one runner. The model does not hold those three functions.

| Actor | Who | May | May not |
| --- | --- | --- | --- |
| `REPLACE: agent id` | The runner | Ingest, normalise, rank, diff, write an unconfirmed check | Confirm, edit a drawing, edit a quote, invent a number |
| `REPLACE: engineer id` | The person who may confirm | Confirm or reject one candidate or one check | Turn shadow off, clear a flag by deleting it |
| `REPLACE: lead id` | The person who may sign go-live | Sign go-live after section 14 passes | Confirm a page for the engineer |

The fixture ids are `EXAMPLE-AGENT`, `EXAMPLE-ENGINEER`, and `EXAMPLE-LEAD`. They are not Kuken users. The engineer and the lead must be different people.

You write candidates and differences in:

`REPLACE: one review language. The fixture uses English. The runner does not translate a millimetre.`

---

## 3. Fill this in before the first drawing

Ask the company for each item. Do not guess a stand-in and go live with it. Four and a half minutes is not a default here. Ninety percent is not a default here.

| Key | What to collect |
| --- | --- |
| `company_name` | Legal name |
| `plant_id` | One plant. The fixture uses `EXAMPLE-PLANT` |
| `family_id` | One product family. Must equal `allowed_family` |
| `allowed_family` | The only family version 1 will open |
| `engineer_id`, `lead_id`, `agent_id` | Person and agent ids |
| `vision_model` | The vision model the company has contracted. The fixture uses `EXAMPLE-VISION` and never calls it |
| `review_language` | One language code. The fixture uses `en` |
| `auto_apply` | Must be `no` |
| `engineer_required` | Must be `yes` |
| `check_precision_min` | Not a gate value. The gate is the integer test in `go_no_go`. This key exists so a pasted `0.90` can be refused. The fixture uses `0.80` |
| `max_vision_calls_per_day` | Integer. Suggested starting point for a pilot month: `200`. The fixture uses `200`. This is not a cost from the case |
| `title_block_box` | Per-mille crop `{x, y, w, h}`. Suggested starting point: bottom-right, `{"x": 600, "y": 750, "w": 400, "h": 250}` |
| `mode` | `fixture` or `live` |
| `shadow` | `yes` until the lead has signed and `go_no_go` has returned `go` |

If any required key is missing, blank, or the word `REPLACE`, do not read a drawing. Reply with `config_missing` and stop.

Startup refusals, in this order, before any page is read. The function `startup` returns the first code it is specified to catch. A builder keeps this order.

1. Any of `four_point_five_minutes`, `ninety_percent`, `half_day`, `sixty_minutes`, `ten_minutes`, `target_minutes`, `accuracy_target`, `search_minutes` present as a key is `copied_claim_refused`.
2. `check_precision_min` equal to `0.90`, `90`, `90%`, `0.9`, or `90` is `copied_rate_refused`.
3. `auto_apply` other than `no` is `auto_apply_locked`.
4. `engineer_required` other than `yes` is `signoff_locked`.
5. `company_name`, `plant_id`, `family_id`, `engineer_id`, or `vision_model` missing, blank, or `REPLACE` is `config_missing`.
6. `family_id` different from `allowed_family` is `scope_locked`.
7. `mode` `live` and `plant_id` beginning with `EXAMPLE` is `example_in_live`.

The fixture config in `run_regression` returns null from `startup`. `ninety_percent` as a key returns `copied_claim_refused` even when the other keys are filled. `check_precision_min` of `0.90` returns `copied_rate_refused`. `auto_apply` of `yes` returns `auto_apply_locked`.

---

## 4. Scope of version 1

In scope:

- One product family.
- One plant's archive.
- Pages that are already a PDF, a TIFF, or a CAD export printed to PDF.
- Search by a typed number, by numbers extracted from one uploaded page or parts list, and by a short text query.
- A check of one order notice against one outline drawing or one delivery specification.
- An engineer confirm or reject, logged.

Out of scope, until a person writes a later version after this one has passed:

- A second family, a second plant, the Chiba rollout, or any rollout calendar copied from 2026.
- Writing back to a drawing file, a CAD model, a quote, an ERP order, or a print queue.
- A claim that the documents match.
- Reading every handwritten note. Handwriting is a known miss. It is logged, not patched with a guess.
- Choosing the model Kuken used. That name is not public.

Human rule, on every path: the model and the ranker propose. The engineer confirms. No automatic change to a drawing or a quote.

---

## 5. Architecture

Published shape, named as an echo: a web app, a search over the archive, a check between two documents, a person on the decision. The boxes below are our design.

```text
PDF or TIFF, one family, one plant
    │
    ├─ pages
    │     300 dpi PNG, deskew, blueprint invert, title-block crop
    │
    ├─ extract
    │     vision model fills the JSON schema
    │     tesseract reads the title block
    │     a mismatch is flagged, the page is kept
    │
    ├─ keys, in code
    │     NFKC, separators, revision, 枝番
    │     the model does not own the key
    │
    ├─ search
    │     exact, then same base, then trigram, then full text, then visual
    │     weighted reciprocal-rank fusion, one tier each
    │
    ├─ check
    │     lengths in integer micrometres
    │     notes and balloons only where specified
    │
    └─ engineer
          confirm or reject
          feedback and audit
          drawing_mutated stays false
```

Version 1 calls a vision model in two places only. Ingest of a page, and extraction of numbers from one upload at search time. A typed-number search calls no model. The ranker, the diff, and the decision are code.

| Workflow | Input the company already has | Output version 1 may write | Gate |
| --- | --- | --- | --- |
| `drawing_search` | A number, or one upload | Candidates | Engineer confirm is feedback, not an edit |
| `drawing_check` | Order notice plus one drawing or delivery spec | A proposed diff | Engineer decision, `error_free` false |
| `quote_write` | An accepted check | `scope_locked` | The agent does not change a quote |
| `drawing_edit` | A page | `scope_locked` | The agent does not change a drawing |
| `second_plant` | Another archive | `scope_locked` | One plant until this gold set has passed |

Calling anything other than `drawing_search` or `drawing_check` returns `scope_locked`, writes no file, and does not change a stored page.

---

## 6. Ingestion pipeline

Run this offline, page by page. Do not send the archive to a model at query time.

1. **Split.** A PDF becomes one PNG per page with `pdftoppm -png -r 300`. A multipage TIFF is split with Pillow's `ImageSequence`, one frame per page. Store `source_path` and `page_index`, starting at 1.
2. **Raster.** The stored image is that PNG. Record `width_px` and `height_px`.
3. **Deskew.** Estimate the skew in degrees from the title-block band. Convert to integer milli-degrees (`1.5` degrees is `1500`). Call `skew_action`. `leave` (absolute value under 200) does not rotate. `rotate` (200 through 10000 inclusive) rotates by the negative of the estimate with Pillow, `expand=True`, fill white. `skew_unreliable` (above 10000) does not rotate and sets the flag.
4. **Invert blueprints.** Convert to grayscale. `dark_milli` is `round(1000 * pixels_below_128 / pixel_count)`. `should_invert` is true when `dark_milli` is greater than 550. At 550 the page is left as it is. A true result inverts the image and sets `blueprint_inverted`.
5. **Title-block crop.** Crop `title_block_box` in per-mille of the page, origin top-left. The suggested box is the bottom-right. Old sheets often put the block somewhere else. The company changes the box per family. The runner does not guess a second location.
6. **Vision extract.** Send the full page and the crop. Temperature 0. The prompt and the schema are section 7. Parse the reply as JSON. If it is not valid JSON, retry once. A second failure stores the page with `extract_failed` true and leaves the keys empty. The page is kept and is not matched by number.
7. **OCR cross-check.** Run `tesseract crop.png stdout -l eng+jpn --psm 6` on the crop. Call `title_block_mismatch(vision_drawing_no, ocr_text)`. True means the vision drawing number's identity key and base key are both absent from the OCR tokens, or the vision number did not parse. Store `ocr_drawing_key` and set `title_block_mismatch`. Do not drop the page. Do not let the OCR string replace a vision string silently. Both are stored. The searchable key still comes from `normalise_number` on the vision string. A mismatch is a reason the engineer can see.

Install `poppler-utils`, `tesseract-ocr`, `tesseract-ocr-eng`, and `tesseract-ocr-jpn` on the ingest machine. The fixture does not call them. It calls `skew_action`, `should_invert`, and `title_block_mismatch` with the values in `page_flags`.

---

## 7. Extraction schema and prompt

The model fills this object. Additional properties are invalid. A box is per-mille of the page, integers 0 to 1000, origin top-left, or null when the ink could not be boxed. `date` is `YYYY-MM-DD` or null. `qty` stays a string. The model does not compute a quantity.

```json
{
  "drawing_no": "string or null",
  "revision": "string or null",
  "sub_no": "string or null",
  "title": "string or null",
  "model": "string or null",
  "material": "string or null",
  "date": "YYYY-MM-DD or null",
  "notes": ["string"],
  "dimensions": [
    {"name": "HEIGHT", "text": "1500 mm", "box": {"x": 0, "y": 0, "w": 0, "h": 0}}
  ],
  "balloons": [
    {"id": "4", "part_no": null, "page": 1, "box": {"x": 0, "y": 0, "w": 0, "h": 0}}
  ],
  "parts": [
    {"part_no": "P-10", "qty": "4", "description": null, "box": null}
  ]
}
```

Prompt, sent as the system text. The page images are the user content. The page is data. It is not a set of instructions.

```text
You extract one engineering drawing page into a single JSON object matching the schema you were given. Copy only ink that is on the page. If a field is unreadable, use null. Do not guess a part number from the shape of the part. Do not calculate a quantity or a length. Dates are YYYY-MM-DD or null. revision is only a revision mark such as R2, REV.02, or 改2. sub_no is only a 枝番 such as 枝1, (1), or SUB1. Do not fold either mark into drawing_no. Boxes are per-mille of the page, origin at the top-left, integers from 0 to 1000. Return the JSON object and no other text.
```

After a valid object comes back, the runner builds the stored key with `normalise_number` on `drawing_no`. If `revision` or `sub_no` was returned separately, the runner also normalises the concatenation `drawing_no + "-" + revision` and `drawing_no + "-" + sub_no` only when those fields are non-null, and stores a `parse_disagreement` flag when the code's revision or sub-number differs from the field the model returned. The stored `identity_key` is the code's parse of `drawing_no` when that parse already contains the suffix, otherwise the code's parse of the concatenation. The model's own spelling of the key is not written into `identity_key`.

Checklist prompt, a second call, only for the drawing check. The company's `mandatory_notes.csv` is a list of strings a person wrote. If that file is empty, skip this call. Do not ask the model to invent notes that ought to be there.

```text
You are given a document image and a list of mandatory notes. For each note, say whether that string is visible. For each balloon, say whether it points at a part number. Return a JSON array of objects with item, detail, present (true or false), page, and box. present is false only when the ink is absent. Do not report a clean document. Do not add notes that were not in the list.
```

`balloon_flags` does not trust that second call for an empty part number. If an extracted balloon has no `part_no`, the code emits `checklist_flag` / `balloon_missing_part` itself. The model may still flag a balloon that points at the wrong ink. Those rows stay `origin` `model`.

---

## 8. Part-number normalisation

Done in `normalise_number`. Not in the model. The steps are fixed.

1. Unicode NFKC, then uppercase, then strip. Full-width Latin letters and digits become ASCII here.
2. Remove every whitespace character. `ABC 123` and `ABC123` share a key.
3. Map `－ ー – — ‐ ‑ − _ /` to `-`. Collapse repeated hyphens. Strip hyphens at the ends. A slash is a separator: `abc／123` becomes base `ABC-123`.
4. Strip at most one revision suffix and one 枝番 suffix, in whichever order they are printed. A revision matches `REV.02`, `REV2`, `改2`, or `-R2`. A 枝番 matches `枝1`, `EDABAN1`, `SUB1`, or a trailing `(2)`. Leading zeros on the numeric part are removed with `int`, so `REV.02` is revision `2`.
5. Only after those suffixes are gone, map a remaining `.` to `-`. A bare trailing `-02` is not a revision and not a 枝番. It stays in the base. `ABC-123-02` has identity key `ABC12302`.
6. `base_key` is the base with everything except `A-Z` and `0-9` removed. `identity_key` is `base_key`, plus `R` and the revision when there is one, plus `S` and the sub-number when there is one.

The fixture samples and the keys they must produce:

| Raw | Base | Revision | Sub-number | Identity key |
| --- | --- | --- | --- | --- |
| `ＡＢＣ－１２３` | `ABC-123` | | | `ABC123` |
| `abc 123` | `ABC123` | | | `ABC123` |
| `ABC-123` | `ABC-123` | | | `ABC123` |
| `ABC--123` | `ABC-123` | | | `ABC123` |
| `ABC-123-R2` | `ABC-123` | `2` | | `ABC123R2` |
| `ABC-123-枝1` | `ABC-123` | | `1` | `ABC123S1` |
| `ABC-123（2）` | `ABC-123` | | `2` | `ABC123S2` |
| `ABC-123-R2-枝1` | `ABC-123` | `2` | `1` | `ABC123R2S1` |
| `ABC-123-枝1-R2` | `ABC-123` | `2` | `1` | `ABC123R2S1` |
| `Ｐ－１０` | `P-10` | | | `P10` |
| `P-10-R1` | `P-10` | `1` | | `P10R1` |
| `ABX-124` | `ABX-124` | | | `ABX124` |
| `ABC-123-REV.02` | `ABC-123` | `2` | | `ABC123R2` |
| `abc／123` | `ABC-123` | | | `ABC123` |
| `ABC.123` | `ABC-123` | | | `ABC123` |
| `ABC-123-02` | `ABC-123-02` | | | `ABC12302` |

`abc 123` displays without a hyphen because the space was removed rather than turned into a separator. It still matches `ABC-123` on `base_key`. The match uses the key. The base string is for display.

A number that truly ends in the letters `-R2` will be read as revision 2. Version 1 has no exception list. That false split is a known limit. The company writes those numbers into the gold set and looks at them. The runner does not add a special case to make one row pass.

The SHA-256 of the sixteen `normalise_number` results, in the order above, canonical JSON, is `d1d145b7d491121497e7b0f1ee1177c9952d7062f4bf9f1636ef65e6763a9261`.

Canonical JSON is `json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(",", ":"))` encoded as UTF-8. Every hash in this file uses that.

---

## 9. Storage

Postgres 16. `pg_trgm` is required. `vector` is optional and unused until the company has embeddings. Page images are not in the database. They live on a private store at `pages/{plant_id}/{drawing_id}.png`. The API returns a signed URL that lasts 600 seconds. The fixture preview is `preview://{id}` and is not a URL.

```sql
CREATE EXTENSION IF NOT EXISTS pg_trgm;
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE drawings (
  id              uuid PRIMARY KEY,
  plant_id        text NOT NULL,
  family_id       text NOT NULL,
  source_path     text NOT NULL,
  page_index      integer NOT NULL,
  image_uri       text NOT NULL,
  width_px        integer,
  height_px       integer,
  drawing_no_raw  text,
  base_key        text,
  identity_key    text,
  revision        text,
  sub_no          text,
  title           text,
  model           text,
  material        text,
  drawn_date      date,
  parts           jsonb NOT NULL DEFAULT '[]',
  extract         jsonb NOT NULL DEFAULT '{}',
  ocr_text        text,
  title_block_mismatch boolean NOT NULL DEFAULT false,
  blueprint_inverted   boolean NOT NULL DEFAULT false,
  extract_failed  boolean NOT NULL DEFAULT false,
  search_text     tsvector GENERATED ALWAYS AS (
                    to_tsvector('simple', coalesce(title, '') || ' ' || coalesce(extract::text, ''))
                  ) STORED,
  embedding       vector(1536),
  created_at      timestamptz NOT NULL DEFAULT now(),
  UNIQUE (plant_id, source_path, page_index)
);

CREATE INDEX drawings_identity_idx ON drawings (plant_id, family_id, identity_key);
CREATE INDEX drawings_base_idx ON drawings (plant_id, family_id, base_key);
CREATE INDEX drawings_trgm_idx ON drawings USING gin (base_key gin_trgm_ops);
CREATE INDEX drawings_fts_idx ON drawings USING gin (search_text);

CREATE TABLE parts (
  id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  drawing_id   uuid NOT NULL REFERENCES drawings (id),
  part_no_raw  text,
  base_key     text,
  identity_key text,
  revision     text,
  sub_no       text,
  qty_text     text,
  description  text
);

CREATE INDEX parts_identity_idx ON parts (identity_key);
CREATE INDEX parts_base_idx ON parts (base_key);
CREATE INDEX parts_trgm_idx ON parts USING gin (base_key gin_trgm_ops);

CREATE TABLE feedback (
  id           bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  search_id    uuid NOT NULL,
  drawing_id   uuid,
  action       text NOT NULL CHECK (action IN ('confirm', 'reject')),
  engineer_id  text NOT NULL,
  created_at   timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE checks (
  id            uuid PRIMARY KEY,
  plant_id      text NOT NULL,
  family_id     text NOT NULL,
  order_extract jsonb NOT NULL,
  drawing_extract jsonb NOT NULL,
  diffs         jsonb NOT NULL,
  status        text NOT NULL CHECK (status IN ('proposed', 'confirmed', 'rejected')),
  engineer_id   text,
  error_free    boolean NOT NULL DEFAULT false CHECK (error_free = false),
  created_at    timestamptz NOT NULL DEFAULT now()
);

CREATE TABLE audit_log (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  actor       text NOT NULL,
  action      text NOT NULL,
  subject_id  text,
  detail      jsonb NOT NULL,
  created_at  timestamptz NOT NULL DEFAULT now()
);

ALTER TABLE drawings ENABLE ROW LEVEL SECURITY;
CREATE POLICY drawings_plant ON drawings
  USING (plant_id = current_setting('app.plant_id', true));
```

The check constraint on `error_free` is intentional. A row that claims the document is clean cannot be inserted.

`pg_trgm` is a candidate generator in production, not the score the tests lock. Fetch up to 50 rows with `base_key % $query` and `similarity(base_key, $query) > 0.3`, then re-score with `sim_milli` and drop anything under 400. The locked order is the pure function. Do not sort the API by Postgres `similarity` and expect the fixture hashes to hold.

Full text uses the `simple` configuration so Japanese titles are not stemmed away by an English parser. A text query still has to pass `word_tokens`: every Latin or digit token of length 3 or more in the query must occur in the title plus the page text. That AND rule is what the fixture locks. The `tsvector` is there so the plant archive can be fetched. Re-rank with the pure function.

An embedding, when the company adds one later, is a vector of the page image or of the extracted text. It is optional. The fixture supplies visual scores as integers and does not call an embedding model. A visual hit under `sim_milli` 500 is ignored. A drawing already placed on a higher tier keeps that tier. The visual score is recorded as `visual_noted` and does not add to the rank score. A visual-only hit cannot pass an exact match.

---

## 10. Search API

`POST /v1/search`

```json
{
  "plant_id": "EXAMPLE-PLANT",
  "family_id": "EXAMPLE-FAMILY",
  "query": "ABC-123",
  "upload_id": null,
  "visual": {}
}
```

A typed `query` is used as-is. An `upload_id` points at one image, one PDF page, or one screenshot already stored for this request. The vision step extracts `parts[].part_no` and `drawing_no` from that upload only. Each extracted number is passed to `search`. The candidate lists are the union, with the best tier kept for each drawing. The fixture calls `search` directly and does not upload.

`is_text_query` is true when NFKC of the string contains at least two letter-words of three or more letters. `fan stack` is text. `ABC 123` is a number, because the second token is digits. Text queries do not consult the number tiers.

Tiers, highest first. A drawing is placed on exactly one tier.

| Tier | Rule | Weight |
| --- | --- | --- |
| `exact` | Drawing `identity_key` equals the query, or a part's `identity_key` equals the query | 100 |
| `same_base` | Same `base_key`, different identity, on the drawing or on a part. Not used when the drawing already matched exactly | 20 |
| `trigram` | `sim_milli` of the query `base_key` against the drawing or a part is at least 400. Highest similarity wins. Not used when a higher tier hit | 5 |
| `fulltext` | Text mode only. Every query token of length 3 or more is in the title plus the text | 2 |
| `visual` | A supplied visual score of at least 500, and the drawing is on no higher tier | 1 |

`sim_milli` pads the key with two spaces on each side, takes the set of character trigrams, and returns `(shared * 1000) // union`. Identical keys score 1000. An empty key scores 0.

Rank inside a tier: exact and same-base and full text follow drawing id ascending, because the fixture ids are `D1` through `D5` and that order is stable. Trigram sorts by similarity descending, then id. Visual sorts by the supplied score descending, then id.

Weighted reciprocal-rank fusion, one tier per drawing:

```text
score = weight * 100000 // (60 + rank_within_tier)
```

Rank within the tier starts at 1. Sort candidates by score descending, then drawing id ascending. Confidence is `high` for exact, `medium` for same base, `low` otherwise.

The response always includes `"claim": "candidates_only"`. Each candidate includes `drawing_id`, `rank`, `score`, `confidence`, `list`, `list_rank`, `reasons`, and `preview`.

Fixture archive, which is not a Kuken drawing:

| Id | Drawing number | Title | Text | Parts |
| --- | --- | --- | --- | --- |
| D1 | `ABC-123` | COOLING TOWER OUTLINE | casing panel | `P-10` qty 4 |
| D2 | `ABC-123-R2` | COOLING TOWER OUTLINE | revised fan stack | `P-10-R1` qty 4 |
| D3 | `ABC-123-枝1` | BRANCH DETAIL | branch nozzle | |
| D4 | `ABX-123` | DAMPER FRAME | damper frame assembly | |
| D5 | `ZZ-999` | NAMEPLATE | nameplate | |

What the seven fixture queries return, as ranks:

- `ＡＢＣ－１２３` is number mode, identity `ABC123`. D1 exact, D2 and D3 same base, D4 trigram at `sim_milli` 400, which is the floor. D4 is a weak candidate on purpose.
- `ABC-123-R2` exact on D2, then D1, D3, and the same weak D4.
- `ABC-123（1）` exact on D3, then D1 and D2.
- `ABX-124` has no exact and no same base. D4 comes back on trigram at `sim_milli` 555. Confidence is low.
- `fan stack` is text. Only D2 contains both tokens.
- `Ｐ－１０` exact on D1 through the part, same base on D2 through `P-10-R1`.
- `ABC-123` with visual scores D5 = 900 and D1 = 990. D1 stays exact. The visual note on D1 does not change its score. D5 is last, on the visual tier. D4 still appears as the weak trigram.

Hashes of those seven `search` results: q1 `99a0f993ef07e53db29879ad7158c1ca56dcadd353ae50e118f27bcde75ca119`, q2 `72027e59e3160de9f902cb90c035328514ec88a0a91e91a16c91c7f6a804a00d`, q3 `b0ec11fc6ff317802e7810d122641650d64ff98b9343d2fc47b2a7aa9c350a4f`, q4 `a86112e94cf95850b9bf7e4b56097038ee7431ec06134c282615254becd233c2`, q5 `eb0eded591fc07c6d52602fab1df9a9900ad5df2fa486ba7ca4b74e73d2de7bc`, q6 `322706389136b28706a614eee3bf2005c4a1e739113e0c330f751fd4498d02a0`, q7 `36a7a074d7e5850c2e67039b1ae92f7184545ea189eda2e7261d71353659718d`.

An upload that yields several part numbers runs `search` once per number and keeps, for each drawing, the candidate with the better score. The fixture does not cover that merge. A builder tests it with two calls whose winners differ, and checks that the higher score survives. Do not average the scores.

---

## 11. Drawing check API

`POST /v1/checks`

```json
{
  "plant_id": "EXAMPLE-PLANT",
  "family_id": "EXAMPLE-FAMILY",
  "order_notice": {},
  "drawing": {}
}
```

Both bodies are extraction objects from section 7, plus `dimensions` and, on the drawing, an optional `checklist` array and a `boxes` map for the model and the material. The runner does not call the model inside `diff_documents`. The service calls the model, validates the JSON, then calls the function.

Lengths are parsed by `parse_length` into integer micrometres. Units: `MM` 1000, `CM` 10000, `M` 1000000, `IN` 25400. A decimal is truncated, not rounded: `59.06 in` is `1500124` micrometres, and `1500 mm` is `1500000`. The form `1500 ± 2 mm` and the form `1500 mm ± 2 mm` both parse. The order notice owns the tolerance. The drawing's tolerance does not widen the order. A difference is recorded when `abs(order_um - drawing_um) > order_tol_um`. `1.5 m` and `1500 mm` are the same integer and are not a difference. `about 1500 mm` does not parse. The function records `dimension_unparsed` and does not invent 1500.

Model and material use `normalise_number`. `SS304` and `SS 304` match. `KT-10` and `KT-11` do not. `SUS304` is not rewritten to `SS304`. A missing model or material is `missing_model` or `missing_material`, not a guess. A dimension name present on only one side is `missing_dimension`. Names are compared with letters and digits only, uppercased.

Checklist rows with `present` false are copied through as `checklist_flag` with `origin` `model`, including the page and the box the model returned. The code does not flip `present` to true. `balloon_flags` adds a code flag when `part_no` is empty. The fixture balloons are one missing part number on balloon `4` and one present part number on balloon `5`. Only `4` is flagged. That list hashes to `13dbe86b2e2a7deb61f042d89035fcaee2f4ad39d338d4a972ff5dff0fce9e69`.

Every check returns `status` `proposed`, `error_free` false, and the fixed statement. Differences are sorted by their canonical JSON so the hash does not depend on map order.

The nine fixture checks:

| Id | What is different | Diffs |
| --- | --- | --- |
| c1 | Order `1500 mm` against drawing `1.5 m`, material `SS304` against `SS 304`, checklist present | none |
| c2 | Model `KT-10` against `KT-11`, with a box on the drawing model | `model_mismatch` |
| c3 | `1500 ± 2 mm` against `1503 mm` | `dimension_mismatch`, delta 3000, allowed 2000 |
| c4 | `1500 ± 5 mm` against `1503 mm` | none |
| c5 | `1500 mm` against `59.06 in` | `dimension_mismatch`, delta 124, allowed 0 |
| c6 | Models match, balloon checklist `present` false | `checklist_flag` from the model |
| c7 | Nothing numeric differs, checklist present | none, and `error_free` is still false |
| c8 | `about 1500 mm` against `1500 mm` | `dimension_unparsed` |
| c9 | Width on the order only | `missing_dimension` for `WIDTH` |

The SHA-256 of the object `{"c1": ..., "c9": ...}` is `99b1efbe003eb093a6302db3bbe7f6d0f98cd7e49633273e82b6797255e305c5`.

`POST /v1/checks/{id}/decision` with `confirm` or `reject` and an engineer id calls `decide`. Any other action returns `action_invalid`. A missing engineer returns `engineer_required`. Both failures leave `drawing_mutated` and `quote_mutated` false. A successful confirm of `D1` by `E-1` hashes to `9a750562fdc94de711dc608ef85b71ff9bc03c94d525ad934e1bf44332f4bcbf`.

The response must not contain the words "no errors", "clean", or "match confirmed" as a verdict on the document. `confirmed` is a status of the engineer's decision. It is not a verdict that the pages agree.

---

## 12. Engineer UI

Two screens. No third screen that applies a change.

**Search.** A text field and one upload button. Results are a list of cards. Each card shows the preview image, the raw drawing number, the revision, the 枝番, the confidence, and the reasons in the words the ranker stored (`drawing_identity`, `part_identity`, `drawing_base`, `part_base`, `drawing_trigram`, `part_trigram`, `fulltext_and`, `visual`). Buttons: `Confirm this page` and `Reject`. There is no `Accept all`. Confirm writes `feedback` and `audit_log` and leaves the archive bytes alone. Reject does the same with action `reject`. A rejected exact match stays in the index. It is not deleted. Later ranking may demote drawings this engineer has rejected for this identity key, by sorting them after unrejected rows of the same score. The fixture ranker does not demote. Demotion is a live-only tie-break, and it must not change the fixture hashes. Apply it after the score sort, only when `mode` is `live`.

**Check.** Two page viewers. The difference list sits beside them. A click scrolls to `box` on the page named by the diff. Code diffs and model diffs are labeled with `origin`, so a missed note does not look like a failed millimetre. When `diffs` is empty, the screen shows the fixed statement and does not show a green tick. The decision buttons are `Confirm these flags` and `Reject these flags`. Confirming an empty list is allowed. It still does not set `error_free`, and it still does not edit the quote. The button label must not say that the documents match.

Every confirm, reject, search, and check writes `audit_log` with the actor, the action, the subject id, and the request id. The engineer can open the log for their own plant. They cannot open another plant. `app.plant_id` is set on the database session from the signed-in engineer. The row-level policy does the rest.

---

## 13. Security, access, and cost

- One `plant_id` on every drawing and every check. The session variable is the signed-in engineer's plant. A query without it sees no rows.
- Images are private. The signed URL lasts 600 seconds. The bucket is not public.
- The vision call receives one page or one upload, not the archive, and not a prompt built by concatenating a customer's file into the system text. The system text is section 7. The page is the user message.
- Do not send drawings to a training programme. The company's API account has training disabled. The runner does not flip that setting.
- `lead_id` and `engineer_id` are different people. The lead's signature does not confirm a page.
- Access-permission work is named in the Kuken sources as something still ahead of their full rollout. Version 1 does not wait. The policy above is on from the first ingested page. A later, finer permission (by customer, by programme) is a new policy. It is not a reason to turn this one off.
- Cost. A typed-number search costs no vision call. An upload search costs one call for that upload. Ingest costs one call per page, and one OCR pass, cached on the row. Re-running search does not re-extract. `max_vision_calls_per_day` stops ingest and upload extraction when the day's count is reached. Typed search keeps working. The suggested pilot cap is 200 calls a day. That number is ours. It is not a Kuken spend. A hard monthly cap, if the company sets one in the provider console, is the real stop. The daily counter is the one the runner enforces.
- When the cap is hit the API returns `budget_locked` for any route that would call the model. It does not retry in a loop.

---

## 14. Evaluation and go-live

Build a gold set before shadow ends. One hundred past searches where a person already knows the correct drawing id. Write `gold.csv` with `query,correct_drawing_id`. The agent does not fill that file. The fixture's five drawings are not a gold set. `go_no_go` on any mode other than `live` returns `fixture_not_a_gate`.

On the gold queries, count `top1` and `top5` as integers. Do not print a rate.

For the check, label at least 50 flags the desk produced, and plant at least 20 discrepancies the desk did not know about (a changed dimension, a swapped model, a deleted mandatory note, a balloon with the part number removed). Count `flags_real`, `flags_seen`, `seeded_found`, `seeded_total`.

`go_no_go` returns `go` only when all of these hold. Otherwise it returns the first failing code.

1. `mode` is `live`. Otherwise `fixture_not_a_gate`.
2. `claimed_no_errors` is false. Otherwise `no_go_claimed_clean`.
3. `agent_wrote_timing` is false. Otherwise `no_go_timing`.
4. `n` is at least 100. Otherwise `no_go_gold`.
5. `top1` is at least 70 and `top5` is at least 85. Otherwise `no_go_search`.
6. `flags_seen` is at least 50 and `flags_real * 5 >= flags_seen * 4`. Otherwise `no_go_precision`.
7. `seeded_total` is at least 20 and `seeded_found * 5 >= seeded_total * 4`. Otherwise `no_go_recall`.
8. `median_before > median_after >= 0`. Otherwise `no_go_time`.

The boundary that returns `go` is `n` 100, `top1` 70, `top5` 85, `flags_seen` 50, `flags_real` 40, `seeded_total` 20, `seeded_found` 16, `median_before` 30, `median_after` 12, no claimed-clean flag, timing written by a person. Those integers are the gate. They are not Kuken's trial. `top1` of 69 returns `no_go_search`. `flags_real` of 39 with `flags_seen` of 50 returns `no_go_precision`. `claimed_no_errors` set returns `no_go_claimed_clean` even when every count would otherwise pass.

A `go` lets the lead sign. It does not confirm a drawing, and it does not turn `auto_apply` on. That key cannot be turned on.

The page-flag fixture hashes to `8337b0f9b83bb1176f6daa3cf2229b9ddfbcdd9cc6c2c592d190703b7cec522f`. It locks the OCR match, the OCR miss, the blank vision number, skew leave / rotate / unreliable, and invert above 550 but not at 550.

The whole `run_regression` bundle hashes to `bf7aebcd3d2ac768bbee119841e5de64ddc069fd93ebf1f79dffb847abd33378`.

---

## 15. How to measure your own baseline

Do this in the first two weeks, before anyone is asked to use the desk as the way they find a drawing.

1. Pick 20 searches a person actually did, or is about to do. Mix veterans and newer engineers if both do the job. Write the clue they started with: a number, a photo, or a parts list.
2. Start the clock when the clue is in hand. Stop it when the correct page is on screen. Minutes are an integer. Round up to the next minute only if the company says so in writing; otherwise truncate. The agent does not fill the file either way.
3. Write `timing.csv` with the header `job_id,minutes,found,who`. `found` is `yes` or `no`. `who` is `veteran` or `newer`. One row per search.
4. `median_minutes` is the baseline. Keep the file. After shadow, time the same kind of search again into a second file. The gate compares the two medians. It does not compare either of them with 4.5.
5. Do not write 4, 5, 10, 60, or 90 into the file because those numbers appeared in a case study. If a real search took 10 minutes, write 10 because the stopwatch said 10.

A baseline of "tens of minutes" is not a number the gate can read. The integer is the point of the exercise.

---

## 16. Rollout

Twelve weeks. This calendar is our design. The sources describe a trial at the Fukuoka factory and a full rollout at Fukuoka and Chiba targeted within 2026. Neither of those is this schedule.

Weeks 1 and 2. One family, one plant. Write the baseline in section 15. Pull the 100 gold queries from jobs a person already finished. Ingest nothing outside that family.

Weeks 3 and 4. Ingest a sample large enough to contain the gold drawings, and a further set the engineer will recognise. Read the title-block mismatches with the person who knows the old sheets. Fix the crop box if the block is not in the bottom-right. Do not "fix" a mismatched key by copying the OCR text over the vision text. Add the company's real part numbers to a normalisation spot-check: twenty numbers, including full-width digits, a revision, and a 枝番. `normalise_number` either matches what the engineer says the base and the suffix are, or the case is written down. The grammar does not grow a special case in the same week.

Weeks 5 to 8. Search runs in shadow. Engineers still find drawings the way they find them now. They may look at candidates. They may confirm or reject. Nothing in the queue is the official page until the old method has also been written down. Checks run in shadow on quotes the company is already reviewing by hand. An empty diff is still not a release.

Weeks 9 to 12. If `go_no_go` has returned `go` and the lead has signed, an engineer may use a confirmed search hit as the page they work from. The check may sit beside the quote. The quote is still edited by a person, somewhere else. `quote_write` stays `scope_locked`. A second plant stays `scope_locked`.

The morning file is the counts: gold `n`, `top1`, `top5`, flags seen and real, seeded found and total, the two medians, confirms, rejects, title-block mismatches, extract failures. It is not a leaderboard against the case study.

---

## 17. Failure handling

| What happened | Code | What the runner does |
| --- | --- | --- |
| The vision reply is not JSON twice | `extract_failed` | Store the page. Leave the keys empty. Do not guess a number from the file name |
| OCR and vision disagree on the drawing number | `title_block_mismatch` | Store both. Keep the code key from the vision string. Show the flag |
| Skew looks larger than 10 degrees | `skew_unreliable` | Do not rotate. Keep the page |
| A length says "about" or otherwise will not parse | `dimension_unparsed` | Flag it. Do not coerce |
| The model and the order disagree by more than the order tolerance | `dimension_mismatch` | Show delta and allowed. Do not clamp the drawing to the order |
| A balloon has no part number | `balloon_missing_part` | Code flag. Do not copy a nearby part number |
| Handwriting, a faded scan, a stamp across the title block | logged on the page | Leave the key empty if it did not parse. Do not inpaint a digit |
| The daily vision cap is spent | `budget_locked` | Typed search still runs. Ingest waits |
| Someone calls quote write, drawing edit, or a second plant | `scope_locked` | Write nothing |
| Someone confirms with no engineer id | `engineer_required` | Write nothing |
| A check is saved with `error_free` true | rejected by the table | The insert fails |

A failure is a row. It is not a retry that deletes the conflicting dimension to make the check empty.

---

## 18. Risks

- **A fluent title block.** The model has seen drawing numbers before and will complete one that the scan does not contain. Mitigation: the key is `normalise_number` of the extracted string, OCR has to agree or the page is flagged, and a failed extract does not fall back to the file name.
- **The unmarked suffix.** `ABC-123-02` stays one identity. Treating every trailing number as a 枝番 would glue unrelated sheets together. Mitigation: only `REV`, `R`, `改`, `枝`, `EDABAN`, `SUB`, and parentheses are suffixes.
- **The weak trigram.** At the floor of 400, `ABC-123` also surfaces `ABX-123`. That is a candidate, confidence low, behind the exact page and the other revisions. Mitigation: the tier weights, and a reject button. Do not raise the floor to hide D4 and then claim the fixture still hashes.
- **A clean check.** An empty diff feels like permission to send the quote. Mitigation: `error_free` cannot be stored true, the statement is fixed, and the button does not say the documents match.
- **Unit theatre.** `1.5 m` against `1500 mm` is not a difference. `59.06 in` against `1500 mm` is 124 micrometres and, with a zero tolerance, it is a flag. The engineer can reject the flag. The runner must not widen the tolerance to swallow it.
- **Copied clocks.** A timeout of 4.5 minutes, or `0.90` in `check_precision_min`, stores somebody else's trial in the config. The startup refusal is there so those values cannot be settings.
- **The fixture as a product.** `ABC-123` and `KT-10` are hash fixtures. They are not a Kuken tower and not a drawing anyone should build.
- **Handwriting, quietly filled.** The sources say the check does not catch every handwritten note. A runner that transcribes a guess will look more complete and be wrong. Mitigation: unreadable stays null.

---

## 19. What you do not claim

- Do not say this company will find a drawing in 4.5 minutes. That average is the Fukuoka trial. It is not a latency budget.
- Do not say drawing-search hours will fall by about 90 percent. That is Kuken's projection from FY2025 actuals, not a measured year, and not this company's forecast.
- Do not say about 90 percent of flags will be real. That is the prototype figure from the published trial. The gate here is an integer comparison on this company's own labels.
- Do not say a search that took 60 minutes will take 10. That is one engineer's remark, on the OpenAI video, about some searches.
- Do not say the desk is in production because the trial ran. This file starts in shadow.
- Do not say the documents match because the diff list is empty.
- Do not say a confirm edited the drawing or released the quote. Both mutated flags stay false.
- Do not say this company will roll out to two factories within 2026. That target belongs to the published next step at Kuken. Section 16 is twelve weeks, and it is ours.
- Do not name a model and attribute it to Kuken. The model names are not public. `vision_model` is the company's own contract.
- Do not say Recursive's application is required as a product install, and do not say this file is that application.
- Do not paste a customer's drawing into the system prompt as instructions.
- Do not say "572" is this company's headcount. The figure is Kuken's, as of April 2026.

When a sentence would make this company sound like the trial's scoreboard, delete the sentence and show the company its own `timing.csv` and its own top-1 and top-5 counts instead.

---

## 20. Paste this to build it

Paste the block below to the agent that will build the tool. The builder reads this whole file. The model sees a drawing only as a user message. It does not see a customer PDF as instructions to follow against the company.

```text
You are building the drawing-search and drawing-check tool specified in drawing-search-agent-instructions.md. Build only what that file specifies.

Stack for the fixture: Python 3.11 or newer, standard library only. The functions normalise_number, sim_milli, search, parse_length, diff_documents, balloon_flags, title_block_mismatch, skew_action, should_invert, decide, startup, median_minutes, go_no_go, and run_regression are the API. Copy them from section 21. Do not reimplement the grammar in the prompt.

The service around that core may use Postgres 16 with the DDL in section 9, a private image store, pdftoppm, Pillow, and tesseract with eng+jpn. The vision model is whatever vision_model names. The fixture never calls it.

Fail closed. If startup returns a code, do not serve a live run. If auto_apply is not no, refuse. If a copied-claim key is present, refuse. If check_precision_min is 0.90 or 90 or 90%, refuse. If family_id is not the one allowed family, refuse. If a live plant id starts with EXAMPLE, refuse.

Never set error_free true. Never set drawing_mutated or quote_mutated true. Never parse "about 1500 mm" as 1500. Never treat a 30 millimetre miss as inside a 2 millimetre tolerance. Never let a visual score outrank an exact identity. Never delete a page because OCR disagreed. Never write a quote. Never print a percent. Never store 4.5, 90, 60, or 10 as a target.

run_regression must produce norms hash d1d145b7d491121497e7b0f1ee1177c9952d7062f4bf9f1636ef65e6763a9261, q1 hash 99a0f993ef07e53db29879ad7158c1ca56dcadd353ae50e118f27bcde75ca119, q2 hash 72027e59e3160de9f902cb90c035328514ec88a0a91e91a16c91c7f6a804a00d, q3 hash b0ec11fc6ff317802e7810d122641650d64ff98b9343d2fc47b2a7aa9c350a4f, q4 hash a86112e94cf95850b9bf7e4b56097038ee7431ec06134c282615254becd233c2, q5 hash eb0eded591fc07c6d52602fab1df9a9900ad5df2fa486ba7ca4b74e73d2de7bc, q6 hash 322706389136b28706a614eee3bf2005c4a1e739113e0c330f751fd4498d02a0, q7 hash 36a7a074d7e5850c2e67039b1ae92f7184545ea189eda2e7261d71353659718d, checks hash 99b1efbe003eb093a6302db3bbe7f6d0f98cd7e49633273e82b6797255e305c5, flags hash 8337b0f9b83bb1176f6daa3cf2229b9ddfbcdd9cc6c2c592d190703b7cec522f, balloons hash 13dbe86b2e2a7deb61f042d89035fcaee2f4ad39d338d4a972ff5dff0fce9e69, decide hash 9a750562fdc94de711dc608ef85b71ff9bc03c94d525ad934e1bf44332f4bcbf, and bundle hash bf7aebcd3d2ac768bbee119841e5de64ddc069fd93ebf1f79dffb847abd33378. Section 14 must pass before a lead is asked to leave shadow, and before a candidate is treated as the drawing the quote has already been changed to match.
```

---

## 21. Normative runner

The block below is the implementation the hashes were computed from. Copy it. Python 3.11 or newer. Standard library only. If a prose sentence and this block disagree, this block is the one the tests lock.

```python
"""Normative v1 core for the drawing-search desk. Standard library only. No model calls."""
import hashlib
import json
import re
import unicodedata

HYPHEN_CHARS = "－ー–—‐‑−_/"
WEIGHTS = {"exact": 100, "same_base": 20, "trigram": 5, "fulltext": 2, "visual": 1}
RRF_K = 60
TRIGRAM_MIN = 400
VISUAL_MIN = 500
UNIT_UM = {"MM": 1000, "CM": 10000, "M": 1000000, "IN": 25400}
TOKEN = re.compile(r"[A-Za-z0-9Ａ-Ｚａ-ｚ０-９\-\.／_～~－ー–—‐‑−枝改（）()]+")
REFUSED_KEYS = {
    "four_point_five_minutes",
    "ninety_percent",
    "half_day",
    "sixty_minutes",
    "ten_minutes",
    "target_minutes",
    "accuracy_target",
    "search_minutes",
}
STATEMENT = "Differences below are candidates. An empty list is not a claim that the documents match."

DRAWINGS = [
    {"id": "D1", "drawing_no": "ABC-123", "title": "COOLING TOWER OUTLINE", "text": "casing panel", "model": "KT-10"},
    {"id": "D2", "drawing_no": "ABC-123-R2", "title": "COOLING TOWER OUTLINE", "text": "revised fan stack", "model": "KT-10"},
    {"id": "D3", "drawing_no": "ABC-123-枝1", "title": "BRANCH DETAIL", "text": "branch nozzle", "model": "KT-10"},
    {"id": "D4", "drawing_no": "ABX-123", "title": "DAMPER FRAME", "text": "damper frame assembly", "model": "DF-2"},
    {"id": "D5", "drawing_no": "ZZ-999", "title": "NAMEPLATE", "text": "nameplate", "model": "NP-1"},
]
PARTS = [
    {"drawing_id": "D1", "part_no": "P-10", "qty": "4"},
    {"drawing_id": "D2", "part_no": "P-10-R1", "qty": "4"},
]
NORM_SAMPLES = [
    "ＡＢＣ－１２３",
    "abc 123",
    "ABC-123",
    "ABC--123",
    "ABC-123-R2",
    "ABC-123-枝1",
    "ABC-123（2）",
    "ABC-123-R2-枝1",
    "ABC-123-枝1-R2",
    "Ｐ－１０",
    "P-10-R1",
    "ABX-124",
    "ABC-123-REV.02",
    "abc／123",
    "ABC.123",
    "ABC-123-02",
]


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


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


def normalise_number(raw):
    if raw is None or str(raw).strip() == "":
        return {"raw": raw, "base": "", "base_key": "", "revision": None, "sub_no": None, "identity_key": ""}
    text = unicodedata.normalize("NFKC", str(raw)).upper().strip()
    text = re.sub(r"\s+", "", text)
    for ch in HYPHEN_CHARS:
        text = text.replace(ch, "-")
    text = re.sub(r"-{2,}", "-", text).strip("-")
    revision = None
    sub_no = None
    for _ in range(2):
        matched = False
        m = re.search(r"(?:-)?(?:REV\.?|改)-?(\d{1,2})$", text)
        if m and revision is None:
            revision = str(int(m.group(1)))
            text = text[: m.start()].strip("-")
            matched = True
        if not matched:
            m = re.search(r"-R(\d{1,2})$", text)
            if m and revision is None:
                revision = str(int(m.group(1)))
                text = text[: m.start()].strip("-")
                matched = True
        if not matched:
            m = re.search(r"(?:-)?(?:枝|EDABAN|SUB)\.?-?(\d{1,3})$", text)
            if not m:
                m = re.search(r"\((\d{1,3})\)$", text)
            if m and sub_no is None:
                sub_no = str(int(m.group(1)))
                text = text[: m.start()].strip("-")
                matched = True
        if not matched:
            break
    text = text.replace(".", "-")
    text = re.sub(r"-{2,}", "-", text).strip("-")
    base = "-".join(p for p in text.split("-") if p)
    base_key = re.sub(r"[^A-Z0-9]", "", base)
    identity = base_key
    if revision is not None:
        identity += "R" + revision
    if sub_no is not None:
        identity += "S" + sub_no
    return {
        "raw": raw,
        "base": base,
        "base_key": base_key,
        "revision": revision,
        "sub_no": sub_no,
        "identity_key": identity,
    }


def trigrams(value):
    padded = "  " + value + " "
    return {padded[i : i + 3] for i in range(len(padded) - 2)}


def sim_milli(left, right):
    if not left or not right:
        return 0
    a, b = trigrams(left), trigrams(right)
    union = len(a | b)
    if union == 0:
        return 0
    return (len(a & b) * 1000) // union


def rrf(weight, rank):
    return weight * 100000 // (RRF_K + rank)


def is_text_query(raw):
    words = re.findall(r"[A-Za-zＡ-Ｚａ-ｚ]{3,}", unicodedata.normalize("NFKC", str(raw)))
    return len(words) >= 2


def word_tokens(value):
    text = unicodedata.normalize("NFKC", str(value)).upper()
    return re.findall(r"[A-Z0-9]{3,}", text)


def parts_of(drawing_id):
    return [p for p in PARTS if p["drawing_id"] == drawing_id]


def search(query, visual=None):
    visual = visual or {}
    mode = "text" if is_text_query(query) else "number"
    qn = normalise_number(query) if mode == "number" else None
    lists = {name: [] for name in WEIGHTS}
    details = {d["id"]: [] for d in DRAWINGS}
    known = {d["id"] for d in DRAWINGS}

    if mode == "number" and qn["base_key"]:
        exact, same = [], []
        for d in DRAWINGS:
            dn = normalise_number(d["drawing_no"])
            reasons = []
            if dn["identity_key"] == qn["identity_key"]:
                reasons.append("drawing_identity")
            part_base = False
            for p in parts_of(d["id"]):
                pn = normalise_number(p["part_no"])
                if pn["identity_key"] == qn["identity_key"]:
                    reasons.append("part_identity")
                elif pn["base_key"] == qn["base_key"]:
                    part_base = True
            if reasons:
                exact.append(d["id"])
                details[d["id"]].extend(reasons)
                continue
            if dn["base_key"] == qn["base_key"]:
                details[d["id"]].append("drawing_base")
                same.append(d["id"])
                continue
            if part_base:
                details[d["id"]].append("part_base")
                same.append(d["id"])
        lists["exact"] = exact
        lists["same_base"] = same
        taken = set(exact) | set(same)
        tri = []
        for d in DRAWINGS:
            if d["id"] in taken:
                continue
            dn = normalise_number(d["drawing_no"])
            best = sim_milli(qn["base_key"], dn["base_key"])
            why = "drawing_trigram"
            for p in parts_of(d["id"]):
                pn = normalise_number(p["part_no"])
                score = sim_milli(qn["base_key"], pn["base_key"])
                if score > best:
                    best = score
                    why = "part_trigram"
            if best >= TRIGRAM_MIN:
                tri.append((-best, d["id"], best, why))
        tri.sort()
        for _neg, did, best, why in tri:
            lists["trigram"].append(did)
            details[did].append({"detail": why, "sim_milli": best})
    else:
        qtokens = word_tokens(query)
        for d in DRAWINGS:
            blob = set(word_tokens(d["title"] + " " + d["text"]))
            if qtokens and all(t in blob for t in qtokens):
                lists["fulltext"].append(d["id"])
                details[d["id"]].append("fulltext_and")

    placed = {did for name in ("exact", "same_base", "trigram", "fulltext") for did in lists[name]}
    vis = []
    for did, milli in visual.items():
        if did not in known or int(milli) < VISUAL_MIN:
            continue
        if did in placed:
            details[did].append({"detail": "visual_noted", "sim_milli": int(milli)})
        else:
            vis.append((-int(milli), did, int(milli)))
    vis.sort()
    for _neg, did, milli in vis:
        lists["visual"].append(did)
        details[did].append({"detail": "visual", "sim_milli": milli})

    scored = []
    for name, ids in lists.items():
        for rank, did in enumerate(ids, start=1):
            scored.append((-rrf(WEIGHTS[name], rank), did, name, rank, rrf(WEIGHTS[name], rank)))
    scored.sort()
    confidence = {"exact": "high", "same_base": "medium"}
    candidates = []
    for index, (_neg, did, name, rank, score) in enumerate(scored, start=1):
        candidates.append(
            {
                "drawing_id": did,
                "rank": index,
                "score": score,
                "confidence": confidence.get(name, "low"),
                "list": name,
                "list_rank": rank,
                "reasons": details[did],
                "preview": "preview://" + did,
            }
        )
    return {
        "query": query,
        "mode": mode,
        "normalised": qn,
        "candidates": candidates,
        "claim": "candidates_only",
    }


def to_um(whole, frac, unit):
    scale = UNIT_UM[unit]
    value = int(whole) * scale
    if frac:
        value += (int(frac) * scale) // (10 ** len(frac))
    return value


def parse_length(text):
    if text is None:
        return None
    t = unicodedata.normalize("NFKC", str(text)).upper().replace(" ", "").replace("±", "+/-")
    m = re.fullmatch(
        r"(\d+)(?:\.(\d+))?((?:MM|CM|M|IN))(?:\+/-(\d+)(?:\.(\d+))?((?:MM|CM|M|IN))?)?",
        t,
    )
    if m:
        unit = m.group(3)
        tol = 0
        if m.group(4) is not None:
            tol = to_um(m.group(4), m.group(5), m.group(6) or unit)
        return {"um": to_um(m.group(1), m.group(2), unit), "tol_um": tol, "unit": unit}
    m = re.fullmatch(r"(\d+)(?:\.(\d+))?\+/-(\d+)(?:\.(\d+))?((?:MM|CM|M|IN))", t)
    if not m:
        return None
    unit = m.group(5)
    return {
        "um": to_um(m.group(1), m.group(2), unit),
        "tol_um": to_um(m.group(3), m.group(4), unit),
        "unit": unit,
    }


def dim_name(name):
    return re.sub(r"[^A-Z0-9]", "", unicodedata.normalize("NFKC", str(name)).upper())


def diff_documents(order, drawing):
    diffs = []
    om = normalise_number(order.get("model") or "")
    dm = normalise_number(drawing.get("model") or "")
    model_box = (drawing.get("boxes") or {}).get("model")
    if not om["base_key"] or not dm["base_key"]:
        diffs.append({"kind": "missing_model", "origin": "code", "box": model_box})
    elif om["identity_key"] != dm["identity_key"]:
        diffs.append(
            {
                "kind": "model_mismatch",
                "origin": "code",
                "order": om["identity_key"],
                "drawing": dm["identity_key"],
                "box": model_box,
            }
        )
    material_box = (drawing.get("boxes") or {}).get("material")
    os_ = normalise_number(order.get("material") or "")
    ds = normalise_number(drawing.get("material") or "")
    if not os_["base_key"] or not ds["base_key"]:
        diffs.append({"kind": "missing_material", "origin": "code", "box": material_box})
    elif os_["identity_key"] != ds["identity_key"]:
        diffs.append(
            {
                "kind": "material_mismatch",
                "origin": "code",
                "order": os_["identity_key"],
                "drawing": ds["identity_key"],
                "box": material_box,
            }
        )
    od = {dim_name(d["name"]): d for d in (order.get("dimensions") or [])}
    dd = {dim_name(d["name"]): d for d in (drawing.get("dimensions") or [])}
    for name in sorted(set(od) | set(dd)):
        if name not in od or name not in dd:
            side = "order" if name not in od else "drawing"
            present = dd.get(name) or od.get(name) or {}
            diffs.append(
                {
                    "kind": "missing_dimension",
                    "origin": "code",
                    "name": name,
                    "side": side,
                    "box": present.get("box"),
                }
            )
            continue
        parsed_order = parse_length(od[name].get("text"))
        parsed_drawing = parse_length(dd[name].get("text"))
        if parsed_order is None or parsed_drawing is None:
            diffs.append(
                {
                    "kind": "dimension_unparsed",
                    "origin": "code",
                    "name": name,
                    "order_text": od[name].get("text"),
                    "drawing_text": dd[name].get("text"),
                    "box": dd[name].get("box"),
                }
            )
            continue
        delta = abs(parsed_order["um"] - parsed_drawing["um"])
        if delta > parsed_order["tol_um"]:
            diffs.append(
                {
                    "kind": "dimension_mismatch",
                    "origin": "code",
                    "name": name,
                    "order_um": parsed_order["um"],
                    "drawing_um": parsed_drawing["um"],
                    "delta_um": delta,
                    "allowed_um": parsed_order["tol_um"],
                    "box": dd[name].get("box"),
                }
            )
    for item in drawing.get("checklist") or []:
        if item.get("present") is False:
            diffs.append(
                {
                    "kind": "checklist_flag",
                    "origin": "model",
                    "item": item.get("item"),
                    "detail": item.get("detail"),
                    "page": item.get("page"),
                    "box": item.get("box"),
                }
            )
    diffs.sort(key=canon)
    return {"status": "proposed", "error_free": False, "statement": STATEMENT, "diffs": diffs}


def title_block_mismatch(vision_no, ocr):
    parsed = normalise_number(vision_no or "")
    if not parsed["base_key"]:
        return True
    keys = set()
    for tok in TOKEN.findall(ocr or ""):
        tn = normalise_number(tok)
        if tn["base_key"]:
            keys.add(tn["base_key"])
            keys.add(tn["identity_key"])
    return parsed["identity_key"] not in keys and parsed["base_key"] not in keys


def skew_action(degrees_milli):
    magnitude = abs(int(degrees_milli))
    if magnitude > 10000:
        return "skew_unreliable"
    if magnitude < 200:
        return "leave"
    return "rotate"


def should_invert(dark_milli):
    return int(dark_milli) > 550


def balloon_flags(balloons):
    flags = []
    for balloon in balloons or []:
        if not balloon.get("part_no"):
            flags.append(
                {
                    "kind": "checklist_flag",
                    "origin": "code",
                    "item": "balloon_missing_part",
                    "detail": balloon.get("id"),
                    "page": balloon.get("page"),
                    "box": balloon.get("box"),
                }
            )
    flags.sort(key=canon)
    return flags


def decide(drawing_id, action, engineer_id):
    if action not in ("confirm", "reject"):
        return {"error": "action_invalid", "drawing_mutated": False, "quote_mutated": False}
    if not engineer_id or engineer_id == "REPLACE":
        return {"error": "engineer_required", "drawing_mutated": False, "quote_mutated": False}
    return {
        "drawing_id": drawing_id,
        "action": action,
        "engineer_id": engineer_id,
        "drawing_mutated": False,
        "quote_mutated": False,
    }


def startup(config):
    for key in REFUSED_KEYS:
        if key in config:
            return "copied_claim_refused"
    if config.get("check_precision_min") in ("0.90", "90", "90%", "0.9", 90, "0.90 "):
        return "copied_rate_refused"
    if config.get("auto_apply", "no") != "no":
        return "auto_apply_locked"
    if config.get("engineer_required", "yes") != "yes":
        return "signoff_locked"
    for key in ("company_name", "plant_id", "family_id", "engineer_id", "vision_model"):
        if config.get(key) in (None, "", "REPLACE"):
            return "config_missing"
    if config.get("family_id") != config.get("allowed_family"):
        return "scope_locked"
    if config.get("mode") == "live" and str(config.get("plant_id", "")).startswith("EXAMPLE"):
        return "example_in_live"
    return None


def median_minutes(values):
    xs = sorted(int(v) for v in values)
    if not xs:
        return None
    return xs[(len(xs) - 1) // 2]


def go_no_go(report, mode):
    if mode != "live":
        return "fixture_not_a_gate"
    if report.get("claimed_no_errors"):
        return "no_go_claimed_clean"
    if report.get("agent_wrote_timing"):
        return "no_go_timing"
    if int(report["n"]) < 100:
        return "no_go_gold"
    if int(report["top1"]) < 70 or int(report["top5"]) < 85:
        return "no_go_search"
    if int(report["flags_seen"]) < 50 or int(report["flags_real"]) * 5 < int(report["flags_seen"]) * 4:
        return "no_go_precision"
    if int(report["seeded_total"]) < 20 or int(report["seeded_found"]) * 5 < int(report["seeded_total"]) * 4:
        return "no_go_recall"
    if not (int(report["median_before"]) > int(report["median_after"]) >= 0):
        return "no_go_time"
    return "go"


def live_pass():
    return {
        "n": 100,
        "top1": 70,
        "top5": 85,
        "flags_seen": 50,
        "flags_real": 40,
        "seeded_total": 20,
        "seeded_found": 16,
        "median_before": 30,
        "median_after": 12,
        "claimed_no_errors": 0,
        "agent_wrote_timing": False,
    }


def checks():
    box = {"x": 10, "y": 20, "w": 30, "h": 8}
    return {
        "c1": diff_documents(
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1500 mm"}, {"name": "WIDTH", "text": "800 mm"}]},
            {"model": "KT-10", "material": "SS 304", "dimensions": [{"name": "HEIGHT", "text": "1.5 m"}, {"name": "WIDTH", "text": "800 mm"}], "checklist": [{"item": "mandatory_note", "detail": "paint note present", "present": True, "page": 1, "box": {"x": 1, "y": 2, "w": 3, "h": 4}}]},
        ),
        "c2": diff_documents(
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1500 mm"}]},
            {"model": "KT-11", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1500 mm"}], "boxes": {"model": box}},
        ),
        "c3": diff_documents(
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1500 ± 2 mm"}]},
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1503 mm", "box": box}]},
        ),
        "c4": diff_documents(
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1500 ± 5 mm"}]},
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1503 mm"}]},
        ),
        "c5": diff_documents(
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1500 mm"}]},
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "59.06 in", "box": box}]},
        ),
        "c6": diff_documents(
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1500 mm"}]},
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1500 mm"}], "checklist": [{"item": "balloon", "detail": "balloon 4 has no part number", "present": False, "page": 2, "box": box}]},
        ),
        "c7": diff_documents(
            {"model": "KT-10", "material": "SS304", "dimensions": []},
            {"model": "KT-10", "material": "SS304", "dimensions": [], "checklist": [{"item": "mandatory_note", "detail": "present", "present": True, "page": 1, "box": box}]},
        ),
        "c8": diff_documents(
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "about 1500 mm"}]},
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1500 mm", "box": box}]},
        ),
        "c9": diff_documents(
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1500 mm"}, {"name": "WIDTH", "text": "800 mm"}]},
            {"model": "KT-10", "material": "SS304", "dimensions": [{"name": "HEIGHT", "text": "1500 mm"}]},
        ),
    }


def page_flags():
    return [
        {"case": "ocr_match", "mismatch": title_block_mismatch("ABC-123", "DWG NO ABC-123 REV A")},
        {"case": "ocr_base", "mismatch": title_block_mismatch("ABC-123-R2", "DWG NO ABC-123")},
        {"case": "ocr_miss", "mismatch": title_block_mismatch("ABC-123", "DWG NO ABX-999")},
        {"case": "ocr_blank", "mismatch": title_block_mismatch("", "ABC-123")},
        {"case": "skew_leave", "action": skew_action(100)},
        {"case": "skew_rotate", "action": skew_action(1500)},
        {"case": "skew_bad", "action": skew_action(12000)},
        {"case": "invert_yes", "invert": should_invert(800)},
        {"case": "invert_no", "invert": should_invert(400)},
        {"case": "invert_edge", "invert": should_invert(550)},
    ]


def run_regression():
    norms = [normalise_number(s) for s in NORM_SAMPLES]
    searches = {
        "q1": search("ＡＢＣ－１２３"),
        "q2": search("ABC-123-R2"),
        "q3": search("ABC-123（1）"),
        "q4": search("ABX-124"),
        "q5": search("fan stack"),
        "q6": search("Ｐ－１０"),
        "q7": search("ABC-123", {"D5": 900, "D1": 990}),
    }
    bundle = {
        "norms": norms,
        "searches": searches,
        "checks": checks(),
        "flags": page_flags(),
        "balloons": balloon_flags(
            [
                {"id": "4", "part_no": None, "page": 2, "box": {"x": 1, "y": 2, "w": 3, "h": 4}},
                {"id": "5", "part_no": "P-10", "page": 2, "box": {"x": 1, "y": 2, "w": 3, "h": 4}},
            ]
        ),
        "decide_ok": decide("D1", "confirm", "E-1"),
        "decide_bad": decide("D1", "apply", "E-1"),
        "startup_ok": startup(
            {
                "company_name": "EXAMPLE Works",
                "plant_id": "EXAMPLE-PLANT",
                "family_id": "EXAMPLE-FAMILY",
                "allowed_family": "EXAMPLE-FAMILY",
                "engineer_id": "EXAMPLE-ENGINEER",
                "vision_model": "EXAMPLE-VISION",
                "auto_apply": "no",
                "engineer_required": "yes",
                "mode": "fixture",
                "check_precision_min": "0.80",
            }
        ),
        "startup_copied": startup({"ninety_percent": True, "company_name": "EXAMPLE Works", "plant_id": "EXAMPLE-PLANT", "family_id": "EXAMPLE-FAMILY", "allowed_family": "EXAMPLE-FAMILY", "engineer_id": "EXAMPLE-ENGINEER", "vision_model": "EXAMPLE-VISION"}),
        "startup_rate": startup({"company_name": "EXAMPLE Works", "plant_id": "EXAMPLE-PLANT", "family_id": "EXAMPLE-FAMILY", "allowed_family": "EXAMPLE-FAMILY", "engineer_id": "EXAMPLE-ENGINEER", "vision_model": "EXAMPLE-VISION", "check_precision_min": "0.90"}),
        "startup_auto": startup({"company_name": "EXAMPLE Works", "plant_id": "EXAMPLE-PLANT", "family_id": "EXAMPLE-FAMILY", "allowed_family": "EXAMPLE-FAMILY", "engineer_id": "EXAMPLE-ENGINEER", "vision_model": "EXAMPLE-VISION", "auto_apply": "yes"}),
        "gate_fixture": go_no_go(live_pass(), "fixture"),
        "gate_go": go_no_go(live_pass(), "live"),
        "gate_search": go_no_go({**live_pass(), "top1": 69}, "live"),
        "gate_precision": go_no_go({**live_pass(), "flags_real": 39}, "live"),
        "gate_clean": go_no_go({**live_pass(), "claimed_no_errors": 1}, "live"),
    }
    named = {
        "norms": sha(norms),
        "q1": sha(searches["q1"]),
        "q2": sha(searches["q2"]),
        "q3": sha(searches["q3"]),
        "q4": sha(searches["q4"]),
        "q5": sha(searches["q5"]),
        "q6": sha(searches["q6"]),
        "q7": sha(searches["q7"]),
        "checks": sha(bundle["checks"]),
        "flags": sha(bundle["flags"]),
        "balloons": sha(bundle["balloons"]),
        "decide_ok": sha(bundle["decide_ok"]),
        "bundle": sha(bundle),
    }
    return bundle, named


if __name__ == "__main__":
    bundle, named = run_regression()
    print(json.dumps(named, indent=2))
    print("---Q1---")
    print(json.dumps(bundle["searches"]["q1"], ensure_ascii=False, indent=2))
    print("---Q4---")
    print(json.dumps(bundle["searches"]["q4"], ensure_ascii=False, indent=2))
    print("---Q5---")
    print(json.dumps(bundle["searches"]["q5"], ensure_ascii=False, indent=2))
    print("---Q6---")
    print(json.dumps(bundle["searches"]["q6"], ensure_ascii=False, indent=2))
    print("---Q7 ids---")
    print([(c["drawing_id"], c["list"], c["score"], c["confidence"]) for c in bundle["searches"]["q7"]["candidates"]])
    print("---CHECKS kinds---")
    for k, v in bundle["checks"].items():
        print(k, [(d["kind"], d.get("delta_um"), d.get("name")) for d in v["diffs"]], "error_free", v["error_free"])
    print("---FLAGS---")
    print(bundle["flags"])
    print("---GATES---", bundle["gate_fixture"], bundle["gate_go"], bundle["gate_search"], bundle["gate_precision"], bundle["gate_clean"])
    print("---START---", bundle["startup_ok"], bundle["startup_copied"], bundle["startup_rate"], bundle["startup_auto"])

```
