# Maker BOM agent guide

You work on bills of materials (BOMs) for one maker. Your token acts as that maker. Every change you make is recorded under your token's name and shows up live in their browser.

Base URL: `/api/v1`. Machine-readable contract: `GET /api/v1/openapi.json`.

## Authentication

Send `Authorization: Bearer <token>` on every request except `GET /api/v1`, `/openapi.json`, and `/guide`. Call `GET /me` first. It returns your token name, the owner, your permissions, and the rate limit. A missing or revoked token returns `401 unauthorized`.

## Data model

1. A **BOM** is one build. `build_count` multiplies every requirement.
2. A **group** is a functional part or assembly. Groups nest. A group's `quantity` multiplies the lines inside it.
3. A **line** is one requirement: `quantity` per group instance, `unit`, `spares`, `inclusion` (`required`, `optional`, `dnp`), and `supply` (`purchase`, `on_hand`, `salvaged`, `fabricated`, `supplied`, `kit`).
4. A line may select a **part** from the catalog (`part_id`). A part has supplier **listings** with pack size and price. The preferred listing drives estimates.
5. An **alternate** proposes a substitute part for a line. The maker accepts or rejects it.
6. An **order** has **order items**. An item's `quantity` counts usable units.
7. An **allocation** assigns units to a line, from an order item (`source: order`) or from stock, salvage, fabrication, a supplier, or a kit.
8. A **receipt** records what arrived. Accepted units make order allocations ready.
9. A **comment** is a note or a **question** on a BOM, group, line, or order. Unresolved questions are the open questions.
10. A **revision** is a named snapshot. Compare revisions with each other or with the current draft.

## Quantity rules

- `required = quantity × group quantities up the chain × build_count + spares`. A `dnp` line requires 0. A null quantity makes the line `unresolved`.
- Canceling an order or an order item releases only the units that have not arrived. Units already accepted on a receipt stay ready.
- A deleted line keeps its allocations, but they are inactive: they cover nothing, take no received units, and free their order item's capacity. Read `GET /lines/{id}/deletion-impact` before deleting. A restored line takes back only the capacity that is still free.
- Each required unit is in exactly one bucket: `ready`, `on_order`, `in_progress` (assigned, not ready yet), or `uncovered`. Extra coverage is `excess`.
- Accepted receipt units fill an item's allocations first in, first out.
- Line `status`: `excluded`, `unresolved`, `to_source` (uncovered > 0), `in_progress` (covered, not all ready), `ready`. `needs_part` flags a purchase line with no selected part.
- Decimals are JSON strings: `"12"`, `"0.25"`. Send strings or numbers. Money totals are maps of currency to amount. A missing price is reported as missing, never as zero.

Worked example: 12 screws plus 2 spares need 14. 5 come from stock (ready 5). An order item of 10 allocates 9 to the line. A receipt accepts 4. Result: ready 9, on order 5, uncovered 0. Canceling the order keeps the 4 accepted units ready and reopens the 5 that never arrived: ready 9, on order 0, uncovered 5.

## Workflows

### Import a BOM

1. `POST /imports` with `{"text": "<csv>", "bom": {"name": "..."}}` to create a new BOM, or `POST /boms/{id}/import/preview` for an existing one.
2. Read the preview: `mapping` shows how each column was understood, `rows[].action` is `add`, `update`, `unchanged`, or `error`. Fix columns with `mapping` (`{"Header": "quantity"}`, `"attribute:<name>"`, or `"ignore"`).
3. `POST /boms/{id}/import` with the same body. The default mode is all-or-nothing. `"mode": "valid_rows"` skips bad rows and reports them.
4. Reference designators survive (`references`). Ranges such as `R1-R4` expand. Re-importing the same file changes nothing.
5. One import is one change in the feed: a `bom.imported` event whose `line_ids` lists every line it created or updated. The parts and listings it created have their own events, marked `part_of: "bom.imported"`.
6. At most 2,000 rows per import (`413 import_too_large`). Text that is not UTF-8 is read as Windows-1252; text in no readable encoding is `422 import_parse_error` with `invalid_encoding`.

### Find what to do next

