# Strategic-sourcing and RFQ agent

Instructions for an AI agent that will **build and then run** one strategic-sourcing desk for a mid-size manufacturer. One plant. One wave. One part family. The desk pulls part rows and drawing files, extracts a standard part record, checks the commodity code, groups parts that are actually alike, and names the approved supplier who has already quoted or made one of them. It drafts a redacted RFQ package and a quote comparison. A buyer approves every release and every award. Version 1 never emails a supplier, never uploads to SharePoint, and never writes a purchase order.

Version 1 reads an export. It can write its own tables: a run log, packages, proposals, and decisions. `release_approved` becomes true only from the form. `sharepoint_written` stays false. `transmitted` stays false. `po_written` stays false. `erp_written` stays false. There is no Graph token and no mail password in this file.

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

The pattern is the one [Paperless Parts](https://radar.paperlessparts.com/resources/case-studies/watlow-centralizes-sourcing-intelligence-to-accelerate-rfqs-by-80-and-unlock-cost-savings-with-radar) published for Watlow. Watlow is an industrial thermal-technology maker, established in 1922, headquarters in St. Louis, Missouri. The work on that page is Radar, Paperless Parts' sourcing-intelligence platform: extraction from 2D and 3D files, commodity-code checks, similarity on geometry and GD&T, RFQ packages with cover sheets, redaction, and SharePoint. Company facts are in the next section. They are background. They are not a configuration.

[KOEPFER](/blog/how-koepfer-captured-tail-spend-savings-with-ai-agents) is a different desk. That file starts when a quote is already on the requisition. [Kuken](/blog/how-kuken-industries-cut-drawing-search-time-with-ai) searches a drawing archive. This file is the stretch between them: make the part record, find who on the approved list can make the part, and only then build the package. Do not paste those schemas into this one.

Their published results are not a forecast for anyone else. Section 24 says what you must not copy. No threshold, weight, or calendar in this file is a Watlow or Paperless Parts setting. Each one is our design, and each live value stays blank until this plant types it.

A plant that buys custom parts, can export items and an approved-supplier list, and keeps current PDFs and STEP files in a folder, can use this file. Nothing here says this file is Radar. The Watlow page does not publish an entity list, a column, a prompt, a model name, or a redaction rule.

---

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

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

- Watlow Electric Manufacturing Company. The case study calls Watlow a global leader in industrial heating technology. Header on the page: location global (13 sites); processes metallics, plastics, advanced components; established 1922; use case enterprise strategic sourcing. The body says 13 manufacturing sites worldwide and tens of thousands of active part numbers across categories including metallics and plastics. The header also names advanced components.
- Watlow's own worldwide page says the company employs more than 4,200 team members, in 11 manufacturing facilities and nine technology and development centers, in the United States, Mexico, Europe, and Asia. The case study's "13 manufacturing sites" and the worldwide page's "11 manufacturing facilities" are both published. This file does not reconcile them and does not use either number as a setting. The headquarters city, St. Louis, is the city Watlow lists for the company and on its locations page. The case study page itself does not print the street address.
- Part and supplier data were fragmented. The case names Macpac, Oracle, and various PLM platforms. RFQ response times stretched to 45–60 days for typical packages after notice went out. Limited quote coverage delayed revenue, tied up working capital, and raised direct material cost. 235 parts the team called unsourceable sat idle. Staff spent hours a day on manual work. Mark Dufrain, Senior Director, Sourcing: "We had 235 'unsourceable' parts sitting idle because we simply didn't have the data visibility to find the right partners." Liying Luplow, Project Manager, Global Sourcing: "I was spending hours manually downloading every single drawing, one at a time. It was a massive waste of time. We would spend hours on non-value-added work that kept us from moving faster."
- The platform on the page is Paperless Parts' Radar. The page says a patented geometric engine and AI-powered data extraction pull material, process, and feature-level data from 2D and 3D files. Radar validates and recommends commodity codes and flags errors. Similarity matching groups related part numbers and families on geometric features, specifications, and GD&T callouts. It shows whether similar parts were sourced before and from which supplier. It builds quote packages with auto-generated cover sheets so a supplier can see the scope and confirm capability. SharePoint integration and automated redaction scrub sensitive data before it reaches the supply base.
- Results the case study states: an 80%+ reduction in RFQ time. A strategic sourcing action that would have taken 4–5 weeks of manufacturing engineering and procurement management time was condensed to 2–3 days. Watlow felt Radar delivered 3–4x more time savings than expected. All 235 previously unsourceable parts were categorized, with potential sources from the existing approved supplier list. Wave 1 delivered 35% direct cost savings on parts quoted via Radar. In a poll, 4 of 5 suppliers said the Radar packages made quoting easier, citing faster access to the right drawings, a higher-fidelity cover sheet, and less time organizing the package. Wave 2 is underway on 187 additional part numbers. The page says early results point to savings potential above Wave 1, pending final validation of landed costs and tooling impacts. This file does not store that as a number and does not treat it as a result. Those figures are the vendor's published customer case. This file uses none of them as a setting, a target, or a default.
- Paperless Parts' sourcing-intelligence page, which is not the Watlow deployment, says Radar is not a supplier marketplace and does not route parts to new suppliers. It works with the approved supplier list. A complete package, on that page, includes the current revision, the 3D model, the specs the print references, quantities and dates, and requirements such as ITAR or a first article when they apply. Security claims on that page (CMMC, ITAR registration, GovCloud) describe Paperless Parts. They do not describe a Watlow tenant, and this file does not copy them into a config key.

No source used here names the table, the column, the prompt, the model, the similarity threshold, the redaction dictionary, or the approval screen. This file does not invent them and then attribute them.

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

One departure is deliberate. The published platform builds the package, redacts, and files to SharePoint, and people act on the quotes. Version 1 makes the release and the award stored decisions. An approval writes an audit row. It does not upload, it does not email, and it does not write a purchase order. `auto_release_rfq`, `auto_award`, and `auto_send` stay `no`. The staged folder is the handoff to the SharePoint library the plant already syncs, after the buyer has approved. The agent does not hold the token.

Another departure is the geometry. Radar's page names a patented geometric engine and does not publish it. Version 1 uses six integers from a STEP feature reader the plant already runs, a size-ratio gate, and a spec vector. An off-the-shelf embedding model may replace the spec vector. It may not name the family. A cosine on raw millimetres is not a family: a small bushing and a larger flange can point the same direction.

Another departure is the agent layer. Paperless Parts has not published the internals of the Watlow tenant. The tools, the prompts, and the redaction list in this file are ours. They are labelled as ours. They are not a reconstruction of a Radar screen.

The 80%, the 35%, the 235, the 187, the 3–4x, the 4–5 weeks, the 2–3 days, the 45–60 days, and the 4 of 5 are not defaults and not goals for the morning file.

---

## 1. Role

You are the strategic-sourcing agent for:

`REPLACE: legal name, for example "EXAMPLE Fabrication Co."`

You load the export, extract and check the part record, group one family, draft the package, and compare the quotes that come back. You write notes in:

`REPLACE: internal language, usually the language the desk already works in`

You may read the files in section 7. You may write the output tables in section 6. You may not open a network connection except the read-only extract the plant has already approved. You may not store a mail password, a Graph token, or an API key. You may not look up a supplier, a price, or a lead time that is not on the export. You may not add a supplier who is not on the approved list.

You may not invent a date, a quantity, a percent, a material, or a GD&T number. You may not release an RFQ, award a supplier, or send a message. You may not treat a draft as a package the supplier has already received.

The buyer who may approve a release and an award:

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

The steward who may accept a commodity recommendation and a parsed GD&T callout:

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

A backup who may act for either of them when the named person is away:

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

Inbox for every task and every morning file:

`REPLACE: desk@company.example`

---

## 2. Fill this in before the first extract

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

| Key | What to collect |
| --- | --- |
| `company_name` | Legal name |
| `buyer`, `steward`, `backup` | Named people. `backup` may be `none`. Only the role that owns the action, or the backup, may approve it |
| `desk_inbox` | Mailbox for the morning file |
| `timezone` | The plant's own zone. The fixture uses `America/Chicago` because the fixture company is typed as a St. Louis desk. That is not Watlow's setting |
| `run_clock` | The clock the code uses. Tests pin it. A live run uses the host clock in `timezone`. Format `YYYY-MM-DDTHH:MM:SS+HH:MM` or with a minus offset |
| `plant_id` | One plant. The fixture uses `PLT-1` |
| `sharepoint_site`, `sharepoint_library` | Where a person will file the staged folder. The fixture uses a local library name. Version 1 does not call Graph |
| `export_max_age_hours` | A file older than this is stale. Suggested starting point: `6`. Age equal to this value is still fresh |
| `max_row_drop_pct` | Integer. On a full extract, if this file has fewer rows than `previous_row_count * (100 - this) / 100`, refuse. The fixture uses `50` |
| `similarity_geometry_bps` | Integer 0–10000. Shape cosine, after the vector is scaled by its own longest side. The fixture uses `9800` |
| `similarity_spec_bps` | Integer 0–10000. Spec cosine. The fixture uses `8500` |
| `size_ratio_max` | Integer percent. Larger envelope times 100, divided by the smaller, must be at or under this. The fixture uses `125`, which is a 25% size gap. Equal parts score `100` |
| `confidence_min_bps` | Below this, the extraction is not classified. The fixture uses `7000` |
| `max_lead_days` | A quote with a longer lead is not comparable. The fixture uses `30` |
| `note_min` | Minimum characters in an approval note. Suggested starting point: `15` |
| `rfq_qty` | The quantity this wave is quoting. The fixture uses `100`. A quote at another quantity does not compare |
| `need_date` | The date printed on the cover sheet. The fixture uses `2026-12-15` |
| `wave_family` | The one family id this wave may package. The fixture uses `FAM-P-100` |
| `require_human_approval` | Must be `yes` |
| `auto_release_rfq` | Must be `no` |
| `auto_award` | Must be `no` |
| `auto_send` | Must be `no` |
| `mail_mode` | Must be `file` |
| `send_email` | Must be `no` |
| `write_back` | Must be `no` |
| `sharepoint_mode` | Must be `local` in this program. `graph` is `sharepoint_mode_locked` |
| `shadow` | `yes` until a person has signed section 19 and then set this to `no` themselves. The program never flips it |
| `wave1_signed` | `no` until a person sets `yes` after the go/no-go. The program never flips it. A second family stays closed |

If any required key is missing, blank, or the word `REPLACE`, do not package. Reply with `replace_unset` and stop. `backup` may be `none`.

Startup refusals, in this order, before any row is read as a package.

1. Any of these keys present, at any value, is `copied_claim_refused`: `rfq_time_reduction_pct`, `wave1_savings_pct`, `unsourceable_count`, `time_savings_multiple`, `supplier_poll_easier`, `case_cycle_days`, `wave2_part_count`.
2. Any config value containing `80%`, `35%`, `3-4x`, `3–4x`, `4-5 weeks`, `4–5 weeks`, `2-3 days`, `2–3 days`, `45-60`, `45–60`, `4 of 5`, `4 out of 5`, `235`, or `187` is `copied_claim_refused`.
3. `auto_release_rfq` or `auto_award` other than `no` is `release_locked`.
4. `auto_send` or `send_email` other than `no` is `send_locked`.
5. `require_human_approval` other than `yes` is `approval_locked`.
6. `mail_mode` other than `file` is `mail_mode_locked`.
7. `sharepoint_mode` other than `local` is `sharepoint_mode_locked`.
8. `write_back` other than `no` is `write_back_locked`.
9. A key whose name contains `password`, `api_key`, `secret`, or `token` is `credential_too_wide`.
10. A required key missing, blank, or `REPLACE` is `replace_unset`.
11. A `run_clock` that does not match the timestamp shape above is `clock_unparsed`.
12. On a live run, a string value that begins with `EXAMPLE` or `FIXTURE` is `example_row_in_live`.

The run date is the calendar date of `run_clock` in that offset. It is not converted through UTC. The fixture clock `2026-11-29T08:00:00-06:00` is the morning of 29 November.

---

## 3. Scope of version 1

In scope: one plant, one named part family, on demand. Part rows. Current PDF drawings and STEP files. A closed commodity list a person maintains. Geometry features from a CAD reader. An approved-supplier list with capability rows (process, material, maximum envelope). History rows of parts those suppliers have quoted or made. Quote responses the buyer has already received into a folder. A cover sheet. A redaction log. A comparison. A decision log. A poll the buyer records after talking to suppliers.

Out of scope: emailing a supplier; uploading to SharePoint from this program; creating a supplier who is not approved; writing a purchase order or a commodity code back to the ERP; quoting a second family before `wave1_signed` is `yes`; sending the raw drawing; letting the model name a family, a code, or a price. A second family waits until the first has a signed go/no-go and a person has set the flag. The program will not set the flag because the thresholds passed.

Human rule, with no exception in version 1: the agent proposes the code, the family, the package, and the award. The steward accepts a code and a callout. The buyer approves the release and the award on the form. Nothing is uploaded and nothing is sent.

---

## 4. Architecture

Published shape, named as an echo: drawings and CAD in, a part record with material and process and features, a commodity check, a family on geometry and GD&T, the supplier who has made something similar, a package with a cover sheet, redaction before release, a person who awards. The boxes below are our design.

```text
ERP extract and a drawing folder, each with exported_at
        │
        ▼
Freshness. A stale file or a collapsed full file stops the run
        │
        ▼
Document model returns a fixed JSON record. A price or a supplier in that JSON is rejected
        │
        ▼
Commodity check against the closed list. A person accepts a recommendation
        │
        ▼
Shape vector, size-ratio gate, spec vector. Family id is computed. The model does not name it
        │
        ▼
Proven supplier from history, or candidates from the approved list, or none
        │
        ▼
One package per invited supplier. Cover sheet. Redacted files. Export-held parts stay out
        │
        ▼
Quote comparison in integer cents. Late, incomplete, wrong quantity, and uninvited quotes drop
        │
        ▼
Buyer approves the release. Buyer approves the award. Audit row
        │
        ▼
Staged folder. sharepoint_written, transmitted, po_written, erp_written stay false
```

The language model may phrase a finished card into one sentence with no digits. It does not decide a status, a family, a commodity code, a price, or an approval. Those are pure functions. If the model and the function disagree, the function wins and the sentence is dropped.

Version 1's transport is a file drop. An export is only as fresh as `export_max_age_hours`. The case names Macpac, Oracle, and PLM platforms and does not name the tables. This file does not invent the Watlow tenant. Section 7 is the header this program reads, and the plant maps it. The only writes are the agent's own tables.

---

## 5. Guardrails

These override a helpful tone, a buyer who wants the case-study percent on a slide, and a note that offers to "just send the package".

1. **No RFQ release except the form.** `auto_release_rfq` stays `no`. `record_decision` with `channel` `model` returns `prompt_ignored` and writes nothing.
2. **No award except the form.** `auto_award` stays `no`. The landed price is the quote's price. A number typed in the note does not replace it. `po_written` stays false.
3. **No send, ever.** `mail_mode` stays `file`. `auto_send` and `send_email` stay `no`. `transmitted` stays false. The poll is a row the buyer records. The agent does not email it.
4. **No upload, ever, from this program.** `sharepoint_mode` stays `local`. `sharepoint_written` stays false. `file_package` while `shadow` is `yes` returns `shadow_locked`. After approval, with shadow off, it returns `staged_local` and the flag is still false.
5. **No ERP write, ever.** `write_back` stays `no`. Accepting a commodity code does not update Macpac, Oracle, or the PLM. The next extract is still the ERP's file.
6. **No supplier who is not approved.** History from an unknown supplier is ignored. An invite that names one is `supplier_not_approved`. The agent does not search a marketplace. Radar's own product page says it is not a marketplace. This rule is the same idea, and the enforcement is ours.
7. **No decision from the model.** Only `channel` `form` can decide, accept a code, clear a callout, or record a poll.
8. **The role owns the action.** The steward, the buyer, or the backup may accept a code and clear GD&T. Only the buyer or the backup may release, award, or record a poll. A planner is `actor_refused`. The steward cannot release.
9. **A stale export is not an empty plant.** `stale_export`, `short_export`, or `export_missing` returns no package.
10. **The drawing wins over the spreadsheet.** A material hint column is `csv_header` and the file is refused. Classification uses the extraction, not the ERP description.
11. **The model does not bring a price.** An extraction payload with `price`, `unit_cents`, `supplier`, `supplier_id`, `commodity`, `family_id`, `target_price`, or `margin` is `extraction_leaked_commercial`. The whole payload is dropped.
12. **A code is valid only against the list.** One matching code and a matching ERP value is `VALID`. A blank ERP value with one match is `RECOMMENDED` until a person accepts it. A code not on the list is `INVALID`. A code on the list that contradicts the extraction is `CONFLICT`. No match is `UNMAPPED`. Two matches is `AMBIGUOUS`. Confidence under the line is `LOW-CONFIDENCE` and cannot be accepted. A missing material is `MISSING-MATERIAL`.
13. **`SEE NOTE` is not a callout.** It flags `gdt_unparsed` and it changes the spec vector, so the part does not join a family whose callout is a real number. A person clears it by typing a callout that matches `PROFILE 0.2` (one decimal) or `FLATNESS`, `POSITION`, `PERPENDICULARITY` in that same shape, or `NONE`. The plant may widen the pattern later. The agent does not invent the number.
14. **Family membership is a gate, not a cosine.** Same material, same process, geometry score at or above the line, spec score at or above the line, and size ratio at or under the line. All five. A family id passed into the scorer is ignored.
15. **Export control holds the part.** `export_control` other than `none`, or a drawing line that says ITAR, EAR, or CUI, keeps the part out of every package. Redaction does not make an export-controlled file sendable.
16. **Redaction drops the line.** It does not black out a word inside a sentence and hope. A line that matches the sensitive list is removed and counted. A STEP header that matches is withheld whole. This program does not edit STEP geometry.
17. **A quote counts only when it is complete, invited, at the RFQ quantity, on or before the run date, with a positive price and a lead inside the maximum.** Tooling is `tooling_cents // qty`. The winner is the lowest landed cost, then the shorter lead, then the supplier id. A tie on landed cost and lead sets `tied` true and the supplier id breaks it for the proposal. The buyer still has to approve.
18. **Savings are not booked until the award is approved, and only against one last paid price at the same quantity.** No baseline is `null`. It is not zero, and it is not 35%.
19. **A second family is closed.** `build_package` on any id other than `wave_family`, while `wave1_signed` is not `yes`, returns `wave_not_open`. Passing `go_no_go` does not sign the wave. `signed` in that reply is false.

---

## 6. Postgres schema

The reference program in section 16 keeps these rows in memory so a plant can run the fixture with no database. The live build uses Postgres 15 or newer. `plant_id` is on every business table. Version 1 has one value.

```sql
create table part (
  plant_id text not null,
  part_id text not null,
  rev text not null,
  erp_commodity text not null default '',
  description text not null,
  primary key (plant_id, part_id)
);

create table extraction (
  plant_id text not null,
  part_id text not null,
  material text not null,
  process text not null,
  gdt text not null,
  features text not null,
  specs text not null,
  confidence_bps integer not null check (confidence_bps between 0 and 10000),
  evidence text not null,
  primary key (plant_id, part_id)
);

create table geometry_feature (
  plant_id text not null,
  part_id text not null,
  length_mm integer not null check (length_mm >= 0),
  width_mm integer not null check (width_mm >= 0),
  height_mm integer not null check (height_mm >= 0),
  hole_count integer not null check (hole_count >= 0),
  tight_tol_count integer not null check (tight_tol_count >= 0),
  thread_count integer not null check (thread_count >= 0),
  source text not null check (source in ('step', 'person')),
  primary key (plant_id, part_id)
);

create table commodity_code (
  plant_id text not null,
  code text not null,
  process text not null,
  material text not null,
  primary key (plant_id, code, material)
);

create table supplier (
  plant_id text not null,
  supplier_id text not null,
  name text not null,
  approved boolean not null,
  primary key (plant_id, supplier_id)
);

create table supplier_capability (
  plant_id text not null,
  supplier_id text not null,
  process text not null,
  material text not null,
  max_envelope_mm integer not null check (max_envelope_mm > 0),
  primary key (plant_id, supplier_id, process, material)
);

create table sourcing_history (
  plant_id text not null,
  part_id text not null,
  supplier_id text not null,
  relation text not null check (relation in ('made', 'quoted')),
  last_price_cents integer not null check (last_price_cents >= 0),
  qty integer not null check (qty > 0)
);

create table drawing_file (
  plant_id text not null,
  part_id text not null,
  rev text not null,
  kind text not null check (kind in ('pdf', 'step')),
  current boolean not null,
  export_control text not null,
  body text not null
);

create table quote_response (
  plant_id text not null,
  quote_id text primary key,
  part_id text not null,
  supplier_id text not null,
  unit_cents integer not null,
  qty integer not null,
  lead_days integer not null,
  tooling_cents integer not null,
  received_on date not null,
  complete boolean not null
);

create table decision (
  decision_id bigint generated always as identity primary key,
  kind text not null,
  target_id text not null,
  action text not null,
  actor text not null,
  channel text not null check (channel = 'form'),
  note text not null,
  decided_at timestamptz not null default now(),
  release_approved boolean not null default false,
  award_approved boolean not null default false,
  sharepoint_written boolean not null default false check (sharepoint_written = false),
  transmitted boolean not null default false check (transmitted = false),
  erp_written boolean not null default false check (erp_written = false),
  po_written boolean not null default false check (po_written = false)
);

revoke update, delete on decision from public;
```

The checks that keep `sharepoint_written`, `transmitted`, `erp_written`, and `po_written` false are the point of the table. A later migration that drops them is a different product. Do not drop them to "make the approval send".

---

## 7. Ingestion

One full extract for the ERP side and one for the drawing folder. Land both before a package is built. Carry `plant_id` from the connection, never from a column the source system can leave blank.

Freshness, or the run stops:

- The newest `exported_at` for `erp` and for `drawings` is not older than `export_max_age_hours` against `run_clock`, and it is not in the future. Age is whole seconds. Age equal to the limit is still fresh.
- On a `full` extract, `row_count * 100` is not below `previous_row_count * (100 - max_row_drop_pct)`. A previous count of 0 is the first night and skips this test.
- A missing system is `export_missing`.

The case names Macpac, Oracle, and various PLM platforms. It does not name a table. Version 1 does not ship a certified connector. It ships a header. The plant confirms the map on a sheet before the first pull. If the plant's column has another name, the sheet says so. The agent does not guess a second column.

- **The part file this program reads.** Header exactly `part_id,rev,erp_commodity,description`. UTF-8. No material column. A header that adds `material_hint` is `csv_header` and nothing is loaded. The hint would let a spreadsheet override the drawing. That is the bug the refusal exists to prevent. Descriptions must not contain commas. A commodity cell may be empty.
- **Oracle, or another ERP.** The plant's own extract of item, revision, and commodity code, saved to that header. Approved suppliers as `supplier_id,name,approved`. Capability as `supplier_id,process,material,max_envelope_mm`. History as `part_id,supplier_id,relation,last_price_cents,qty` with `relation` of `made` or `quoted`. Prices are integer cents in the plant's currency. This file does not convert currency.
- **Macpac, or any legacy system that will not give an API.** The CSV the plant already knows how to run, mapped by a person onto the same header. This file does not invent Macpac's screen names.
- **PLM or a drawing folder.** Files named `{part_id}_{rev}.pdf` and `{part_id}_{rev}.step`. A manifest marks which revision is current. Two current files of the same kind for one part is `duplicate_current_drawing` and the part is blocked. A missing current PDF blocks the part. A missing STEP is `step_missing` and the line can still go, with the warning on the package, because some suppliers quote from the print. The warning is visible. It is not hidden to make the package look finished.
- **Quotes.** A CSV the buyer drops after responses arrive. The agent does not log into a supplier portal.

`parse_parts_csv` in section 16 is the part-file parser. Anything else is `csv_header` or `csv_row`.

---

## 8. Extraction, the prompt, and the commodity rules

The document step is an off-the-shelf vision model the plant already pays for. A current GPT, Claude, or Gemini document model is a fit. Temperature 0. One page, or one STEP header summary a local reader already pulled. The model returns JSON. The program validates it. The model is replaceable. The gates are not.

The STEP file itself does not go to the language model. A CAD kernel reads geometry. Section 9.

`EXTRACTION_PROMPT` is this text. It is ours. The Watlow page does not publish a prompt.

```text
You extract a manufacturing part record from one drawing page, or from a STEP header summary the tool already pulled. Return JSON only.

Keys, and only these keys: material, process, gdt, features, specs, confidence_bps, evidence.
material is the material callout as printed, or an empty string if the page does not state one.
process is MACH, FORM, CERAMIC, or an empty string if the page does not state a process.
gdt is one callout such as "PROFILE 0.2", or "SEE NOTE" if the page points at a note you cannot read, or "NONE".
features is a short phrase such as "4X HOLE", "TUBE", or "BUSHING".
specs is the specification callout, or "NONE".
confidence_bps is an integer from 0 to 10000 for how sure you are that the material and the process are actually printed.
evidence is the place on the page, such as "title block" or "note 3".

Do not return a price, a supplier, a commodity code, a family, a lead time, or a quantity. Do not guess a material that is not printed. If the page says SEE NOTE and you cannot read the note, return SEE NOTE. Do not invent the number.
```

`apply_extraction` keeps those seven keys and rejects a payload that carries a commercial field. Confidence has to be an integer from 0 to 10000. A boolean is rejected. The commodity code is computed after, from the closed list.

The fixture list, which is not a Watlow list:

| Code | Process | Materials |
| --- | --- | --- |
| `MACH-SS` | `MACH` | `304SS`, `316SS` |
| `FORM-NI` | `FORM` | `INCOLOY`, `INCONEL` |
| `CER-INS` | `CERAMIC` | `ALUMINA` |

Status rules are in section 5. A person accepts a recommendation, an invalid code that has exactly one recommendation, or a conflict that has exactly one recommendation. The accepted value is the recommendation, not whatever the note asks for. Accepting does not write the ERP. A low-confidence record and a record with no recommendation cannot be accepted.

Worked statuses on the fixture, before anyone clicks:

- `P-100`, ERP `MACH-SS`, drawing 316 stainless, machined. `VALID`.
- `P-110`, ERP blank, drawing the same, GD&T `SEE NOTE`. `RECOMMENDED`, flag `gdt_unparsed`.
- `P-120`, ERP blank, drawing the same, callout parsed. `RECOMMENDED`.
- `P-200`, ERP `MACH-SS`, drawing Incoloy, formed. `CONFLICT`, recommendation `FORM-NI`.
- `P-300`, ERP blank, alumina ceramic. `RECOMMENDED` `CER-INS`.
- `P-400`, ERP `MACH-SS`, drawing matches, file marked ITAR. Commodity `VALID`, and the part is still not sendable.
- `P-500`, ERP `ZZZ-BAD`, drawing matches `MACH-SS`. `INVALID`, recommendation `MACH-SS`.
- `P-600`, ERP `MACH-SS`, drawing aluminum. `CONFLICT`, no recommendation. Aluminum is not on the list. The stainless code is not borrowed.
- `P-700`, confidence 5000, under 7000. `LOW-CONFIDENCE`. Not classified.
- `P-800`, no material and no process. `MISSING-MATERIAL`.

---

## 9. Geometry, embeddings, and families

**CAD geometry, off the shelf.** A STEP reader the plant already licenses (Open CASCADE, or the kernel in the CAD tool they use) writes six integers: length, width, height, hole count, tight-tolerance count, thread count. Millimetres. Counts are integers. `source` is `step` or `person`. The language model does not fill these in. A part with no geometry row is not clustered.

**Shape, then size.** Raw cosine on millimetres is a trap. A 30 mm bushing and an 80 mm flange can score as if they were the same shape, because the vector points the same way. The program first divides the three envelope numbers by the longest side, in integers, and scales the counts so they are not drowned by the millimetres. That is `shape_vector`. It then requires the size ratio: larger envelope times 100, divided by the smaller. On the fixture, `P-100` against `P-110` is geometry 9996 and size ratio 102, inside a max of 125. `P-100` against `P-300` is size ratio 266, which fails the gate even before anyone argues about the cosine. `P-200`, a 400 mm sheath, fails it too.

**Spec embeddings, off the shelf.** Build one line: material, process, GD&T, features, spec. Embed it with an off-the-shelf model (a small local model or the embedding endpoint the plant already uses). Cosine, in basis points, is the spec score. The reference program does not call a network. `spec_vector` is a fixed vocabulary count, which is the offline stand-in, so the fixture runs on a laptop. Swap the vector. Do not swap the gates. The scorer throws away a `family_id` argument. On the fixture, `P-100` against `P-110` while the callout is still `SEE NOTE` scores spec 8000, under the 8500 line, so `P-110` stays in its own family. After a person types `PROFILE 0.2`, the spec score clears and `P-110` joins `FAM-P-100`.

That is the whole point of the gate. The supplier who had already made `P-100` was invisible while the note was dirty. Cleaning the callout is what makes the history show up. The case study's lesson about data visibility is theirs. This mechanism is ours.

Clustering walks part ids in order. A part joins the first family whose medoid passes all five gates. Otherwise it seeds a new family, `FAM-` plus its own id. Low confidence and missing material are not clustered. Their sourcing status is `HELD`.

---

## 10. Suppliers, unsourceable parts, candidates

A supplier counts only when `approved` is true.

A part is `SOURCEABLE` when an approved supplier has `made` or `quoted` any member of its family, including itself. Those supplier ids are `proven`.

Otherwise the part is `UNSOURCEABLE-WITH-CANDIDATES` when at least one approved supplier's capability covers the process, the material, and the envelope. Those ids are `candidates`. They are not proven. They have not made the part.

Otherwise `UNSOURCEABLE-NO-CANDIDATE`. The agent stops. It does not propose a name from outside the list.

On the fixture, before the GD&T clear: `P-110` is unsourceable with candidates `SUP-A` and `SUP-E`, because it is stuck in its own family and the history sits on `P-100`. After the clear, it is sourceable through `SUP-A`. `P-300`, the ceramic, has no history and one candidate, `SUP-C`. `P-600`, the aluminum flange, has one candidate, `SUP-D`, and a commodity conflict, so it still cannot be packaged. `SUP-Z` appears on a history row for `P-100` and is not approved, so it is not proven and it cannot be invited.

The invite list for a package is the proven suppliers who can make every line, plus any `also_invite` id that is approved and can make every line. A proven supplier who cannot make one of the lines is `proven_not_capable_of_all` and is not invited. Sending them a package they cannot quote is how a supplier learns to ignore the next one.

---

## 11. Redaction, the cover sheet, and the staged folder

Sensitive lines, case insensitive, whole line dropped: `target price`, `internal cost`, `margin`, `do not send`, `customer:`, `buyer:`, `incumbent`, and the export markers `ITAR`, `EAR`, and `CUI`. An export marker also holds the file. A held file is not "redacted and sent".

The fixture PDF for `P-100` carries three bad lines: a target price of 12.40, an internal cost, and `CUSTOMER: ACME`. The packaged text keeps the material and the profile callout. It does not keep those three lines. The hit count is 3. A stale revision B is on the extract and is not copied. A STEP header that contains a target price is `step_withheld`. The program does not try to rewrite the STEP.

The cover sheet is built from the structured record, never from the raw text. Fields: RFQ id, the addressee supplier and nobody else, part id, revision, material, process, commodity, family id, envelope, hole count, GD&T, specs, quantity, need date, and the redacted file names with their redacted hashes. No last price. No other supplier. No target. The fixture's last paid price of 3200 cents must not appear.

One folder per supplier, so the addressee is the only supplier name in that folder:

```text
RFQ/RFQ-1/SUP-A/cover-P-100.json
RFQ/RFQ-1/SUP-A/P-100_C.pdf
RFQ/RFQ-1/SUP-A/P-100_C.step
RFQ/RFQ-1/SUP-E/cover-P-100.json
```

`file_package` returns those paths only after the buyer has approved and `shadow` is `no`. `status` is `staged_local`. `sharepoint_written` is false. A person, or the SharePoint sync the plant already runs, copies that folder into the library named in config. The Graph token stays out of this file. Putting it in a key is `credential_too_wide`.

Lines that do not ship, on the fixture, after the steward has accepted `P-110` and `P-120` and cleared the callout: `P-400` export-held, `P-500` still `INVALID` until someone accepts the recommendation, and anyone whose commodity is not `VALID` or `ACCEPTED`. The package lines are `P-100`, `P-110`, `P-120`. `P-120` has no STEP, so `step_missing` is on the line and the line still goes.

---

## 12. Quotes, comparison, and the award

Quotes are rows the buyer has filed. The comparison is a pure function.

Ignored, with a reason, and not a winner:

- part not on this RFQ
- received after the run date (`quote_in_future`)
- supplier not invited
- `complete` false
- quantity different from `rfq_qty`
- lead days over `max_lead_days`
- unit price at or under zero, or negative tooling

Landed cents are `unit_cents + tooling_cents // qty`. Integer division. No float.

Fixture outcome, which is our arithmetic:

- `P-100`. `SUP-A` at 2500 cents, lead 20, no tooling. `SUP-E` at 2100 plus 50000 cents of tooling, which is 500 cents a part at quantity 100, landed 2600. A 1000-cent quote from `SUP-A` at 45 days is disqualified and does not win. `SUP-A` wins at 2500. Last paid price, same quantity, 3200. Savings 2187 basis points, and only after the buyer approves.
- `P-110`. `SUP-E` at 2200 beats `SUP-A` at 2600. No last paid price. Savings are null, not zero.
- `P-120`. The only response is incomplete. `no_complete_quote`. Coverage is 2 of 3 lines, 6666 basis points.

Cycle days are from `opened_on` (the fixture package opens 2026-11-01) to the earliest quote that actually counts. That date is 2026-11-10. Nine days. The disqualified quote dated 2 November does not make the cycle shorter. A future-dated quote does not count.

`record_decision` on `RFQ-1` with `approve`, the buyer or the backup, `channel` `form`, and a long enough note sets `release_approved`. It does not upload. A second approve is `already_decided`. An award decision stores the landed cents from the proposal. The note "award at 100 cents" still stores 2500.

---

## 13. What the language model may do

The model may summarise a finished card in a sentence with no digits, name the status the tool already returned, and point at a draft the tool returned.

The model may not compute a price, a saving, a family, a commodity code, or a supplier list. It may not release, award, upload, or approve itself.

`SYSTEM_PROMPT` is this text:

```text
You are the strategic-sourcing desk for one manufacturer, one wave, one part family.
You prepare a part record, a family, a redacted RFQ package, and a quote comparison. A person decides. You never release an RFQ, never award a supplier, never write the ERP, and never upload a file.

Material, process, GD&T, commodity codes, family ids, supplier names, prices, and dates come only from tool results. If a number is not in a tool result, you do not have it. You do not estimate a price, a saving, or a cycle time.

You do not invent a supplier. Candidates come from the approved list the tool returned. A supplier who is not on that list is not a candidate.

Tools you may call: score_parts, accept_commodity, clear_gdt, build_package, compare_quotes, record_decision, file_package, record_poll.
accept_commodity and clear_gdt are data gates. record_decision with channel model is refused. file_package does not upload. A draft package is not a released RFQ. An award proposal is not a purchase order. record_poll does not email a supplier.

When you write prose, use no digit, no percent sign, and no case-study result. The figures stay in the JSON. Say the status the tool returned. Say when a part is held. Do not call a package a file the supplier has already received.

If a tool returns stale_export, export_held, commodity_mismatch, release_not_approved, or copied_claim_refused, say that and stop. Do not fill the gap from memory.
```

`phrase_summary` drops any sentence with a digit or a percent sign, and any sentence that still contains a blocked case-study phrase. "The order stays uncovered." is allowed. "Down 80% in two weeks." is `digit_refused`.

Tool definitions. The Python methods of the same names are the implementation.

```json
{
  "name": "score_parts",
  "parameters": {
    "type": "object",
    "additionalProperties": false,
    "required": ["left_id", "right_id"],
    "properties": {
      "left_id": {"type": "string"},
      "right_id": {"type": "string"},
      "family_id": {"type": "string", "description": "Ignored. The scorer computes the family."}
    }
  }
}
```

```json
{
  "name": "accept_commodity",
  "parameters": {
    "type": "object",
    "additionalProperties": false,
    "required": ["part_id", "actor", "note", "channel"],
    "properties": {
      "part_id": {"type": "string"},
      "actor": {"type": "string"},
      "note": {"type": "string"},
      "channel": {"type": "string", "enum": ["form", "model"]}
    }
  }
}
```

```json
{
  "name": "clear_gdt",
  "parameters": {
    "type": "object",
    "additionalProperties": false,
    "required": ["part_id", "gdt", "actor", "note", "channel"],
    "properties": {
      "part_id": {"type": "string"},
      "gdt": {"type": "string"},
      "actor": {"type": "string"},
      "note": {"type": "string"},
      "channel": {"type": "string", "enum": ["form", "model"]}
    }
  }
}
```

```json
{
  "name": "build_package",
  "parameters": {
    "type": "object",
    "additionalProperties": false,
    "required": ["family_id", "also_invite"],
    "properties": {
      "family_id": {"type": "string"},
      "also_invite": {"type": "array", "items": {"type": "string"}}
    }
  }
}
```

```json
{
  "name": "compare_quotes",
  "parameters": {
    "type": "object",
    "additionalProperties": false,
    "properties": {}
  }
}
```

```json
{
  "name": "record_decision",
  "parameters": {
    "type": "object",
    "additionalProperties": false,
    "required": ["kind", "target", "action", "actor", "note", "channel"],
    "properties": {
      "kind": {"type": "string", "enum": ["rfq", "award"]},
      "target": {"type": "string"},
      "action": {"type": "string", "enum": ["approve", "reject", "snooze"]},
      "actor": {"type": "string"},
      "note": {"type": "string"},
      "channel": {"type": "string", "enum": ["form", "model"]}
    }
  }
}
```

```json
{
  "name": "file_package",
  "parameters": {
    "type": "object",
    "additionalProperties": false,
    "properties": {}
  }
}
```

```json
{
  "name": "record_poll",
  "parameters": {
    "type": "object",
    "additionalProperties": false,
    "required": ["supplier_id", "easier", "actor", "note", "channel"],
    "properties": {
      "supplier_id": {"type": "string"},
      "easier": {"type": "string", "enum": ["yes", "no"]},
      "actor": {"type": "string"},
      "note": {"type": "string"},
      "channel": {"type": "string", "enum": ["form", "model"]}
    }
  }
}
```

Example of a tool result, from the fixture, not from a plant. The model may talk about this object. It may not add a number that is not here.

```json
{
  "ok": true,
  "part_id": "P-100",
  "supplier_id": "SUP-A",
  "landed_cents": 2500,
  "award_approved": true,
  "po_written": false,
  "erp_written": false
}
```

A sentence the model may add, because it has no digit: "The award is approved. No purchase order was written." A sentence the model may not add: "Saved 35 percent" or "Two days faster."

---

## 14. Human gates

| Gate | Who | What changes | What does not |
| --- | --- | --- | --- |
| Accept commodity | Steward, buyer, or backup | Status becomes `ACCEPTED` for a single recommendation | The ERP code. A low-confidence row. A row with no recommendation |
| Clear GD&T | Steward, buyer, or backup | The callout, then the family is recomputed | A free-typed novel. `SEE NOTE` is refused as a clear |
| Release the RFQ | Buyer or backup | `release_approved` on that RFQ | Upload, email, the file bytes |
| Award | Buyer or backup | `award_approved` on that proposal | The purchase order. The landed price |
| Poll | Buyer or backup | A yes or no row | Any message to the supplier |
| Sign wave 1 | A person, editing config | `wave1_signed` and, separately, `shadow` | The program. `go_no_go` returns `signed: false` always |

A note shorter than `note_min` is `note_short`. `channel` `model` is `prompt_ignored` and writes no row.

---

## 15. The fixture, worked

The fixture company is `FIXTURE Thermal Co.` It is not Watlow. The parts are not Watlow part numbers. The suppliers are not Watlow suppliers. The clock is 29 November 2026, 08:00, offset minus six hours.

Ten parts. Three codes. Five approved suppliers. One unapproved id on a history row, which is ignored. Geometry and drawings as in section 16.

The path the regression locks:

1. `P-110` does not join `FAM-P-100` while the callout is `SEE NOTE`. It is unsourceable, with `SUP-A` and `SUP-E` as candidates from capability, not from history.
2. The steward accepts the commodity on `P-110`. The buyer accepts `P-120`. The callout is still blocking. A package of the flange family does not include `P-110`.
3. The steward types `PROFILE 0.2`. `P-110` joins the family and becomes sourceable through `SUP-A`, because `P-100` was made by `SUP-A`.
4. A package of `FAM-P-300` is `wave_not_open`.
5. The flange package lines are `P-100`, `P-110`, `P-120`. Invites are `SUP-A` and `SUP-E`. `SUP-Z` is refused. `P-400` is export-held. The redacted PDF has three hits and no target price.
6. Comparison: `P-100` to `SUP-A` at 2500, `P-110` to `SUP-E` at 2200, `P-120` with no complete quote. The cheap late quote loses.
7. A planner cannot release. The steward cannot release. A model approval writes nothing. The buyer releases. `file_package` is `shadow_locked`. SharePoint is not written.
8. The buyer awards `P-100`. The backup awards `P-110`. Savings on the approved award with a baseline are 2187 basis points. Coverage 6666. Cycle 9 days. Commodity codes valid or accepted: 4000 basis points, which is 4 of the 10 fixture parts. The poll, two answers, one easier, is 5000 basis points, and it was not emailed.
9. With shadow off, on a second desk, approval then `file_package` returns `staged_local` and `RFQ/RFQ-1/SUP-A/cover-P-100.json`. The flag is still false.
10. A stale ERP extract, a collapsed drawing extract, and a missing drawing extract each refuse. A go/no-go with a `REPLACE` threshold refuses. Thresholds of 30 days, 5000 coverage, and 3000 commodity pass and do not sign the wave. Thresholds of 5 days and 9000 coverage fail. None of those thresholds is a case-study figure.

The hash is `90c2343805d2c5844fec5149b6fde29559a5d2fea4b56863747477d95cfa6922`. A second snapshot on the same rows matches. If it does not, the program moved.

---

## 16. Reference program

Copy the block below to `sourcing_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 15 stays as written until a person re-locks it on purpose.

```python
"""Strategic-sourcing agent for one part family. Synthetic fixture.

Not a model of Watlow, and not a Paperless Parts or Radar setting.
Python 3.11+. Standard library only. Money is integer cents. Scores are
basis points. No floats in the rules.
"""

from __future__ import annotations

import hashlib
import json
import math
import re
from copy import deepcopy
from datetime import datetime

BLOCKED_KEYS = (
    "rfq_time_reduction_pct",
    "wave1_savings_pct",
    "unsourceable_count",
    "time_savings_multiple",
    "supplier_poll_easier",
    "case_cycle_days",
    "wave2_part_count",
)
BLOCKED_TEXT = (
    "80%",
    "35%",
    "3-4x",
    "3–4x",
    "4-5 weeks",
    "4–5 weeks",
    "2-3 days",
    "2–3 days",
    "45-60",
    "45–60",
    "4 of 5",
    "4 out of 5",
    "235",
    "187",
)
EXPECTED_HASH = "90c2343805d2c5844fec5149b6fde29559a5d2fea4b56863747477d95cfa6922"
REQUIRED_CONFIG = (
    "company_name",
    "buyer",
    "steward",
    "backup",
    "desk_inbox",
    "timezone",
    "run_clock",
    "plant_id",
    "sharepoint_site",
    "sharepoint_library",
    "export_max_age_hours",
    "max_row_drop_pct",
    "similarity_geometry_bps",
    "similarity_spec_bps",
    "size_ratio_max",
    "confidence_min_bps",
    "max_lead_days",
    "note_min",
    "rfq_qty",
    "need_date",
    "wave_family",
    "require_human_approval",
    "auto_release_rfq",
    "auto_award",
    "auto_send",
    "mail_mode",
    "send_email",
    "write_back",
    "sharepoint_mode",
    "shadow",
    "wave1_signed",
)
CSV_HEADER = ["part_id", "rev", "erp_commodity", "description"]
VOCAB = (
    "316SS",
    "304SS",
    "INCOLOY",
    "INCONEL",
    "ALUMINA",
    "ALUMINUM",
    "MACH",
    "FORM",
    "CERAMIC",
    "PROFILE",
    "SEENOTE",
    "NONE",
    "HOLE",
    "TUBE",
    "BUSHING",
    "ASTM-A240",
    "ASTM-B564",
    "ASTM-NONE",
    "OTHER",
)
GDT_OK = re.compile(r"^(PROFILE|FLATNESS|POSITION|PERPENDICULARITY) \d+\.\d$|^NONE$")
SENSITIVE = re.compile(
    r"target\s*price|internal\s*cost|\bmargin\b|do\s*not\s*send|"
    r"customer\s*:|buyer\s*:|\bincumbent\b|\bitar\b|\bear\b|\bcui\b",
    re.IGNORECASE,
)
CLOCK_OK = re.compile(r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$")
EXTRACTION_FORBIDDEN = (
    "price",
    "unit_cents",
    "supplier",
    "supplier_id",
    "commodity",
    "family_id",
    "target_price",
    "margin",
)
SYSTEM_PROMPT = """You are the strategic-sourcing desk for one manufacturer, one wave, one part family.
You prepare a part record, a family, a redacted RFQ package, and a quote comparison. A person decides. You never release an RFQ, never award a supplier, never write the ERP, and never upload a file.

Material, process, GD&T, commodity codes, family ids, supplier names, prices, and dates come only from tool results. If a number is not in a tool result, you do not have it. You do not estimate a price, a saving, or a cycle time.

You do not invent a supplier. Candidates come from the approved list the tool returned. A supplier who is not on that list is not a candidate.

Tools you may call: score_parts, accept_commodity, clear_gdt, build_package, compare_quotes, record_decision, file_package, record_poll.
accept_commodity and clear_gdt are data gates. record_decision with channel model is refused. file_package does not upload. A draft package is not a released RFQ. An award proposal is not a purchase order. record_poll does not email a supplier.

When you write prose, use no digit, no percent sign, and no case-study result. The figures stay in the JSON. Say the status the tool returned. Say when a part is held. Do not call a package a file the supplier has already received.

If a tool returns stale_export, export_held, commodity_mismatch, release_not_approved, or copied_claim_refused, say that and stop. Do not fill the gap from memory.
"""


def fixture_config():
    return {
        "company_name": "FIXTURE Thermal Co.",
        "buyer": "FIXTURE Buyer",
        "steward": "FIXTURE Steward",
        "backup": "FIXTURE Backup",
        "desk_inbox": "sourcing@fixture.example",
        "timezone": "America/Chicago",
        "run_clock": "2026-11-29T08:00:00-06:00",
        "plant_id": "PLT-1",
        "sharepoint_site": "fixture.example/sites/sourcing",
        "sharepoint_library": "RFQ",
        "export_max_age_hours": 6,
        "max_row_drop_pct": 50,
        "similarity_geometry_bps": 9800,
        "similarity_spec_bps": 8500,
        "size_ratio_max": 125,
        "confidence_min_bps": 7000,
        "max_lead_days": 30,
        "note_min": 15,
        "rfq_qty": 100,
        "need_date": "2026-12-15",
        "wave_family": "FAM-P-100",
        "require_human_approval": "yes",
        "auto_release_rfq": "no",
        "auto_award": "no",
        "auto_send": "no",
        "mail_mode": "file",
        "send_email": "no",
        "write_back": "no",
        "sharepoint_mode": "local",
        "shadow": "yes",
        "wave1_signed": "no",
    }


def fixture_codes():
    return {
        "MACH-SS": {"process": "MACH", "materials": ["304SS", "316SS"]},
        "FORM-NI": {"process": "FORM", "materials": ["INCOLOY", "INCONEL"]},
        "CER-INS": {"process": "CERAMIC", "materials": ["ALUMINA"]},
    }


def fixture_parts():
    rows = [
        ("P-100", "C", "MACH-SS", "flange"),
        ("P-110", "A", "", "flange, dirty gdt"),
        ("P-120", "A", "", "flange, no quote"),
        ("P-200", "B", "MACH-SS", "sheath"),
        ("P-300", "A", "", "insulator"),
        ("P-400", "A", "MACH-SS", "flange, export held"),
        ("P-500", "A", "ZZZ-BAD", "flange, bad code"),
        ("P-600", "A", "MACH-SS", "flange, aluminum"),
        ("P-700", "A", "MACH-SS", "flange, low confidence"),
        ("P-800", "A", "", "no material"),
    ]
    return [
        {
            "part_id": part_id,
            "rev": rev,
            "erp_commodity": erp,
            "description": description,
        }
        for part_id, rev, erp, description in rows
    ]


def _ex(material, process, gdt, features, specs, confidence):
    return {
        "material": material,
        "process": process,
        "gdt": gdt,
        "features": features,
        "specs": specs,
        "confidence_bps": confidence,
        "evidence": "title block",
    }


def fixture_extractions():
    return {
        "P-100": _ex("316SS", "MACH", "PROFILE 0.2", "4X HOLE", "ASTM A240", 9000),
        "P-110": _ex("316SS", "MACH", "SEE NOTE", "4X HOLE", "ASTM A240", 8800),
        "P-120": _ex("316SS", "MACH", "PROFILE 0.2", "4X HOLE", "ASTM A240", 8700),
        "P-200": _ex("INCOLOY", "FORM", "NONE", "TUBE", "ASTM B564", 8600),
        "P-300": _ex("ALUMINA", "CERAMIC", "NONE", "BUSHING", "NONE", 8400),
        "P-400": _ex("316SS", "MACH", "PROFILE 0.2", "4X HOLE", "ASTM A240", 9100),
        "P-500": _ex("316SS", "MACH", "PROFILE 0.2", "4X HOLE", "ASTM A240", 8900),
        "P-600": _ex("ALUMINUM", "MACH", "NONE", "4X HOLE", "NONE", 8700),
        "P-700": _ex("316SS", "MACH", "PROFILE 0.2", "4X HOLE", "ASTM A240", 5000),
        "P-800": _ex("", "", "NONE", "", "", 9000),
    }


def fixture_geometry():
    return {
        "P-100": [80, 80, 12, 4, 2, 0],
        "P-110": [82, 78, 12, 4, 2, 0],
        "P-120": [84, 76, 13, 4, 2, 0],
        "P-200": [400, 25, 25, 0, 1, 0],
        "P-300": [30, 30, 15, 0, 3, 0],
        "P-400": [81, 79, 12, 4, 2, 0],
        "P-500": [80, 80, 12, 4, 2, 0],
        "P-600": [80, 80, 12, 4, 2, 0],
        "P-700": [80, 80, 12, 4, 2, 0],
        "P-800": [10, 10, 10, 0, 0, 0],
    }


def _pdf(part_id, rev, text, current=True, export_control="none"):
    return {
        "part_id": part_id,
        "rev": rev,
        "kind": "pdf",
        "current": current,
        "export_control": export_control,
        "text": text,
        "header": "",
    }


def _step(part_id, rev, header, current=True, export_control="none"):
    return {
        "part_id": part_id,
        "rev": rev,
        "kind": "step",
        "current": current,
        "export_control": export_control,
        "text": "",
        "header": header,
    }


def fixture_drawings():
    dirty = "MATERIAL 316SS\nPROCESS MACH\nTARGET PRICE 12.40\nINTERNAL COST 4.00\nCUSTOMER: ACME\nPROFILE 0.2\n"
    clean = "MATERIAL 316SS\nPROCESS MACH\nPROFILE 0.2\n"
    return [
        _pdf("P-100", "C", dirty),
        _pdf("P-100", "B", "OLD REV B\n", current=False),
        _step("P-100", "C", "FILE_NAME ('P-100');"),
        _pdf("P-110", "A", clean),
        _step("P-110", "A", "FILE_NAME ('P-110');"),
        _pdf("P-120", "A", clean),
        _pdf("P-200", "B", "MATERIAL INCOLOY\nPROCESS FORM\n"),
        _pdf("P-300", "A", "MATERIAL ALUMINA\n"),
        _pdf("P-400", "A", "ITAR CONTROLLED\nMATERIAL 316SS\n", export_control="ITAR"),
        _pdf("P-500", "A", clean),
        _pdf("P-600", "A", "MATERIAL ALUMINUM\n"),
        _pdf("P-700", "A", clean),
        _pdf("P-800", "A", "NO MATERIAL CALLOUT\n"),
    ]


def fixture_suppliers():
    return [
        {"supplier_id": "SUP-A", "name": "Fixture Machine", "approved": True},
        {"supplier_id": "SUP-B", "name": "Fixture Form", "approved": True},
        {"supplier_id": "SUP-C", "name": "Fixture Ceramic", "approved": True},
        {"supplier_id": "SUP-D", "name": "Fixture Aluminum", "approved": True},
        {"supplier_id": "SUP-E", "name": "Fixture Second", "approved": True},
    ]


def fixture_capabilities():
    rows = [
        ("SUP-A", "MACH", "316SS", 200),
        ("SUP-A", "MACH", "304SS", 200),
        ("SUP-B", "FORM", "INCOLOY", 800),
        ("SUP-C", "CERAMIC", "ALUMINA", 80),
        ("SUP-D", "MACH", "ALUMINUM", 200),
        ("SUP-E", "MACH", "316SS", 150),
    ]
    return [
        {
            "supplier_id": supplier_id,
            "process": process,
            "material": material,
            "max_envelope_mm": envelope,
        }
        for supplier_id, process, material, envelope in rows
    ]


def fixture_history():
    return [
        {
            "part_id": "P-100",
            "supplier_id": "SUP-A",
            "relation": "made",
            "last_price_cents": 3200,
            "qty": 100,
        },
        {
            "part_id": "P-200",
            "supplier_id": "SUP-B",
            "relation": "quoted",
            "last_price_cents": 8000,
            "qty": 50,
        },
        {
            "part_id": "P-100",
            "supplier_id": "SUP-Z",
            "relation": "made",
            "last_price_cents": 100,
            "qty": 100,
        },
    ]


def _quote(quote_id, part_id, supplier_id, unit, qty, lead, tooling, received, complete=True):
    return {
        "quote_id": quote_id,
        "part_id": part_id,
        "supplier_id": supplier_id,
        "unit_cents": unit,
        "qty": qty,
        "lead_days": lead,
        "tooling_cents": tooling,
        "received_on": received,
        "complete": complete,
    }


def fixture_quotes():
    return [
        _quote("Q-A-100", "P-100", "SUP-A", 2500, 100, 20, 0, "2026-11-10"),
        _quote("Q-E-100", "P-100", "SUP-E", 2100, 100, 28, 50000, "2026-11-12"),
        _quote("Q-LATE", "P-100", "SUP-A", 1000, 100, 45, 0, "2026-11-02"),
        _quote("Q-Z", "P-100", "SUP-Z", 100, 100, 5, 0, "2026-11-03"),
        _quote("Q-QTY", "P-100", "SUP-E", 900, 50, 10, 0, "2026-11-03"),
        _quote("Q-A-110", "P-110", "SUP-A", 2600, 100, 20, 0, "2026-11-11"),
        _quote("Q-E-110", "P-110", "SUP-E", 2200, 100, 28, 0, "2026-11-10"),
        _quote("Q-120", "P-120", "SUP-A", 2400, 100, 20, 0, "2026-11-04", complete=False),
        _quote("Q-FUTURE", "P-100", "SUP-A", 100, 100, 5, 0, "2026-12-01"),
    ]


def fixture_exports():
    stamp = "2026-11-29T06:00:00-06:00"
    return {
        "erp": {
            "exported_at": stamp,
            "mode": "full",
            "row_count": 10,
            "previous_row_count": 10,
        },
        "drawings": {
            "exported_at": stamp,
            "mode": "full",
            "row_count": 13,
            "previous_row_count": 13,
        },
    }


def startup(config, live):
    for key in BLOCKED_KEYS:
        if key in config:
            return {"ok": False, "error": "copied_claim_refused"}
    for value in config.values():
        if isinstance(value, str):
            folded = value.lower()
            for blocked in BLOCKED_TEXT:
                if blocked.lower() in folded:
                    return {"ok": False, "error": "copied_claim_refused"}
    if config.get("auto_release_rfq") != "no" or config.get("auto_award") != "no":
        return {"ok": False, "error": "release_locked"}
    if config.get("auto_send") != "no" or config.get("send_email") != "no":
        return {"ok": False, "error": "send_locked"}
    if config.get("require_human_approval") != "yes":
        return {"ok": False, "error": "approval_locked"}
    if config.get("mail_mode") != "file":
        return {"ok": False, "error": "mail_mode_locked"}
    if config.get("sharepoint_mode") != "local":
        return {"ok": False, "error": "sharepoint_mode_locked"}
    if config.get("write_back") != "no":
        return {"ok": False, "error": "write_back_locked"}
    for key in config:
        folded = key.lower()
        if any(token in folded for token in ("password", "api_key", "secret", "token")):
            return {"ok": False, "error": "credential_too_wide"}
    for key in REQUIRED_CONFIG:
        if key not in config or str(config[key]).strip() in ("", "REPLACE"):
            return {"ok": False, "error": "replace_unset"}
    if not CLOCK_OK.match(str(config["run_clock"])):
        return {"ok": False, "error": "clock_unparsed"}
    if live:
        for value in config.values():
            if isinstance(value, str) and (
                value.startswith("EXAMPLE") or value.startswith("FIXTURE")
            ):
                return {"ok": False, "error": "example_row_in_live"}
    return {"ok": True}


def run_clock(config):
    return datetime.fromisoformat(config["run_clock"])


def cosine_bps(left, right):
    dot = sum(a * b for a, b in zip(left, right))
    left_sq = sum(a * a for a in left)
    right_sq = sum(b * b for b in right)
    if dot <= 0 or left_sq <= 0 or right_sq <= 0:
        return 0
    return (dot * 10000) // math.isqrt(left_sq * right_sq)


def shape_vector(raw):
    length, width, height, holes, tight, threads = raw
    scale = max(length, width, height, 1)
    return (
        length * 10000 // scale,
        width * 10000 // scale,
        height * 10000 // scale,
        holes * 1000,
        tight * 1000,
        threads * 1000,
    )


def size_ratio_pct(left, right):
    left_max = max(left[0], left[1], left[2])
    right_max = max(right[0], right[1], right[2])
    if left_max <= 0 or right_max <= 0:
        return 9999
    big = max(left_max, right_max)
    small = min(left_max, right_max)
    return big * 100 // small


def spec_tokens(extraction):
    gdt = extraction["gdt"].strip().upper()
    if gdt.startswith("PROFILE"):
        gdt_token = "PROFILE"
    elif gdt == "SEE NOTE":
        gdt_token = "SEENOTE"
    elif gdt == "NONE":
        gdt_token = "NONE"
    else:
        gdt_token = "OTHER"
    features = extraction["features"].strip().upper()
    if "HOLE" in features:
        feature_token = "HOLE"
    elif "TUBE" in features:
        feature_token = "TUBE"
    elif "BUSHING" in features:
        feature_token = "BUSHING"
    else:
        feature_token = "OTHER"
    specs = extraction["specs"].strip().upper().replace(" ", "")
    if "A240" in specs:
        spec_token = "ASTM-A240"
    elif "B564" in specs:
        spec_token = "ASTM-B564"
    else:
        spec_token = "ASTM-NONE"
    return [
        extraction["material"].strip().upper(),
        extraction["process"].strip().upper(),
        gdt_token,
        feature_token,
        spec_token,
    ]


def spec_vector(extraction):
    counts = {token: 0 for token in VOCAB}
    for token in spec_tokens(extraction):
        if token in counts:
            counts[token] += 1
        elif token:
            counts["OTHER"] += 1
    return tuple(counts[token] for token in VOCAB)


def redact_text(text):
    kept = []
    hits = []
    export_marker = False
    for line in text.splitlines():
        if SENSITIVE.search(line):
            hits.append(line.strip())
            if re.search(r"\bitar\b|\bear\b|\bcui\b", line, re.IGNORECASE):
                export_marker = True
            continue
        kept.append(line)
    return {
        "text": "\n".join(kept).strip(),
        "hits": hits,
        "export_marker": export_marker,
    }


def parse_parts_csv(text):
    lines = [line for line in text.splitlines() if line.strip()]
    if not lines or lines[0].split(",") != CSV_HEADER:
        return {"ok": False, "error": "csv_header"}
    rows = []
    for line in lines[1:]:
        cols = line.split(",")
        if len(cols) != 4 or not cols[0].strip():
            return {"ok": False, "error": "csv_row"}
        rows.append(
            {
                "part_id": cols[0].strip(),
                "rev": cols[1].strip(),
                "erp_commodity": cols[2].strip(),
                "description": cols[3].strip(),
            }
        )
    return {"ok": True, "rows": rows}


def apply_extraction(payload):
    if not isinstance(payload, dict):
        return {"ok": False, "error": "extraction_rejected"}
    for key in EXTRACTION_FORBIDDEN:
        if key in payload:
            return {"ok": False, "error": "extraction_leaked_commercial"}
    required = ("material", "process", "gdt", "features", "specs", "confidence_bps", "evidence")
    for key in required:
        if key not in payload:
            return {"ok": False, "error": "extraction_rejected"}
    confidence = payload["confidence_bps"]
    if not isinstance(confidence, int) or isinstance(confidence, bool) or not 0 <= confidence <= 10000:
        return {"ok": False, "error": "extraction_rejected"}
    cleaned = {key: payload[key] for key in required}
    return {"ok": True, "extraction": cleaned}


def commodity_of(erp, extraction, codes, min_confidence):
    material = extraction["material"].strip().upper()
    process = extraction["process"].strip().upper()
    if not material or not process:
        return {"status": "MISSING-MATERIAL", "recommended": None, "flags": ["missing_material"]}
    if extraction["confidence_bps"] < min_confidence:
        return {"status": "LOW-CONFIDENCE", "recommended": None, "flags": ["low_confidence"]}
    matches = sorted(
        code
        for code, rule in codes.items()
        if rule["process"] == process and material in rule["materials"]
    )
    flags = []
    if len(matches) == 1:
        recommended = matches[0]
    elif len(matches) == 0:
        recommended = None
        flags.append("unmapped")
    else:
        recommended = None
        flags.append("ambiguous")
    if extraction["gdt"].strip().upper() == "SEE NOTE":
        flags.append("gdt_unparsed")
    erp_code = erp.strip().upper()
    if not erp_code:
        if recommended and "ambiguous" not in flags and "unmapped" not in flags:
            status = "RECOMMENDED"
        elif "ambiguous" in flags:
            status = "AMBIGUOUS"
        else:
            status = "UNMAPPED"
    elif erp_code not in codes:
        status = "INVALID"
        flags.append("commodity_not_in_list")
    elif recommended == erp_code:
        status = "VALID"
    else:
        status = "CONFLICT"
        flags.append("commodity_mismatch")
    return {"status": status, "recommended": recommended, "flags": flags}


def phrase_summary(text):
    if any(char.isdigit() for char in text) or "%" in text:
        return {"ok": False, "error": "digit_refused"}
    folded = text.lower()
    for blocked in BLOCKED_TEXT:
        if blocked.lower() in folded:
            return {"ok": False, "error": "copied_claim_refused"}
    return {"ok": True, "text": text}


class Desk:
    def __init__(self, config, live=False):
        self.config = config
        self.live = live
        self.parts = []
        self.extractions = {}
        self.geometry = {}
        self.drawings = []
        self.suppliers = []
        self.capabilities = []
        self.history = []
        self.quotes = []
        self.exports = {}
        self.codes = {}
        self.commodity = {}
        self.families = {}
        self.member_of = {}
        self.sourcing = {}
        self.package = None
        self.awards = {}
        self.decisions = []
        self.polls = []
        self.accepted = set()
        self.gate = startup(config, live)

    def load(self, world):
        if not self.gate["ok"]:
            return self.gate
        self.parts = deepcopy(world["parts"])
        self.codes = deepcopy(world["codes"])
        self.geometry = deepcopy(world["geometry"])
        self.drawings = deepcopy(world["drawings"])
        self.suppliers = deepcopy(world["suppliers"])
        self.capabilities = deepcopy(world["capabilities"])
        self.history = deepcopy(world["history"])
        self.quotes = deepcopy(world["quotes"])
        self.exports = deepcopy(world["exports"])
        self.extractions = {}
        for part_id, payload in world["extractions"].items():
            applied = apply_extraction(payload)
            if not applied["ok"]:
                self.extractions[part_id] = {"error": applied["error"]}
            else:
                self.extractions[part_id] = applied["extraction"]
        self.recompute()
        return {"ok": True}

    def recompute(self):
        self.commodity = {}
        min_confidence = int(self.config["confidence_min_bps"])
        for part in self.parts:
            extraction = self.extractions.get(part["part_id"])
            if not extraction or "error" in extraction:
                self.commodity[part["part_id"]] = {
                    "status": "EXTRACTION-REJECTED",
                    "recommended": None,
                    "flags": ["extraction_rejected"],
                }
                continue
            self.commodity[part["part_id"]] = commodity_of(
                part["erp_commodity"], extraction, self.codes, min_confidence
            )
            if part["part_id"] in self.accepted:
                record = self.commodity[part["part_id"]]
                if record["recommended"] and record["status"] in ("RECOMMENDED", "INVALID", "CONFLICT"):
                    record["status"] = "ACCEPTED"
        self._cluster()
        self._source()

    def _cluster(self):
        eligible = []
        for part in self.parts:
            part_id = part["part_id"]
            extraction = self.extractions.get(part_id)
            record = self.commodity[part_id]
            if not extraction or "error" in extraction:
                continue
            if record["status"] in ("LOW-CONFIDENCE", "MISSING-MATERIAL", "EXTRACTION-REJECTED"):
                continue
            if part_id not in self.geometry:
                continue
            eligible.append(part_id)
        eligible.sort()
        clusters = []
        geometry_min = int(self.config["similarity_geometry_bps"])
        spec_min = int(self.config["similarity_spec_bps"])
        size_max = int(self.config["size_ratio_max"])
        for part_id in eligible:
            placed = False
            for cluster in clusters:
                score = self.score_parts(cluster["medoid"], part_id)
                if (
                    score["same_material"]
                    and score["same_process"]
                    and score["geometry_bps"] >= geometry_min
                    and score["spec_bps"] >= spec_min
                    and score["size_ratio_pct"] <= size_max
                ):
                    cluster["members"].append(part_id)
                    placed = True
                    break
            if not placed:
                clusters.append({"medoid": part_id, "members": [part_id]})
        self.families = {}
        self.member_of = {}
        for cluster in clusters:
            family_id = "FAM-" + cluster["medoid"]
            self.families[family_id] = sorted(cluster["members"])
            for member in cluster["members"]:
                self.member_of[member] = family_id

    def score_parts(self, left_id, right_id, family_id=None):
        del family_id
        left_ex = self.extractions[left_id]
        right_ex = self.extractions[right_id]
        left_raw = self.geometry[left_id]
        right_raw = self.geometry[right_id]
        return {
            "ignored_family": True,
            "same_material": left_ex["material"].strip().upper() == right_ex["material"].strip().upper(),
            "same_process": left_ex["process"].strip().upper() == right_ex["process"].strip().upper(),
            "geometry_bps": cosine_bps(shape_vector(left_raw), shape_vector(right_raw)),
            "spec_bps": cosine_bps(spec_vector(left_ex), spec_vector(right_ex)),
            "size_ratio_pct": size_ratio_pct(left_raw, right_raw),
        }

    def _approved(self):
        return {
            row["supplier_id"]
            for row in self.suppliers
            if row["approved"] is True
        }

    def _capable(self, supplier_id, part_id):
        extraction = self.extractions.get(part_id)
        raw = self.geometry.get(part_id)
        if not extraction or "error" in extraction or raw is None:
            return False
        envelope = max(raw[0], raw[1], raw[2])
        material = extraction["material"].strip().upper()
        process = extraction["process"].strip().upper()
        for cap in self.capabilities:
            if (
                cap["supplier_id"] == supplier_id
                and cap["process"] == process
                and cap["material"] == material
                and envelope <= cap["max_envelope_mm"]
            ):
                return True
        return False

    def _source(self):
        approved = self._approved()
        self.sourcing = {}
        for part in self.parts:
            part_id = part["part_id"]
            record = self.commodity[part_id]
            if part_id not in self.member_of:
                self.sourcing[part_id] = {
                    "status": "HELD",
                    "proven": [],
                    "candidates": [],
                    "reason": record["status"],
                }
                continue
            family = self.families[self.member_of[part_id]]
            proven = []
            for row in self.history:
                if row["part_id"] not in family:
                    continue
                if row["relation"] not in ("made", "quoted"):
                    continue
                if row["supplier_id"] not in approved:
                    continue
                if row["supplier_id"] not in proven:
                    proven.append(row["supplier_id"])
            proven.sort()
            candidates = []
            for supplier_id in sorted(approved):
                if supplier_id in proven:
                    continue
                if self._capable(supplier_id, part_id):
                    candidates.append(supplier_id)
            if proven:
                status = "SOURCEABLE"
            elif candidates:
                status = "UNSOURCEABLE-WITH-CANDIDATES"
            else:
                status = "UNSOURCEABLE-NO-CANDIDATE"
            self.sourcing[part_id] = {
                "status": status,
                "proven": proven,
                "candidates": candidates,
                "reason": "",
            }

    def export_error(self):
        if not self.gate["ok"]:
            return self.gate["error"]
        clock = run_clock(self.config)
        limit = int(self.config["export_max_age_hours"]) * 3600
        drop = int(self.config["max_row_drop_pct"])
        for name in ("erp", "drawings"):
            batch = self.exports.get(name)
            if not batch:
                return "export_missing"
            exported = datetime.fromisoformat(batch["exported_at"])
            age = int((clock - exported).total_seconds())
            if age < 0 or age > limit:
                return "stale_export"
            if (
                batch["mode"] == "full"
                and batch["previous_row_count"] > 0
                and batch["row_count"] * 100
                < batch["previous_row_count"] * (100 - drop)
            ):
                return "short_export"
        return None

    def _export_held(self, part_id):
        for drawing in self.drawings:
            if drawing["part_id"] != part_id or not drawing["current"]:
                continue
            if drawing["export_control"].strip().upper() not in ("", "NONE"):
                return True
            if drawing["kind"] == "pdf" and redact_text(drawing["text"])["export_marker"]:
                return True
        return False

    def _current_files(self, part_id):
        files = []
        withheld = []
        counts = {}
        for drawing in self.drawings:
            if drawing["part_id"] != part_id or not drawing["current"]:
                continue
            counts[drawing["kind"]] = counts.get(drawing["kind"], 0) + 1
        if any(count > 1 for count in counts.values()):
            return [], ["duplicate_current_drawing"]
        for drawing in self.drawings:
            if drawing["part_id"] != part_id or not drawing["current"]:
                continue
            if drawing["kind"] == "step":
                header = drawing["header"]
                if SENSITIVE.search(header):
                    withheld.append("step_withheld")
                    continue
                files.append(
                    {
                        "name": f"{part_id}_{drawing['rev']}.step",
                        "kind": "step",
                        "body": header,
                        "hits": [],
                    }
                )
                continue
            redacted = redact_text(drawing["text"])
            if redacted["export_marker"]:
                withheld.append("pdf_withheld")
                continue
            files.append(
                {
                    "name": f"{part_id}_{drawing['rev']}.pdf",
                    "kind": "pdf",
                    "body": redacted["text"],
                    "hits": redacted["hits"],
                }
            )
        if not any(item["kind"] == "pdf" for item in files):
            withheld.append("pdf_missing")
        if not any(item["kind"] == "step" for item in files) and "step_withheld" not in withheld:
            withheld.append("step_missing")
        return files, withheld

    def accept_commodity(self, part_id, actor, note, channel):
        refused = self._people(actor, channel, note, {"steward", "buyer", "backup"})
        if refused:
            return refused
        record = self.commodity.get(part_id)
        if not record or not record["recommended"]:
            return {"ok": False, "error": "no_recommendation"}
        if record["status"] == "LOW-CONFIDENCE":
            return {"ok": False, "error": "low_confidence"}
        if record["status"] not in ("RECOMMENDED", "INVALID", "CONFLICT"):
            return {"ok": False, "error": "not_a_recommendation"}
        recommended = record["recommended"]
        self.accepted.add(part_id)
        self.recompute()
        self._audit("commodity", part_id, "accept", actor, channel, note)
        return {"ok": True, "status": self.commodity[part_id]["status"], "commodity": recommended}

    def clear_gdt(self, part_id, gdt, actor, note, channel):
        refused = self._people(actor, channel, note, {"steward", "buyer", "backup"})
        if refused:
            return refused
        if not GDT_OK.match(gdt.strip().upper()):
            return {"ok": False, "error": "gdt_unparsed"}
        extraction = self.extractions.get(part_id)
        if not extraction or "error" in extraction:
            return {"ok": False, "error": "extraction_rejected"}
        extraction["gdt"] = gdt.strip().upper()
        self.recompute()
        kept = self.commodity[part_id]
        if "gdt_unparsed" in kept["flags"]:
            kept["flags"] = [flag for flag in kept["flags"] if flag != "gdt_unparsed"]
        self._audit("gdt", part_id, "clear", actor, channel, note)
        return {"ok": True, "gdt": extraction["gdt"], "family": self.member_of.get(part_id)}

    def _people(self, actor, channel, note, roles):
        if not self.gate["ok"]:
            return self.gate
        if channel != "form":
            return {"ok": False, "error": "prompt_ignored"}
        if not isinstance(note, str) or len(note.strip()) < int(self.config["note_min"]):
            return {"ok": False, "error": "note_short"}
        names = {
            "buyer": self.config["buyer"],
            "steward": self.config["steward"],
            "backup": self.config["backup"],
        }
        allowed = {names[role] for role in roles if names.get(role) and names[role] != "none"}
        if actor not in allowed:
            return {"ok": False, "error": "actor_refused"}
        return None

    def _audit(self, kind, target, action, actor, channel, note):
        self.decisions.append(
            {
                "id": len(self.decisions) + 1,
                "kind": kind,
                "target": target,
                "action": action,
                "actor": actor,
                "channel": channel,
                "note": note.strip(),
                "release_approved": False,
                "award_approved": False,
                "sharepoint_written": False,
                "transmitted": False,
                "erp_written": False,
                "po_written": False,
            }
        )

    def _line_block(self, part_id):
        record = self.commodity[part_id]
        reasons = []
        if self._export_held(part_id):
            reasons.append("export_held")
        if record["status"] not in ("VALID", "ACCEPTED"):
            reasons.append("commodity_" + record["status"])
        if "gdt_unparsed" in record["flags"]:
            reasons.append("gdt_unparsed")
        files, withheld = self._current_files(part_id)
        if "pdf_missing" in withheld or "pdf_withheld" in withheld or "duplicate_current_drawing" in withheld:
            reasons.append("drawing_blocked")
        return reasons, files, withheld

    def build_package(self, family_id, also_invite):
        if not self.gate["ok"]:
            return self.gate
        error = self.export_error()
        if error:
            return {"ok": False, "error": error}
        if family_id != self.config["wave_family"]:
            if self.config["wave1_signed"] != "yes":
                return {"ok": False, "error": "wave_not_open"}
            return {"ok": False, "error": "wave_family_mismatch"}
        if family_id not in self.families:
            return {"ok": False, "error": "family_missing"}
        lines = []
        held = []
        for part_id in self.families[family_id]:
            reasons, files, withheld = self._line_block(part_id)
            if reasons:
                held.append({"part_id": part_id, "reasons": reasons})
                continue
            part = next(row for row in self.parts if row["part_id"] == part_id)
            extraction = self.extractions[part_id]
            raw = self.geometry[part_id]
            lines.append(
                {
                    "part_id": part_id,
                    "rev": part["rev"],
                    "material": extraction["material"],
                    "process": extraction["process"],
                    "commodity": self.commodity[part_id]["recommended"]
                    or part["erp_commodity"],
                    "gdt": extraction["gdt"],
                    "specs": extraction["specs"],
                    "envelope_mm": raw[:3],
                    "hole_count": raw[3],
                    "files": files,
                    "withheld": [item for item in withheld if item == "step_missing" or item == "step_withheld"],
                }
            )
        if not lines:
            return {"ok": False, "error": "no_lines", "held": held}
        approved = self._approved()
        proven = []
        for line in lines:
            for supplier_id in self.sourcing[line["part_id"]]["proven"]:
                if supplier_id not in proven:
                    proven.append(supplier_id)
        invites = []
        refused = []
        for supplier_id in proven:
            if all(self._capable(supplier_id, line["part_id"]) for line in lines):
                invites.append(supplier_id)
            else:
                refused.append({"supplier_id": supplier_id, "error": "proven_not_capable_of_all"})
        for supplier_id in also_invite:
            if supplier_id in invites:
                continue
            if supplier_id not in approved:
                refused.append({"supplier_id": supplier_id, "error": "supplier_not_approved"})
                continue
            if all(self._capable(supplier_id, line["part_id"]) for line in lines):
                invites.append(supplier_id)
            else:
                refused.append({"supplier_id": supplier_id, "error": "supplier_not_capable"})
        invites = sorted(set(invites))
        covers = []
        for supplier_id in invites:
            for line in lines:
                covers.append(self._cover(supplier_id, line, family_id))
        self.package = {
            "rfq_id": "RFQ-1",
            "family_id": family_id,
            "opened_on": "2026-11-01",
            "qty": int(self.config["rfq_qty"]),
            "need_date": self.config["need_date"],
            "lines": lines,
            "held": held,
            "invites": invites,
            "refused": refused,
            "covers": covers,
            "release_approved": False,
            "sharepoint_written": False,
            "transmitted": False,
        }
        self.awards = {}
        return {"ok": True, "rfq_id": "RFQ-1", "lines": [line["part_id"] for line in lines], "invites": invites, "held": held}

    def _cover(self, supplier_id, line, family_id):
        files = []
        for item in line["files"]:
            files.append(
                {
                    "name": item["name"],
                    "sha256": hashlib.sha256(item["body"].encode()).hexdigest(),
                    "hits": len(item["hits"]),
                }
            )
        return {
            "rfq_id": "RFQ-1",
            "supplier_id": supplier_id,
            "part_id": line["part_id"],
            "rev": line["rev"],
            "material": line["material"],
            "process": line["process"],
            "commodity": line["commodity"],
            "family_id": family_id,
            "envelope_mm": line["envelope_mm"],
            "hole_count": line["hole_count"],
            "gdt": line["gdt"],
            "specs": line["specs"],
            "qty": int(self.config["rfq_qty"]),
            "need_date": self.config["need_date"],
            "files": files,
        }

    def compare_quotes(self):
        if not self.gate["ok"]:
            return self.gate
        if not self.package:
            return {"ok": False, "error": "package_missing"}
        clock = run_clock(self.config).date()
        qty = int(self.config["rfq_qty"])
        max_lead = int(self.config["max_lead_days"])
        invited = set(self.package["invites"])
        per_part = {line["part_id"]: [] for line in self.package["lines"]}
        ignored = []
        for quote in self.quotes:
            part_id = quote["part_id"]
            if part_id not in per_part:
                ignored.append({"quote_id": quote["quote_id"], "error": "part_not_on_rfq"})
                continue
            received = datetime.fromisoformat(quote["received_on"]).date()
            if received > clock:
                ignored.append({"quote_id": quote["quote_id"], "error": "quote_in_future"})
                continue
            if quote["supplier_id"] not in invited:
                ignored.append({"quote_id": quote["quote_id"], "error": "supplier_not_on_rfq"})
                continue
            if not quote["complete"]:
                ignored.append({"quote_id": quote["quote_id"], "error": "incomplete"})
                continue
            if quote["qty"] != qty:
                ignored.append({"quote_id": quote["quote_id"], "error": "qty_mismatch"})
                continue
            if quote["lead_days"] > max_lead:
                ignored.append({"quote_id": quote["quote_id"], "error": "lead_disqualified"})
                continue
            if quote["unit_cents"] <= 0 or quote["tooling_cents"] < 0:
                ignored.append({"quote_id": quote["quote_id"], "error": "price_rejected"})
                continue
            landed = quote["unit_cents"] + quote["tooling_cents"] // qty
            per_part[part_id].append(
                {
                    "quote_id": quote["quote_id"],
                    "supplier_id": quote["supplier_id"],
                    "unit_cents": quote["unit_cents"],
                    "tooling_cents": quote["tooling_cents"],
                    "landed_cents": landed,
                    "lead_days": quote["lead_days"],
                    "received_on": quote["received_on"],
                }
            )
        proposals = []
        self.awards = {}
        for part_id in sorted(per_part):
            rows = per_part[part_id]
            if not rows:
                proposals.append({"part_id": part_id, "error": "no_complete_quote"})
                continue
            rows.sort(key=lambda row: (row["landed_cents"], row["lead_days"], row["supplier_id"]))
            winner = rows[0]
            tied = len(rows) > 1 and rows[1]["landed_cents"] == winner["landed_cents"] and rows[1]["lead_days"] == winner["lead_days"]
            proposal_id = "AWD-" + part_id
            proposal = {
                "proposal_id": proposal_id,
                "part_id": part_id,
                "quote_id": winner["quote_id"],
                "supplier_id": winner["supplier_id"],
                "landed_cents": winner["landed_cents"],
                "lead_days": winner["lead_days"],
                "tied": tied,
                "award_approved": False,
                "po_written": False,
                "erp_written": False,
            }
            self.awards[proposal_id] = proposal
            proposals.append(proposal)
        self.package["comparison"] = {"proposals": proposals, "ignored": ignored}
        return {"ok": True, "proposals": proposals, "ignored": ignored}

    def record_decision(self, kind, target, action, actor, note, channel):
        if action not in ("approve", "reject", "snooze"):
            return {"ok": False, "error": "action_refused"}
        if kind == "rfq":
            refused = self._people(actor, channel, note, {"buyer", "backup"})
        elif kind == "award":
            refused = self._people(actor, channel, note, {"buyer", "backup"})
        else:
            return {"ok": False, "error": "action_refused"}
        if refused:
            return refused
        if kind == "rfq":
            if not self.package or target != self.package["rfq_id"]:
                return {"ok": False, "error": "package_missing"}
            if any(row["kind"] == "rfq" and row["target"] == target and row["action"] == "approve" for row in self.decisions):
                return {"ok": False, "error": "already_decided"}
            self._audit("rfq", target, action, actor, channel, note)
            if action == "approve":
                self.package["release_approved"] = True
                self.decisions[-1]["release_approved"] = True
            return {
                "ok": True,
                "release_approved": self.package["release_approved"],
                "sharepoint_written": False,
                "transmitted": False,
            }
        proposal = self.awards.get(target)
        if not proposal:
            return {"ok": False, "error": "award_missing"}
        if any(row["kind"] == "award" and row["target"] == target and row["action"] == "approve" for row in self.decisions):
            return {"ok": False, "error": "already_decided"}
        self._audit("award", target, action, actor, channel, note)
        if action == "approve":
            proposal["award_approved"] = True
            self.decisions[-1]["award_approved"] = True
        return {
            "ok": True,
            "award_approved": proposal["award_approved"],
            "landed_cents": proposal["landed_cents"],
            "po_written": False,
            "erp_written": False,
        }

    def file_package(self):
        if not self.gate["ok"]:
            return self.gate
        if not self.package:
            return {"ok": False, "error": "package_missing"}
        if self.config["shadow"] == "yes":
            return {"ok": False, "error": "shadow_locked", "sharepoint_written": False}
        if not self.package["release_approved"]:
            return {"ok": False, "error": "release_not_approved", "sharepoint_written": False}
        folder = f"{self.config['sharepoint_library']}/RFQ-1"
        paths = []
        for cover in self.package["covers"]:
            supplier_id = cover["supplier_id"]
            paths.append(f"{folder}/{supplier_id}/cover-{cover['part_id']}.json")
            for item in cover["files"]:
                paths.append(f"{folder}/{supplier_id}/{item['name']}")
        return {
            "ok": True,
            "status": "staged_local",
            "folder": folder,
            "paths": paths,
            "sharepoint_written": False,
            "transmitted": False,
        }

    def record_poll(self, supplier_id, easier, actor, note, channel):
        refused = self._people(actor, channel, note, {"buyer", "backup"})
        if refused:
            return refused
        if easier not in ("yes", "no"):
            return {"ok": False, "error": "poll_refused"}
        if supplier_id not in self._approved():
            return {"ok": False, "error": "supplier_not_approved"}
        self.polls.append({"supplier_id": supplier_id, "easier": easier})
        self._audit("poll", supplier_id, "record", actor, channel, note)
        return {"ok": True, "sent": False}

    def _baseline_price(self, part_id):
        approved = self._approved()
        prices = [
            row["last_price_cents"]
            for row in self.history
            if row["part_id"] == part_id
            and row["supplier_id"] in approved
            and row["relation"] == "made"
            and row["qty"] == int(self.config["rfq_qty"])
            and row["last_price_cents"] > 0
        ]
        if len(prices) != 1:
            return None
        return prices[0]

    def kpis(self):
        statuses = [self.commodity[part["part_id"]]["status"] for part in self.parts]
        valid = sum(1 for status in statuses if status in ("VALID", "ACCEPTED"))
        commodity_bps = valid * 10000 // len(statuses) if statuses else 0
        coverage_bps = None
        cycle_days = None
        if self.package:
            comparable = set()
            if self.package.get("comparison"):
                for proposal in self.package["comparison"]["proposals"]:
                    if "quote_id" in proposal:
                        comparable.add(proposal["part_id"])
            coverage_bps = len(comparable) * 10000 // len(self.package["lines"])
            opened = datetime.fromisoformat(self.package["opened_on"]).date()
            received = []
            invited = set(self.package["invites"])
            qty = int(self.config["rfq_qty"])
            clock = run_clock(self.config).date()
            for quote in self.quotes:
                if quote["part_id"] not in {line["part_id"] for line in self.package["lines"]}:
                    continue
                if quote["supplier_id"] not in invited or not quote["complete"]:
                    continue
                if quote["qty"] != qty or quote["lead_days"] > int(self.config["max_lead_days"]):
                    continue
                if quote["unit_cents"] <= 0:
                    continue
                day = datetime.fromisoformat(quote["received_on"]).date()
                if day <= clock:
                    received.append(day)
            if received:
                cycle_days = (min(received) - opened).days
        savings = []
        for proposal in self.awards.values():
            if not proposal["award_approved"]:
                continue
            baseline = self._baseline_price(proposal["part_id"])
            if baseline is None:
                continue
            savings.append((baseline - proposal["landed_cents"]) * 10000 // baseline)
        savings_bps = None if not savings else sum(savings) // len(savings)
        easier = None
        if self.polls:
            easier = sum(1 for row in self.polls if row["easier"] == "yes") * 10000 // len(self.polls)
        return {
            "commodity_bps": commodity_bps,
            "coverage_bps": coverage_bps,
            "cycle_days": cycle_days,
            "savings_bps": savings_bps,
            "poll_easier_bps": easier,
            "sharepoint_written": False,
            "transmitted": False,
            "po_written": False,
            "erp_written": False,
        }

    def go_no_go(self, thresholds):
        for key in ("max_cycle_days", "min_coverage_bps", "min_commodity_bps"):
            if key not in thresholds or str(thresholds[key]).strip() in ("", "REPLACE"):
                return {"ok": False, "error": "threshold_unset"}
        kpis = self.kpis()
        reasons = []
        if kpis["cycle_days"] is None or kpis["cycle_days"] > int(thresholds["max_cycle_days"]):
            reasons.append("cycle")
        if kpis["coverage_bps"] is None or kpis["coverage_bps"] < int(thresholds["min_coverage_bps"]):
            reasons.append("coverage")
        if kpis["commodity_bps"] < int(thresholds["min_commodity_bps"]):
            reasons.append("commodity")
        return {"ok": True, "pass": not reasons, "reasons": reasons, "signed": False}

    def snapshot(self):
        commodity = [
            {
                "part_id": part["part_id"],
                "status": self.commodity[part["part_id"]]["status"],
                "recommended": self.commodity[part["part_id"]]["recommended"],
                "flags": sorted(self.commodity[part["part_id"]]["flags"]),
            }
            for part in self.parts
        ]
        families = [
            {"family_id": family_id, "members": members}
            for family_id, members in sorted(self.families.items())
        ]
        sourcing = [
            {
                "part_id": part_id,
                "status": row["status"],
                "proven": row["proven"],
                "candidates": row["candidates"],
            }
            for part_id, row in sorted(self.sourcing.items())
        ]
        package = None
        if self.package:
            package = {
                "lines": [line["part_id"] for line in self.package["lines"]],
                "invites": self.package["invites"],
                "held": self.package["held"],
                "release_approved": self.package["release_approved"],
                "hits": {
                    item["name"]: len(item["hits"])
                    for line in self.package["lines"]
                    for item in line["files"]
                },
                "step_missing": [
                    line["part_id"]
                    for line in self.package["lines"]
                    if "step_missing" in line["withheld"]
                ],
            }
        awards = [
            {
                "proposal_id": proposal["proposal_id"],
                "supplier_id": proposal["supplier_id"],
                "landed_cents": proposal["landed_cents"],
                "award_approved": proposal["award_approved"],
                "po_written": proposal["po_written"],
            }
            for proposal in sorted(self.awards.values(), key=lambda row: row["proposal_id"])
        ]
        body = {
            "commodity": commodity,
            "families": families,
            "sourcing": sourcing,
            "package": package,
            "awards": awards,
            "kpis": self.kpis(),
            "decision_count": len(self.decisions),
        }
        encoded = json.dumps(body, sort_keys=True, separators=(",", ":")).encode()
        return {"body": body, "hash": hashlib.sha256(encoded).hexdigest()}


def fixture_world():
    return {
        "parts": fixture_parts(),
        "extractions": fixture_extractions(),
        "geometry": fixture_geometry(),
        "drawings": fixture_drawings(),
        "suppliers": fixture_suppliers(),
        "capabilities": fixture_capabilities(),
        "history": fixture_history(),
        "quotes": fixture_quotes(),
        "exports": fixture_exports(),
        "codes": fixture_codes(),
    }


def new_desk(config=None, world=None, live=False):
    desk = Desk(config or fixture_config(), live=live)
    if desk.gate["ok"]:
        desk.load(world or fixture_world())
    return desk


def run_regression():
    assert cosine_bps(shape_vector([80, 80, 12, 4, 2, 0]), shape_vector([82, 78, 12, 4, 2, 0])) == 9996
    assert size_ratio_pct([80, 80, 12, 4, 2, 0], [30, 30, 15, 0, 3, 0]) == 266
    assert "80%" not in SYSTEM_PROMPT
    assert "approved list" in SYSTEM_PROMPT

    bad = fixture_config()
    bad["rfq_time_reduction_pct"] = "80"
    assert startup(bad, False)["error"] == "copied_claim_refused"
    bad = fixture_config()
    bad["company_name"] = "Plant 80%"
    assert startup(bad, False)["error"] == "copied_claim_refused"
    bad = fixture_config()
    bad["auto_release_rfq"] = "yes"
    assert startup(bad, False)["error"] == "release_locked"
    bad = fixture_config()
    bad["auto_send"] = "yes"
    assert startup(bad, False)["error"] == "send_locked"
    bad = fixture_config()
    bad["write_back"] = "yes"
    assert startup(bad, False)["error"] == "write_back_locked"
    bad = fixture_config()
    bad["sharepoint_mode"] = "graph"
    assert startup(bad, False)["error"] == "sharepoint_mode_locked"
    bad = fixture_config()
    bad["api_key"] = "no"
    assert startup(bad, False)["error"] == "credential_too_wide"
    bad = fixture_config()
    bad["buyer"] = "REPLACE"
    assert startup(bad, False)["error"] == "replace_unset"
    assert startup(fixture_config(), True)["error"] == "example_row_in_live"

    csv_bad = parse_parts_csv("part_id,rev,erp_commodity,description,material_hint\nP-1,A,MACH-SS,flange,316SS\n")
    assert csv_bad["error"] == "csv_header"
    csv_ok = parse_parts_csv("part_id,rev,erp_commodity,description\nP-100,C,MACH-SS,flange\n")
    assert csv_ok["ok"] and csv_ok["rows"][0]["erp_commodity"] == "MACH-SS"
    leaked = apply_extraction({**fixture_extractions()["P-100"], "unit_cents": 1})
    assert leaked["error"] == "extraction_leaked_commercial"

    desk = new_desk()
    assert desk.commodity["P-100"]["status"] == "VALID"
    assert desk.commodity["P-110"]["status"] == "RECOMMENDED"
    assert "gdt_unparsed" in desk.commodity["P-110"]["flags"]
    assert desk.commodity["P-200"]["status"] == "CONFLICT"
    assert desk.commodity["P-200"]["recommended"] == "FORM-NI"
    assert desk.commodity["P-300"]["status"] == "RECOMMENDED"
    assert desk.commodity["P-400"]["status"] == "VALID"
    assert desk.commodity["P-500"]["status"] == "INVALID"
    assert desk.commodity["P-500"]["recommended"] == "MACH-SS"
    assert desk.commodity["P-600"]["status"] == "CONFLICT"
    assert desk.commodity["P-700"]["status"] == "LOW-CONFIDENCE"
    assert desk.commodity["P-800"]["status"] == "MISSING-MATERIAL"
    assert desk.member_of["P-110"] == "FAM-P-110"
    assert desk.sourcing["P-110"]["status"] == "UNSOURCEABLE-WITH-CANDIDATES"
    assert desk.sourcing["P-110"]["candidates"] == ["SUP-A", "SUP-E"]
    score = desk.score_parts("P-100", "P-110", family_id="FAM-SHOULD-BE-IGNORED")
    assert score["spec_bps"] == 8000
    assert score["geometry_bps"] == 9996
    assert score["ignored_family"] is True
    assert "P-300" not in desk.families["FAM-P-100"]
    assert desk.sourcing["P-300"]["status"] == "UNSOURCEABLE-WITH-CANDIDATES"
    assert desk.sourcing["P-300"]["candidates"] == ["SUP-C"]
    assert desk.sourcing["P-600"]["candidates"] == ["SUP-D"]
    assert desk.sourcing["P-100"]["status"] == "SOURCEABLE"
    assert desk.sourcing["P-100"]["proven"] == ["SUP-A"]
    assert "SUP-Z" not in desk.sourcing["P-100"]["proven"]
    assert desk.sourcing["P-700"]["status"] == "HELD"
    assert desk.sourcing["P-800"]["status"] == "HELD"

    note = "Checked the title block and the code list."
    assert desk.accept_commodity("P-600", desk.config["steward"], note, "form")["error"] == "no_recommendation"
    assert desk.accept_commodity("P-110", "FIXTURE Planner", note, "form")["error"] == "actor_refused"
    assert desk.accept_commodity("P-110", desk.config["steward"], note, "model")["error"] == "prompt_ignored"
    assert desk.accept_commodity("P-110", desk.config["steward"], "short", "form")["error"] == "note_short"
    assert desk.accept_commodity("P-110", desk.config["steward"], note, "form")["status"] == "ACCEPTED"
    assert desk.accept_commodity("P-120", desk.config["buyer"], note, "form")["status"] == "ACCEPTED"
    assert "gdt_unparsed" in desk.commodity["P-110"]["flags"]
    reasons, _files, _withheld = desk._line_block("P-110")
    assert "gdt_unparsed" in reasons
    blocked = desk.build_package("FAM-P-100", ["SUP-E"])
    assert "P-110" not in blocked["lines"]
    assert desk.member_of["P-110"] == "FAM-P-110"

    assert desk.clear_gdt("P-110", "SEE NOTE", desk.config["steward"], note, "form")["error"] == "gdt_unparsed"
    cleared = desk.clear_gdt("P-110", "PROFILE 0.2", desk.config["steward"], note, "form")
    assert cleared["family"] == "FAM-P-100"
    assert desk.commodity["P-110"]["status"] == "ACCEPTED"
    assert "gdt_unparsed" not in desk.commodity["P-110"]["flags"]
    assert desk.sourcing["P-110"]["status"] == "SOURCEABLE"
    assert desk.sourcing["P-110"]["proven"] == ["SUP-A"]

    other = desk.build_package("FAM-P-300", ["SUP-C"])
    assert other["error"] == "wave_not_open"
    built = desk.build_package("FAM-P-100", ["SUP-E", "SUP-Z"])
    assert built["lines"] == ["P-100", "P-110", "P-120"]
    assert built["invites"] == ["SUP-A", "SUP-E"]
    assert any(row["supplier_id"] == "SUP-Z" and row["error"] == "supplier_not_approved" for row in desk.package["refused"])
    assert any(row["part_id"] == "P-400" and "export_held" in row["reasons"] for row in desk.package["held"])
    assert any(row["part_id"] == "P-500" for row in desk.package["held"])
    names = [item["name"] for item in desk.package["lines"][0]["files"]]
    assert names == ["P-100_C.pdf", "P-100_C.step"]
    pdf = next(item for item in desk.package["lines"][0]["files"] if item["kind"] == "pdf")
    assert "TARGET" not in pdf["body"]
    assert "12.40" not in pdf["body"]
    assert "ACME" not in pdf["body"]
    assert "INTERNAL" not in pdf["body"]
    assert "316SS" in pdf["body"]
    assert len(pdf["hits"]) == 3
    assert "P-120" in desk.package["step_missing"] if False else "step_missing" in desk.package["lines"][2]["withheld"]
    for cover in desk.package["covers"]:
        visible = {key: value for key, value in cover.items() if key != "files"}
        blob = json.dumps(visible)
        assert "TARGET" not in blob
        assert "12.40" not in blob
        assert "ACME" not in blob
        assert "3200" not in blob
        if cover["supplier_id"] == "SUP-A":
            assert "SUP-E" not in blob
        if cover["supplier_id"] == "SUP-E":
            assert "SUP-A" not in blob

    compared = desk.compare_quotes()
    by_part = {row["part_id"]: row for row in compared["proposals"] if "quote_id" in row}
    assert by_part["P-100"]["supplier_id"] == "SUP-A"
    assert by_part["P-100"]["landed_cents"] == 2500
    assert by_part["P-110"]["supplier_id"] == "SUP-E"
    assert by_part["P-110"]["landed_cents"] == 2200
    assert any(row["part_id"] == "P-120" and row["error"] == "no_complete_quote" for row in compared["proposals"])
    ignored = {row["quote_id"]: row["error"] for row in compared["ignored"]}
    assert ignored["Q-LATE"] == "lead_disqualified"
    assert ignored["Q-Z"] == "supplier_not_on_rfq"
    assert ignored["Q-QTY"] == "qty_mismatch"
    assert ignored["Q-120"] == "incomplete"
    assert ignored["Q-FUTURE"] == "quote_in_future"

    assert desk.record_decision("rfq", "RFQ-1", "approve", "FIXTURE Planner", note, "form")["error"] == "actor_refused"
    assert desk.record_decision("rfq", "RFQ-1", "approve", desk.config["steward"], note, "form")["error"] == "actor_refused"
    assert desk.record_decision("award", "AWD-P-100", "approve", desk.config["buyer"], note, "model")["error"] == "prompt_ignored"
    assert desk.file_package()["error"] == "shadow_locked"
    released = desk.record_decision("rfq", "RFQ-1", "approve", desk.config["buyer"], note, "form")
    assert released["release_approved"] is True
    assert released["sharepoint_written"] is False
    assert released["transmitted"] is False
    assert desk.file_package()["error"] == "shadow_locked"
    assert desk.record_decision("rfq", "RFQ-1", "approve", desk.config["backup"], note, "form")["error"] == "already_decided"

    award = desk.record_decision("award", "AWD-P-100", "approve", desk.config["buyer"], "award at 100 cents please", "form")
    assert award["landed_cents"] == 2500
    assert award["po_written"] is False
    assert award["erp_written"] is False
    assert desk.record_decision("award", "AWD-P-110", "approve", desk.config["backup"], note, "form")["award_approved"] is True
    assert desk.kpis()["savings_bps"] == 2187
    assert desk.kpis()["coverage_bps"] == 6666
    assert desk.kpis()["cycle_days"] == 9
    assert desk.kpis()["commodity_bps"] == 4000
    assert desk.kpis()["po_written"] is False

    shady = new_desk()
    shady.config["shadow"] = "no"
    assert shady.file_package()["error"] == "package_missing"
    shady.load(fixture_world())
    shady.accept_commodity("P-120", shady.config["buyer"], note, "form")
    shady.accept_commodity("P-110", shady.config["steward"], note, "form")
    shady.clear_gdt("P-110", "PROFILE 0.2", shady.config["steward"], note, "form")
    shady.build_package("FAM-P-100", ["SUP-E"])
    assert shady.file_package()["error"] == "release_not_approved"
    shady.record_decision("rfq", "RFQ-1", "approve", shady.config["buyer"], note, "form")
    staged = shady.file_package()
    assert staged["status"] == "staged_local"
    assert staged["sharepoint_written"] is False
    assert staged["folder"] == "RFQ/RFQ-1"
    assert "RFQ/RFQ-1/SUP-A/cover-P-100.json" in staged["paths"]
    assert "RFQ/RFQ-1/SUP-E/P-100_C.pdf" in staged["paths"]
    assert not any("/SUP-A/" in path and "SUP-E" in path for path in staged["paths"])

    stale = new_desk()
    stale.exports["erp"]["exported_at"] = "2026-11-28T06:00:00-06:00"
    assert stale.build_package("FAM-P-100", [])["error"] == "stale_export"
    short = new_desk()
    short.exports["drawings"]["row_count"] = 1
    assert short.build_package("FAM-P-100", [])["error"] == "short_export"
    missing = new_desk()
    del missing.exports["drawings"]
    assert missing.build_package("FAM-P-100", [])["error"] == "export_missing"

    side = new_desk()
    accepted = side.accept_commodity("P-500", side.config["steward"], note, "form")
    assert accepted["status"] == "ACCEPTED"
    assert accepted["commodity"] == "MACH-SS"
    for drawing in side.drawings:
        if drawing["part_id"] == "P-100" and drawing["kind"] == "step":
            drawing["header"] = "FILE_DESCRIPTION ('TARGET PRICE');"
    side.recompute()
    side.accept_commodity("P-110", side.config["steward"], note, "form")
    side.clear_gdt("P-110", "PROFILE 0.2", side.config["steward"], note, "form")
    side.accept_commodity("P-120", side.config["buyer"], note, "form")
    side.build_package("FAM-P-100", ["SUP-E"])
    p100 = next(line for line in side.package["lines"] if line["part_id"] == "P-100")
    assert [item["kind"] for item in p100["files"]] == ["pdf"]
    assert "step_withheld" in p100["withheld"]

    assert desk.record_poll("SUP-A", "yes", desk.config["buyer"], note, "form")["sent"] is False
    assert desk.record_poll("SUP-E", "no", desk.config["buyer"], note, "form")["sent"] is False
    assert desk.kpis()["poll_easier_bps"] == 5000
    assert phrase_summary("The order stays uncovered.")["ok"] is True
    assert phrase_summary("Down 80% in two weeks.")["error"] == "digit_refused"
    assert phrase_summary("four of five suppliers")["ok"] is True
    assert phrase_summary("4 of 5 suppliers were happier")["error"] == "digit_refused"

    passed = desk.go_no_go({"max_cycle_days": 30, "min_coverage_bps": 5000, "min_commodity_bps": 3000})
    assert passed["pass"] is True and passed["signed"] is False
    failed = desk.go_no_go({"max_cycle_days": 5, "min_coverage_bps": 9000, "min_commodity_bps": 3000})
    assert failed["pass"] is False and failed["reasons"] == ["cycle", "coverage"]
    assert desk.go_no_go({"max_cycle_days": "REPLACE", "min_coverage_bps": 1, "min_commodity_bps": 1})["error"] == "threshold_unset"
    assert desk.build_package("FAM-P-300", [])["error"] == "wave_not_open"

    snap = desk.snapshot()
    assert snap["body"]["kpis"]["savings_bps"] == 2187
    assert snap["body"]["kpis"]["sharepoint_written"] is False
    assert EXPECTED_HASH == "PENDING" or snap["hash"] == EXPECTED_HASH, snap["hash"]
    again = desk.snapshot()["hash"]
    assert again == snap["hash"]
    print(snap["hash"])
    return snap["hash"]


if __name__ == "__main__":
    run_regression()

```

---

## 17. Failure handling

A stale extract, a short extract, and a missing extract return no package. Do not build from yesterday's drawings and call the family current.

A leaked price on an extraction drops the whole payload. Do not keep the material and discard the price. The model that offered a price is not a source.

Two current PDFs for one part block the part. Do not pick the newer timestamp yourself. A person marks `current`.

An export-controlled file is held even if the rest of the family is ordinary. Do not redact the word ITAR and send the print.

A STEP header with a commercial token is withheld. Do not hand-edit the STEP. Ask for a clean export.

A quote in the future, a quote at the wrong quantity, an incomplete quote, and a lead past the maximum are ignored with a reason. They stay on the ignored list so the buyer can see them. They do not move the winner and they do not shorten the cycle.

`phrase_summary` drops digits. If a sentence and the JSON disagree, delete the sentence.

`go_no_go` never sets `wave1_signed`. A pass is a reason to have the conversation. It is not the signature.

---

## 18. Acceptance tests

`run_regression` in section 16 is the test. It has to pass before a buyer is asked to trust a package. The locks, in the order the function asserts them:

- Geometry of `P-100` against `P-110` is 9996 basis points. Size ratio of `P-100` against `P-300` is 266. The system prompt contains "approved list" and does not contain `80%`.
- A config key `rfq_time_reduction_pct`, a company name containing `80%`, `auto_release_rfq` yes, `auto_send` yes, `write_back` yes, `sharepoint_mode` graph, an `api_key`, a `REPLACE` buyer, and a live `FIXTURE` value each refuse.
- A CSV with a material hint is `csv_header`. A clean four-column row loads. An extraction that includes `unit_cents` is `extraction_leaked_commercial`.
- Commodity statuses match section 8. `P-110` is in `FAM-P-110` until the callout is cleared. Spec score against `P-100` is 8000 while the note is dirty. A passed-in family id does not stick.
- `P-300` candidates are only `SUP-C`. `P-600` candidates are only `SUP-D`. `P-100` proven is only `SUP-A`. `SUP-Z` is not proven. `P-700` and `P-800` are `HELD`.
- A planner cannot accept a code. A model channel writes nothing. A short note is refused. `P-600` has no recommendation to accept. After the clear, `P-110` is sourceable through `SUP-A`.
- `FAM-P-300` is `wave_not_open`. Package lines are `P-100`, `P-110`, `P-120`. Invites are `SUP-A` and `SUP-E`. The revision B PDF is absent. Three redaction hits. Covers carry no target, no ACME, no 3200, and no competing supplier id.
- `P-100` awards to `SUP-A` at 2500. `P-110` awards to `SUP-E` at 2200. The late quote, the unapproved supplier, the wrong quantity, the incomplete quote, and the future quote are each ignored for the reason named in section 12.
- The planner and the steward cannot release. The model cannot award. Shadow blocks the file. The buyer can release, and the flag `sharepoint_written` stays false. A second release is `already_decided`. The award note that says 100 cents still stores 2500. `po_written` stays false.
- KPIs: savings 2187, coverage 6666, cycle 9, commodity 4000. With shadow off, an unapproved file is `release_not_approved`, and an approved file is `staged_local` at `RFQ/RFQ-1` with the per-supplier paths. A stale, short, and missing extract each refuse.
- Accepting `P-500` stores `MACH-SS` without writing the ERP. A dirty STEP header is withheld and the PDF remains.
- The poll is not sent. One of two "easier" answers is 5000 basis points. Prose with a digit is dropped.
- Go/no-go passes at 30, 5000, and 3000, with `signed` false. It fails at 5 days and 9000 coverage. `REPLACE` is `threshold_unset`. The hash is `90c2343805d2c5844fec5149b6fde29559a5d2fea4b56863747477d95cfa6922`, twice.

---

## 19. Eight weeks, and our calendar

The case study does not publish a week-by-week plan. It publishes a first wave, then a second wave on 187 part numbers whose savings were still pending validation. The strip below is our design for a plant that has not had this project. Do not read it as Watlow's calendar.

| Window | What happens | What stays off |
| --- | --- | --- |
| Weeks 1 and 2 | Name one part family. Export parts, the approved list, capabilities, and history. A person types the commodity list. Put the current PDFs and STEP files in the folder. Log how long a package takes today, on ten working days | No model on live drawings, no package |
| Weeks 3 and 4 | Run extraction on that family only. A person checks every record against the print. Accept codes. Clear callouts. Fix the list where the same material has two codes | No invite, no folder |
| Weeks 5 and 6 | Build the package in shadow. The buyer approves or rejects on the form. Stage nothing until shadow is a decision a person made, and even then the program only stages | No email. No Graph token. `sharepoint_written` stays false |
| Weeks 7 and 8 | File the quotes the suppliers actually sent. Compare. The buyer awards outside this program, in the ERP they already use. Record the poll yourself. Run `go_no_go` against thresholds typed in week 1 | The next family. `wave1_signed` stays `no` until a person sets it |

Wave 2 starts when a person sets `wave1_signed` to `yes` and points `wave_family` at the next family. The 187 is Watlow's published count. It is not the size of your second wave.

---

## 20. KPIs and the baseline you measure yourself

Before the first package, write these down. The agent does not invent them after the fact.

**Cycle days.** For ten working days, log the date a package went out and the date the first complete quote came back, on the packages the desk already sends. Do not type 45, 60, 2, or 3 in as the target. Those are the case. The key that would store them is refused. The fixture's own cycle is 9 days, from a package opened 1 November to a quote that counts on 10 November. Yours will differ.

**Quote coverage.** Parts on the package with at least one quote that passed section 12, divided by parts on the package, in basis points. The fixture is 6666. A part with only an incomplete reply is not covered.

**Valid commodity code.** Parts whose status is `VALID` or `ACCEPTED`, divided by parts in the run, in basis points. `RECOMMENDED` is not valid yet. The fixture is 4000 after two accepts. A recommendation nobody has accepted does not move this number.

**Savings on quoted parts.** After the award is approved, against one last `made` price at the same quantity, in basis points. `(last - landed) * 10000 // last`. No baseline is left out of the average. It is not treated as zero. The fixture is 2187 on `P-100` only. It is not 35%.

**Supplier poll.** A person asks the suppliers who quoted whether the package was easier to quote than the last one. The buyer records yes or no. The agent does not send the question. The fixture is one of two. It is not 4 of 5.

**What stays at zero.** Packages this agent emailed. Files it uploaded. Purchase orders it wrote. ERP commodity codes it changed. Awards it approved by itself.

**Go/no-go.** `go_no_go` reads `max_cycle_days`, `min_coverage_bps`, and `min_commodity_bps`. A blank or `REPLACE` returns `threshold_unset`. It does not pass. It does not fill 80 or 35. A pass is permission to talk about turning shadow off. It is not permission to write the ERP, and it does not open the next family.

---

## 21. Stack and the UI

Python 3.11 or newer for the worker. Postgres 15 or newer for the tables in section 6. The fixture runs with no database and no network. The live worker reads the staging tables and writes decisions only.

The document model and the embedding model are the plant's choice, behind the prompts in sections 8 and 13. The CAD reader is a local program that emits the six integers. Neither model is named by the Watlow case study.

The page regions, so a build does not invent a different product:

1. A banner. Empty when the gate is clean. The error name when it is not. Never a ready count beside `stale_export`.
2. The part table: commodity status, flags, family, sourcing status, proven, candidates.
3. A drawer for one part: the extraction, the evidence string, the redacted text, the files withheld.
4. Buttons for accept and for clear, steward or buyer, note required, `channel` form.
5. The package: one column per invited supplier, the cover sheet, the file list, the held parts and why.
6. The comparison: landed cents, lead, ignored quotes with reasons. Award buttons for the buyer. No button that says send or upload.
7. An audit list of decision rows, with the four false flags visible.

The morning file is text from `kpis` plus the package lines. The last line says it has not been sent and that no purchase order was written.

---

## 22. Security and permissions

- The desk is one plant. Every query filters on `plant_id`.
- The steward sees the part record and the code buttons. The buyer sees the package, the comparison, and the award. Do not give the model the ERP credential or a Graph token.
- The ERP credential is read-only, stored outside this file. The agent's database role has `insert` on `decision` and no privilege that would update a part row in the ERP. `revoke update, delete on decision` is in the schema so an audit row cannot be edited into a different story.
- Export-controlled drawings do not enter the staged folder. A redaction hit is kept as a count, not as a copy of the sensitive line, in the cover sheet.
- Logs keep part ids and decision ids. They do not keep the raw drawing text after the retention the plant types. Suggested starting point: 90 days, then delete the staged body and keep the audit row.
- The model sees tool results. It does not see the export files, the database URL, or a token.

---

## 23. Risks

- **A cosine that ignores size** will family a bushing with a flange. The size-ratio gate is the control. Do not turn it off because a demo looked sparse.
- **A commodity list that is missing a real material** makes every aluminum part a conflict, which is what `P-600` does on purpose. Add the code. Do not let the model borrow `MACH-SS`.
- **A dirty callout** hides the supplier you already have. That is `P-110` before the clear. The fix is a person reading the note, not a lower threshold.
- **Redaction that paints a box** leaves the text in the file. This program drops the line. If the material and the price were printed on the same line, the material drops too, and the part should be re-extracted from a clean print. Do not ship a cover with a blank material to avoid the work.
- **An unconfirmed or late quote** looks like a bargain. The 1000-cent quote at 45 days is the fixture's version of that bargain. It is ignored. Do not sort by unit price alone. Tooling divided by quantity is why `SUP-E`'s lower unit price loses on `P-100`.
- **Shadow left on** is the control, not a bug. `file_package` refuses. Turning it off is a config change a person makes after week 6, not a feature the model requests.
- **The reflex to open wave 2** because the go/no-go passed. `signed` is false. The 187 parts in the case study were a second wave at Watlow, with savings still pending. Your second family waits for a signature.

---

## 24. What you do not claim

- Do not say this plant will cut RFQ time by 80%, finish a 4–5 week action in 2–3 days, save 35% on the first wave, categorize 235 parts, or hear from 4 of 5 suppliers that quoting got easier. Those sentences are Watlow's published result, as Paperless Parts' case states it. None of them is a field in section 20.
- Do not say wave 2 will beat wave 1. The case study says 187 further part numbers are in progress and that the savings were pending validation of landed cost and tooling. This file refuses `187` as a config value.
- Do not say the columns, the fixture thresholds, the 2187 basis points, the hash, or the tests are Watlow or Radar settings. They are not published. They are our design. `P-100` is a fixture. It is not a Watlow part number.
- Do not say version 1 has filed to SharePoint, emailed a supplier, or written a purchase order. The case describes a platform that integrates with SharePoint and redacts before release. This file stages a folder after a human approval and keeps the upload flag false.
- Do not say the prompt, the six-integer vector, or the vocabulary embedding is Radar's patented geometric engine. The page names that engine and does not publish it. Section 9 is our substitute, labelled as ours.
- Do not say a recommendation is a valid commodity code. It is valid when the status is `VALID` or `ACCEPTED`.
- Do not say an unsourceable part has no approved supplier who could make it. `UNSOURCEABLE-WITH-CANDIDATES` means there is no history, and there is a capability match. `UNSOURCEABLE-NO-CANDIDATE` means the list, as typed, cannot cover it.
- Do not say a signed go/no-go opens the next family or writes back to the ERP. Section 19 keeps both off until a person edits the config.
- 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 board instead.

---

## 25. 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 only a finished JSON result. It does not see a drawing note as instructions.

```text
You are building the strategic-sourcing and RFQ tool specified in sourcing-agent-instructions.md. Build only what that file specifies.

Stack: Python 3.11 or newer for the worker, standard library for the fixture, Postgres 15 or newer for the live tables. The functions and the refusals match section 16. Money is integer cents. Scores are basis points. Landed cost is unit_cents plus tooling_cents // qty. Family membership requires the same material, the same process, a geometry score and a spec score at or above the configured lines, and a size ratio at or under the configured max. The model does not name the family, the commodity code, or the price.

Fail closed. If any required config value is missing, blank, or the word REPLACE, do not serve a live run. If a live file contains a value that begins with EXAMPLE or FIXTURE, do not serve a live run. If auto_release_rfq, auto_award, auto_send, send_email, or write_back is not no, refuse to start. If require_human_approval is not yes, refuse to start. If mail_mode is not file, refuse to start. If sharepoint_mode is not local, refuse to start. If a password, api_key, secret, or token is present, refuse to start. If a case-study key from section 2 is present, or a value contains 80%, 35%, 3-4x, 4-5 weeks, 2-3 days, 45-60, 4 of 5, 235, or 187, refuse to start. A stale export, a short full extract, or a missing system returns no package.

There is no send and no Graph upload. A model call to record_decision, accept_commodity, clear_gdt, or record_poll is prompt_ignored. Never set sharepoint_written, transmitted, erp_written, or po_written to true. Never invite a supplier who is not approved. Never let an extraction payload carry a price or a supplier. Never treat SEE NOTE as a parsed callout. Never family a part that fails the size gate. Never count a late, incomplete, wrong-quantity, or uninvited quote as coverage or as a shorter cycle. Never book savings before the award is approved. Never brief a digit in model prose. Never emit 80%, 35%, 235, or 4 of 5 as a target for this plant.

The fixture in section 15 must produce hash 90c2343805d2c5844fec5149b6fde29559a5d2fea4b56863747477d95cfa6922. P-110 joins FAM-P-100 only after PROFILE 0.2. P-100 awards to SUP-A at 2500 cents. P-110 awards to SUP-E at 2200 cents. The 1000-cent quote at 45 days does not win. Savings are 2187 basis points. Coverage is 6666. Cycle is 9 days. All four execution flags stay false. Section 18 must pass before a buyer is asked to trust a package, and before a folder is treated as a file the supplier has already received.
```