- `GET /boms/{id}/checklist` is the same list the maker sees under What to do next, in five steps: `decide` (unknown quantity, no part, a proposed substitute, an open question), `order`, `receive`, `make`, and `set_aside`. Each item names the line, the units, the reason, and the supplier or order. Narrow it with `?step=order`, `?supplier=DigiKey`, or `?group_id=12`.
- `GET /boms/{id}/lines?status=to_source&include=breakdown` lists lines with uncovered units and their quantities.
- `GET /boms/{id}` carries `cost`: `estimate` (what the build costs) and `to_buy` (what is still to buy) are priced per part from preferred listings, with packs rounded once per part. `estimated` and `to_source`, like the group rollups, are per-line sums and can be higher. `estimate_missing_line_ids` lists lines without a price; `committed_missing` says an ordered item has no unit price. Money is per currency; never add currencies.
- `GET /boms/{id}/analysis` has everything: per-line breakdown, group rollups, the same cost fields, the identical-part rollup, and completeness checks.
- `GET /boms/{id}/order-list` plans what to buy per supplier.

### Propose a substitute

1. Find or create the candidate: `GET /parts?search=...` or `POST /parts`.
2. `POST /lines/{id}/alternates` with `part_id`, `rationale`, and `trade_offs`.
3. Before accepting, read `GET /alternates/{id}/impact`. If `requires_allocation_decision` is true, accept with `"allocations": "keep"` or `"release"`.
4. Leave the decision to the maker unless they asked you to decide.

### Record an order and a receipt

1. `POST /orders/order-lines` with `{"order": {"supplier": "DigiKey", "status": "ordered"}, "entries": [{"line_id": 100, "quantity": "10"}]}`. Lines that select the same part share one item. An entry without `unit_price` is priced from the line's preferred listing. Or `POST /orders` with `items` and their `allocations`; `GET /order-items/allocatable` finds items with free units to allocate.
2. Send an `Idempotency-Key` header so a retry cannot create a second order.
3. When goods arrive: `POST /orders/{id}/receipts` with `receipts: [{order_item_id, quantity_received, quantity_accepted}]` records a parcel in one all-or-nothing step, or `POST /order-items/{id}/receipts` for one item.
4. To correct a receipt: `POST /receipts/{id}/void` with a `replacement`.
5. Before canceling, read `GET /orders/{id}/cancel-impact` (or `/order-items/{id}/cancel-impact`): per line, the units that stop being covered and the units that stay ready. Tell the maker, then `POST /orders/{id}/cancel` or `POST /order-items/{id}/cancel`. Units not yet received go back to uncovered; accepted units stay ready.

### Where to shop

Maker BOM does not look up prices or stock, and it never fetches a supplier's site. You do the shopping; the supplier directory tells you where.

1. `GET /suppliers/categories` lists the categories and kinds. `GET /suppliers?category=electronic_components` lists the published suppliers for one category; add `kind=distributor,manufacturer` or `search=...` (name, host, what they sell, ships from, ships to, currencies) to narrow it. Without `sort` the list is in id order; for shopping, ask for `sort=-price_rating`, `sort=-availability_rating`, or `sort=name`. Suppliers without a rating come last in both directions of a rating sort. Each supplier is one host: `amazon.com` and `amazon.de` are different suppliers.
2. Read the judgment before you search: `kind` (an authorized distributor sells traceable stock; on a marketplace quality depends on the seller), `best_for`, and `watch_out_for`. Ratings are Maker BOM's own, 1 to 5 or null, and 5 is best for the buyer on every criterion: `price_rating` 5 means low prices. Never average them. `review_stale: true` means the entry is more than a year old; trust the site over it.
3. Check whether they serve the maker: `ships_from`, `ships_to`, `currencies`, `sells_single_units`, `minimum_order`, and `account_required`.
4. Search the site yourself: put the URL-encoded search words in place of `{query}` in `search_url_template`. When `api_docs_url` is set, the supplier has an API. Read `agent_notes` first and follow them: they say how to search, how part numbers look, and what the site's terms say about automated access.
5. Record what you find as a listing (`POST /parts/{part_id}/listings`) with the price you observed, `observed_at`, and `confidence`. A listing whose `url` is at a published supplier carries `directory_supplier_id`; it describes the supplier, not the price.

To suggest a supplier that is missing: `POST /supplier-suggestions` with `url` and `reason` (why it is good for makers), and optionally `name` and `categories`. The host of `url` is the key, so suggesting the same site again only replaces your reason. `outcome` tells you what happened: `queued`, `reason_added`, `already_suggested`, `already_published` (with the directory entry in `supplier`), or `not_listed` (reviewed before and rejected or retired). An admin reviews every suggestion before it is published. `GET /supplier-suggestions` lists this account's suggestions with their status and, for a rejected or retired supplier, the reason given. Each account may make 20 new suggestions in any 24 hours (a reason added to a supplier another account suggested counts; replacing your own reason does not). Past that the answer is `429 suggestion_limit` with `Retry-After` and `error.retry_after` (seconds) and `error.retry_at` (when the oldest counted suggestion leaves the 24-hour window). Wait until then; an earlier retry fails the same way.

### Sharing

A shared build is a read-only snapshot of a build at an unlisted public link, stored once in the Maker BOM format (`/docs/format`, schema at `/schemas/builderbom/v1.json`). Anyone who can open the link can download and copy the build. Ask the maker before you share, change who can open it, or stop sharing.

Share a build:

1. `POST /boms/{id}/share` with the settings: `access` (`link` for anyone with the link, `code` for the link and an access code), `title`, `description`, `author_name`, `license` (an optional terms or credit line), `include_notes` (default true), and `include_prices` (default false). Sharing saves a revision named `revision_name` (default "Shared copy"), or uses the revision you name in `revision_id`.
2. The answer has the `url`, the `access_code` when `access` is `code`, and `lock_version`. A shared document never contains orders, receipts, coverage, comments, activity, token names, emails, or record ids.
3. `GET /boms/{id}/share` reads it again. `changed_since_shared: true` means the build changed after the snapshot; `PUT /boms/{id}/share` with `lock_version` updates the shared copy at the same link (`"snapshot": false` changes only the settings).
4. `POST /boms/{id}/share/code` replaces the code; the old one stops working. `DELETE /boms/{id}/share` stops sharing, and the link answers `410 Gone`. Trashing or deleting the build stops sharing too.
5. A link anyone can open is cached for up to 60 seconds, so an update or a stop reaches every reader within a minute.

Copy a shared build into this account:

1. Fetch the document: `GET /b/{slug}/builderbom.json` (no token). For a link with a code, send the code in the `BuilderBom-Access-Code` header, never in the URL. The code is checked first, so a right code always works. Only wrong codes count: more than 30 wrong codes a minute from one address (an IPv6 address counts by its /64) answer `429 rate_limited` with `Retry-After`, and a wrong code is `401 wrong_access_code`. Requests with the right code never count. A link anyone can open sends `Access-Control-Allow-Origin: *`, so a browser tool can read it. A stopped link is `410 gone`.
2. `POST /imports` with `{"text": "<the document>"}`. The new BOM takes the document's title. It records where it came from only when the document's `shared.url` is a live shared build of this server, and then from that shared build itself. A part this account has is reused when the manufacturer part number matches (with the manufacturer, when the document names one); it may gain the document's sources as listings, but its preferred listing never changes. Other parts are created with their sources. Substitutes become proposed or accepted alternates. A document over the size limits (2,000 requirements, 500 assemblies, 4,000 parts, 8,000 sources and 10 per part, 2,000 substitutes and 5 per requirement, 20,000 characters per text) is refused with `413 import_too_large` before anything is written.
3. Maker BOM never fetches a URL for you: you fetch the document, then post it.

The same document format comes out of `GET /boms/{id}/export.json` (with the private sections `records` and `status`, and `orders` and `comments` when asked). `GET /b/{slug}/builderbom.csv?builds=N` is the CSV projection, one row per requirement.

### Ask a question

`POST /comments` with `{"line_id": 100, "kind": "question", "body": "..."}`. `GET /boms/{id}/questions` lists open questions. Resolve with `POST /comments/{id}/resolve` once answered.

### Follow changes

`GET /events?after=<cursor>` returns changes oldest first. Store `next_cursor` and poll with it. Add `bom_id` to follow one BOM. Each event names the actor, the action (such as `line.updated` or `line.deleted`), and the changed fields.

### Export everything

`GET /me/export` returns everything the maker's account holds as one JSON document (`format: builder_bom_account`, `version: 1`), sent in chunks. Each table is a list of its rows with every column, in id order: `boms` (builds), `groups` (assemblies), `lines` (requirements, deleted ones too, with `deleted_at`), `alternates`, `revisions` (with their snapshots), `parts`, `listings`, `orders`, `order_items`, `allocations`, `receipts`, `comments`, `events`, `bom_views`, `marketing_consent_events`. `account` and `api_tokens` carry the profile and token metadata, never a secret. `bom_exports` holds each build's `builder_bom` export, which `POST /imports` accepts. `supplier_suggestions` lists the account's suggestions. The last member is always `"complete": true`. The 200 status goes out before the body, so an export that stops part way still answers 200: if the body does not parse or has no `complete: true`, it is cut short; fetch it again. Each account may start a few exports per minute (`429 export_limited` with `Retry-After` past that), counted on each server machine; export once and work from the file. No API operation deletes an account: the maker does that in the browser.

### Undo a mistake

`GET /events/{id}/undo` says whether a change can still be undone; `POST /events/{id}/undo` reverses it and records the undo under your name. Undo works while the record still holds what the change left: `409 changed_since` means someone changed it since, so edit the record instead. `409 not_undoable` means this kind of change has no undo, or the event was one step of a larger operation (`part_of` is set: an accepted substitute's line change, lines moved by a part merge, the parts an import created); undo the operation's own event instead. Check many events at once with `POST /events/undo-check`.

## Archived and trashed builds

An archived or trashed BOM is read-only. Writes to its contents (the BOM's fields, groups, lines, bulk edits, alternates, revisions, imports, and comments on it) return `409 bom_archived` or `409 bom_trashed`. Reads and exports keep working. Allocations to lines of an archived BOM stay allowed, because orders are real history; a trashed BOM refuses them too. Ask the maker before you unarchive (`POST /boms/{id}/unarchive`) or restore (`POST /boms/{id}/restore`) a build.

## Concurrency

BOMs, groups, lines, parts, orders, and order items carry `lock_version`, also sent as `ETag: "<version>"`.

- Updates (`PATCH`) of these records require the version you read: `"lock_version": 3` in the body or `If-Match: "3"`. Send one strong tag: `W/"3"` never matches, and a body version that disagrees with `If-Match` is refused; both are `412 precondition_failed`.
- A stale version returns `409 conflict` with the stored record in `error.current`. Re-read, reapply your change, and retry with the new version. Do not blindly resend.
- Line and group deletes, line restores, BOM lifecycle actions, part retire, merges, cancels, and moves check the version when you send one. Merges also take `target_lock_version` (groups) or `merged_lock_version` (parts).
- Reorders (`.../groups/reorder`, `.../lines/reorder`) take a full permutation: every child exactly once.
- Bulk apply and import commit accept `expected_versions` (line id to version) from the preview you reviewed (`versions` and `expected_versions` in the previews). If any of those lines changed, nothing is written: `409 conflict` for bulk edits, `409 import_stale_rows` for imports.

## Lists and requests

- Lists page with a cursor: pass `next_cursor` as `after` (`limit` up to 200, default 50). `next_cursor` is null on the last page.
- The default order is id, ascending. It is the only order that never moves a record, so a record changed between pages is never skipped or repeated. Sync a whole list in id order.
- `GET /boms`, `/parts`, `/orders`, `/suppliers`, and `/boms/{id}/lines` take `sort`: one field, named as the records show it, `sort=name` ascending or `sort=-name` descending. Ties break by id; null values come last ascending and first descending. Text sorts by the database collation (linguistic order, mostly ignoring case and accents). `GET /boms?sort=-updated_at` lists the builds changed most recently first; `sort=-inserted_at` lists the newest. In a sorted list, a record whose value changes between pages can move, so it can be missed or seen twice.
- Send a cursor back to the list that returned it, with the same `sort`. Another `sort` returns `422 validation_failed` with detail code `cursor_mismatch`; a cursor of another list, or a changed one, has detail code `invalid`. Start again without `after`.
- Lines sort by `name`, `category`, `quantity`, `inserted_at`, `updated_at`, and `id` in the database. `position` (outline order) comes from the assembly tree: adding, moving, or reordering an assembly between pages shifts every later line. `status`, `required`, and `uncovered` come from the quantity analysis, which runs once per page. Status order is excluded, unresolved, to_source, in_progress, ready.
- `GET /boms/{id}/lines` without `limit`, `after`, or `sort` returns every matching line in outline order (up to 2000, `truncated` says more exist). With any of them and no `sort`, lines page in id order. An empty value (`limit=`) counts as absent. Add `include=breakdown` for quantities; it costs a full analysis.
- Send only the query parameters the operation declares in the OpenAPI document. Any other one, such as a misspelled `sort` or `stauts`, returns `400 unknown_parameter`, and `details[].allowed` lists the declared names. A declared parameter with a bad value (`limit=0`, `sort=price`, an unusable `after`) returns `422 validation_failed`. This applies to every method, and a rejected request stores nothing under its `Idempotency-Key`.
- The checklist caps each step at `limit` items (default 200).
- Bodies are `application/json` (imports also accept a multipart `file`). Send only the fields of the operation's request schema: an unknown field or a value of the wrong type is `422 validation_failed` with code `unknown_field` or `invalid_type`. `id`, `object`, `links`, `inserted_at`, and `updated_at` are ignored, so echoing a record's envelope is harmless.
- Imports take at most 2,000 rows per request; split larger lists.

## Dry runs

- `POST /boms/{id}/lines?dry_run=true` and `PATCH /lines/{id}?dry_run=true` validate and return the would-be line with `impact` (line breakdown and BOM summary before and after). Nothing is written.
- `POST /boms/{id}/lines/bulk/preview` and `POST /boms/{id}/import/preview` preview bulk edits and imports.

## Idempotency

Every POST accepts `Idempotency-Key` (1 to 255 characters; use a UUID per intended write). A retry with the same key and body replays the first response with `Idempotent-Replayed: true` and writes nothing. The same key with a different body returns `422 idempotency_key_reused`. While the first request still runs, a retry gets `409 idempotency_in_progress`; wait a second and retry. If the first request never finished (it crashed or the connection dropped), a retry with the same body takes the key over after 105 seconds (a full write lock wait plus the longest transaction, plus a margin) and runs the write once. A `500` is stored and replayed like any answer, because it can come after the write committed: read the record or the change feed, then decide with a new key. A response over 1 MB is not stored; a retry gets `409 idempotency_response_not_stored` with the first status. Previews and dry runs ignore the key. Keys last 24 hours.

## Errors

Every error uses one envelope:

```json
{"error": {"code": "validation_failed", "message": "...", "details": [{"field": "supply", "code": "invalid", "message": "is invalid", "allowed": ["purchase", "on_hand"]}]}}
```

| Status | Codes | What to do |
| --- | --- | --- |
| 400 | `bad_request` | Fix the JSON, the query string, or the header. |
| 400 | `unknown_parameter` | Drop or fix the query parameter named in `details`; `allowed` lists the declared ones. |
| 405 | `method_not_allowed` | Use a method from the `Allow` header. |
| 412 | `precondition_failed` | Send one strong version (`If-Match: "3"` or `lock_version`). |
| 413 | `import_too_large`, `request_too_large` | Split the import or the body. |
| 415 | `unsupported_media_type` | Send `Content-Type: application/json`. |
| 401 | `unauthorized` | Check the token. |
| 404 | `not_found` | The id is wrong or belongs to someone else. |
| 409 | `conflict` | Re-read `error.current` and retry with its version. |
| 409 | `bom_archived`, `bom_trashed` | Ask the maker; unarchive or restore first. |
| 409 | `allocation_decision_required` | Accept again with `allocations: keep` or `release`. |
| 409 | `in_use`, `has_receipts`, `not_trashed`, `already_decided`, `already_voided` | The domain refused; read the message. |
| 409 | `idempotency_in_progress` | Retry after `Retry-After`. |
| 409 | `not_undoable`, `changed_since` | The change cannot be undone; edit the record instead. |
| 409 | `already_shared`, `not_shared`, `taken_down`, `no_code` | Read the build's shared build with `GET /boms/{id}/share`. |
| 422 | `validation_failed` | Fix the fields named in `details` (`unknown_field`, `invalid_type`, ...). |
| 409 | `idempotency_response_not_stored` | Read the record named in `location`. |
| 422 | `idempotency_key_reused`, `import_*` | Use a new key; fix the import. |
| 429 | `rate_limited` | Wait `Retry-After` seconds. |
| 429 | `export_limited` | The account started its exports for this minute. Wait `Retry-After` seconds. |
| 429 | `suggestion_limit` | The account made its daily number of new supplier suggestions. Wait until `error.retry_at` (also `Retry-After`), not the rate-limit window. |
| 500 | `internal_error` | The change may have been applied: read before you write again. |
| 503 | `busy` | Other writes of this account ran long and this one waited too long. With `Retry-After`: nothing was written; retry after that many seconds, with the same `Idempotency-Key` if you sent one. Without it: the request stopped part way; read the records, then decide with a new key. |
