← Commit history
.adomignoreadded+2
@@ -0,0 +1,2 @@+__pycache__/+*.pyc
README.md+62−15
@@ -1,22 +1,69 @@ # molecule-publish-# molecule-publish — source bundle → wiki molecule -The EDA-agnostic middle of the molecule pipeline. Input is the **bare-minimum-bundle** any EDA export produces; output is a published, pipeline-ready wiki-component. The Hydrogen half is `adom-molecule-import` — this skill is its-publish-side companion.+Publishes the sources of a molecule to the Adom wiki. The wiki's 3D model+registry builds the page's model, render copy, footprint and symbol from those+sources; this skill never converts the STEP and never pushes a GLB or+footprint/symbol JSON to a molecule page. It is the EDA-agnostic middle of the+pipeline; `adom-wiki model import` takes the page on to Hydrogen.  ```-EDA export skill        THIS SKILL                     adom-molecule-import-(kicad/fusion/altium) → convert → package → publish  → wiki → Hydrogen+EDA export skill        molecule-publish                                   adom-wiki model import+(kicad/fusion/altium) -> check -> publish private -> wait for build -> hero -> public -> Hydrogen ``` -## Input contract — the bare-minimum bundle+## What it publishes -| Required | File | Notes |-|---|---|---|-| yes | STEP (`.step`) | exported ON the design machine so all 3D models (machine pins, contacts, MP markers) are baked in |-| yes | Board/layout (`.kicad_pcb` or `.brd`) | what footprint+symbol generation parses |-| yes | Schematic (`.kicad_sch` or `.sch`) | source completeness — a molecule without its schematic is not reproducible |-| EDA molecule | `<slug>-fab.zip` + `export.json` | Required fabrication layers, drill files and hashed export provenance; see [fabrication.md](docs/fabrication.md) |-| yes | Metadata | `package.json` (authored below) + the OCCT-generated footprint/symbol JSONs |+| Bundle | Sources | Route | The registry builds |+|---|---|---|---|+| KiCad or Fusion/EAGLE molecule | STEP, `.kicad_pcb` or `.brd`, every schematic sheet, `<slug>-fab.zip`, `export.json` | board | model, web, footprint, symbol |+| Altium molecule | STEP, `.PcbDoc`, schematics, `<slug>-fab.zip`, `export.json` | board | model, web, footprint, symbol |++A STEP with no board file is refused (`board-file-required`): the build+places a molecule's model on the machine pins its board file names. Every+board, Altium included, is checked against the pin rule+`adom.molecule-pins/2`: two or four machine pins named `MP1` to `MP4`, all+one size and length, and machine contacts named `MC<n>`.++Fabrication files and the export record are described in+[docs/fabrication.md](docs/fabrication.md). The exact matching rules for each+source, and what an exporter must hand over, are in `SKILL.md` ("Handoff+input"). Plain KiCad/EAGLE boards without machine pins use board mode, which+still converts and pushes its own GLB, because the registry builds models+only for molecule pages.++## How a publish runs++1. `scripts/versions_check.py`: adom-wiki 1.8.0 or newer and the installed+   exporters at their current releases.+2. `scripts/bundle_check.py`, `scripts/pin_names.py`, `scripts/fab_bundle.py`+   and `scripts/bundle_3d.py` check the bundle the way the registry will.+3. `adom-wiki pkg publish --private --wait` writes the sources in one commit+   and waits for the build the registry queues from it.+4. The publish is done when that build passed with no error, wrote the+   footprint and symbol (`metadataComplete: true`), and the page's `model`+   comes from the pipeline.+5. The hero is posed from the built model, then the page goes public, APM's+   `render/` assets are refreshed, and `adom-wiki model import` takes it to+   Hydrogen.++A write that carries a file the registry generates is refused with+`REGISTRY_MODEL_FILE_REFUSED`; the skill removes the named files from the+package folder and publishes again.++## Scripts++| Script | Does |+|---|---|+| `versions_check.py` | the minimum versions, with the update commands |+| `bundle_check.py` | which recipe the page builds from, its sources, generated files, the fabrication pair and the record |+| `pin_names.py` | machine pin and contact names on a `.kicad_pcb`, `.brd` or `.PcbDoc`; a byte copy of the registry program's `names.py` |+| `pcbdoc.py` | reads an Altium `.PcbDoc` into the KiCad board `pin_names.py` checks; a byte copy of the program's `pcbdoc.py` |+| `pins.json`, `contract.json` | byte copies of the wiki's molecule contract files |+| `fab_bundle.py` | creates and checks `<slug>-fab.zip` and `export.json` |+| `bundle_3d.py` | custom 3D models under `3d/` for APM |+| `component_graph.py` | the board's component dependencies, checked before publish |+| `hero_camera.py` | the page's canonical hero camera |+| `tested_with.py` | the `tested-with:<family>` tag |++Run the tests with `python3 -m unittest discover -s tests` from the package+directory.
SKILL.md+670−417
@@ -1,489 +1,742 @@ --- name: molecule-publish-description: Publish a molecule OR a generic KiCad/EAGLE board to the Adom wiki - one publisher, two shapes — runs the OCCT molecule-mode conversion (anchored GLB + footprint + symbol with stats gates), assembles the component package, and publishes via adom-wiki. The EDA-agnostic middle of the pipeline; companion to adom-molecule-import (which does wiki → Hydrogen). Use when the user says "publish this molecule to the wiki", "upload molecule bundle", "convert and publish my molecule", "publish my board" (plain, non-molecule boards use BOARD MODE - no anchoring gates), or an EDA export skill (kicad-export-molecule, fusion-export-molecule, altium-export-molecule) hands off here after exporting. Every publish also emits the render/ assets (including APM's per-version render archive behind the board version selector) and component dependencies adom-project-manager (APM) reads.+description: Publish molecule sources to the Adom wiki (STEP, board, schematic, <slug>-fab.zip, export.json). The wiki's 3D model registry builds the GLB, footprint and symbol from them; this skill checks the bundle, publishes it private, waits for the build, sets the hero from the built model and makes the page public. It never pushes a GLB or footprint/symbol JSON to a molecule page. KiCad, Fusion/EAGLE and Altium boards all build a full molecule (model, footprint, symbol); a STEP with no board file is refused, since the model is placed from the board file. Plain KiCad/EAGLE boards use board mode, which still converts and pushes its own GLB. Use when the user says "publish this molecule to the wiki", "publish molecule sources", "upload molecule bundle", "publish my board", "I only have a STEP", or when kicad-export-molecule, fusion-export-molecule or altium-export-molecule hands off a bundle. Every publish also writes the render/ assets and component dependencies that adom-project-manager (APM) reads. Companion to adom-wiki model import (wiki to Hydrogen). user-invocable: true-argument-hint: "<name> --step <f.step> --board <f.kicad_pcb|f.brd> --sch <schematic> [--pin medium|large] [--silk-top png --silk-bottom png] [--org adom]"+argument-hint: "<bundle folder> --slug <slug> [--org adom]" --- -# molecule-publish — source bundle → wiki molecule+# molecule-publish: molecule sources to a wiki page -The EDA-agnostic middle of the molecule pipeline. Input is the **bare-minimum-bundle** any EDA export produces; output is a published, pipeline-ready wiki-component. The Hydrogen half is `adom-molecule-import` — this skill is its-publish-side companion.+The EDA-agnostic middle of the molecule pipeline. Input is a bundle of+sources from an EDA export; output is a public wiki molecule page whose model+the registry built. The Hydrogen half is `adom-wiki model import`.  ```-EDA export skill        THIS SKILL                     adom-molecule-import-(kicad/fusion/altium) → convert → package → publish  → wiki → Hydrogen+EDA export skill        THIS SKILL                                         adom-wiki model import+(kicad/fusion/altium) -> check -> publish private -> wait for build -> hero -> public -> Hydrogen ``` -## Two shapes: molecule vs board+**Sources only.** On a molecule page the registry builds (program+`molecule/8`), the registry writes these files, and a write that adds or+changes one of them is refused with `REGISTRY_MODEL_FILE_REFUSED`, nothing+written: -| | **Molecule** (machine pins + MP markers) | **Board** (plain KiCad/EAGLE) |+| Slot | Path | Routes | |---|---|---|-| Convert | `--molecule --board` (anchor/gold/footprint, ALL stats gates) | plain `step2glb convert` (no molecule flags, no anchor gates) |-| Tag | `molecule` | `board` |-| Footprint/symbol JSON | required (wire attach points) | not applicable |-| render/ + deps (APM) | yes | yes |--Decide by the board itself: Adom machine pins + MP1-MP4 markers -> molecule;-otherwise board. Both shapes get `<slug>.glb` from step2glb (never an-EDA-native GLB), `model_3d_path` pointing at it, and the APM stages below.+| model | `<slug>.glb` | all |+| web (render profile, what the viewer shows) | `<slug>.web.glb` | all |+| footprint | `<slug>_footprint.json` | circuit, board |+| symbol | `<slug>_symbol.json` | circuit, board |+| report | `<slug>.pipeline.json` | all | -## Contract — inputs vs the published set+The refusal also covers the root names `<slug>.render.glb` and+`<slug>.metadata.json`, and, on a route with footprint and symbol slots, any+root file ending `_footprint.json` or `_symbol.json`. Only paths a write adds+or changes count. `render/**`, `3d/**`, `viewer/**`, `libraries/**` and+`**/*.3dshapes/**` are never generated files. This skill never converts a+molecule's STEP and never pushes any of these files. The step route (a STEP+with no board file) builds none of them: the build refuses it+(`board-file-required`), and its slot paths are still refused in a write. -**The user supplies sources; this skill generates and attaches the rest.**-The published page always carries the full set — **GLB + STEP + schematic +-board + metadata** — and every downstream tool expects all five (import-reuses the GLB, wiring reads the metadata). The GLB and footprint/symbol-JSON are never user-supplied: they come out of the OCCT conversion below.+## Requirements -### Inputs — the bare-minimum bundle+Run this before the first registry step, from this package's directory: -| Required | File | Notes |-|---|---|---|-| yes | STEP (`.step`) | exported ON the design machine so all 3D models (machine pins, contacts, MP markers) are baked in |-| yes | Board/layout (`.kicad_pcb` or `.brd`) | what footprint+symbol generation parses |-| yes | Schematic — `.kicad_sch` (EVERY sheet: root + sub-sheets) or `.sch` | source completeness + APM's hierarchical schematic view renders from these |-| EDA molecule | `<slug>-fab.zip` | both sides' copper, mask and silk, outline, Gerber job when available, and Excellon drill files |-| EDA molecule | `export.json` | `adom.export/1`, producer versions and hashes of sources and every zip member |-| board shape | `.kicad_pro` + any `.kicad_sym`/`.pretty` used | APM render sources |-| generated | GLB | OCCT conversion output — never user-supplied, always published |-| generated | Metadata | OCCT footprint/symbol JSONs + the authored `package.json` |-| board shape | Bundled 3D — `3d/<basename>` for every CUSTOM `(model ...)` | see below (#16); recipients render blank without it |-| optional | Silk PNGs (top/bottom) | white artwork on transparent |-| optional | Extras | `.f3d`/`.usdz`/BOM/CPL — carry what the EDA produced |--**Fabrication handoff for EDA molecules.** Read [docs/fabrication.md](docs/fabrication.md).-Before conversion and again after final packaging, run-`python3 scripts/fab_bundle.py check <bundle-dir> --slug <slug>` from this-package's directory. A missing or stale fabrication bundle stops this publish;-return to the exporter for the missing files. Keep all existing GLB and metadata-checks until the registry rollout explicitly replaces that publishing path.--**Bundle custom 3D models so the board renders on ANY machine (#16).** The-whole-board GLB drives the wiki 3D viewer, so a board looks fine on the page-even when its per-component models are NOT bundled — the gap only appears when-a recipient pulls the project (APM/Nucleus "Add Project") and the machine-local-models render blank. Rule: stock `${KICADn_3DMODEL_DIR}/...` refs resolve-everywhere (leave them). EVERY other `(model ...)` ref — absolute paths-(`C:/Users/...`), personal env vars (`${KICAD_USER_PROJECTS_LIBRARY}`,-`${KISYS3DMOD}`, …) — must travel in the page's `3d/` folder with its path-rewritten to `${KIPRJMOD}/3d/<basename>`. Gate it: ```bash-python3 scripts/bundle_3d.py check <board>.kicad_pcb --page <owner>/<slug>-# and produce the format from your local model dirs:-python3 scripts/bundle_3d.py bundle <board>.kicad_pcb --models <dir>... --write+python3 scripts/versions_check.py ```-`check` fails with a per-file list of what's missing; anything it can't find-must be exported off the design machine (`kicad-cli pcb export glb---subst-models` names each unresolved ref). -**Rule: never accept an EDA-native GLB.** KiCad, Fusion, and service-kicad can-all emit GLBs — those bypass anchoring, gold materials, meter normalization,-optimization, and footprint emit. The ONLY GLB in a molecule package comes-from the OCCT conversion below.+- **adom-wiki 1.8.0 or newer.** Older CLIs have no `model` verbs and no+  `--wait`. The script exits 1 and prints: "This skill needs adom-wiki 1.8.0+  or newer (found <v>). Run: adom-wiki self-update". Stop until it passes.+  The same applies whenever an `adom-wiki model ...` call prints+  "'model' is not an adom-wiki command" (code `UNKNOWN_COMMAND`): the CLI is+  older than 1.8.0; print that message and stop.+- **The Hydrogen handoff** (Stage 7) is `adom-wiki model import`, in the+  same CLI. `adom-molecule` is deprecated; this skill no longer installs it.+- **Installed exporters.** The script reads `~/.claude/skills/<name>/package.json`+  of each installed `kicad-export-molecule` (needs 2.0.0),+  `fusion-export-molecule` (2.0.0), `altium-export-molecule` (3.0.0) and+  `molecule-pipeline` (2.0.0), and prints "Update adom/<name> to <version>:+  adom-wiki pkg install adom/<name>" for any older one. An installed exporter+  with no `package.json` there is older than that release. Older exporters+  still tell the agent to hand over a GLB; pass the update line on to the+  user, then carry on: Stage 1 finds whatever an old exporter left in the+  bundle.+- Python 3.9 or newer for the scripts (standard library only).++## Two shapes: molecule and board++| | **Molecule** (machine pins and contacts) | **Board** (plain KiCad/EAGLE, no machine pins) |+|---|---|---|+| Model | built by the registry from the sources | `step2glb convert` here, pushed as `<slug>.glb` (Board mode below) |+| `package.json` | `"kind": "molecule"`, tag `molecule` | tag `board`, no `kind` |+| Footprint/symbol JSON | built by the registry (board and circuit routes) | not applicable |+| render/ + deps (APM) | yes | yes | -## Stage 1 — Convert (OCCT molecule mode)+Decide by the board itself: Adom machine pins (MP1 to MP4) and machine+contacts (MC1, ...) make a molecule; otherwise it is a board. The registry's+recipes apply only to pages of kind molecule, so a molecule's package.json+always declares `"kind": "molecule"`. -```bash-step2glb convert <name>.step --board <name>.kicad_pcb --pin medium \-  -o <slug>.glb   # --board implies --molecule; add --silk-top/--silk-bottom PNGs-```+## Handoff input -Requires `step2glb` >= 0.11.0 (`adom-wiki pkg install adom/adom-step2glb`).-(No `adom-wiki` on the container? Bootstrap it first:-`curl -fsSL https://wiki.adom.inc/download/adom/adom-wiki-cli/1.0.2/adom-wiki-cli-v1.0.2 -o ~/.local/bin/adom-wiki && chmod +x ~/.local/bin/adom-wiki` — then keep using `adom-wiki`, not legacy tools.)-It posts multipart to `/convert?molecule=true&pin=...`, polls the job,-downloads the GLB **and** `<slug>_footprint.json` + `<slug>_symbol.json`-beside it, prints the full stats block, and emits gate hints on failures.-Fallback (older CLI): `curl -X POST ".../convert?molecule=true&pin=..."--H "X-Client: <agent>" -H "X-Job-Name: <name>" -F "step=@..." -F "board=@..."`.+An exporter hands this skill a folder and the page slug. The folder holds the+sources at the paths the export record names. molecule-publish finds each+source the way the registry does (`scripts/contract.json`, a byte copy of the+wiki's molecule contract), so an exporter can be checked against this+section and against `scripts/bundle_check.py`. -**Board shape:** use a plain convert instead — `step2glb convert <name>.step--o <slug>.glb` — and SKIP the molecule stats gates below (they do not apply;-if the output warns `molecule_markers_detected`, it IS a molecule — switch).+**How a role is matched.** A pattern without `/` matches a file name at any+depth; a pattern with `/` matches the whole repo path. `*` stays inside one+path segment, a segment `**` matches zero or more segments, `{slug}` is the+page slug, and case is ignored. Excluded paths are removed first. The+patterns of a role are tried in order and the first with a hit wins; among+its hits the shallowest wins, and two hits at that depth are ambiguous. An+ambiguous role ends the search: no recipe, no build. A required role that+matches nothing rules out only its own recipe. -`pin` = machine-pin size on the board (`medium` | `large`). Poll-`GET /jobs/{id}` until complete, then **gate on the stats — never publish a-degraded conversion**:+**The roles** (recipes tried in this order: `molecule-circuit`,+`molecule-board`, `molecule-step`): -| Field | Must be | If not |+| Role | Patterns, first hit wins | Excluded | |---|---|---|-| `anchored` | `true` | MP markers missing/undetected — fix the board, re-export |-| `footprint_applied` | `true` | board parse failed — read `warnings[]` |-| `contact_z` | ≈2.8–8.4 mm | wrong `pin` param or missing contact models |-| `warnings[]` | empty | each entry is a stop-sign, not a footnote |+| `circuit` | `circuit.json`, `*.circuit.json` | `**/node_modules/**` |+| `step` | `{slug}.step`, `{slug}.stp`, `*.step`, `*.stp` | `**/*.3dshapes/**`, `**/lib/**`, `**/libs/**`, `**/library/**`, `**/libraries/**`, `3d/**`, `render/**`, `viewer/**` |+| `board` | `{slug}.kicad_pcb`, `{slug}.brd`, `{slug}.PcbDoc`, `*.kicad_pcb`, `*.brd`, `*.PcbDoc`, `{slug}.fbrd`, `*.fbrd` | as `step` |+| `fab` (optional) | `{slug}-fab.zip`, `*-fab.zip` | none |+| `export` (optional) | `export.json` | `render/**`, `viewer/**` |++**The bundles this skill publishes:**++| Bundle | Must resolve | Route | The build makes |+|---|---|---|---|+| KiCad, Fusion/EAGLE | `step`, `board` (`.kicad_pcb` or `.brd`), `fab` and `export` | board (`molecule-board/1`) | model, web, footprint, symbol, report |+| Altium | `step`, `board` (`.PcbDoc`), `fab` and `export` | board (`molecule-board/1`) | model, web, footprint, symbol, report |++The build reads an Altium `.PcbDoc` as the KiCad board its `pcbdoc.py`+writes from it; the names census and the importer both read that board. A+Fusion `.fbrd` (the zip Fusion saves) is read as the EAGLE board it holds, and+only when the page has no other board file, so the `.brd` the Fusion exporter+writes wins.++A STEP with no board file resolves `molecule-step/1` (route step), which the+build refuses (`board-file-required`): a molecule's model is placed from its+board file, which says where its machine pins are. There is no 3D-only build.+`bundle_check.py` reports it as a problem. Ask the user for the board file+the STEP was exported from, and run its exporter for the fab zip and record.++Rules every bundle meets:++- **No `circuit.json`** (or `*.circuit.json`) outside `node_modules/`: it+  switches the page to the circuit route, which tscircuit pages use. Those+  publish through `adom-tsci export-wiki`, not this skill.+- **One STEP and one board at the shallowest depth**, or one named for the+  slug (`<slug>.step` wins over `Other.step`). A custom part's STEP goes under+  `3d/`, a `*.3dshapes/` folder or a library folder, where the build does not+  look.+- **`<slug>-fab.zip` and `export.json` come both or neither, in one folder**+  (check `fabrication-pair`). Exporters always write both; a hand-made bundle+  without them publishes with the fabrication check skipped, and Stage 1 says+  so. A page renamed after its export still builds: its zip keeps the old+  slug and matches `*-fab.zip`.+- **The record names the selected sources.** The `step` entry of+  `export.json` and its `board_kicad_pcb`, `board_eagle_brd` or+  `board_altium_pcbdoc` entry name the STEP and board the build selects+  (check `export-matches-sources`), and every recorded file is in the folder+  at its recorded path with its recorded bytes. Never rename or edit a+  recorded file; regenerate the record instead+  ([docs/fabrication.md](docs/fabrication.md)).+- **Nothing generated**: none of the paths in the table at the top.+- **Pin names** (rule `adom.molecule-pins/2`, `scripts/pins.json`), the same+  on KiCad, Fusion/EAGLE and Altium boards: two or four machine pins named+  `MP1` to `MP4`, all one size and length; machine contacts named `MC<n>`,+  one pad each; designators unique and in capitals. Refused: a machine pin+  numbered outside `MP1` to `MP4`, a designator in the wrong case (`mp1`,+  `Mc2`), and a contact named `MP<n>` (as older Fusion `CONTACT_MED` boards+  numbered them). A part that fits the standard only in part (the footprint+  and not the name, or the reverse) is not a pin or contact; the build warns+  and carries on.+- **Hole sizes.** A part named or packaged as a machine pin or contact whose+  hole is within 0.15 mm of a table size in `scripts/pins.json` is read as+  that size. The hole is clearance for inserting the pin, so its exact size+  never needs a board revision. Any other part's hole counts as a pin or+  contact hole only within 0.001 mm of a table size.+- **One orientation.** The build places the STEP on the board file's machine+  pins by shape, translation only. A STEP, or fab artwork, that fits the+  board only turned or mirrored is refused: export the STEP, the board and+  the fab files from one saved design without rotating any of them. Two-pin+  boards place like four-pin ones.++Also carried, not read by the build: every schematic sheet (`.kicad_sch`,+root and sub-sheets, or `.sch`), the `.kicad_pro` and any `.kicad_sym` or+`.pretty` used, `3d/<basename>` custom models, silk PNGs, `.f3d`, `.usdz`,+BOM and CPL. A molecule without its schematic is not reproducible, and APM+renders its sheets from these files.++## Stage 1: Check the bundle++Run from this package's directory: on the bundle as handed over, again on+the package folder after Stage 2, and for an existing page again with the+page's file listing (Stage 3.1). All of these must pass before the publish;+each failure names the file and the fix, and the fix is in the sources or the+exporter, never in this skill. -Artifacts: `GET /jobs/{id}/result` → `<name>.glb`,-`/jobs/{id}/footprint` → `<name>_footprint.json`,-`/jobs/{id}/symbol` → `<name>_symbol.json`.+```bash+# 1. Which recipe the page builds from, the sources it reads, and anything refused+python3 scripts/bundle_check.py <folder> --slug <slug> [--page-files <listing>]+# 2. Pin and contact names, the registry's own rule (.kicad_pcb, .brd, .PcbDoc or .fbrd)+python3 scripts/pin_names.py check <folder>/<board file>+# 3. The fabrication pair, when the bundle has it+python3 scripts/fab_bundle.py check <folder> --slug <zip name without -fab.zip>+# 4. Custom 3D models for APM (KiCad boards)+python3 scripts/bundle_3d.py check <folder>/<board>.kicad_pcb --page <owner>/<slug>+``` -## Stage 2 — Package+1. `bundle_check.py` applies the recipes above to the folder (plus, for an+   existing page, the files the page already holds: old files stay in a page+   repo and take part in the choice). It prints the recipe, the route, each+   source, the files the build does not read, and the problems: `no-recipe`,+   `ambiguous`, `overflow`, `board-file-required`, `generated`, `fab-pair`,+   `export-record`, `kind`. Exit 1 on any problem. A `generated` problem+   names files to delete from the folder (not from the page). Notes it+   prints: a fab zip not named for the slug, and ignore files that the CLI+   applies when it packs. `--json` gives the same as one object.+2. `pin_names.py` is a byte copy of the program's `names.py` (rule+   `adom.molecule-pins/2`), and `pcbdoc.py` beside it is the program's+   Altium reader: a `.PcbDoc` is read as the KiCad board `pcbdoc.py` writes+   from it, as the build reads it. It prints the census (each part, its+   hole, its class and whether the build keeps it), then one line per+   finding. Its findings are the build's `names` stage:+   - refused (exit 1): `board-read`, `pin-names`, `contact-names`,+     `hole-sizes` (a part named `MP<n>` or `MC<n>` drilled off the standard+     sizes: pins 1.20 or 3.45 mm, contacts 0.78 or 2.62 mm, within+     0.001 mm), `pin-count`, `corner-pins` (an `MS<n>` pin further out+     than the `MP<n>` pins toward a corner), `designators-unique`,+     `pins-uniform`;+   - warned: `not-machine-pins`, `not-machine-contacts`, `groups`,+     `test-points` (also KiCad test-point footprints not named `TP<n>`,+     which are not imported);+   - info: `extra-pins`, `ignored`.++   `MP1` to `MP4` are the outermost corner machine pins. A board with more+   machine pins names the others `MS1`, `MS2`, ... (a tentative name); they+   are not published as machine pins.++   Run it on the board file `bundle_check.py` selected, or on the folder+   with `--slug <slug>` to let it pick the board file by the same recipes.+   Renaming happens in the board and the schematic, then the exporter exports+   again; never rename parts inside the exported STEP.+3. `fab_bundle.py check` is the registry's fabrication check (fab_bundle+   1.1.0). The `--slug` is the zip's own stem, which is the slug the export+   used. "source changed since export" means a recorded file was edited or+   rewritten after the export: export again.+4. `bundle_3d.py check` (#16): stock `${KICADn_3DMODEL_DIR}/...` model refs+   resolve everywhere. Every other `(model ...)` ref (absolute paths, personal+   env vars like `${KICAD_USER_PROJECTS_LIBRARY}`) must travel in `3d/` with+   its path rewritten to `${KIPRJMOD}/3d/<basename>`, or the board renders+   blank when someone pulls the project in APM. `bundle_3d.py bundle <board>+   --models <dir>... --write` rewrites the board, which changes its hash, so+   it runs before the exporter writes `export.json`. When check fails on a+   bundle with a record, go back to the exporter (bundle, then export).+   `check` names each missing file; `kicad-cli pcb export glb --subst-models`+   names each unresolved ref on the design machine.++Self-check of the contract copies (run once per install, and in the tests):+`python3 scripts/pin_names.py --self-check scripts/contract.json` prints the+sha256 of `pin_names.py` and `pins.json`; both equal `versions.namesPy` and+`versions.pins` in `contract.json`, and it warns on any difference.++The registry runs the same checks on every build, plus the ones only it can+run (anchor, attachments, normalize). Stage 1 finds a bad bundle before it+reaches the page.++## Stage 2: Package++The package folder is what `adom-wiki pkg publish` packs, whole. Start from a+fresh folder per publish, copy the bundle into it keeping every relative path+(the record names paths relative to its own folder), and add `package.json`+and `README.md`:  ```-<slug>/-  package.json          # see REQUIRED fields below-  <slug>.glb            # OCCT artifact — MUST be named exactly <slug>.glb (see below)-  <name>.kicad_pcb|.brd # board source-  <name>.kicad_sch|.sch # schematic source-  <name>.step          # native EDA source, with models resolved on the design machine-  <slug>-fab.zip       # required fabrication sources for EDA molecules-  export.json         # required versioned export record for EDA molecules-  <name>_footprint.json # OCCT artifact — per-pad wire-attach Z-  <name>_symbol.json    # OCCT artifact+<folder>/+  package.json            # authored here, template below   README.md-  [extras: silk PNGs, .f3d, .usdz, bom, cpl]+  <name>.step             # role step+  <name>.kicad_pcb|.brd|.PcbDoc   # role board+  <name>.kicad_sch ...    # every schematic sheet, or <name>.sch+  <name>.kicad_pro        # KiCad project and any .kicad_sym / .pretty used (APM)+  <slug>-fab.zip          # role fab+  export.json             # role export+  3d/<basename>           # custom component models (APM, Stage 1 step 4)+  [extras: silk PNGs, .f3d, .usdz, BOM, CPL] ``` +Nothing generated goes in the folder: no `<slug>.glb`, `<slug>.web.glb`,+`*_footprint.json`, `*_symbol.json` or `<slug>.pipeline.json`, and no+`page.json` (`pkg publish` ignores it; the page's own `page.json` is merged+from `package.json`). Keep working files such as `component-plan.json`+outside the folder.+ **Key components by MPN, never by value (#142).** The `slug` is the-normalized MPN (lowercase, non-alphanumerics -> dashes), the page title IS+normalized MPN (lowercase, non-alphanumerics to dashes), the page title is the MPN, and `component.mpn` carries it verbatim. Value-named symbols like-`R_4.3K_0402` are properties, not identities — resolve the real MPN before+`R_4.3K_0402` are properties, not identities: resolve the real MPN before publishing, and never mint a page keyed on a value string. -`package.json` REQUIRED fields (publish 400s or silently under-registers-without them):+`package.json`:  ```json {-  "slug": "<slug>", "version": "1.0.0", "type": "component",-  "description": "<≥20 chars>", "tags": ["molecule", "..."],+  "slug": "<slug>", "version": "1.0.0", "type": "component", "kind": "molecule",+  "description": "<at least 20 characters>", "tags": ["molecule", "..."],   "component": { "mpn": "<name>", "manufacturer": "", "category": "other" },-  "dependencies": {},-  "hero": { "headline": "...", "subhead": "...", "screenshot": "screenshots/hero.png" }+  "dependencies": {} } ``` -- The **`component` block is what creates the page's component_metadata row —-  without it `metadata.model_3d_path` is never set and imports fail** with-  "no published GLB" even though the file is there.-- The **`hero` block + `screenshots/hero.png` are hard-required** at publish.--Do NOT include a `page.json` — the server generates it, and a hand-made one-can blank the page brief or override org/visibility on reindex.--**Name the GLB exactly `<slug>.glb`.** At publish the wiki auto-converts the-STEP to a PLAIN `<slug>.glb` (no anchoring, no gold) and points-`model_3d_path` at it — if your anchored OCCT GLB has any other name, the-plain one shadows it and every import silently gets an unanchored model.-(This is exactly what broke the COSMIIC boards.) Matching the name ensures-your anchored GLB is the one `model_3d_path` resolves to.--## Stage 2.5 — Component dependencies (ENFORCED, BEFORE publish)--> **This is a GATE, not a convention** (molecule-pipeline #4). Boards kept-> publishing with `dependencies: {}` — the page renders, the 3D and schematics-> show, and Nucleus/APM displays an empty BOM panel. A publish that skips this-> LOOKS successful, which is why it must be machine-checked.->-> ```bash-> # 1. plan: parse the BOM, classify, probe the global namespace by MPN-> python3 scripts/component_graph.py plan <board.kicad_pcb|.brd> --out component-plan.json-> # 2. build/reuse component pages per the plan (Stage 2.6), wire deps on the board-> # 3. GATE: refuses to let you publish a broken graph (non-zero exit)-> python3 scripts/component_graph.py gate package.json --plan component-plan.json \->     --expect-board <board.kicad_pcb> --resolve-> ```-> The graph is **two layers — `board -> components`** (#18: the auto-generated-> `<board>-library` middle page was dropped; a board depends on its component-> pages directly). The gate enforces two DISTINCT properties (#17):-> - **DECLARED (coverage)** — every electrical BOM part has a dependency naming->   it. A non-empty `dependencies:{}` is not enough; it must actually cover the->   parts, or APM/Nucleus shows a partial/empty BOM panel.-> - **RESOLVED (existence)** — with `--resolve`, every declared dependency must->   resolve to a real wiki page. A dep on a page that does not exist installs->   broken in APM (core owner-pinning fragility); the old "declared" check never->   caught this. An indeterminate probe (offline/error) degrades to a WARN, never->   a false FAIL.->-> The gate also FAILS on: any part with no resolved MPN, a slug keyed on an LCSC-> code or value string (#142), and a stale plan from a different board. The ONLY-> bypass is `--allow-no-components` — an explicit statement that this board has no-> component pages on purpose.--APM lists a board/molecule's components from `package.json.dependencies`-(one-hop expand). This stage is NOT optional and NOT the user's job — a-publish that skips it produces a board that looks successful but shows up-in APM with no BOM panel (#247, the Taprite carriers). Do it every publish:+- `"kind": "molecule"` is required: the recipes, the refusal and the build+  key on the page's kind after the write.+- The `component` block creates the page's component metadata. A publish+  merges `package.json` over the page's `page.json` key by key, so this block+  replaces the page's `component` block: anything the page should keep there+  (the hero camera of Stage 4) belongs in `package.json` too.+- No `hero` block: the hero is set in Stage 4 from the built model, and a+  component package publishes without one (the hero is required only when+  the page goes public).+- No `visibility` field: a value there would override the page's visibility+  on every publish.+- Bump `version` on every publish.++## Stage 2.5: Component dependencies (enforced, before publish)++This is a gate, not a convention (molecule-pipeline #4). A board published+with `dependencies: {}` renders, shows its 3D and schematics, and has an empty+BOM panel in Nucleus/APM. Such a publish looks successful, which is why it is+machine-checked:++```bash+# 1. plan: parse the BOM, classify, probe the global namespace by MPN+python3 scripts/component_graph.py plan <folder>/<board.kicad_pcb|.brd|.PcbDoc|.fbrd> --out <work>/component-plan.json+# 2. build or reuse component pages per the plan (Stage 2.6), wire deps on the board+# 3. gate: refuses a broken graph (non-zero exit)+python3 scripts/component_graph.py gate <folder>/package.json --plan <work>/component-plan.json \+    --expect-board <board.kicad_pcb> --resolve+```++The graph has two layers, `board -> components` (#18: the auto-generated+`<board>-library` middle page was dropped; a board depends on its component+pages directly). The gate enforces two separate properties (#17):++- **Declared (coverage)**: every electrical BOM part has a dependency naming+  it. A non-empty `dependencies` is not enough; it must cover the parts.+- **Resolved (existence)**: with `--resolve`, every declared dependency+  resolves to a real wiki page. A dependency on a missing page installs+  broken in APM. An indeterminate probe (offline, error) is a warning, never+  a false failure.++The gate also fails on a part with no resolved MPN, a slug keyed on an LCSC+code or value string (#142), and a stale plan from a different board. The+only bypass is `--allow-no-components`, an explicit statement that this+board has no component pages on purpose. Machine pins and contacts are+furniture, not BOM parts. `component_graph.py` takes them from the pin-name+census of `scripts/pin_names.py`: every part the census classes as a machine+pin or contact, whether it accepts, warns about or refuses it. `plan` prints+which parts those are and the checks the census refuses the board on. When+the census cannot read the board, `plan` says so and falls back to the+designator rule (`designators.nearMiss` in `scripts/pins.json`).++APM lists a board's components from `package.json.dependencies` (one-hop+expand). Do this every publish:  1. **Parse the BOM** (BOM CSV beside the sources, else the `.kicad_sch`).-2. **Electrical rows only** — skip logos, silkscreen art, fiducials,-   mounting holes, DIN adapters, graphic/mechanical symbols.-3. **Resolve the real MPN** for each row (never value names — #142). A row-   with no MPN and no unambiguous standard part = FLAG for human-   resolution; report it, never silently drop it.-4. **Depend on the component pages directly (#18)** — the board's+2. **Electrical rows only**: skip logos, silkscreen art, fiducials, mounting+   holes, DIN adapters, graphic and mechanical symbols.+3. **Resolve the real MPN** for each row (never value names, #142). A row+   with no MPN and no unambiguous standard part is flagged for a person;+   report it, never drop it silently.+4. **Depend on the component pages directly (#18)**: the board's    `dependencies` are the owner-qualified component refs themselves-   (`{ "adom/<mpn-slug>": "*", ... }`). Graph: **`board -> components`**, two-   layers. The old auto-generated `<board>-library` middle page was dropped:-   it added a page to maintain for no BOM benefit (APM one-hop-expands the-   board's deps directly). Do NOT create a `-library` page. *(A hand-made-   library page is still permitted for genuine reuse groupings; if you make-   one, its tags are `["library", <topical>...]` and MUST NOT contain `board`-   or `molecule` — the kind tag is what Nucleus keys on (#5), so a stray one-   makes the library render as a board/molecule.)*-5. **Order + one version per cycle**: publish the component pages first, then-   the board — a dep must exist and RESOLVE when the board publishes (the-   `--resolve` gate enforces this). Merge everything BEFORE the board's-   Stage 3 publish so each cycle produces exactly ONE registry version.--- **Resolve a real MPN for every electrical part.** An LCSC/distributor code-  (`c11702`) or a value string (`R_10K_0402`, `100nF`) is a property, not an-  identity — the gate refuses both (#142). Resolve codes with-  `adom-jlcpcb search <code>` before minting a page; a part you cannot resolve-  is FLAGGED for a human, never silently dropped.-- **Reuse beats recreate.** The component namespace is shared across owners, so-  `plan` probes it by resolved MPN and wires the EXISTING page (whatever its-  owner) into the board's `dependencies` instead of publishing a duplicate.-- **Throttle component publishes.** The registry rate-limits after ~10 rapid-  publishes; pace them (~2 s apart) on boards with large BOMs.+   (`{ "adom/<mpn-slug>": "*", ... }`). Do not create a `-library` page. A+   hand-made library page is still allowed for real reuse groupings; its+   tags are `["library", <topical>...]` and must not contain `board` or+   `molecule`, because Nucleus keys on the kind tag (#5).+5. **Order, and one version per cycle**: publish the component pages first,+   then the board; a dependency must resolve when the board publishes (the+   `--resolve` gate checks it). Merge everything before Stage 3 so each cycle+   produces one registry version.++- Resolve LCSC/distributor codes with `adom-jlcpcb search <code>` before+  minting a page.+- **Reuse beats recreate.** The component namespace is shared across owners;+  `plan` probes it by MPN and wires the existing page, whatever its owner.+- **Throttle component publishes**: the registry rate-limits after about 10+  rapid publishes; pace them about 2 s apart on large BOMs. - Mapping helper: `skills/publish-board/kicad_board_bundle.py` on the-  `adom/adom-project-manager` page (`adom-wiki repo clone adom/adom-project-manager`).-  Mind its Value-fallback caveat: value-named symbols like `R_4.3K_0402` are-  NOT component slugs — resolve the real MPN.-- Write owner-qualified refs (`adom/<slug>`) into `dependencies`. **MERGE,-  never overwrite** — preserve `component`, `hero`, `tags`, `model_3d_path`.-- Verify each referenced component page exists; flag missing ones.-- The dependency graph is a REGISTRY concept — it rides Stage 3's-  `pkg publish`, not the repo push.-- Known behavior to keep in mind: deps are real registry deps, so-  `pkg install <board>` will pull the component pages too.--## Stage 2.6 — Auto-create missing component pages--A dep that references a nonexistent page dangles. For each electrical BOM-part with no wiki page, CREATE one (then reference it) — report created vs-reused vs flagged:--- **Page standard**: `type: component`, slug/title = normalized MPN, with-  `<MPN>.kicad_sym` + `<MPN>.kicad_mod` + STEP + **step2glb** GLB +-  `<MPN>.adom-lbr.json` + hero + `component` block.-- **Asset sources, in order**: KiCad stdlib via `service-kicad`-  (`fp fetch <lib> <name>`, `sym fetch <lib>`, `model fetch <lib>.3dshapes/-  <name>.step`); the board's own embedded footprints/symbols for custom-  parts (extract the `(footprint ...)` block from the `.kicad_pcb`, the-  lib symbol from the `.kicad_sch`).+  `adom/adom-project-manager` page (`adom-wiki repo clone+  adom/adom-project-manager`). Value-named symbols like `R_4.3K_0402` are not+  component slugs: resolve the real MPN.+- Write owner-qualified refs (`adom/<slug>`) into `dependencies`. Merge, never+  overwrite: keep `component`, `kind` and `tags`.+- Dependencies ride Stage 3's `pkg publish`; they are a registry concept, and+  `pkg install <board>` pulls the component pages too.++## Stage 2.6: Auto-create missing component pages++For each electrical BOM part with no wiki page, create one (then reference+it), and report created, reused and flagged parts:++- **Page standard**: `type: component`, slug and title the normalized MPN,+  with `<MPN>.kicad_sym`, `<MPN>.kicad_mod`, STEP, a `step2glb` GLB,+  `<MPN>.adom-lbr.json`, hero and `component` block. Component pages are not+  molecule pages: the registry's molecule recipes and the refusal do not+  apply to them, so their GLB is still converted and pushed here.+- **Asset sources, in order**: KiCad stdlib via `service-kicad` (`fp fetch+  <lib> <name>`, `sym fetch <lib>`, `model fetch <lib>.3dshapes/<name>.step`);+  the board's own embedded footprints and symbols for custom parts (the+  `(footprint ...)` block from the `.kicad_pcb`, the lib symbol from the+  `.kicad_sch`). - **adom-lbr JSON**: `adom-lbr import-kicad --sym <f> --fp <f> --mpn <MPN>`;   also ship the Fusion `.lbr` from `adom-lbr generate`.-- **3D is hard-required by publish lint.** If the part's model exists only-  in the designer's local library (footprint `(model ...)` pointing at a-  local path), FLAG the page as pending with the exact missing file — do-  NOT fabricate geometry and do NOT drop the part. The dep is added only-  once the page exists.-- Hero: render the GLB with adom-glb2png (iso view), or for pending-3D-  parts a real KiCad footprint render (`service-kicad pcb export svg` on a-  small custom sheet).+- **3D is required by publish lint.** If the part's model exists only in the+  designer's local library, flag the page as pending with the exact missing+  file; do not fabricate geometry and do not drop the part. The dependency is+  added once the page exists.+- Hero: render the GLB with adom-glb2png (iso view), or for pending-3D parts a+  real KiCad footprint render (`service-kicad pcb export svg` on a small+  custom sheet).++## Stage 3: Publish private, wait for the build -## Stage 3 — Publish + verify+**3.1 Read the page first** (an existing page only; `<ref>` is+`<owner>/<slug>`):  ```bash-adom-wiki pkg publish [--org adom]-adom-wiki repo push <owner>/<slug> --files <every file above> -m "<name> molecule"-adom-wiki page visibility <owner>/<slug> --preset open   # or private+adom-wiki --json model status <ref>+adom-wiki --json model builds <ref> --limit 1+MSYS_NO_PATHCONV=1 adom-wiki --json api "/api/pages/<owner>/<slug>/files?recursive=1" > <work>/page-files.json ``` -Verify before declaring done:-- For an EDA molecule, the explicit push list includes `<slug>-fab.zip`,-  `export.json` and every recorded source. Download that complete set at the-  returned commit into a fresh directory and run `fab_bundle.py check` there;-  all hashes must match. See [docs/fabrication.md](docs/fabrication.md).-- `adom-wiki api /api/v1/pages/<slug>` → `metadata.model_3d_path` is set-- **the GLB at `model_3d_path` is byte-identical to YOUR gated conversion-  output** — this is the anchoring proof. (Do NOT inspect the GLB for a-  `molecule_anchor` node: the optimizer flattens it away by design — the-  anchoring survives as baked geometry, not as a node. A gate on that node-  false-fails every properly converted molecule.)-  ```bash-  curl -fsSL "https://wiki.adom.inc/blob/component/<slug>/<slug>.glb" -o /tmp/check.glb-  sha256sum /tmp/check.glb <slug>.glb   # MUST match — if not, the page is-  # serving a different GLB (e.g. the wiki's plain auto-conversion): re-push-  # your OCCT GLB as <slug>.glb and re-verify.-  ```-  Your conversion's stats block (`molecule_anchored: true`, no warnings) plus-  this checksum equals a verified anchored GLB on the page.-- the page's Files tab shows the full bundle (registry and git layers are-  separate — publish alone does not populate Files)-- the registry tarball is the **source of record per version**: Stage 2's-  layout means every publish carries the full board source, and-  `adom-wiki pkg install <owner>/<slug>@<version>` delivers any past-  version's files (APM's version selector relies on this for "give me the-  source of an older version" — render/ is previews only, never source).--## Stage 3.5 — APM render assets + version archive (AFTER publish, every time)--APM shows PCB + hierarchical schematics + the board **version selector**-from a pre-rendered `render/` folder; without it, boards trip APM's red-"missing render folder" bar and fall back to slow live rendering.+- `model status`: a page that answers `PAGE_NOT_FOUND` is new (go to 3.2,+  first publish). Otherwise `data.manifest.policy.buildsThisPage` must be+  true ("the registry builds and serves this page's models"). Anything else+  ("the server reports no build policy", "it does not build this page",+  "the registry is not active for this page" `MODEL_REGISTRY_OFF`,+  `MODEL_SOURCE_HIDDEN`) means no build would follow: stop, print the status+  line, and leave the page as it is. Never fall back to converting the STEP+  and pushing a GLB.+- `model builds`: note `data.builds[0].id` (0 when there is none). The build+  that counts in 3.4 has a higher id.+- The files listing goes to `bundle_check.py --page-files`; run Stage 1 step+  1 again with it. (`MSYS_NO_PATHCONV=1` keeps Git Bash on Windows from+  rewriting `/api/...`; the CLI has no file-listing verb, so this is a GET+  through `adom-wiki api`.)++**3.2 Publish** from the package folder. This one `pkg publish` is the only+write of the sources: its "Publish X.Y.Z" commit carries every recorded+source and `export.json` together, and the registry queues one build from it.  ```bash-adom-wiki pkg install adom/adom-nucleus    # once per container (APM was RENAMED-adom-nucleus --render-board <slug>         # to adom-nucleus; the old-# adom-project-manager name still works via the rename shim's symlink)+# first publish of a new page+adom-wiki --json pkg publish --private --wait --timeout 1200 [--org <org>]+# update of an existing page (no --private: on a republish it would make a public page private)+adom-wiki --json pkg publish --wait --timeout 1200 ``` -**Ordering is load-bearing: run this AFTER Stage 3's `pkg publish` + repo-push.** `--render-board` stamps the archive with the version it reads from-the PUBLISHED `package.json` on the page — run it before the publish and it-stamps the previous version.--`--render-board` (APM >= 0.4.0) **fully owns the version archive** — never-write `render/<version>/` or edit `render/manifest.json` yourself-(double-writing fights its content dedup). On each run it:-- renders + pushes the top-level `render/*` = current version (including-  `render/board.glb` whenever a GLB exists);-- content-hashes the rendered assets and, ONLY if they differ from the last-  archived version, writes `render/<version>/...` and prepends a-  `versions[]` entry to `manifest.json` (v2: `{v:2, current, versions[]}`,-  newest-first). A deps/metadata-only republish adds NO entry.--Verify after the run:-- `render/manifest.json` is on the page, parses, and `current` == the-  version you just published;-- a content-changing publish added a `versions[]` entry + `render/<version>/`-  files; a metadata-only republish did NOT (dedup working as intended).-- **`render/board.glb` is not DEGRADED (adom/wiki#91).** `--render-board`-  sometimes writes a `render/board.glb` with far fewer meshes than the board-  actually has, and the page serves it via `model_3d_path`. Gate on MESH-  COUNT, never file size (size gives false positives both ways):-  ```bash-  python3 scripts/render_parity.py render/board.glb <slug>.glb-  ```-  A faithful render has the SAME mesh count as the page-level `<slug>.glb`-  (verified: zu 190=190, pinch 155=155; the degraded ones were 35 vs 336 and-  11 vs 20). Non-zero exit = the render dropped geometry: re-run-  `--render-board`; if it recurs, the render *emitter* is at fault (report the-  board to the `--render-board` / service-kicad owner, this is not fixable in-  the publish flow beyond refusing to ship it).--**Make the sheets VISIBLE (#3):** component pages have no schematic viewer-slot, so rendered `render/sheet-*.svg` are invisible unless embedded. After-the render, append a `## Schematics` section to the page README — one-`### <sheet name>` + `![](render/sheet-NNN.svg)` per `manifest.sheets[]`-entry (+ `## Board layout` with `render/pcb.svg` if absent). Skip when the-README already has the section; refresh it when sheet count/names change.-(Interim until the wiki component page renders `manifest.sheets` natively —-FR filed on adom-wiki-cli.)--Re-run on every content update so it never goes stale. KiCad sources render-today; EAGLE/Fusion (`.brd`/`.sch`) pages report "nothing rendered" and skip-gracefully — APM shows a static version label for them (Fusion rendering is-landing in APM; nothing changes on this side when it does).--## Publish completion checklist (a publish is NOT done until all pass)--- [ ] `metadata.model_3d_path` set; page GLB sha256 == your gated conversion+The job budget is 900 s and a build can queue first, hence `--timeout 1200`+(the default is 600). Do not follow the publish with a `repo push` of the+same files: it changes nothing (`PUSH_UNCHANGED`) and queues no build.++**3.3 The write was refused** (`status: "error"`, exit 1, nothing written).+The server's code is `data.response.code`:++- `REGISTRY_MODEL_FILE_REFUSED`: the package holds files the registry+  generates; they are listed in `data.response.data.paths`. Tell the user+  which files were refused and why (the registry builds them from the+  sources). Delete those paths from the package folder, run Stage 1 again,+  and publish again with the same command. `data.response.data.minimum`+  names the publisher and CLI versions that no longer pack them. Never route+  around a refusal: no `ADOM_WIKI_HARDWARE_PRECHECK=0`, no renamed copies of+  the files, no split publish or push, no other slug or second page, no+  `repo push` of the refused files.+- `HARDWARE_3D_MODEL_REQUIRED` on a first publish: the page would have gone+  public with no model. Publish with `--private`.+- Any other code: show the error and its hints, and stop.++**3.4 The write landed** (`status: "ok"`). `data.model` is the build's+result, or null with `data.model_skipped` naming why no wait ran:++| `data.model.outcome` / `data.model_skipped` | Exit | What to do |+|---|---|---|+| `passed` | 0 | run the done check below |+| `superseded` (the newer build could not be read) | 0 | `adom-wiki --json model wait <ref> --build <N> --timeout 1200` (N from the hint) |+| `failed`, `cancelled` | 1 | the failure path below |+| `timeout` | 3 | `adom-wiki --json model wait <ref> --build <id> --timeout 2400` |+| `no_build` | 0 | `adom-wiki model status <ref>`: if the sources did not change and the served model is from a passed pipeline build of them, the page is done; else `adom-wiki model plan <ref>` names why no recipe applies, and a page manager can run `adom-wiki --json model rebuild <ref> --wait --timeout 1200` |+| `registry_off`, `source_hidden` | 0 | stop as in 3.1; on a first publish the page stays private with its sources |+| `error`, or skipped `pre_read_failed`, `no_owner`, `other_page` | 0 | `adom-wiki --json model wait <ref> --after <id from 3.1> --timeout 1200` |++`model wait` takes the same table, with exit 4 for "nothing to wait for".++**Done check.** The publish is done only when all of these hold:++1. `data.model.outcome` is `passed`, `data.model.build.status` is `passed`+   and `data.model.build.error` is null.+2. `data.model.build.id` is higher than the id read in 3.1.+3. The page's `model` slot has `origin: "pipeline"`: `data.model.served`+   (the `model` entry of `GET .../models`), or `adom-wiki model status <ref>`.+   When the CLI prints "build N moved no model pointer", the outputs matched+   a model already served; check that `model status` lists it with origin+   pipeline.+4. `data.model.build.result.metadataComplete` is true. A passed+   `molecule/8` build always writes the footprint and symbol. When it is+   false, the server ran an older program; print a warning naming+   `data.model.build.result.pipeline` and the route, for example: "warning:+   build 812 passed on molecule/6, route step, with metadataComplete false:+   the page has a 3D model and no footprint or symbol, so Hydrogen has no+   wire attach points for it."+5. Show each of `data.model.build.warnings` (`<stage>: <check>: <detail>`),+   for example `not-machine-pins` or `anchor-by-names`.++**Failure path.** `adom-wiki model report <ref> <id>` names the failed checks+with their detail texts (counts, part names, the fix). Show them. The page+keeps the model it had; a new page has none and stays private. The fix is in+the sources: rename pins in the board and schematic, or export the STEP and+fab files again from the saved board when the model or artwork fit only+turned or mirrored, then run Stage 1 and publish a new version. Never push a+GLB to get past a failed build.++## Stage 4: Hero from the registry model++The hero is posed from the model the registry built:++```bash+adom-wiki repo show <ref> <data.model.served.path> --out <work>/<slug>.glb+sha256sum <work>/<slug>.glb        # must equal data.model.served.sha256+adom-wiki repo show <ref> page.json --out <work>/page.json+python3 scripts/hero_camera.py pose <work>/<slug>.glb --page <work>/page.json+python3 scripts/hero_camera.py pose <work>/<slug>.glb --page <folder>/package.json+```++- At the slot path the files route serves the registry's object, and `repo+  show` checks the bytes against the listing. If the sha256 still differs,+  the CLI read an older file of the repo: stop and report it (the CLI has no+  verb that downloads `/api/pages/<ref>/models/<sha256>` itself).+- `hero_camera.py pose` writes Ray's canonical `alpha 1.571, beta 0.785` and a+  bounds-computed `radiusScale` into `component.viewer_3d.camera` (#87) and+  prints the `?camera=a,b,scale` string. Write it into both files: the+  page's `page.json` now, and `package.json` so the next publish keeps it.+  Override `--alpha/--beta` only for a board whose canonical orientation is+  not the default iso.+- Capture a 16:10 PNG, at least 1600 px wide, at that pose (the page's 3D tab+  with `?camera=`), as `<work>/screenshots/hero.png`.+- Push both and set the hero (neither file is a source, so no build follows):++```bash+cd <work> && adom-wiki repo push <ref> --files page.json screenshots/hero.png -m "hero"+adom-wiki page hero <ref> --image screenshots/hero.png+```++## Stage 5: Public++```bash+adom-wiki page visibility <ref> --preset open+```++This passes once a build has passed: the hardware gate counts the served+`model` pointer. While a build is queued or running it is refused with+`HARDWARE_3D_MODEL_REQUIRED` (`data.lastBuild.status` says which); wait for+it (Stage 3.4) and run it again. An update of a page that is already public+skips this stage.++## Stage 6: APM render assets and version archive (after the publish, every time)++APM shows the PCB, the hierarchical schematics and the board version selector+from a pre-rendered `render/` folder; without it APM shows its red "missing+render folder" bar and renders live, slowly. `render/**` is never a+generated file, so these pushes are accepted on molecule pages.++```bash+adom-wiki pkg install adom/adom-project-manager   # once per container; installs the adom-nucleus command+adom-nucleus --render-board <owner>/<slug>+```++Run it after Stage 3's publish: `--render-board` stamps the archive with the+version it reads from the published `package.json`, so before the publish it+stamps the previous version. `--render-board` (APM 0.4.0 or newer) owns the+version archive; never write `render/<version>/` or edit+`render/manifest.json` yourself. On each run it:++- renders and pushes the top-level `render/*` for the current version+  (including `render/board.glb` when it can render one);+- hashes the rendered assets and, only if they differ from the last archived+  version, writes `render/<version>/...` and prepends a `versions[]` entry to+  `manifest.json` (v2: `{v:2, current, versions[]}`, newest first). A+  deps-only or metadata-only republish adds no entry.++Verify after the run: `render/manifest.json` is on the page, parses, and+`current` equals the version this publish made; a content change added a+`versions[]` entry and `render/<version>/` files, and a metadata-only+republish did not. The page's 3D viewer shows the registry model, not+`render/board.glb`.++**Make the sheets visible (#3):** component pages have no schematic viewer+slot, so `render/sheet-*.svg` are invisible unless embedded. After the render,+append a `## Schematics` section to the README: one `### <sheet name>` and+`![](render/sheet-NNN.svg)` per `manifest.sheets[]` entry (and `## Board+layout` with `render/pcb.svg` if absent). Skip when the README already has+the section; refresh it when sheet count or names change. Edit the README in+the package folder and push it (`repo push <ref> --files README.md`), so the+next publish keeps it.++Run it on every content update. KiCad sources render today; EAGLE/Fusion+(`.brd`/`.sch`) pages report "nothing rendered" and skip, and APM shows a+static version label for them.++## Stage 7: Handoff to Hydrogen++After the done check passed (a private page imports too: Hydrogen reads it+with your own token, so anyone who can read the page can import it):++```bash+adom-wiki model import <owner>/<slug> --owner <your user or org> [--name <name>]+```++It reads the page first and refuses one with no model yet before anything is+sent to Hydrogen (`MODEL_IMPORT_NO_MODEL`, exit 1, naming+`adom-wiki model status <ref>`). Hydrogen then reads the registry model the+page serves and the page's sources: the board, the schematic, and the+`<slug>_footprint.json` and `<slug>_symbol.json` the build wrote, which carry+the wire attach points. A page an older program built 3D-only imports with no+attach points until a build from its board file passes. `--name` defaults to+the page slug less a trailing all-digit part.++The handoff is done when it exits 0 and prints `<owner>/<slug>: imported into+Hydrogen as <hydrogen-owner>/<name>, version <v>, from <glb>` and the link+`https://hydrogen.adom.inc/<hydrogen-owner>/molecules/<name>`. Each Hydrogen+warning is a `HYDROGEN_IMPORT_WARNING` hint (the exit is still 0); report+every one. With `--json`, `data` is `{ ref, url, hydrogen }`, `hydrogen` being+Hydrogen's reply (`name`, `owner`, `version`, `reusedGlb`, `sourceCarried`,+`warnings`). `HYDROGEN_IMPORT_FAILED` (exit 1) carries Hydrogen's status and+message: 401 sign in, 403 an owner you may act for, 404 a page you can read,+422 no model yet. With the CLI pointed at a wiki other than wiki.adom.inc and+`ADOM_HYDROGEN_URL` unset, it refuses before sending+(`MODEL_IMPORT_OTHER_WIKI`, exit 2): Hydrogen reads pages from wiki.adom.inc.+Do not re-implement import here.++## Board mode (plain boards, no machine pins)++The registry builds models only for pages of kind molecule, so a plain board+keeps the conversion it had:++```bash+adom-wiki pkg install adom/adom-step2glb+step2glb convert <name>.step -o <slug>.glb+```++Use a plain convert, with no molecule flags and no anchoring gates. If the+output warns `molecule_markers_detected`, the board is a molecule: switch to+the molecule flow. Name the GLB exactly `<slug>.glb`, publish with tag+`board` and no `kind`, push the GLB with the sources, and check that+`metadata.model_3d_path` names it. If `web_grade.overBudget` is true, the+convert also writes `<slug>.web.glb` (decimated, under 8 MB and 4M vertices,+adom/wiki#82): push it beside `<slug>.glb` so the page viewer shows it inline.+Stages 2.5, 2.6 and 6 apply as for molecules.++## Completion checklist (a publish is not done until all pass)++- [ ] `scripts/versions_check.py` passed (adom-wiki 1.8.0 or newer)+- [ ] Stage 1 passed on the folder that was published+- [ ] the done check of Stage 3.4 passed, with `metadataComplete: true` - [ ] board `dependencies` name every electrical BOM part directly-      (`board -> components`, #18) — DECLARED coverage; `{}` on a board with-      electrical parts is a FAILED publish, not a done one-- [ ] `gate --resolve` passes: every declared dependency resolves to a real-      page (#17) — a dangling dep installs broken in APM-- [ ] every referenced component page exists (Stage 2.6), or is explicitly-      flagged pending with what it needs-- [ ] if you actually exercised this molecule this session, stamp it:-      `scripts/tested_with.py stamp package.json --family <your-model>` — adds-      `tested-with:<family>` forward-only (never backfill existing pages, #85)-- [ ] `render/manifest.json` on the page with `current` == the version you-      just published (Stage 3.5)-- [ ] `render/board.glb` mesh count == the page `<slug>.glb` (adom/wiki#91) —-      `scripts/render_parity.py render/board.glb <slug>.glb`; a degraded-      render is what the 3D tab serves, so refuse to ship it-- [ ] every CUSTOM `(model ...)` in the board is bundled under `3d/` (#16) —-      `scripts/bundle_3d.py check <board> --page <owner>/<slug>`; unbundled-      custom models render blank when a recipient pulls the project-- [ ] molecule shape only: provenance stamp + footprint/symbol artifacts-- [ ] **web-grade GLB** — if `web_grade.overBudget` is `true`, the convert-      now ALSO emits `<slug>.web.glb` (decimated, decoder-free, under 8 MB /-      4M verts — adom/wiki#82). **Push it alongside `<slug>.glb`**: the page-      viewer renders the `.web.glb` inline and offers the full model as the-      download, so a heavy board (workcell, multi-board scene) no longer-      click-to-load-gates. Verify `stats.web_lod.fits == true`; if a model is-      irreducibly large it stays gated. Under-budget models get no twin (and-      need none).+      (`board -> components`, #18); `{}` on a board with electrical parts is+      a failed publish+- [ ] `gate --resolve` passes: every declared dependency resolves (#17)+- [ ] every referenced component page exists (Stage 2.6), or is flagged+      pending with what it needs+- [ ] the hero is posed from the registry model, and the camera is in both+      `page.json` and `package.json`+- [ ] the page is public (new pages)+- [ ] `render/manifest.json` on the page with `current` equal to the version+      this publish made (Stage 6)+- [ ] every custom `(model ...)` in the board is bundled under `3d/` (#16)+- [ ] if you exercised this molecule this session, stamp it:+      `scripts/tested_with.py stamp package.json --family <your-model>`  ### Tested-with tagging (#85) -When an agent has actually **exercised** a molecule/board this session (loaded it,-verified the render/BOM, ran the gates), stamp the page so a reader can tell-verified pages from merely-published ones:+When an agent has exercised a molecule or board this session (loaded it,+checked the render and BOM, ran the gates), stamp the page so a reader can+tell verified pages from published ones:  ```bash python3 scripts/tested_with.py stamp package.json --family <model> [--version <exact>] ```  Rules the helper enforces, per the #85 decision (drew2):-- **Forward-only, NO backfill.** Stamp at publish going forward; never run it-  across existing pages. Absence must stay meaningful — a `tested-with:` tag-  present means a model really verified that page, not that a migration stamped-  it. The helper has no bulk mode on purpose.-- **The tag is the model FAMILY** (`tested-with:claude`, `tested-with:gpt`), not-  the version — families stay accurate as versions roll (Colby). The exact-  version, if given, is recorded in `metadata.tested_with[]`, out of the tag space.-- **Tested-only.** There is deliberately no `authored-with` tag — authorship is-  not a verification signal.--## Stage 4 — Handoff--Import to Hydrogen is `adom-molecule-import`'s job (ships with-`adom/adom-molecule`): authenticated clone + `adom-molecule create --glb ...---no-optimize`. Do not re-implement it here.--**Attach-points caveat:** `adom-molecule import <slug>` (the one-shot verb)-currently carries ONLY the GLB — no footprint/symbol reach Hydrogen, so the-molecule has no wire attach points. Until that's fixed, register with the-board included so Hydrogen generates and attaches the footprint at create:-`adom-molecule create --owner <o> --name <n> --glb <slug>.glb --pcb <board>---no-optimize` (use `--brd` for EAGLE/Fusion boards).--## Page polish rules (field-tested — molecule-pipeline #190)--Hard-won from ~10 real imports; each one cost a debugging detour:--- **Heroes on board/component pages are static images** — `page hero --image`,-  never `--screenshot`/billboard (billboard composes an app-style browser-  frame around the render: "images within images").-- **Pose the hero at the board's CANONICAL camera, not a hardcoded angle-  (adom/wiki#87).** A board's correct orientation is designer-known (alpha-  encodes it), so it now lives ON the page: `page.json`'s-  `component.viewer_3d.camera` `{alpha, beta[, radiusScale]}` (radians;-  precedence `?camera=` query > page declaration > platform home view). When-  capturing the hero, DON'T invent angles — capture at the page's declared-  camera (or open the 3D tab bare and let precedence resolve to the home-  view), and **vary radius only** to frame it. This keeps the hero and the-  live 3D tab showing the same pose. If the board has a known good-  orientation, declare it in the page's `component.viewer_3d.camera` block-  (`{alpha, beta[, radiusScale]}`, sanitized at index time like the other-  component keys) so every consumer — 3D tab, hero capture, downstream-  embeds — agrees. Ray's rule: the home/declared view is right; only the old-  hardcoded renderer defaults were wrong.-  **Declare it with the helper** (don't hand-edit angles):-  `scripts/hero_camera.py pose <slug>.glb --page page.json` writes Ray's-  canonical `alpha 1.571, beta 0.785` plus a bounds-computed `radiusScale`-  (vary-radius-only) into `component.viewer_3d.camera`, and prints the-  `?camera=α,β,scale` string to capture the hero at that exact pose. Override-  `--alpha/--beta` only for a board whose canonical orientation isn't the-  default iso.-- **Browse-card thumbnails bake at publish time** — a repo-only hero push-  does NOT refresh the card. Republish with a version bump, then verify the-  served card PNG actually changed (sha256 the blob).-- **Keep board pages PDF-free.** Any PDF in the repo becomes an unwanted-  auto-scanned "Datasheet" section with no manifest opt-out — ship docs on a-  dedicated docs page or as release assets instead.-- **Draco-compress big scene GLBs only.** Multi-MB workcell/scene models:-  `gltf-transform optimize --compress draco` (35 MB → ~1.3 MB, <3 s load).-  Chip/molecule-sized GLBs: do NOT draco — it comes out ~40% BIGGER than-  quantized and the wiki readme sandbox can't decode it (adom-step2glb #3).-  Your published molecule GLB is already optimized by OCCT — leave it alone.-- **Plain components (no MP markers) skip axis normalization** — molecule-  mode anchors Z-up, but a plain `step2glb convert` preserves the source-  STEP's axes; check orientation per board and bake a ±90° X root rotation-  only when the source needs it.-- **Wiki page animations are baked glTF animations** in the viewer GLB —-  GIFs only work inside README sections.++- **Forward-only, no backfill.** Stamp at publish from now on; never run it+  across existing pages. A `tested-with:` tag means a model really verified+  that page, not that a migration stamped it. The helper has no bulk mode on+  purpose.+- **The tag is the model family** (`tested-with:claude`, `tested-with:gpt`),+  not the version, so it stays accurate as versions roll (Colby). The exact+  version, if given, goes into `metadata.tested_with[]`.+- **Tested only.** There is no `authored-with` tag: authorship is not a+  verification signal.++## Old files and old publishers++- Files an older publisher pushed (`<slug>.glb`, `<stem>_footprint.json`,+  `render/board.glb`, ...) stay in the page repo. No skill deletes them.+  Readers see the registry objects at the slot paths; `bundle_check.py` reads+  the page listing so an old second STEP or board shows up before the+  publish.+- A `repo pull` or `repo clone` of an old page brings those files into a+  local folder; that is the usual cause of a refused publish. Delete them+  from the folder, not from the page.+- `adom-wiki model status <ref>` warning `MODEL_SLOTS_SPLIT` (the `model` and+  `web` slots come from different builds, usually after a 2.x publish pushed a+  GLB): a page manager runs `adom-wiki --json model rebuild <ref> --wait`.++## Page polish rules (field-tested, molecule-pipeline #190)++- **Heroes on board and component pages are static images**: `page hero+  --image`, never `--screenshot` or a billboard (a billboard frames the render+  in an app-style browser window).+- **Pose the hero at the board's canonical camera, not an invented angle+  (adom/wiki#87).** The pose lives on the page: `component.viewer_3d.camera`+  `{alpha, beta[, radiusScale]}` (radians; precedence `?camera=` query, then+  the page declaration, then the platform home view). Capture at the declared+  camera and vary the radius only, so the hero and the live 3D tab show the+  same pose. Declare it with `scripts/hero_camera.py pose` (Stage 4), never by+  hand-editing angles.+- **Browse-card thumbnails bake at publish time**: a hero set after the+  publish shows on the card from the next published version. If the card+  must change now, publish a patch version; its sources are unchanged, so no+  build follows. Then check the served card PNG changed (sha256 the blob).+- **Keep board pages PDF-free.** Any PDF in the repo becomes an auto-scanned+  "Datasheet" section with no opt-out; ship docs on a separate docs page or+  as release assets.+- **Never draco-compress or re-optimize a model here.** The registry's model+  is already optimized (Draco geometry, PNG/JPEG textures). In board mode,+  multi-MB workcell or scene GLBs may use `gltf-transform optimize --compress+  draco`; chip and molecule-sized GLBs come out about 40% bigger with Draco+  and the wiki README sandbox cannot decode it (adom-step2glb #3).+- **Plain boards (no machine pins) skip axis normalization**: a plain+  `step2glb convert` keeps the source STEP's axes; check orientation per+  board and bake a 90 degree X root rotation only when the source needs it.+  The registry normalizes molecules itself.+- **Wiki page animations are baked glTF animations** in the viewer GLB. On a+  molecule page the registry builds, the model comes from the sources, so a+  hand-animated GLB cannot be the page's model; GIFs work inside README+  sections.  ## Related -- `adom-molecule-import` — the wiki → Hydrogen companion-- `kicad-export-molecule` / `fusion-export-molecule` / `altium-export-molecule` — the EDA → bundle front-ends that hand off here-- `adom-step2glb` — the conversion CLI/service this skill drives-- `molecule-pipeline` — the top-level router across the whole chain+- `adom-wiki model import` (in the adom-wiki-cli skill): the wiki to Hydrogen companion+- `kicad-export-molecule` / `fusion-export-molecule` / `altium-export-molecule`:+  the EDA front ends that hand a bundle to this skill+- `adom-tsci export-wiki`: tscircuit molecules (`circuit.json`, circuit route)+- `adom-step2glb`: board mode and component pages only+- `molecule-pipeline`: the router across the whole chain
docs/fabrication.md+76−23
@@ -2,17 +2,22 @@  Every new KiCad, Fusion or Altium molecule export includes `<slug>-fab.zip` and `export.json`. Make them from the same saved board revision as the STEP.-Finish source edits, including custom-model path rewrites, before exporting.-Use a fresh folder per export so old files cannot enter a new bundle.+Finish source edits, including custom-model path rewrites+(`scripts/bundle_3d.py bundle --write`), before exporting: the record hashes+the board. Use a fresh folder per export so old files cannot enter a new+bundle.  The zip contains both sides' copper, solder mask and silkscreen, the actual board outline, and Excellon drill files. Keep plated and unplated drills separate where the exporter supports it; record mixed drills honestly. Keep the original file bytes and names inside the zip. Optional inner-copper, paste and Gerber job files may travel too. Preserve silk PNGs while-the current converter still consumes them.+copper, paste and Gerber job files may travel too. The registry build takes+its board layers from this zip; it does not read silk PNGs, so carry those+only as extras when the exporter made them. -`export.json` uses the existing `adom.export/1` contract from Fusion PR #17:+`export.json` uses schema `adom.export/1`, defined by `scripts/fab_bundle.py`+(`create` writes it, `check` enforces it). Fusion bridge PR #17 (open,+unreleased) drafts a bridge-side writer for the same schema.  - `tool`, `toolVersion`, `exporter`, `exporterVersion`: actual producers. - `files[]`: relative path, role, byte count and SHA-256 for the STEP, saved@@ -21,14 +26,16 @@ the current converter still consumes them.   the zip, role, byte count and SHA-256. Nested entries avoid confusing   archive members with real page paths. - Layer roles: `copper_top`, `copper_bottom`, `mask_top`, `mask_bottom`,-  `silk_top`, `silk_bottom`, `outline`; drill roles: `drill_plated`,-  `drill_unplated`, `drill_mixed`; optional `paste_top`, `paste_bottom`,-  `copper_inner_1` (and subsequent inner layers), `gerber_job` and `other`.+  `silk_top`, `silk_bottom`, `outline`, `keepout`; drill roles:+  `drill_plated`, `drill_unplated`, `drill_mixed`; optional `paste_top`,+  `paste_bottom`, `copper_inner_1` (and subsequent inner layers),+  `gerber_job` and `other`. - Source roles: `step`, `board_kicad_pcb`, `board_eagle_brd`,   `board_altium_pcbdoc`, `schematic`, `project`, and descriptive roles for   optional sources (for example `fusion_archive`, `usdz`, `bom`, `cpl`). - `stackup`: known `thicknessMm`, `copperLayers`, `maskColor` and-  `silkColor` by `top`/`bottom`, and `finish`. Unknown values stay null or+  `silkColor` by `top`/`bottom`, and `finish`. The reader also accepts the+  British spelling (`maskColour`, `silkColour`). Unknown values stay null or   absent; never turn a viewer's default into claimed design data. - `gerbers.included` is true. `drill.plating` says `split`, `mixed`,   `plated` (no unplated drill file) or `unplated`. A drill file's role comes@@ -44,7 +51,7 @@ Run it from the package directory, with the export folder as its argument: ```sh python3 scripts/fab_bundle.py create /path/to/bundle --slug my-board \   --fab /path/to/fresh-gerbers --tool KiCad --tool-version 10.0.3 \-  --exporter adom/kicad-export-molecule --exporter-version 1.2.0 \+  --exporter adom/kicad-export-molecule --exporter-version 2.0.0 \   --source step=Board.step --source board_kicad_pcb=Board.kicad_pcb \   --source schematic=Board.kicad_sch --source project=Board.kicad_pro \   --stackup /path/to/known-stackup.json@@ -63,22 +70,68 @@ changed hashes, two files for one required layer, two files of the same name in different folders, layer files with names the board reader skips (use KiCad or Protel extensions) and archives over 2000 files or 512 MiB unpacked. A `.GKO` counts as the outline only when no other outline file-exists, since Altium writes its keep-out layer there. It does not prove-alignment or validate the circuit; the existing conversion and-manufacturing checks still apply.+exists, since Altium writes its keep-out layer there; otherwise it is+`keepout`. It does not prove alignment or validate the circuit; the registry+build's own checks (anchor, normalize, attachments) do that part. Export the+STEP and the fabrication files without rotating or mirroring either: artwork+that registers against the model only turned or mirrored is refused+(`registration-turned`).++## How the registry finds and checks the pair++The registry's molecule recipes read the pair on the board route+(`.kicad_pcb`, `.brd` or Altium `.PcbDoc`):++- `fab` matches `{slug}-fab.zip`, then `*-fab.zip`; `export` matches+  `export.json` outside `render/` and `viewer/`. Both roles are optional, but+  they come both or neither, in the same folder; anything else fails the+  build's `fabrication-pair` check.+- A page renamed after its export still builds: the zip and its record keep+  the old slug, `*-fab.zip` finds the zip, and the check takes its slug from+  the zip's own name. To check such a bundle by hand, pass that name:+  `check <folder> --slug <zip name without -fab.zip>`.+- The record's `step` entry and its `board_*` entry must name the STEP and+  board the build selected; otherwise the build fails+  `export-matches-sources`.+- The build runs fab_bundle 1.1.0, the same file as `scripts/fab_bundle.py`,+  on a filtered record: the entries whose files are build inputs (the STEP+  and the board) plus `fab_zip`. Other recorded files (schematics, projects)+  are listed under `fabrication.unverified` in the build report and raise no+  warning. The local `check` verifies every recorded file, so run it before+  publishing.+- A STEP with no board file takes the step route, with or without the pair,+  and the build refuses it (`board-file-required`): the model is placed from+  the board file.  For a bridge-produced record, verify it before any packaging rename. If the bridge used a design stem instead of the wiki slug, use a fresh staging folder and regenerate the record against the final filenames. Never rename-a recorded source or zip without updating and checking the record.+a recorded source or zip without regenerating and checking the record.++## Publishing the pair -Before publishing, run `check` after all local source changes. Include the-zip, record and every recorded source in both the package and the explicit-repo push list. Re-fetch those files at the returned commit into a fresh-folder, then run the same check there. A successful push response alone does-not prove that the complete export reached the page.+Before publishing, run `check` after all local source changes. Put the zip,+the record and every recorded source in the package folder, at their+recorded paths. The private `adom-wiki pkg publish --wait` of that folder is+the one write that carries them: its commit holds all of them, and the+registry queues one build from it. Do not split them over several pushes; a+write after which the sources resolve queues a build, and a build that sees+the zip without its record fails.++A passed build on the board route with the pair present ran the+fabrication check on the committed files, which proves the export reached+the page intact. To check by hand as well, download the page at the build's+source commit (`data.model.build.sourceCommit` of the publish) into a fresh+folder and run the same check there:++```sh+adom-wiki repo download <owner>/<slug> --ref <commit> --extract /path/to/fresh+python3 scripts/fab_bundle.py check /path/to/fresh --slug <slug>+``` -This contract applies to EDA molecule exports. tscircuit retains-`circuit.json` and its build inputs; its pipeline generates fabrication-layers. Existing pages are backfilled separately. This source addition does-not enable registry model serving or replace any page's current model.+This contract applies to EDA molecule exports. tscircuit pages publish+`circuit.json` and build on the circuit route, which has no `fab` or `export`+role: the build takes their layers from `circuit.json`. The registry builds a+molecule's model, footprint and symbol from these sources; pages that+published a converted GLB before keep their old files in the repo, and once a+build passes the page serves the registry's model in their place.
docs/hero-src.html+14−15
@@ -7,13 +7,13 @@   .glow { position:absolute; width:900px; height:900px; border-radius:50%;     background: radial-gradient(circle, rgba(45,212,191,.10) 0%, rgba(59,130,246,.06) 45%, transparent 70%);     right:-180px; top:-260px; }-  .win { position:absolute; left:170px; top:210px; width:1260px; border-radius:14px;+  .win { position:absolute; left:150px; top:170px; width:1300px; border-radius:14px;     background:#0d1826; border:1px solid #1e3348;     box-shadow: 0 40px 90px rgba(0,0,0,.65), 0 0 0 1px rgba(45,212,191,.05); }   .bar { height:46px; display:flex; align-items:center; padding:0 18px; gap:8px;     border-bottom:1px solid #16293c; }   .dot { width:12px; height:12px; border-radius:50%; background:#22384e; }-  .title { margin-left:12px; color:#5b7astro; color:#5b7a99; font-size:14px; letter-spacing:.4px; }+  .title { margin-left:12px; color:#5b7a99; font-size:14px; letter-spacing:.4px; }   .body { padding:26px 34px 34px; font-family:'Cascadia Mono','Consolas',monospace; font-size:17px; line-height:1.85; }   .p  { color:#7dd3c8; }   .cmd{ color:#e6edf5; }@@ -26,20 +26,19 @@   <div class="win">     <div class="accent"></div>     <div class="bar"><div class="dot"></div><div class="dot"></div><div class="dot"></div>-      <div class="title">adom-desktop &nbsp;·&nbsp; Fusion 360 Electronics &nbsp;·&nbsp; piprobe.fbrd</div></div>+      <div class="title">molecule-publish 3.0.0 &nbsp;&middot;&nbsp; sources only &nbsp;&middot;&nbsp; adom/abc</div></div>     <div class="body">-      <div><span class="p">$</span> <span class="cmd">kicad-cli pcb export step</span> <span class="fl">--subst-models -o ABC.step</span></div>-      <div class="ok">   ABC.step                           written   3.2 MB</div>-      <div><span class="p">$</span> <span class="cmd">curl POST /convert?molecule=true</span> <span class="fl">step + board</span></div>-      <div class="ok">   anchored  gold pins  footprint_applied  contact_z 5.35mm</div>-      <div><span class="p">$</span> <span class="cmd">adom-wiki pkg publish</span></div>-      <div class="ok">   component published — GLB + footprint + symbol + schematic</div>-      <div><span class="p">$</span> <span class="cmd">adom-wiki repo push adom/abc</span> <span class="fl">--files ...</span></div>-      <div class="ok">   source on the Files tab</div>-      <div><span class="p">$</span> <span class="cmd">adom-molecule create</span> <span class="fl">--glb ABC.glb --no-optimize</span></div>-      <div class="ok">   registered under caleb — no re-optimization</div>-      <div><span class="p">$</span> <span class="cmd">adom-molecule list</span></div>-      <div class="ok">   hydrogen.adom.inc/caleb/molecules/ABC — wires attach clean</div>+      <div><span class="p">$</span> <span class="cmd">python3 scripts/bundle_check.py</span> <span class="fl">ABC --slug abc</span></div>+      <div class="ok">   recipe molecule-board/1 (route board): ABC.step, ABC.kicad_pcb, abc-fab.zip, export.json</div>+      <div><span class="p">$</span> <span class="cmd">python3 scripts/pin_names.py check</span> <span class="fl">ABC/ABC.kicad_pcb --route board</span></div>+      <div class="ok">   4 machine pins, 20 machine contacts, names ok</div>+      <div><span class="p">$</span> <span class="cmd">adom-wiki pkg publish</span> <span class="fl">--private --wait</span></div>+      <div class="ok">   build 812 &middot; passed &middot; the page serves abc.glb from build 812</div>+      <div><span class="p">$</span> <span class="cmd">adom-wiki page hero adom/abc</span> <span class="fl">--image screenshots/hero.png</span></div>+      <div class="ok">   hero posed from the registry model</div>+      <div><span class="p">$</span> <span class="cmd">adom-wiki page visibility adom/abc</span> <span class="fl">--preset open</span></div>+      <div><span class="p">$</span> <span class="cmd">adom-molecule import adom/abc</span> <span class="fl">--owner caleb</span></div>+      <div class="ok">   footprint and symbol from the build: wires attach</div>     </div>   </div> </body></html>
install.sh+2
@@ -6,6 +6,8 @@ mkdir -p "$SKILLS_DIR/molecule-publish" rm -rf "$SKILLS_DIR/molecule-publish" mkdir -p "$SKILLS_DIR/molecule-publish" cp "$PKG_DIR/SKILL.md" "$SKILLS_DIR/molecule-publish/SKILL.md"+# Other skills read the installed version from here.+cp "$PKG_DIR/package.json" "$SKILLS_DIR/molecule-publish/package.json" cp -R "$PKG_DIR/scripts" "$SKILLS_DIR/molecule-publish/scripts" mkdir -p "$SKILLS_DIR/molecule-publish/docs" cp "$PKG_DIR/docs/fabrication.md" "$SKILLS_DIR/molecule-publish/docs/fabrication.md"
package.json+25−19
@@ -1,8 +1,8 @@ {   "slug": "molecule-publish",-  "version": "2.12.0",+  "version": "3.0.0",   "type": "skill",-  "description": "Publish molecules AND generic boards to the Adom wiki - one publisher, two shapes: OCCT conversion (molecule mode with stats gates, or plain for boards), component packaging, adom-wiki publish, APM render assets + component dependencies. Companion to adom-molecule-import.",+  "description": "Publish molecule sources to the Adom wiki (STEP, board, schematic, <slug>-fab.zip, export.json); the wiki's 3D model registry builds the GLB, footprint and symbol. Checks the bundle the way the registry does, publishes private, waits for the build, sets the hero from the built model, then makes the page public. Board mode still converts plain boards. Also writes APM render assets and component dependencies. Companion to adom-wiki model import.",   "tags": [     "molecule",     "pipeline",@@ -10,53 +10,59 @@     "hydrogen",     "skill"   ],-  "dependencies": {-    "adom/adom-molecule": "^1.1.3"-  },+  "dependencies": {},   "scripts": {     "install": "./install.sh",     "uninstall": "./uninstall.sh"   },-  "hero": {-    "headline": "Molecule bundle to wiki page",-    "subhead": "OCCT convert, stats gates, package, publish - EDA-agnostic",-    "screenshot": "docs/shot.png"-  },+  "hero": {
+  "type": "billboard",
+  "headline": "Molecule bundle to wiki page",
+  "subhead": "OCCT convert, stats gates, package, publish - EDA-agnostic",
+  "screenshot": "docs/shot.png"
+},   "discovery_triggers": [     "publish this molecule to the wiki",+    "publish molecule sources",     "upload molecule bundle",-    "convert and publish my molecule",+    "publish sources and wait for the build",     "molecule to the wiki",     "publish molecule package",+    "i only have a step",     "publish my board",     "publish board to the wiki",     "board to project manager",     "render board for apm"   ],-  "discovery_pitch": "Publish a molecule source bundle (STEP + schematic + board + metadata) to the Adom wiki: OCCT molecule-mode conversion with stats gates, component packaging, adom-wiki publish. EDA-agnostic middle of the pipeline; companion to adom-molecule-import.",+  "discovery_pitch": "Publish the sources of a molecule (STEP, board, schematic, <slug>-fab.zip, export.json) to the Adom wiki and let the wiki's 3D model registry build the GLB, footprint and symbol. Checks the bundle first, publishes private, waits for the build, then goes public. EDA-agnostic middle of the pipeline; companion to adom-wiki model import.",   "sample_prompts": [     {       "label": "Publish a bundle",-      "prompt": "I have ABC.step, ABC.kicad_pcb and ABC.kicad_sch - publish this molecule to the wiki"+      "prompt": "I have ABC.step, ABC.kicad_pcb, ABC.kicad_sch, abc-fab.zip and export.json - publish the sources of this molecule to the wiki"     },     {-      "label": "Convert and publish",-      "prompt": "Convert my molecule through OCCT and publish it"+      "label": "STEP only",+      "prompt": "I only have a STEP of my molecule - publish it to the wiki"     }   ],   "files": [     "README.md",     "SKILL.md",-    "docs/fabrication.md",     "install.sh",-    "uninstall.sh",     "package.json",     "page.json",+    "uninstall.sh",+    "docs/fabrication.md",     "scripts/bundle_3d.py",+    "scripts/bundle_check.py",     "scripts/component_graph.py",+    "scripts/contract.json",     "scripts/fab_bundle.py",     "scripts/hero_camera.py",-    "scripts/render_parity.py",-    "scripts/tested_with.py"+    "scripts/pcbdoc.py",+    "scripts/pin_names.py",+    "scripts/pins.json",+    "scripts/tested_with.py",+    "scripts/versions_check.py"   ] }
page.json+26−21
@@ -1,8 +1,8 @@ {   "slug": "molecule-publish",-  "version": "2.12.0",+  "version": "3.0.0",   "type": "skill",-  "description": "Publish molecules AND generic boards to the Adom wiki - one publisher, two shapes: OCCT conversion (molecule mode with stats gates, or plain for boards), component packaging, adom-wiki publish, APM render assets + component dependencies. Companion to adom-molecule-import.",+  "description": "Publish molecule sources to the Adom wiki (STEP, board, schematic, <slug>-fab.zip, export.json); the wiki's 3D model registry builds the GLB, footprint and symbol. Checks the bundle the way the registry does, publishes private, waits for the build, sets the hero from the built model, then makes the page public. Board mode still converts plain boards. Also writes APM render assets and component dependencies. Companion to adom-wiki model import.",   "tags": [     "molecule",     "pipeline",@@ -10,39 +10,39 @@     "hydrogen",     "skill"   ],-  "dependencies": {-    "adom/adom-molecule": "^1.1.3"-  },+  "dependencies": {},   "scripts": {     "install": "./install.sh",     "uninstall": "./uninstall.sh"   },-  "hero": {-    "type": "billboard",-    "headline": "Molecule bundle to wiki page",-    "subhead": "OCCT convert, stats gates, package, publish - EDA-agnostic",-    "screenshot": "docs/shot.png"-  },+  "hero": {
+  "type": "billboard",
+  "headline": "Molecule bundle to wiki page",
+  "subhead": "OCCT convert, stats gates, package, publish - EDA-agnostic",
+  "screenshot": "docs/shot.png"
+},   "discovery_triggers": [     "publish this molecule to the wiki",+    "publish molecule sources",     "upload molecule bundle",-    "convert and publish my molecule",+    "publish sources and wait for the build",     "molecule to the wiki",     "publish molecule package",+    "i only have a step",     "publish my board",     "publish board to the wiki",     "board to project manager",     "render board for apm"   ],-  "discovery_pitch": "Publish a molecule source bundle (STEP + schematic + board + metadata) to the Adom wiki: OCCT molecule-mode conversion with stats gates, component packaging, adom-wiki publish. EDA-agnostic middle of the pipeline; companion to adom-molecule-import.",+  "discovery_pitch": "Publish the sources of a molecule (STEP, board, schematic, <slug>-fab.zip, export.json) to the Adom wiki and let the wiki's 3D model registry build the GLB, footprint and symbol. Checks the bundle first, publishes private, waits for the build, then goes public. EDA-agnostic middle of the pipeline; companion to adom-wiki model import.",   "sample_prompts": [     {       "label": "Publish a bundle",-      "prompt": "I have ABC.step, ABC.kicad_pcb and ABC.kicad_sch - publish this molecule to the wiki"+      "prompt": "I have ABC.step, ABC.kicad_pcb, ABC.kicad_sch, abc-fab.zip and export.json - publish the sources of this molecule to the wiki"     },     {-      "label": "Convert and publish",-      "prompt": "Convert my molecule through OCCT and publish it"+      "label": "STEP only",+      "prompt": "I only have a STEP of my molecule - publish it to the wiki"     }   ],   "org": "adom",@@ -54,16 +54,21 @@   "files": [     "README.md",     "SKILL.md",-    "docs/fabrication.md",     "install.sh",-    "uninstall.sh",     "package.json",     "page.json",+    "uninstall.sh",+    "docs/fabrication.md",     "scripts/bundle_3d.py",+    "scripts/bundle_check.py",     "scripts/component_graph.py",+    "scripts/contract.json",     "scripts/fab_bundle.py",     "scripts/hero_camera.py",-    "scripts/render_parity.py",-    "scripts/tested_with.py"+    "scripts/pcbdoc.py",+    "scripts/pin_names.py",+    "scripts/pins.json",+    "scripts/tested_with.py",+    "scripts/versions_check.py"   ]-}\ No newline at end of file+}
scripts/bundle_check.pyadded+266
@@ -0,0 +1,266 @@+#!/usr/bin/env python3+"""Which molecule recipe a page builds from, checked before the page is published.++The molecule recipes and the generated-path rule are contract.json beside this script, a+byte copy of the wiki's lib/registry/contracts/molecule/contract.json (schema+adom.molecule-contract/1). The recipes are applied the way the wiki's recipe engine applies+them (lib/registry/recipes.js, resolveSources and recipeForPage): a pattern without '/'+matches a file name at any depth and a pattern with '/' the whole path; '*' stays inside one+path segment and a segment '**' matches zero or more segments; case is ignored; excludes are+removed first; the patterns of a role are tried in order and the first with a hit wins;+among its hits the shallowest wins, and two hits at that depth are ambiguous. An ambiguous+role, or a `many` role over its cap, ends the search; a role that matches nothing rules out+only its own recipe. The recipes apply to pages of kind molecule only.++  bundle_check.py <folder> --slug <page slug> [--page-files <listing>] [--json]++The tree checked is every file in <folder> (the package folder that `adom-wiki pkg publish`+packs; node_modules, .git, *.tgz and the ignore files are skipped as the CLI skips them)+plus, with --page-files, the files the page already holds: one repo path per line, or the+JSON that `adom-wiki --json api "/api/pages/<owner>/<slug>/files?recursive=1"` prints. Old+files stay in a page repo, so they take part in the choice.++Problems (exit 1): no-recipe, ambiguous, overflow (no build would run); board-file-required+(the step route: a STEP with no board file, which the build refuses, since a molecule's model+is placed from its board file); generated (a file in <folder> that the registry generates for+the page, which it refuses in a write); fab-pair (<slug>-fab.zip without export.json, the+reverse, or the two in different folders); export-record (export.json records a STEP or board+other than the one the build selects); kind (package.json in <folder> declares a kind other+than molecule). Exit 0 otherwise, and 2 on a usage error. Python 3.9 or newer, standard+library only; it reads no network.+"""+import json+import re+import sys+from pathlib import Path, PurePosixPath++HERE = Path(__file__).resolve().parent+SKIP_DIRS = {"node_modules", ".git", ".adompkg", ".adompkg-build", "__MACOSX"}+SKIP_FILES = {".adomignore", ".pkgignore", ".DS_Store", "Thumbs.db"}+IGNORE_FILES = (".gitignore", ".adomignore", ".pkgignore")+++def matcher(pattern, slug):+    """recipes.js patternMatcher: a predicate over repo paths for one pattern."""+    segs = [s for i, s in enumerate(pattern.split("/")) if not (s == "**" and i and pattern.split("/")[i - 1] == "**")]++    def seg_re(seg):+        out = ""+        for part in re.split(r"(\{slug\}|\*)", seg):+            out += re.escape(slug) if part == "{slug}" else "[^/]*" if part == "*" else re.escape(part)+        return out++    rx = ""+    for i, s in enumerate(segs):+        first, last = i == 0, i == len(segs) - 1+        if s != "**":+            rx += ("" if first or segs[i - 1] == "**" else "/") + seg_re(s)+        elif first and last:+            rx += "[^/]+(?:/[^/]+)*"+        elif last:+            rx += "(?:/[^/]+)*"+        else:+            rx += ("" if first else "/") + "(?:[^/]+/)*"+    compiled = re.compile("^" + rx + "$", re.I)+    whole = "/" in pattern+    return lambda path: bool(compiled.match(path if whole else path.rsplit("/", 1)[-1]))+++def depth(path):+    return path.count("/")+++def resolve_sources(recipe, tree, slug):+    """recipes.js resolveSources: (ok, sources [(role, path)], reason, ambiguous, overflow)."""+    sources = []+    for role, spec in recipe["sources"].items():+        excluded = [matcher(p, slug) for p in spec.get("exclude", [])]+        candidates = [p for p in tree if not any(m(p) for m in excluded)]+        if spec.get("many"):+            ms = [matcher(p, slug) for p in spec["match"]]+            hits = sorted(p for p in candidates if any(m(p) for m in ms))+            if len(hits) > spec["many"]:+                return False, sources, f"source {role}: {len(hits)} files match {', '.join(spec['match'])}, more than its cap of {spec['many']}", None, {"role": role, "count": len(hits), "cap": spec["many"]}+            if not hits and not spec.get("optional"):+                return False, sources, f"source {role}: no file matches {', '.join(spec['match'])}", None, None+            sources += [(f"{role}.{i + 1}", p) for i, p in enumerate(hits)]+            continue+        picked = None+        for pattern in spec["match"]:+            m = matcher(pattern, slug)+            hits = [p for p in candidates if m(p)]+            if not hits:+                continue+            top = min(depth(p) for p in hits)+            best = sorted(p for p in hits if depth(p) == top)+            if len(best) > 1:+                return False, sources, f"source {role} ({pattern}): ambiguous: {', '.join(best)}", {"role": role, "paths": best}, None+            picked = best[0]+            break+        if picked:+            sources.append((role, picked))+        elif not spec.get("optional"):+            return False, sources, f"source {role}: no file matches {', '.join(spec['match'])}", None, None+    return True, sources, None, None, None+++def recipe_for_page(recipes, tree, slug, kind="molecule"):+    """recipes.js recipeForPage: {recipe, sources} or {recipe: None, reasons, ambiguous|overflow}."""+    reasons = []+    for recipe in recipes:+        label = f"{recipe['name']}/{recipe['version']}"+        if kind not in recipe["applies"]["kinds"]:+            reasons.append(f"{label}: does not apply to kind {kind}")+            continue+        ok, sources, reason, ambiguous, overflow = resolve_sources(recipe, tree, slug)+        if ok:+            return {"recipe": recipe, "label": label, "sources": sources, "reasons": reasons}+        reasons.append(f"{label}: {reason}")+        if ambiguous or overflow:+            return {"recipe": None, "reasons": reasons, "ambiguous": ambiguous and {"recipe": label, **ambiguous}, "overflow": overflow and {"recipe": label, **overflow}}+    return {"recipe": None, "reasons": reasons or ["no recipes are listed"]}+++def generated(path, recipe, rule, slug):+    """contract.json generatedPaths: is `path` a file the registry generates for the page?"""+    if recipe and any(path == s["path"].replace("{slug}", slug) for s in recipe["slots"].values()):+        return True+    if "/" in path:+        return False+    if path in (n.replace("{slug}", slug) for n in rule["rootNames"]):+        return True+    return bool(recipe) and any(k in recipe["slots"] for k in rule["suffixSlots"]) and path.endswith(tuple(rule["rootSuffixes"]))+++def folder_files(root):+    out = []+    for p in sorted(root.rglob("*")):+        rel = p.relative_to(root).as_posix()+        if not p.is_file() or set(rel.split("/")[:-1]) & SKIP_DIRS or p.name in SKIP_FILES or p.name.endswith(".tgz"):+            continue+        out.append(rel)+    return out+++def page_files(spec):+    """Repo paths from a listing file: a path per line, or the files API JSON (enveloped or not)."""+    text = Path(spec).read_text(encoding="utf-8")+    try:+        doc = json.loads(text)+    except ValueError:+        return [line.strip() for line in text.splitlines() if line.strip()]+    if isinstance(doc, dict):+        doc = (doc.get("data") or doc) if isinstance(doc.get("data"), dict) else doc+        doc = doc.get("files") or doc.get("tree") or []+    return [e["path"] if isinstance(e, dict) else str(e) for e in doc+            if isinstance(e, str) or (isinstance(e, dict) and e.get("path") and e.get("type", "blob") not in ("tree", "dir"))]+++def check(root, slug, listing=None, contract=None):+    contract = json.loads(Path(contract or HERE / "contract.json").read_text(encoding="utf-8"))+    mine = folder_files(root)+    tree = sorted(set(mine) | set(page_files(listing) if listing else []))+    res = recipe_for_page(contract["recipes"], tree, slug)+    recipe = res["recipe"]+    problems, notes = [], []+    if not recipe:+        if res.get("ambiguous"):+            a = res["ambiguous"]+            problems.append({"id": "ambiguous", "detail": f"{a['recipe']}: role {a['role']} matches {', '.join(a['paths'])} at one depth, so no recipe applies and no build runs. Keep one, or name the one the build should read <slug>.<ext>."})+        elif res.get("overflow"):+            o = res["overflow"]+            problems.append({"id": "overflow", "detail": f"{o['recipe']}: role {o['role']} matches {o['count']} files, more than its cap of {o['cap']}, so no build runs."})+        else:+            problems.append({"id": "no-recipe", "detail": "no molecule recipe resolves, so no build runs: " + "; ".join(res["reasons"])})+    gen = [p for p in mine if generated(p, recipe, contract["generatedPaths"], slug)]+    if gen:+        problems.append({"id": "generated", "detail": "the registry generates " + ", ".join(gen) + " for this page and refuses a write that adds or changes them; remove them from the folder"})+    roles = dict(recipe and res["sources"] or [])+    route = recipe and recipe["pipeline"]["options"]["route"]+    if route == "step":+        problems.append({"id": "board-file-required", "detail": f"{roles.get('step')} has no board file beside it, so the build refuses the page (board-file-required): a molecule's model is placed from its board file, which says where its machine pins are. Add the board (.kicad_pcb, .brd, .PcbDoc or Fusion .fbrd) the STEP was exported from, with its <slug>-fab.zip and export.json."})+    if route == "board":+        fab, exp = roles.get("fab"), roles.get("export")+        if bool(fab) != bool(exp):+            problems.append({"id": "fab-pair", "detail": f"{fab or exp} came without {'export.json' if fab else 'its <slug>-fab.zip'}; publish both, or neither"})+        elif fab and PurePosixPath(fab).parent != PurePosixPath(exp).parent:+            problems.append({"id": "fab-pair", "detail": f"export.json and {PurePosixPath(fab).name} must sit in the same folder; found {exp} and {fab}"})+        elif exp and exp in mine:+            base = PurePosixPath(exp).parent+            try:+                files = json.loads((root / exp).read_text(encoding="utf-8")).get("files") or []+            except (ValueError, OSError, AttributeError):+                files = None+            if not isinstance(files, list):+                problems.append({"id": "export-record", "detail": f"{exp} has no files list; export again"})+            else:+                for f in files:+                    r = str(f.get("role")) if isinstance(f, dict) else ""+                    kind = "STEP" if r == "step" else "board" if r.startswith("board_") else None+                    if not kind:+                        continue+                    rec = (base / f.get("path", "")).as_posix() if str(base) != "." else f.get("path", "")+                    want = roles.get("step" if kind == "STEP" else "board")+                    if rec != want:+                        problems.append({"id": "export-record", "detail": f"export.json records {kind} {rec}; the build selects {want or 'none'}. Export again so the record names the files on the page."})+        if fab and PurePosixPath(fab).name.lower() != f"{slug}-fab.zip":+            notes.append(f"{fab} is not named {slug}-fab.zip; the build still finds it (*-fab.zip) and checks it under its own name")+    elif route == "circuit" and any(p.lower().endswith("-fab.zip") or PurePosixPath(p).name == "export.json" for p in tree):+        notes.append("the circuit route reads no fabrication bundle; a fab zip or export.json on this page is not checked")+    pkg = root / "package.json"+    if pkg.is_file():+        try:+            kind = json.loads(pkg.read_text(encoding="utf-8")).get("kind")+        except ValueError:+            kind = None+        if kind != "molecule":+            problems.append({"id": "kind", "detail": f"package.json declares kind {kind!r}; the molecule recipes apply only to kind \"molecule\""})+    ignores = [n for n in IGNORE_FILES if (root / n).is_file()]+    if ignores:+        notes.append(", ".join(ignores) + " in the folder: this check reads every file, while pkg publish leaves out what they match")+    used = {p for _, p in res.get("sources", [])} if recipe else set()+    return {"slug": slug, "recipe": res.get("label"), "route": route,+            "sources": [{"role": r, "path": p, "inFolder": p in mine} for r, p in (res["sources"] if recipe else [])],+            "unread": [p for p in mine if p not in used and p not in gen], "generated": gen,+            "problems": problems, "notes": notes, "reasons": res["reasons"]}+++def main(argv):+    args, opts, i = [], {}, 0+    while i < len(argv):+        if argv[i] in ("--slug", "--page-files", "--contract"):+            if i + 1 >= len(argv):+                print(f"error: {argv[i]} needs a value", file=sys.stderr)+                return 2+            opts[argv[i]] = argv[i + 1]+            i += 2+        elif argv[i] == "--json":+            opts["--json"] = True+            i += 1+        else:+            args.append(argv[i])+            i += 1+    if len(args) != 1 or "--slug" not in opts or not Path(args[0]).is_dir():+        print(__doc__.split("\n\n")[2], file=sys.stderr)+        return 2+    if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", opts["--slug"]):+        print("error: --slug must be the page slug: lowercase words separated by hyphens", file=sys.stderr)+        return 2+    out = check(Path(args[0]), opts["--slug"], opts.get("--page-files"), opts.get("--contract"))+    if opts.get("--json"):+        print(json.dumps(out, indent=2))+    else:+        print(f"recipe {out['recipe'] or 'none'}" + (f" (route {out['route']})" if out["route"] else ""))+        for s in out["sources"]:+            print(f"  {s['role']:<10} {s['path']}" + ("" if s["inFolder"] else "   (already on the page)"))+        if out["unread"]:+            print("not read by the build: " + ", ".join(out["unread"]))+        for n in out["notes"]:+            print(f"note: {n}")+        for p in out["problems"]:+            print(f"problem {p['id']}: {p['detail']}")+    return 1 if out["problems"] else 0+++if __name__ == "__main__":+    sys.exit(main(sys.argv[1:]))
scripts/component_graph.py+111−11
@@ -18,7 +18,8 @@ directly on each component page. The gate enforces two distinct properties (#17)                            broken in APM/Nucleus (core owner-pinning fragility);                            "declared" alone never caught this. -  plan   <board> [--sch S] [--owner O]   parse BOM -> classify -> probe the wiki+  plan   <board> [--sch S] [--owner O]   parse BOM (.kicad_pcb, .brd, .PcbDoc or .fbrd)+                                          -> classify -> probe the wiki                                           namespace -> emit plan.json + a table                                           of reused / create / FLAGGED parts   gate   <package.json> [--plan P]        HARD GATE, non-zero exit on failure:@@ -34,12 +35,15 @@ directly on each component page. The gate enforces two distinct properties (#17) Stdlib only. Wiki probing shells to `adom-wiki` (skipped with --offline). """ import argparse+import importlib.util import json import os import re import subprocess import sys+import tempfile import time+from pathlib import Path  # ── identity rules (#142: key by MPN, never by value or distributor code) ── LCSC_RE = re.compile(r'^c\d{3,}$', re.I)@@ -51,7 +55,17 @@ VALUE_NAMED_RE = re.compile(r'^[rcl]_[\d.]+[kmunp]?_?\d{4}$', re.I) NON_ELECTRICAL_REFS = re.compile(r'^(LOGO|FID|MH|H|G|TP|NT|REF\*\*)\d*$', re.I) NON_ELECTRICAL_FP = re.compile(     r'logo|fiducial|mounting\s*hole|test\s*point|silk|graphic|icon|keepout', re.I)-FURNITURE_REFS = re.compile(r'^(MP|MC)\d+$', re.I)  # Adom machine pins/contacts+++def pins_pattern(name):+    """A designator pattern of pins.json (adom.molecule-pins/2), shipped beside this script."""+    path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "pins.json")+    with open(path, encoding="utf-8") as f:+        spec = json.load(f)["designators"][name]+    return re.compile(spec["pattern"], re.I if "i" in spec.get("flags", "") else 0)+++FURNITURE_REFS = pins_pattern("nearMiss")  # Adom machine pins and contacts (rule R5)   def sh(cmd, timeout=60):@@ -62,12 +76,50 @@ def sh(cmd, timeout=60):         return 1, "", str(e)  +def read_pcbdoc(board_path):+    """The KiCad board text that pcbdoc.py, beside this script, writes from the Altium+    board `board_path`. Raises ValueError when the file is not a readable PcbDoc."""+    here = os.path.dirname(os.path.abspath(__file__))+    src = os.path.join(here, "pcbdoc.py")+    if not os.path.isfile(src):+        raise ValueError("pcbdoc.py, the Altium reader, is not beside component_graph.py")+    spec = importlib.util.spec_from_file_location("pcbdoc", src)+    mod = importlib.util.module_from_spec(spec)+    spec.loader.exec_module(mod)+    with tempfile.TemporaryDirectory() as d:+        out = os.path.join(d, "board.kicad_pcb")+        mod.convert(board_path, out)+        with open(out, encoding="utf-8", errors="replace") as f:+            return f.read()+++def read_fbrd(board_path):+    """The EAGLE board text a Fusion .fbrd holds, as pin_names.py (beside this script)+    reads it. Raises ValueError when the file holds no board."""+    here = os.path.dirname(os.path.abspath(__file__))+    src = os.path.join(here, "pin_names.py")+    if not os.path.isfile(src):+        raise ValueError("pin_names.py, which reads Fusion boards, is not beside component_graph.py")+    spec = importlib.util.spec_from_file_location("pin_names", src)+    mod = importlib.util.module_from_spec(spec)+    spec.loader.exec_module(mod)+    return mod.read_fbrd(board_path)++ def parse_bom(board_path):-    """Rows from a .kicad_pcb (footprint blocks) or an EAGLE .brd (XML elements).+    """Rows from a .kicad_pcb (footprint blocks), an Altium .PcbDoc (read as the+    .kicad_pcb that pcbdoc.py writes from it), an EAGLE .brd (XML elements) or a+    Fusion .fbrd (the EAGLE board it holds).     Returns [{ref, value, footprint, lcsc, mpn}] with whatever the file carries."""-    txt = open(board_path, encoding="utf-8", errors="replace").read()+    kicad = board_path.lower().endswith((".kicad_pcb", ".kicad_mod", ".pcbdoc"))+    if board_path.lower().endswith(".pcbdoc"):+        txt = read_pcbdoc(board_path)+    elif board_path.lower().endswith(".fbrd"):+        txt = read_fbrd(board_path)+    else:+        txt = open(board_path, encoding="utf-8", errors="replace").read()     rows = []-    if board_path.lower().endswith((".kicad_pcb", ".kicad_mod")):+    if kicad:         for m in re.finditer(r'\(footprint "([^"]+)"', txt):             start = m.start()             depth, i = 0, start@@ -103,14 +155,45 @@ def parse_bom(board_path):     return [r for r in rows if r["ref"]]  -def classify(row):-    """electrical | furniture | skip - only `electrical` is graph-mandatory."""+def census_furniture(board_path):+    """The machine pins and contacts of a board as the pin-name census of pin_names.py,+    beside this script, classes them: every part row of class machine-pin or+    machine-contact, whether the census accepts, warns about or refuses it.++    Returns (designators, refusals): the set of designators and the ids of the checks the+    census refuses the board on ([] when it passes). Returns (None, reason) when the+    census cannot read the board (no pin_names.py, a board format it does not read, or a+    board-read failure); the caller then falls back to the designator rule."""+    here = os.path.dirname(os.path.abspath(__file__))+    src = os.path.join(here, "pin_names.py")+    if not os.path.isfile(src):+        return None, "pin_names.py is not beside component_graph.py"+    try:+        spec = importlib.util.spec_from_file_location("pin_names", src)+        names = importlib.util.module_from_spec(spec)+        spec.loader.exec_module(names)+        result = names.census(Path(board_path), "board", names.Rule())+    except (OSError, ValueError, KeyError) as e:+        return None, f"the census did not run: {e}"+    report = result["report"]+    if report.get("error") or not report.get("applies"):+        return None, report.get("error") or report.get("reason") or "the census does not apply"+    furniture = {r["designator"] for r in report.get("parts", [])+                 if r.get("class") in ("machine-pin", "machine-contact")}+    refused = [c["id"] for c in result["checks"] if not c["pass"]]+    return furniture, refused+++def classify(row, furniture=None):+    """electrical | furniture | skip - only `electrical` is graph-mandatory.+    `furniture` is the census's set of machine pin and contact designators+    (census_furniture); without it the designator rule of pins.json decides."""     ref, fp = row["ref"], row["footprint"]     if row.get("dnp"):         return "skip"     if NON_ELECTRICAL_REFS.match(ref) or NON_ELECTRICAL_FP.search(fp):         return "skip"-    if FURNITURE_REFS.match(ref):+    if (ref in furniture) if furniture is not None else FURNITURE_REFS.match(ref):         return "furniture"     return "electrical" @@ -193,12 +276,29 @@ def page_exists(ref, offline=False):   def cmd_plan(a):-    rows = parse_bom(a.board)-    plan = {"board": os.path.basename(a.board), "parts": [],+    try:+        rows = parse_bom(a.board)+    except ValueError as e:+        print(f"error: {a.board} could not be read: {e}", file=sys.stderr)+        return 2+    furniture, census = census_furniture(a.board)+    if furniture is None:+        rule = {"source": "designators", "detail": census}+        note = (f"machine pins and contacts by designator only (MP<n>, MC<n>): the pin-name "+                f"census could not read the board ({census})")+    else:+        rule = {"source": "census", "furniture": sorted(furniture), "refused": census}+        note = ("machine pins and contacts from the pin-name census (pin_names.py): "+                + (", ".join(sorted(furniture)) or "none"))+        if census:+            note += (f"\n  the census refuses this board ({', '.join(census)}): run "+                     "`pin_names.py check` on it and fix the names before publishing")+    plan = {"board": os.path.basename(a.board), "furnitureRule": rule, "parts": [],             "counts": {"electrical": 0, "furniture": 0, "skip": 0,                        "reuse": 0, "create": 0, "flagged": 0}}+    print(note + "\n")     for row in rows:-        kind = classify(row)+        kind = classify(row, furniture)         plan["counts"][kind] = plan["counts"].get(kind, 0) + 1         if kind == "skip":             continue
scripts/contract.jsonadded+398
@@ -0,0 +1,398 @@+{+  "schema": "adom.molecule-contract/1",+  "version": 1,+  "description": "What the registry reads from a molecule page, what it builds and serves, which written files it refuses, and the checks the molecule program runs. scripts/gen-molecule-contract.mjs writes the recipes, the program's vendored copy and the doc tables from this file, the checks table's texts from pins.json.",+  "recipes": [+    {+      "name": "molecule-circuit",+      "version": 1,+      "description": "A tscircuit molecule: circuit.json and the model files it references.",+      "applies": { "kinds": ["molecule"] },+      "sources": {+        "circuit": { "match": ["circuit.json", "*.circuit.json"], "exclude": ["**/node_modules/**"] },+        "assets": { "match": ["**/libraries/**"], "exclude": ["**/node_modules/**"], "optional": true, "many": 200 }+      },+      "pipeline": { "name": "molecule", "options": { "route": "circuit" } },+      "slots": {+        "model": { "from": "model", "path": "{slug}.glb" },+        "web": { "from": "web", "path": "{slug}.web.glb" },+        "footprint": { "from": "footprint", "path": "{slug}_footprint.json" },+        "symbol": { "from": "symbol", "path": "{slug}_symbol.json" },+        "report": { "from": "report", "path": "{slug}.pipeline.json" }+      }+    },+    {+      "name": "molecule-board",+      "version": 1,+      "description": "A KiCad, Fusion/EAGLE or Altium molecule: STEP plus board file (a Fusion .fbrd when there is no other); optional fabrication bundle.",+      "applies": { "kinds": ["molecule"] },+      "sources": {+        "step": {+          "match": ["{slug}.step", "{slug}.stp", "*.step", "*.stp"],+          "exclude": ["**/*.3dshapes/**", "**/lib/**", "**/libs/**", "**/library/**", "**/libraries/**", "3d/**", "render/**", "viewer/**"]+        },+        "board": {+          "match": ["{slug}.kicad_pcb", "{slug}.brd", "{slug}.PcbDoc", "*.kicad_pcb", "*.brd", "*.PcbDoc", "{slug}.fbrd", "*.fbrd"],+          "exclude": ["**/*.3dshapes/**", "**/lib/**", "**/libs/**", "**/library/**", "**/libraries/**", "3d/**", "render/**", "viewer/**"]+        },+        "fab": { "match": ["{slug}-fab.zip", "*-fab.zip"], "optional": true },+        "export": { "match": ["export.json"], "exclude": ["render/**", "viewer/**"], "optional": true }+      },+      "pipeline": { "name": "molecule", "options": { "route": "board" } },+      "slots": {+        "model": { "from": "model", "path": "{slug}.glb" },+        "web": { "from": "web", "path": "{slug}.web.glb" },+        "footprint": { "from": "footprint", "path": "{slug}_footprint.json" },+        "symbol": { "from": "symbol", "path": "{slug}_symbol.json" },+        "report": { "from": "report", "path": "{slug}.pipeline.json" }+      }+    },+    {+      "name": "molecule-step",+      "version": 1,+      "description": "A molecule with a STEP and no board file: refused (board-file-required), since a molecule's model is placed from its board file.",+      "applies": { "kinds": ["molecule"] },+      "sources": {+        "step": {+          "match": ["{slug}.step", "{slug}.stp", "*.step", "*.stp"],+          "exclude": ["**/*.3dshapes/**", "**/lib/**", "**/libs/**", "**/library/**", "**/libraries/**", "3d/**", "render/**", "viewer/**"]+        },+        "fab": { "match": ["{slug}-fab.zip", "*-fab.zip"], "optional": true },+        "export": { "match": ["export.json"], "exclude": ["render/**", "viewer/**"], "optional": true }+      },+      "pipeline": { "name": "molecule", "options": { "route": "step" } },+      "slots": {+        "model": { "from": "model", "path": "{slug}.glb" },+        "web": { "from": "web", "path": "{slug}.web.glb" },+        "report": { "from": "report", "path": "{slug}.pipeline.json" }+      }+    }+  ],+  "generatedPaths": {+    "rule": "A path a write adds, or whose git blob it changes, is generated when it is a slot path of the molecule recipe that resolves on the tree after the write, one of `rootNames` at the repo root, or a root file name ending in one of `rootSuffixes` when that recipe has a slot named in `suffixSlots`. A path no rule names is not generated; `allowed` lists the folders that are never generated, for readers.",+    "rootNames": ["{slug}.glb", "{slug}.web.glb", "{slug}.render.glb", "{slug}.pipeline.json", "{slug}.metadata.json"],+    "rootSuffixes": ["_footprint.json", "_symbol.json"],+    "suffixSlots": ["footprint", "symbol"],+    "allowed": ["render/**", "3d/**", "viewer/**", "libraries/**", "**/*.3dshapes/**"]+  },+  "refusals": [+    {+      "code": "REGISTRY_MODEL_FILE_REFUSED",+      "status": 400,+      "level": "error",+      "routes": ["push", "publish", "merge", "revert"],+      "data": ["ref", "kind", "route", "paths", "sources", "recipe", "builds", "minimum"],+      "error": "generated model files refused",+      "errors": "{ref} is a molecule page the registry builds; {paths} {pathsAre} it generates",+      "hint": {+        "push": "{ref} is a molecule page the registry builds from its sources ({sources}). {paths} {pathsAre} the registry generates, so this write was refused and nothing was written. Push only the sources, then follow the build: GET {builds}. Export tools older than molecule-publish {publisherMinimum} still push these files; update them.",+        "publish": "{ref} is a molecule page the registry builds from its sources. The package holds {paths}, which the registry generates, so the release was not published. Remove {them} from the package folder (or list {them} in .pkgignore) and publish again. Export tools older than molecule-publish {publisherMinimum} still pack these files; update them.",+        "merge": "{ref} is a molecule page the registry builds from its sources ({sources}). {paths} {pathsAre} the registry generates, so this merge was refused and nothing was merged. Remove {them} from the pull request, then merge again and follow the build: GET {builds}. Export tools older than molecule-publish {publisherMinimum} still push these files; update them.",+        "revert": "{ref} is a molecule page the registry builds from its sources ({sources}). {paths} {pathsAre} the registry generates, so this revert was refused and nothing was reverted. Revert only the sources, then follow the build: GET {builds}."+      },+      "hints": {+        "push": {+          "message": "The registry builds this molecule's model; generated files are not accepted.",+          "action": "Push only the sources and wait for the build."+        },+        "publish": {+          "message": "The registry builds this molecule's model; generated files are not accepted.",+          "action": "Remove the generated files from the package and publish again."+        },+        "merge": {+          "message": "The registry builds this molecule's model; generated files are not accepted.",+          "action": "Remove the generated files from the pull request and merge again."+        },+        "revert": {+          "message": "The registry builds this molecule's model; generated files are not accepted.",+          "action": "Revert only the sources and wait for the build."+        }+      },+      "lists": "{sources} and {paths} name at most 2 entries, each cut to 48 characters: \"a\", \"a and b\", or \"a, b and N more\"; the full lists are in data. {pathsAre} is \"is a file\" for one path and \"are files\" for more, {them} is \"it\" or \"them\". The hint stays under 700 characters.",+      "meaning": "a write that adds or changes a file the registry generates (a slot path of the molecule recipe that applies after the write, or a root `{slug}.glb`, `{slug}.web.glb`, `{slug}.render.glb`, `{slug}.pipeline.json`, `{slug}.metadata.json`, and `*_footprint.json` or `*_symbol.json` when the recipe has those slots) on a molecule page the registry builds (refuseMoleculeModels effective; enabled, serveModels and buildOnPush on; page in buildScope and publishScope and not excluded; the molecule pipeline loads and jobs are configured; a molecule recipe resolves): refused at push (including `branch: main`), package publish, PR and branch merge, and revert, before anything is written",+      "source": "server.js, lib/registry/refuse-models.js"+    },+    {+      "code": "REGISTRY_REBASE_REFUSED",+      "status": 409,+      "level": "error",+      "routes": ["rebase"],+      "data": ["ref", "branch", "onto"],+      "error": "rebase of the default branch refused",+      "errors": "{ref} is a molecule page the registry builds; its default branch {branch} is not rebased",+      "hint": {+        "rebase": "Rebasing the default branch of a molecule page the registry builds is refused: the registry does not follow a rebase (it calls no write hook). Merge the branch with a pull request instead."+      },+      "hints": {+        "rebase": {+          "message": "The registry does not follow a rebase of this page's default branch.",+          "action": "Merge the branch with a pull request instead."+        }+      },+      "meaning": "a rebase of the default branch of a molecule page under the same conditions",+      "source": "server.js, lib/registry/refuse-models.js"+    },+    {+      "code": "REGISTRY_BUILD_EVALUATED",+      "status": null,+      "level": "info",+      "routes": ["push", "publish", "merge", "revert"],+      "data": ["page", "builds"],+      "hints": { "all": { "message": "The registry checks this write for a model build; follow it at {builds}." } },+      "meaning": "info: the registry evaluates this write for a model build",+      "source": "server.js, lib/registry/refuse-models.js"+    }+  ],+  "checks": {+    "items": [+      { "stage": "contract", "id": "job-contract", "level": "fail" },+      { "stage": "contract", "id": "hashes", "level": "fail" },+      { "stage": "contract", "id": "sources-index", "level": "fail" },+      { "stage": "select", "id": "route", "level": "fail" },+      {+        "stage": "select",+        "id": "board-file-required",+        "level": "fail",+        "note": "fails on the step route: a molecule's model is placed from its board file"+      },+      {+        "stage": "select",+        "id": "fabrication-pair",+        "level": "fail",+        "routes": ["board"],+        "note": "a fab zip and export.json come together or not at all, in one folder, the zip named <slug>-fab.zip"+      },+      { "stage": "select", "id": "assets-limit", "level": "fail", "routes": ["circuit", "board"] },+      {+        "stage": "board-read",+        "id": "board-read",+        "level": "fail",+        "routes": ["board"],+        "note": "an Altium .PcbDoc is read as the KiCad board pcbdoc.py writes from it, a Fusion .fbrd as the EAGLE board it holds"+      },+      { "stage": "names", "id": "board-read", "level": "fail", "routes": ["circuit", "board"], "messages": ["boardRead"] },+      { "stage": "names", "id": "pin-names", "level": "fail", "routes": ["circuit", "board"], "messages": ["pinNumber", "designatorCase"] },+      {+        "stage": "names",+        "id": "contact-names",+        "level": "fail",+        "routes": ["circuit", "board"],+        "messages": ["pinNameOnContact", "designatorCase"]+      },+      { "stage": "names", "id": "hole-sizes", "level": "fail", "routes": ["circuit", "board"], "messages": ["holeSizes"] },+      { "stage": "names", "id": "pin-count", "level": "fail", "routes": ["circuit", "board"], "messages": ["pinCount", "pinNone"] },+      { "stage": "names", "id": "corner-pins", "level": "fail", "routes": ["circuit", "board"], "messages": ["cornerPins"] },+      { "stage": "names", "id": "designators-unique", "level": "fail", "routes": ["circuit", "board"], "messages": ["duplicate"] },+      { "stage": "names", "id": "pins-uniform", "level": "fail", "routes": ["circuit", "board"], "messages": ["pinsUniform"] },+      { "stage": "names", "id": "not-machine-pins", "level": "warn", "routes": ["circuit", "board"], "messages": ["notPins"] },+      { "stage": "names", "id": "not-machine-contacts", "level": "warn", "routes": ["circuit", "board"], "messages": ["notContacts"] },+      { "stage": "names", "id": "groups", "level": "warn", "routes": ["circuit", "board"], "messages": ["groups"] },+      {+        "stage": "names",+        "id": "test-points",+        "level": "warn",+        "routes": ["circuit", "board"],+        "messages": ["testPoints", "testPointNames"]+      },+      { "stage": "names", "id": "extra-pins", "level": "info", "routes": ["circuit", "board"], "messages": ["extraPins"] },+      { "stage": "names", "id": "ignored", "level": "info", "routes": ["circuit", "board"], "messages": ["ignored"] },+      { "stage": "metadata", "id": "metadata-read", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "metadata", "id": "machine-pins-found", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "metadata", "id": "pin-heights-uniform", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "metadata", "id": "census-matches-metadata", "level": "fail", "routes": ["circuit", "board"], "messages": ["census"] },+      { "stage": "circuit-assets", "id": "circuit-assets", "level": "fail", "routes": ["circuit"] },+      { "stage": "circuit-assets", "id": "assets-unused", "level": "info", "routes": ["circuit"] },+      { "stage": "circuit-convert", "id": "circuit-convert", "level": "fail", "routes": ["circuit"] },+      { "stage": "anchor", "id": "anchor", "level": "fail", "routes": ["circuit"] },+      { "stage": "anchor", "id": "anchor-rule", "level": "info", "routes": ["circuit"] },+      {+        "stage": "convert-anchor",+        "id": "convert-anchor",+        "level": "fail",+        "routes": ["board"],+        "note": "the STEP is placed on the board file's machine pins by shape, translation only; a model that fits only turned or mirrored is refused"+      },+      { "stage": "convert-anchor", "id": "anchor-rule", "level": "info", "routes": ["board"] },+      {+        "stage": "convert-anchor",+        "id": "anchor-by-names",+        "level": "warn",+        "routes": ["board"],+        "note": "no fit by shape; the machine-pin nodes found by name sit at the board file's pins"+      },+      { "stage": "convert-anchor", "id": "anchor-matches-metadata", "level": "fail", "routes": ["board"] },+      {+        "stage": "fabrication",+        "id": "export-matches-sources",+        "level": "fail",+        "routes": ["board"],+        "note": "export.json lists its files inside its own folder, and the STEP and board it records are the build's inputs"+      },+      { "stage": "fabrication", "id": "fab-bundle", "level": "fail", "routes": ["board"] },+      { "stage": "fabrication", "id": "fab-layers", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "fabrication", "id": "fab-tier", "level": "fail", "routes": ["circuit", "board"] },+      {+        "stage": "normalize",+        "id": "normalize",+        "level": "fail",+        "note": "normalize itself: it ran, wrote its report and exited 0",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "normalize-verdict",+        "level": "fail",+        "note": "normalize gave the look or frame verdict fail and recorded no failed check; the detail names the verdicts and how many checks of each group it recorded",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "core-found",+        "level": "fail",+        "note": "a look check of normalize spec 0.6; the board core is never a machine pin or contact or a node under one, and covers at least half of the model's XY footprint (board-look.json coreMinShare); without one the detail names the largest board body and the share of the model it covers",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "frame-units",+        "level": "fail",+        "note": "a frame check of normalize spec 0.6",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "frame-z-up",+        "level": "fail",+        "note": "a frame check of normalize spec 0.6",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "orientation",+        "level": "fail",+        "note": "a frame check of normalize spec 0.6",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "registration",+        "level": "fail",+        "note": "a look check of normalize spec 0.6; it also fails when the fabrication data names three or more components the model has and the fit puts fewer than half of them at their nodes (board-look.json registration.namedMinShare)",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "surface-kept",+        "level": "fail",+        "note": "a look check of normalize spec 0.6",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "no-leftover-layers",+        "level": "fail",+        "note": "a look check of normalize spec 0.6",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "board-opaque",+        "level": "fail",+        "note": "a look check of normalize spec 0.6",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "top-bottom-separate",+        "level": "fail",+        "note": "a look check of normalize spec 0.6",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "gold-pins",+        "level": "warn",+        "note": "a look check of normalize spec 0.6",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "pin-rims",+        "level": "warn",+        "note": "a look check of normalize spec 0.6",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "anchor-pin-at-origin",+        "level": "fail",+        "note": "a frame check of normalize spec 0.6",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "orient-design",+        "level": "fail",+        "note": "a frame check of normalize spec 0.6",+        "routes": ["circuit", "board"]+      },+      {+        "stage": "normalize",+        "id": "registration-turned",+        "level": "fail",+        "note": "the board artwork registers turned or mirrored against the model: the STEP and the fabrication files were exported in different orientations",+        "routes": ["circuit", "board"]+      },+      { "stage": "attachments-pre", "id": "attachments-at-named-nodes", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "attachments-pre", "id": "machine-pins-match-model", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "attachments-pre", "id": "contacts-match-model", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "attachments-pre", "id": "attachments-match-model", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "attachments-pre", "id": "attachment-heights", "level": "warn", "routes": ["circuit", "board"] },+      { "stage": "attachments-pre", "id": "pin-nodes-as-contacts", "level": "warn", "routes": ["circuit", "board"] },+      { "stage": "board-layers", "id": "layer-geometry", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "board-layers", "id": "distance-fields", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "optimize-canonical", "id": "board-layers-pack", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "optimize-canonical", "id": "board-layers-packed", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "optimize-canonical", "id": "preservation", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "optimize-canonical", "id": "no-ktx2", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "optimize-render", "id": "board-layers-pack", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "optimize-render", "id": "board-layers-packed", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "optimize-render", "id": "preservation", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "optimize-render", "id": "no-ktx2", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "attachments-post", "id": "attachments-at-named-nodes", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "attachments-post", "id": "machine-pins-match-model", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "attachments-post", "id": "contacts-match-model", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "attachments-post", "id": "attachments-match-model", "level": "fail", "routes": ["circuit", "board"] },+      { "stage": "attachments-post", "id": "attachment-heights", "level": "warn", "routes": ["circuit", "board"] },+      { "stage": "attachments-post", "id": "pin-nodes-as-contacts", "level": "warn", "routes": ["circuit", "board"] },+      { "stage": "outputs", "id": "outputs-written", "level": "fail", "routes": ["circuit", "board"] },+      {+        "stage": "pipeline",+        "id": "completed",+        "level": "fail",+        "note": "an error no check names; its detail is the exception's type and message, at most 300 characters"+      }+    ]+  },+  "versions": {+    "program": "molecule/8",+    "toolchain": "sha256:eea7c5d640ed5112a4c308ee1d22b0bd398cb0ffd53ed1d6d8c58e276726a6ec",+    "fabBundle": { "version": "1.1.0", "sha256": "3d22b1d4e98ddb16f5e7d3202e85ffeee2dd45ed120de1cdf8de5aff5837b132" },+    "importer": "1e045f7",+    "normalizeSpec": "0.6",+    "pins": "f1404942e79e3e83f550f70199344b7e86b20e1f07a93cca13a1b8bb3b32d39a",+    "namesPy": "cfdde56176749f36291777741f65fd823dfa841e247fc8ec0a1f1ff107e56fee",+    "anchorFixture": "92d82a583a13a5c4f7fc4e9ae0fa308d8ecd3f209d98caacf1eb2b7fd04c73d3",+    "tscircuitLedger": [+      "https://registry-api.tscircuit.com/package_files/get?package_file_id=f9f26d61-1970-4336-8aad-2c4292790e44",+      "https://registry-api.tscircuit.com/package_files/get?package_file_id=6cfca57f-5109-4233-a8be-f058eaaedcd6",+      "https://registry-api.tscircuit.com/package_files/get?package_file_id=73ff6e6b-9db6-4552-b00b-90ce92e162ad",+      "https://registry-api.tscircuit.com/package_files/get?package_file_id=ddd7f5f8-1bb5-4654-82a3-b65190ce1b10",+      "https://registry-api.tscircuit.com/package_files/get?package_file_id=73b7a88b-aaac-4c6e-9b5e-87910dc2bd9d",+      "https://registry-api.tscircuit.com/package_files/get?package_file_id=e106fd63-1680-4229-bb36-b6a0c272edf6",+      "https://modelcdn.tscircuit.com/easyeda_models/download?uuid=2a4bc2358b36497d9ab2a66ab6419ba3&pn=C165948&cachebust_origin="+    ],+    "cliMinimum": "1.8.0",+    "publisherMinimum": "3.0.0"+  }+}
scripts/pcbdoc.pyadded+603
@@ -0,0 +1,603 @@+"""Altium Designer .PcbDoc to a minimal .kicad_pcb that names.py and the metadata importer read.++A PcbDoc is an OLE2 compound file (CFB) whose storages hold one record stream each+(Board6/Data, Components6/Data, Pads6/Data, ...). The records are read field by field as KiCad+10's Altium importer reads them (pcbnew/pcb_io/altium), with board-to-molecule's rs/src/altium+as the reference port. Altium lengths are 1/10000 mil; every length is converted exactly+(1 mil = 0.0254 mm, no rounding), so a 43 mil drill is 1.0922 mm.++What the KiCad file carries. Each component of Components6 becomes a footprint: its name is+PATTERN as Altium has it (no library prefix), its Reference is the component's designator text+(Texts6, through WideStrings6), else SOURCEDESIGNATOR when the text is missing or a special+string such as .Designator, its Value is the comment text the same way, and its layer is F.Cu or+B.Cu from LAYER. Its placement is X, Y and ROTATION. Every Pads6 pad on the top, bottom or multi+layer, and every pad with a hole, is a pad of its component with its name, position, angle,+shape and size (the top layer's, for a pad stack), drill (round, or oval for a slot) and plated+or not; a pad of no component becomes a footprint of its own with no name or reference, as+KiCad's importer makes it. The file name of each 3D model a ComponentBodies6 record gives the+component (MODEL.NAME, else the Models/Data entry it names) is a (model) of its footprint, in+record order. Board6's outline vertices are lines and arcs on Edge.Cuts.++The frame is Altium's, measured from the board origin (Board6 ORIGINX, ORIGINY), with Y negated+because KiCad's Y grows downward; both readers negate it again. Nothing is renamed. Routing,+nets, vias, zones, text, silkscreen, board cutouts and pads without a hole on other layers are+left out; the report counts them and lists what may surprise as warnings.++Python 3.9 or newer, standard library only. A file that is not a binary PcbDoc, or that cannot+be read, raises ValueError with a one-line reason.++  pcbdoc.py <in.PcbDoc> <out.kicad_pcb> [--report report.json]+"""+import itertools, json, math, struct, sys+from decimal import Decimal, InvalidOperation+from pathlib import Path, PureWindowsPath++CFB_MAGIC = bytes.fromhex('d0cf11e0a1b11ae1')+NOSTREAM = 0xFFFFFFFF+LAST_SECTOR = 0xFFFFFFFA+MM_PER_MIL = Decimal('0.0254')+UNITS_PER_MIL = 10000+NO_COMPONENT = 0xFFFF+TOP, BOTTOM, MULTI = 1, 32, 74+SLOT, SQUARE = 2, 1+ROUNDRECT = 9+EDGE_WIDTH = '0.05'+++# ---------------------------------------------------------------- compound file++class Cfb:+    """An OLE2 compound file read whole: stream(path) returns the bytes of 'Board6/Data'."""++    def __init__(self, data):+        if len(data) < 512 or data[:8] != CFB_MAGIC:+            if data[:8].lstrip(b'\xef\xbb\xbf').startswith(b'|RECORD='):+                raise ValueError('it is an ASCII PcbDoc; save the board as a binary PcbDoc')+            raise ValueError('it is not an OLE2 compound file (no CFB signature)')+        major = struct.unpack_from('<H', data, 0x1A)[0]+        shift, mini_shift = struct.unpack_from('<HH', data, 0x1E)+        if shift not in (9, 12) or mini_shift != 6:+            raise ValueError(f'its compound file header is damaged (sector shift {shift}, mini sector shift {mini_shift})')+        self.data, self.size = data, 1 << shift+        n_fat, first_dir, _, self.cutoff, first_mini, _, first_difat, _ = struct.unpack_from('<8I', data, 0x2C)+        per = self.size // 4+        difat = list(struct.unpack_from('<109I', data, 0x4C))+        seen = set()+        s = first_difat+        while s < LAST_SECTOR and len(difat) < n_fat + 109:+            if s in seen:+                raise ValueError('its compound file DIFAT chain loops')+            seen.add(s)+            entries = struct.unpack(f'<{per}I', self._sector(s, 'DIFAT'))+            difat += entries[:-1]+            s = entries[-1]+        fat_sectors = [x for x in difat if x < LAST_SECTOR][:n_fat]+        if len(fat_sectors) < n_fat:+            raise ValueError('its compound file FAT is incomplete')+        self.fat = struct.unpack(f'<{per * n_fat}I', b''.join(self._sector(x, 'FAT') for x in fat_sectors))+        directory = self._chain_bytes(first_dir, self.fat, self.size, self._sector, 'directory')+        self.entries = []+        for i in range(len(directory) // 128):+            e = directory[i * 128:(i + 1) * 128]+            n = min(struct.unpack_from('<H', e, 64)[0], 64)+            left, right, child = struct.unpack_from('<III', e, 68)+            start, size = struct.unpack_from('<IQ', e, 116)+            self.entries.append({'name': e[:max(n - 2, 0)].decode('utf-16-le', errors='replace'), 'type': e[66],+                                 'left': left, 'right': right, 'child': child, 'start': start,+                                 'size': size & 0xFFFFFFFF if major == 3 else size})+        if not self.entries or self.entries[0]['type'] != 5:+            raise ValueError('its compound file has no root entry')+        root = self.entries[0]+        self.mini_fat = ()+        self.mini = b''+        if root['start'] < LAST_SECTOR:+            self.mini = self._chain_bytes(root['start'], self.fat, self.size, self._sector, 'mini stream')[:root['size']]+            if first_mini < LAST_SECTOR:+                raw = self._chain_bytes(first_mini, self.fat, self.size, self._sector, 'mini FAT')+                self.mini_fat = struct.unpack(f'<{len(raw) // 4}I', raw[:len(raw) // 4 * 4])+        self.paths = {}+        self._walk()++    def _sector(self, s, what):+        """Sector `s`; a stream's last sector may be cut short, a FAT or DIFAT sector may not."""+        off = (s + 1) * self.size+        if off >= len(self.data) or (what in ('FAT', 'DIFAT') and off + self.size > len(self.data)):+            raise ValueError(f'its compound file {what} points past the end of the file (truncated?)')+        return self.data[off:off + self.size]++    def _mini_sector(self, s, what):+        off = s * 64+        if off >= len(self.mini):+            raise ValueError(f'its compound file {what} points past the end of the mini stream')+        return self.mini[off:off + 64]++    @staticmethod+    def _chain_bytes(start, table, size, read, what):+        out, seen, s = [], set(), start+        while s < LAST_SECTOR:+            if s >= len(table) or s in seen:+                raise ValueError(f'its compound file {what} chain is broken')+            seen.add(s)+            out.append(read(s, what))+            s = table[s]+        return b''.join(out)++    def _walk(self):+        todo, seen = [(self.entries[0]['child'], '')], set()+        while todo:+            i, prefix = todo.pop()+            if i == NOSTREAM:+                continue+            if i >= len(self.entries) or i in seen:+                raise ValueError('its compound file directory tree is broken')+            seen.add(i)+            e = self.entries[i]+            todo += [(e['left'], prefix), (e['right'], prefix)]+            if e['type'] == 1:+                todo.append((e['child'], prefix + e['name'] + '/'))+            elif e['type'] == 2:+                self.paths[(prefix + e['name']).lower()] = i++    def stream(self, path):+        """The bytes of the stream at `path` ('Pads6/Data', case ignored), or None."""+        i = self.paths.get(path.lower())+        if i is None:+            return None+        e = self.entries[i]+        if e['size'] < self.cutoff:+            data = self._chain_bytes(e['start'], self.mini_fat, 64, self._mini_sector, path)+        else:+            data = self._chain_bytes(e['start'], self.fat, self.size, self._sector, path)+        if len(data) < e['size']:+            raise ValueError(f'{path} is shorter than its directory entry says (truncated?)')+        return data[:e['size']]+++# ---------------------------------------------------------------- records++def props(payload):+    """A |KEY=VALUE|... record: keys upper-cased, values Latin-1 (UTF-8 under a %UTF8% key), trimmed; the first of a repeated key wins."""+    out = {}+    for tok in payload.split(b'\0', 1)[0].split(b'|'):+        k, eq, v = tok.partition(b'=')+        if eq:+            key = k.decode('latin-1').strip(' \t\r\n').upper()+            out.setdefault(key, (v.decode('utf-8', errors='replace') if key.startswith('%UTF8%') else v.decode('latin-1')).strip(' \t\r\n'))+    return out+++def prop(p, key, default=''):+    return p.get('%UTF8%' + key, p.get(key, default))+++def prop_unicode(p, key):+    """KiCad's ReadUnicodeString: UNICODE__KEY (comma-separated code points) when UNICODE says EXISTS."""+    if 'EXISTS' in p.get('UNICODE', '') and 'UNICODE__' + key in p:+        try:+            return ''.join(chr(int(c)) for c in p['UNICODE__' + key].split(',') if c.strip())+        except (ValueError, OverflowError):+            pass+    return prop(p, key)+++def mil(p, key):+    """A '1234.5678mil' property in units of 1/10000 mil, exactly, or None (also beyond Altium's 32-bit range)."""+    v = prop(p, key, None)+    if v is None or not v.endswith('mil'):+        return None+    try:+        d = Decimal(v[:-3].strip().lstrip('+')) * UNITS_PER_MIL+    except InvalidOperation:+        return None+    return d if d.is_finite() and abs(d) < 2 ** 31 else None+++def number(p, key):+    """A plain number property (an angle, a kind), exactly; 0 when missing, malformed or absurd."""+    try:+        d = Decimal(prop(p, key, '0').strip() or '0')+    except InvalidOperation:+        return Decimal(0)+    return d if d.is_finite() and abs(d) < 10 ** 9 else Decimal(0)+++def text_records(data, stream):+    """A run of u32 length + property record (KiCad's ReadProperties)."""+    out, i = [], 0+    while len(data) - i >= 4:+        n = struct.unpack_from('<I', data, i)[0]+        binary, n = n & 0xFF000000, n & 0x00FFFFFF+        if i + 4 + n > len(data):+            raise ValueError(f'{stream} record {len(out)} runs past the end of the stream')+        if not binary:+            out.append(props(data[i + 4:i + 4 + n]))+        i += 4 + n+    return out+++def binary_records(data, subrecords, kind, stream):+    """A run of u8 record type + `subrecords` u32-length subrecords."""+    out, i = [], 0+    while len(data) - i >= 4:+        if data[i] != kind:+            raise ValueError(f'{stream} record {len(out)} has type {data[i]}, not {kind}')+        i += 1+        subs = []+        for _ in range(subrecords):+            if i + 4 > len(data):+                raise ValueError(f'{stream} record {len(out)} is truncated')+            n = struct.unpack_from('<I', data, i)[0]+            if i + 4 + n > len(data):+                raise ValueError(f'{stream} record {len(out)} runs past the end of the stream')+            subs.append(data[i + 4:i + 4 + n])+            i += 4 + n+        out.append(subs)+    return out+++def wide_strings(data):+    """WideStrings6: u32 index, u32 byte length, UTF-16LE text with its NUL."""+    out, i = {}, 0+    while len(data) - i >= 8:+        idx, n = struct.unpack_from('<II', data, i)+        i += 8+        if n <= 2:+            out[idx] = ''+            continue+        if i + n > len(data):+            break+        out[idx] = data[i:i + n - 2].decode('utf-16-le', errors='replace')+        i += n+    return out+++def pascal(b):+    n = b[0] if b else 0+    return b[1:1 + n].decode('latin-1')+++def i32(b, off):+    return struct.unpack_from('<i', b, off)[0]+++def u16(b, off):+    return struct.unpack_from('<H', b, off)[0]+++def angle(b, off):+    """A little-endian double, in degrees; 0 when it is not finite."""+    a = struct.unpack_from('<d', b, off)[0]+    return a if math.isfinite(a) else 0.0+++def pad_record(subs, index):+    """APAD6: the fields of subrecords 1, 5 and 6 a footprint pad needs."""+    s5, s6 = subs[4], subs[5]+    if not subs[0] or len(s5) < 110:+        raise ValueError(f'Pads6/Data record {index} is too short ({len(s5)}-byte subrecord 5)')+    x, y, w, h = struct.unpack_from('<4i', s5, 13)+    pad = {'name': pascal(subs[0]), 'layer': s5[0], 'component': u16(s5, 7), 'x': x, 'y': y, 'w': w, 'h': h, 'hole': i32(s5, 45),+           'shape': s5[49], 'direction': angle(s5, 52), 'plated': s5[60] != 0, 'mode': s5[62],+           'holeshape': 0, 'slot': 0, 'slotrot': 0.0, 'offset': (0, 0), 'alt': 0, 'radius': 0}+    if len(s6) >= 596:+        pad.update(holeshape=s6[262], slot=i32(s6, 263), slotrot=angle(s6, 267),+                   offset=(i32(s6, 275), i32(s6, 403)), alt=s6[532], radius=s6[564])+    return pad+++def text_record(subs, strings):+    """ATEXT6: component, designator/comment flags and the string (WideStrings6, else the legacy one)."""+    a = subs[0]+    if len(a) < 9:+        return None+    long = len(a) >= 123+    widx = struct.unpack_from('<I', a, 115)[0] if long else None+    text = strings[widx] if widx in strings else pascal(subs[1])+    return {'component': u16(a, 7), 'comment': long and a[40] != 0, 'designator': long and a[41] != 0, 'text': text.replace('\r\n', '\n')}+++def body_record(subs):+    """ACOMPONENTBODY6: the component index and the property block (MODEL.NAME, MODELID, ...)."""+    s = subs[0]+    if len(s) < 22:+        return None+    n = struct.unpack_from('<I', s, 18)[0] & 0x00FFFFFF+    return u16(s, 7), props(s[22:22 + n])+++# ---------------------------------------------------------------- geometry++def mm(units):+    """KiCad text for a length in 1/10000 mil: exact for a Decimal or int, to 1e-6 mm for a float."""+    if isinstance(units, float):+        return num(units * 0.0254 / UNITS_PER_MIL)+    s = format((Decimal(units) * MM_PER_MIL / UNITS_PER_MIL).normalize(), 'f')+    return '0' if s in ('-0', '0') else s+++def num(v):+    """KiCad text for an angle or a float length in mm, to 1e-6."""+    if isinstance(v, Decimal):+        s = format(v.normalize(), 'f')+    else:+        s = format(Decimal(repr(round(v, 6) + 0.0)).normalize(), 'f')+    return '0' if s in ('-0', '0') else s+++def rotate(x, y, angle):+    """(x, y) rotated by `angle` degrees counter-clockwise (Y up); exact for multiples of 90."""+    q = angle / 90+    if q == q.to_integral_value():+        return [(x, y), (-y, x), (-x, -y), (y, -x)][int(q) % 4]+    a = math.radians(float(angle))+    fx, fy = float(x), float(y)+    return fx * math.cos(a) - fy * math.sin(a), fx * math.sin(a) + fy * math.cos(a)+++def outline(board, origin):+    """Board6's vertices as Edge.Cuts pieces [(start, end, mid or None)] in units, read as KiCad+    reads them: a line vertex is a corner; an arc vertex is its arc from the centre, starting at+    the end nearer the vertex point; consecutive pieces are joined by straight edges and the+    chain is closed."""+    pieces = []+    for i in itertools.count():+        vx, vy = mil(board, f'VX{i}'), mil(board, f'VY{i}')+        if vx is None or vy is None:+            break+        p = (vx - origin[0], vy - origin[1])+        r = mil(board, f'R{i}') or Decimal(0)+        if number(board, f'KIND{i}') != 0:+            cx, cy = (mil(board, f'CX{i}') or Decimal(0)) - origin[0], (mil(board, f'CY{i}') or Decimal(0)) - origin[1]+            sa, ea = float(number(board, f'SA{i}')), float(number(board, f'EA{i}'))+            at = lambda deg: (Decimal(round(float(cx) + float(r) * math.cos(math.radians(deg)))), Decimal(round(float(cy) + float(r) * math.sin(math.radians(deg)))))+            a, b = at(sa), at(ea)+            sweep = (ea - sa) % 360+            short = math.hypot(float(a[0] - b[0]), float(a[1] - b[1])) < 0.001 / 0.0254 * UNITS_PER_MIL or sweep < 0.2+            mid = None if short else at(sa + sweep / 2)+            near = lambda q: math.hypot(float(q[0] - p[0]), float(q[1] - p[1]))+            pieces.append((a, b, mid) if near(a) < near(b) else (b, a, mid))+        else:+            pieces.append((p, p, None))+    out = []+    for i, (s, e, m) in enumerate(pieces):+        if m is not None or s != e:+            out.append((s, e, m))+        nxt = pieces[(i + 1) % len(pieces)][0]+        if len(pieces) > 1 and e != nxt:+            out.append((e, nxt, None))+    return out+++# ---------------------------------------------------------------- KiCad text++LAYERS = ('(layers (0 "F.Cu" signal) (2 "B.Cu" signal) (9 "F.Adhes" user "F.Adhesive") (11 "B.Adhes" user "B.Adhesive") '+          '(13 "F.Paste" user) (15 "B.Paste" user) (5 "F.SilkS" user "F.Silkscreen") (7 "B.SilkS" user "B.Silkscreen") '+          '(1 "F.Mask" user) (3 "B.Mask" user) (25 "Edge.Cuts" user) (31 "F.CrtYd" user "F.Courtyard") '+          '(29 "B.CrtYd" user "B.Courtyard") (35 "F.Fab" user) (33 "B.Fab" user))')+++def q(s):+    """A KiCad quoted string."""+    return '"' + s.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n') + '"'+++def xy(p):+    return f'{mm(p[0])} {mm(-p[1])}'+++def pad_text(pad, at, warn):+    """One (pad ...) at the footprint-local point `at` (units, Y up), with the pad's own angle,+    which KiCad stores absolute, and its shape as KiCad's importer maps Altium's."""+    w, h = pad['w'], pad['h']+    if pad['shape'] == 2:+        shape, extra = 'rect', ''+    elif pad['shape'] == 1 and pad['alt'] == ROUNDRECT:+        shape, extra = 'roundrect', f' (roundrect_rratio {num(Decimal(pad["radius"]) / 200)})'+    elif pad['shape'] == 1:+        shape, extra = ('circle' if w == h else 'oval'), ''+    elif pad['shape'] == 3:+        shape, extra = 'roundrect', ' (roundrect_rratio 0) (chamfer_ratio 0.25) (chamfer top_left top_right bottom_left bottom_right)'+    else:+        shape, extra = 'rect', ''+        warn('unknown-shape', f"pad {pad['name']!r} of {pad['owner']} has pad shape {pad['shape']}, written as rect")+    if pad['hole'] > 0:+        if pad['layer'] != MULTI:+            warn('hole-off-multi', f"pad {pad['name']!r} of {pad['owner']} has a hole on layer {pad['layer']}, not the multi layer; written as a through-hole pad")+        kind = 'thru_hole' if pad['plated'] else 'np_thru_hole'+        layers = '"*.Cu" "*.Mask"'+        d = mm(pad['hole'])+        if pad['holeshape'] == SLOT:+            rot = pad['slotrot'] % 180+            if abs(rot - 90) < 1e-9:+                drill = f'(drill oval {d} {mm(pad["slot"])}'+            else:+                drill = f'(drill oval {mm(pad["slot"])} {d}'+                if rot > 1e-9 and abs(rot - 180) > 1e-9:+                    warn('slot-angle', f"pad {pad['name']!r} of {pad['owner']} has a slot at {num(pad['slotrot'])} degrees; written along the pad's x axis")+        else:+            if pad['holeshape'] == SQUARE:+                warn('square-hole', f"pad {pad['name']!r} of {pad['owner']} has a square hole, written as a round drill of its size")+            drill = f'(drill {d}'+        if pad['offset'] != (0, 0):+            drill += f' (offset {mm(pad["offset"][0])} {mm(-pad["offset"][1])})'+        drill = ' ' + drill + ')'+    else:+        kind, drill = 'smd', ''+        layers = '"B.Cu" "B.Paste" "B.Mask"' if pad['layer'] == BOTTOM else '"F.Cu" "F.Paste" "F.Mask"' if pad['layer'] == TOP else '"*.Cu" "*.Mask"'+    rot = '' if pad['direction'] == 0 else ' ' + num(pad['direction'])+    return f'\t\t(pad {q(pad["name"])} {kind} {shape} (at {xy(at)}{rot}) (size {mm(w)} {mm(h)}){drill} (layers {layers}){extra})\n'+++def footprint_text(name, ref, value, layer, at, rotation, pads, models):+    out = [f'\t(footprint {q(name)} (layer {q(layer)}) (at {xy(at)}' + ('' if rotation == 0 else ' ' + num(rotation)) + ')\n',+           f'\t\t(property "Reference" {q(ref)} (at 0 0 0) (layer "F.Fab") (hide yes) (effects (font (size 1 1) (thickness 0.15))))\n',+           f'\t\t(property "Value" {q(value)} (at 0 0 0) (layer "F.Fab") (hide yes) (effects (font (size 1 1) (thickness 0.15))))\n']+    out += pads+    out += [f'\t\t(model {q(m)})\n' for m in models]+    out.append('\t)\n')+    return ''.join(out)+++# ---------------------------------------------------------------- conversion++class Warnings:+    """Warning sentences by kind; lines() gives five of each kind and the count of the rest."""++    def __init__(self):+        self.kinds = {}++    def __call__(self, kind, text):+        self.kinds.setdefault(kind, []).append(text)++    def lines(self):+        out = []+        for kind, texts in self.kinds.items():+            out += texts[:5] + ([f'and {len(texts) - 5} more {kind} warnings'] if len(texts) > 5 else [])+        return out+++def read(src):+    """The board of the PcbDoc at `src`: {origin, components, free, outline, counts, warn}."""+    try:+        data = Path(src).read_bytes()+    except OSError as e:+        raise ValueError(f'it cannot be read ({e.strerror or type(e).__name__})')+    cf = Cfb(data)+    board_data = cf.stream('Board6/Data')+    if board_data is None:+        raise ValueError('it is a compound file but not an Altium PcbDoc (no Board6/Data stream)')+    warn = Warnings()+    boards = text_records(board_data, 'Board6/Data')+    board = boards[0] if boards else {}+    origin = (mil(board, 'ORIGINX') or Decimal(0), mil(board, 'ORIGINY') or Decimal(0))+    stream = lambda path: cf.stream(path) or b''++    comps = []+    for p in text_records(stream('Components6/Data'), 'Components6/Data'):+        layer = prop(p, 'LAYER').upper()+        if layer not in ('TOP', 'BOTTOM'):+            warn('component-layer', f"component {prop(p, 'SOURCEDESIGNATOR')!r} is on layer {layer!r}; written on the top")+        comps.append({'source': prop(p, 'SOURCEDESIGNATOR'), 'designator': None, 'value': None, 'name': prop_unicode(p, 'PATTERN'),+                      'bottom': layer == 'BOTTOM', 'x': (mil(p, 'X') or Decimal(0)) - origin[0], 'y': (mil(p, 'Y') or Decimal(0)) - origin[1],+                      'rotation': number(p, 'ROTATION'), 'pads': [], 'models': []})++    strings = wide_strings(stream('WideStrings6/Data'))+    for subs in binary_records(stream('Texts6/Data'), 2, 5, 'Texts6/Data'):+        t = text_record(subs, strings)+        if not t or t['component'] >= len(comps) or t['text'].startswith('.'):+            continue+        c = comps[t['component']]+        if t['designator'] and c['designator'] is None:+            c['designator'] = t['text']+        elif t['comment'] and c['value'] is None:+            c['value'] = t['text']+    for c in comps:+        if c['designator'] is None:+            c['designator'] = c['source']+        elif c['source'] and c['designator'] != c['source']:+            warn('designator-differs', f"component {c['designator']!r} has SOURCEDESIGNATOR {c['source']!r}; its designator text is written")+        if not c['designator']:+            warn('no-designator', f"a component with footprint {c['name']!r} at ({mm(c['x'])}, {mm(c['y'])}) mm has no designator")++    models = {}+    for p in text_records(stream('Models/Data'), 'Models/Data'):+        models.setdefault(prop(p, 'ID'), prop(p, 'NAME'))+    for subs in binary_records(stream('ComponentBodies6/Data'), 1, 12, 'ComponentBodies6/Data'):+        b = body_record(subs)+        if not b or b[0] >= len(comps):+            continue+        name = prop(b[1], 'MODEL.NAME') or models.get(prop(b[1], 'MODELID'), '')+        name = PureWindowsPath(name).name if name else ''+        if name and name not in comps[b[0]]['models']:+            comps[b[0]]['models'].append(name)++    free, skipped, total = [], {}, 0+    for i, subs in enumerate(binary_records(stream('Pads6/Data'), 6, 2, 'Pads6/Data')):+        pad = pad_record(subs, i)+        total += 1+        if pad['component'] != NO_COMPONENT and pad['component'] >= len(comps):+            raise ValueError(f'Pads6/Data record {i} names component {pad["component"]} of {len(comps)}')+        if pad['layer'] not in (TOP, BOTTOM, MULTI) and pad['hole'] <= 0:+            skipped[pad['layer']] = skipped.get(pad['layer'], 0) + 1+            continue+        owner = comps[pad['component']] if pad['component'] != NO_COMPONENT else None+        pad.update(x=pad['x'] - origin[0], y=pad['y'] - origin[1], owner=repr(owner['designator']) if owner else 'no component')+        if pad['mode'] != 0:+            warn('pad-stack', f"pad {pad['name']!r} of {pad['owner']} has a {'top-middle-bottom' if pad['mode'] == 1 else 'full'} pad stack; "+                              "its top layer's shape and size are written")+        (owner['pads'] if owner else free).append(pad)+    if skipped:+        warn('pad-layer', f"{sum(skipped.values())} pads on layers other than top, bottom and multi (Altium layers {', '.join(str(k) for k in sorted(skipped))}) are left out")++    edge = outline(board, origin)+    if not edge:+        warn('no-outline', 'Board6 has no outline vertices; the KiCad file has no Edge.Cuts')+    for c in comps:+        for s in [c['name'], c['designator'], c['value'] or ''] + c['models']:+            if any(ch in s for ch in '"\\\n'):+                warn('escaped', f'{s!r} holds a quote, backslash or line break, which KiCad escapes and names.py and the importer read escaped')+    return {'origin': origin, 'components': comps, 'free': free, 'outline': edge, 'warn': warn,+            'counts': {'components': len(comps), 'pads': sum(len(c['pads']) for c in comps), 'freePads': len(free),+                       'padsLeftOut': sum(skipped.values()), 'padsInFile': total,+                       'bottomComponents': sum(c['bottom'] for c in comps), 'models': sum(len(c['models']) for c in comps)}}+++def kicad_text(board):+    """The .kicad_pcb text of a board from read()."""+    warn = board['warn']+    out = ['(kicad_pcb (version 20241229) (generator "pcbdoc.py") (generator_version "1")\n',+           '\t(general (thickness 1.6) (legacy_teardrops no))\n\t(paper "A3")\n\t' + LAYERS + '\n',+           '\t(setup (pad_to_mask_clearance 0))\n\t(net 0 "")\n']+    for s, e, m in board['outline']:+        if m is None:+            out.append(f'\t(gr_line (start {xy(s)}) (end {xy(e)}) (stroke (width {EDGE_WIDTH}) (type solid)) (layer "Edge.Cuts"))\n')+        else:+            out.append(f'\t(gr_arc (start {xy(s)}) (mid {xy(m)}) (end {xy(e)}) (stroke (width {EDGE_WIDTH}) (type solid)) (layer "Edge.Cuts"))\n')+    for c in board['components']:+        pads = [pad_text(p, rotate(p['x'] - c['x'], p['y'] - c['y'], -c['rotation']), warn) for p in c['pads']]+        out.append(footprint_text(c['name'], c['designator'], c['value'] or '', 'B.Cu' if c['bottom'] else 'F.Cu', (c['x'], c['y']), c['rotation'], pads, c['models']))+    for p in board['free']:+        layer = 'B.Cu' if p['layer'] == BOTTOM else 'F.Cu'+        out.append(footprint_text('', '', '', layer, (p['x'], p['y']), Decimal(0), [pad_text(p, (0, 0), warn)], []))+    out.append(')\n')+    return ''.join(out)+++def convert(src, out):+    """Write the .kicad_pcb of the PcbDoc `src` to `out`. Returns the report: {source, components,+    pads, freePads, padsLeftOut, padsInFile, bottomComponents, models, outline {found, lines, arcs},+    originMm, warnings}. Raises ValueError when `src` is not a binary PcbDoc or cannot be read."""+    board = read(src)+    text = kicad_text(board)+    Path(out).write_text(text, encoding='utf-8', newline='\n')+    edge = board['outline']+    return {'source': Path(src).name, **board['counts'],+            'outline': {'found': bool(edge), 'lines': sum(m is None for _, _, m in edge), 'arcs': sum(m is not None for _, _, m in edge)},+            'originMm': [float(mm(board['origin'][0])), float(mm(board['origin'][1]))],+            'frame': 'Altium coordinates from the board origin, Y negated',+            'warnings': board['warn'].lines()}+++def main(argv):+    args, report = list(argv), None+    if '--report' in args:+        i = args.index('--report')+        report = args[i + 1] if i + 1 < len(args) else None+        del args[i:i + 2]+    if len(args) != 2 or ('--report' in argv and not report):+        print(__doc__.split('\n\n')[-1], file=sys.stderr)+        return 2+    try:+        result = convert(args[0], args[1])+    except ValueError as e:+        print(f'Error: {Path(args[0]).name} could not be read: {e}', file=sys.stderr)+        return 1+    if report:+        Path(report).write_text(json.dumps(result, indent=2) + '\n', encoding='utf-8')+    print(f"{result['components']} components, {result['pads']} pads, {result['freePads']} free pads, outline "+          f"{'found' if result['outline']['found'] else 'missing'}, {len(result['warnings'])} warnings")+    return 0+++if __name__ == '__main__':+    sys.exit(main(sys.argv[1:]))
scripts/pin_names.pyadded+798
@@ -0,0 +1,798 @@+"""Machine pins and contacts by reference designator: rule adom.molecule-pins/2.++A census of a board file's through-hole parts, classified as molecule-metadata-importer+1e045f7 classifies their pads, and the checks the rule applies to it. The values of the+rule (designator patterns, drill buckets, length words, library model lengths, furniture+names, machine pin counts, message templates) are pins.json; this file is the one+implementation of it.++Classification. A pad whose round hole is within drillToleranceMm of a drill bucket is a+medium or large contact or pin hole. A pin hole has a length when the part's hint holds a+length word (KiCad: footprint name and 3D model path; Fusion/EAGLE .brd: package name;+circuit JSON: the component's metadata, CAD record and part number) or, failing that, its+3D model file is one of libraryModelLengths.++Parts. A part with a pin hole and a length is a machine pin when it is named+designators.machinePin (MP1 to MP4), and an extra machine pin when it is named+designators.extraMachinePin (MS<n>): not one of the machine pins the build publishes, left+out as a part the census warns about is, though without a warning. It is refused when its+name is a machine pin's in the wrong case, or MP<n> outside 1 to 4; named anything else it+is not a machine pin, and the build warns. A single-pad part with a contact hole is a machine contact when it is named+designators.machineContact; it is refused when its name is in the wrong case or a machine+pin's (MP<n>), and warned about when named anything else. A multi-pad part with contact+holes is a group, warned about, unless it is named or packaged as furniture (nearMiss,+furniturePackages), when it is read as a contact. A pin hole without a length is warned+about on furniture, on a part named like a machine pin, and on any single-pad part; on any+other part it is listed as ignored. Furniture with no hole on the table is warned about.+Machine pins and contacts the build keeps have unique designators; a board has+machinePinCounts machine pins (two or four), all of one size and length with its extra+machine pins, and no extra machine pin lies further out than the machine pins toward any+corner (extraPinRule). A KiCad+test-point footprint on the front is a test point when named designators.testPoint, and+warned about otherwise; on .brd and circuit JSON a part named designators.testPoint is+one, and is not imported.++The build keeps what the census accepts (census accepted) and nothing else: metadata.mjs+filters the importer's machine pins, contacts and test points to those designators, so the+census and the importer agree pad for pad (compare).++An Altium .PcbDoc is read through the KiCad board pcbdoc.py (beside this file) writes from+it. A Fusion .fbrd is a zip; a Fusion PCB document holds its board as EAGLE XML+(electron.BlobParts/ExtFile.<id>.brd), which is read as a .brd.++Python 3.9 or newer, standard library only. Nothing in a board's contents raises: a file+that cannot be read becomes the failed check board-read.++A folder is read as a molecule page's repository: its board file is the one the recipes of+contract.json select for the page slug (--slug, default the folder's name), with its route.++  names.py check <board file or folder> [--slug slug] [--route circuit|board] [--pins pins.json] [--contract contract.json] [--json]+  names.py self-check [contract.json]+"""+import collections, fnmatch, hashlib, importlib.util, json, math, re, sys, tempfile, zipfile+import xml.etree.ElementTree as ET+from pathlib import Path, PurePosixPath++HERE = Path(__file__).resolve().parent+SCHEMA = 'adom.molecule-pins/2'+FAILS = ('board-read', 'pin-names', 'contact-names', 'hole-sizes', 'pin-count', 'corner-pins', 'designators-unique', 'pins-uniform')+# The four diagonals the corner rule compares along, with the corner each points to (y up).+CORNERS = (((-1, -1), 'front-left'), ((1, -1), 'front-right'), ((-1, 1), 'back-left'), ((1, 1), 'back-right'))+FORMATS = {'kicad_pcb': 'a KiCad board', 'brd': 'a Fusion/EAGLE .brd board', 'circuit_json': 'a tscircuit circuit.json', 'pcbdoc': 'an Altium board',+           'fbrd': 'a Fusion .fbrd board'}+FBRD_BOARD = re.compile(r'(^|/)electron\.BlobParts/ExtFile\.[^/]+\.brd$')+DETAIL_MAX = 700+PIN_BUCKETS = ('mediumPin', 'largePin')+++def pins_path(path=None):+    """pins.json: `path`, else beside this file, else vendor/molecule-contract/ below it."""+    if path:+        return Path(path)+    for p in (HERE / 'pins.json', HERE / 'vendor/molecule-contract/pins.json'):+        if p.is_file():+            return p+    raise FileNotFoundError('pins.json is neither beside names.py nor in vendor/molecule-contract/')+++def contract_path(path=None):+    """contract.json: `path`, else beside this file, else vendor/molecule-contract/ below it."""+    if path:+        return Path(path)+    for p in (HERE / 'contract.json', HERE / 'vendor/molecule-contract/contract.json'):+        if p.is_file():+            return p+    raise FileNotFoundError('contract.json is neither beside names.py nor in vendor/molecule-contract/')+++def _rx(spec):+    return re.compile(spec['pattern'], re.I if 'i' in spec.get('flags', '') else 0)+++class Rule:+    """pins.json, read and compiled. `sha256` is the hash of its bytes."""+    def __init__(self, path=None):+        raw = pins_path(path).read_bytes()+        doc = json.loads(raw)+        if doc.get('schema') != SCHEMA:+            raise ValueError(f'pins.json is not {SCHEMA}')+        self.doc, self.sha256 = doc, hashlib.sha256(raw).hexdigest()+        d = doc['designators']+        self.mp, self.mpn, self.ms, self.mc, self.tp, self.near = (_rx(d[k]) for k in ('machinePin', 'machinePinNumbered', 'extraMachinePin', 'machineContact', 'testPoint', 'nearMiss'))+        self.corner_tol = doc['cornerToleranceMm']+        self.buckets = [(k, v) for k in ('mediumContact', 'mediumPin', 'largeContact', 'largePin') for v in doc['drillBucketsMm'][k]]+        self.tol = doc['drillToleranceMm']+        self.words = doc['lengthWords']+        self.models = {k.lower(): v for k, v in doc['libraryModelLengths']['models'].items()}+        self.globs = [g.lower() for g in doc['furniturePackages']]+        self.counts = doc['machinePinCounts']+        self.msg = doc['messages']++    def bucket(self, d):+        if d is None:+            return None+        return next((k for k, v in self.buckets if abs(d - v) < self.tol), None)++    def length(self, part):+        """(length, source): 'short' or 'standard' from a length word in the part's hint+        (source 'hint'), else from libraryModelLengths by its 3D model's file name (source+        'libraryModel'), else (None, None)."""+        h = (part.get('hint') or '').lower()+        for k in ('short', 'standard'):+            if any(w in h for w in self.words[k]):+                return k, 'hint'+        name = PurePosixPath((part.get('model') or '').replace('\\', '/')).name.lower()+        return (self.models[name], 'libraryModel') if name in self.models else (None, None)++    def furniture(self, part):+        if self.near.fullmatch(part['designator']):+            return True+        names = [part['package'], PurePosixPath(part.get('model', '').replace('\\', '/')).name]+        return any(fnmatch.fnmatchcase(n.lower(), g) for n in names if n for g in self.globs)+++# ---------------------------------------------------------------- readers+# Each returns parts: {designator, package (after its last ':'), model, hint, pads [{drill, oval}],+# at (x, y) mm, testpoint (None, 'front' or 'back')}, read the way the importer reads the file.++_NUM = re.compile(r'\s*[+-]?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?')+++def _float(v):+    """JavaScript parseFloat: the longest leading number, else None."""+    m = _NUM.match(v) if isinstance(v, str) else None+    return float(m.group()) if m else None+++def _number(v):+    """JavaScript Number() as safeNumber uses it: a whole numeric string, else 0."""+    try:+        n = float((v or '').strip() or 0)+    except ValueError:+        return 0.0+    return n if math.isfinite(n) else 0.0+++_TOK = re.compile(r'[()]|(?:[^ \t\r\n()"]+|"[^"]*"?)+')+++def _sexpr(text):+    # The importer's tokenizer: a double quote toggles quoting, with no escapes.+    stack = [[]]+    for m in _TOK.finditer(text):+        t = m.group()+        if t == '(':+            stack.append([])+        elif t == ')':+            if len(stack) > 1:+                x = stack.pop(); stack[-1].append(x)+        else:+            stack[-1].append(t[1:-1] if len(t) >= 2 and t[0] == t[-1] == '"' else t)+    while len(stack) > 1:+        x = stack.pop(); stack[-1].append(x)+    return stack[0][0] if stack[0] and isinstance(stack[0][0], list) else []+++def _s(x, i):+    return x[i] if isinstance(x, list) and i < len(x) and isinstance(x[i], str) else ''+++def _first(x, key):+    return next((e for e in x if isinstance(e, list) and e and e[0] == key), None)+++def _all(x, key):+    out = []+    for e in x:+        if isinstance(e, list):+            if e and e[0] == key:+                out.append(e)+            out.extend(_all(e, key))+    return out+++def read_kicad(text):+    root = _sexpr(text)+    if _s(root, 0) != 'kicad_pcb':+        raise ValueError('it is not a KiCad PCB (no kicad_pcb root expression)')+    parts = []+    for fp in (e for e in root if isinstance(e, list) and e and e[0] == 'footprint'):+        name = _s(fp, 1)+        props = {_s(p, 1): _s(p, 2) for p in _all(fp, 'property') if len(p) >= 3}+        if not props:+            for t in _all(fp, 'fp_text'):+                if len(t) >= 3 and _s(t, 1) in ('reference', 'value'):+                    props[_s(t, 1).capitalize()] = _s(t, 2)+        at = _first(fp, 'at') or []+        text_of = lambda k: _s(_first(fp, k) or [], 1)+        model = text_of('model')+        pads = []+        for p in _all(fp, 'pad'):+            if len(p) < 4:+                continue+            dr = _first(p, 'drill') or []+            pads.append({'number': _s(p, 1), 'drill': _float(_s(dr, 1)) if len(dr) >= 2 else None, 'oval': _s(dr, 1) == 'oval'})+        tp = 'test point' in f"{text_of('descr')} {text_of('tags')} {props.get('Description', '')}".lower()+        parts.append({'designator': props.get('Reference') or name.split(':')[-1] or name, 'package': name.split(':')[-1], 'footprint': name,+                      'model': model, 'hint': f'{name} {model}'.strip(), 'pads': pads,+                      'at': (_float(_s(at, 1)) or 0.0, -(_float(_s(at, 2)) or 0.0)),+                      'testpoint': ('front' if text_of('layer').startswith('F.') else 'back') if tp else None})+    return parts+++def read_brd(text):+    root = ET.fromstring(text)+    board = root.find('./drawing/board') if root.tag == 'eagle' else None+    if board is None:+        raise ValueError('it is not a Fusion/EAGLE board (no eagle/drawing/board element)')+    libs = {}+    for lib in board.findall('./libraries/library'):+        libs[lib.get('name') or ''] = {pk.get('name') or '': [{'number': p.get('name') or '', 'drill': _number(p.get('drill')), 'oval': False}+                                                             for p in pk.findall('pad')] for pk in lib.findall('./packages/package')}+    parts = []+    for el in board.findall('./elements/element'):+        pads = libs.get(el.get('library') or '', {}).get(el.get('package') or '')+        if pads is None:+            continue+        pkg = el.get('package') or ''+        parts.append({'designator': el.get('name') or '', 'package': pkg.split(':')[-1], 'footprint': pkg, 'model': '', 'hint': pkg, 'pads': pads,+                      'at': (_number(el.get('x')), _number(el.get('y'))), 'testpoint': None})+    return parts+++def read_circuit(text):+    a = json.loads(text)+    if not isinstance(a, list):+        raise ValueError('it is not a circuit JSON array')+    a = [e for e in a if isinstance(e, dict)]+    first = lambda kind, key, value: next((e for e in a if e.get('type') == kind and e.get(key) == value), None)+    by_part = collections.OrderedDict()+    for h in a:+        if h.get('type') == 'pcb_plated_hole':+            by_part.setdefault(h.get('pcb_component_id', ('hole', id(h))), []).append(h)+    smt = collections.Counter(e.get('pcb_component_id') for e in a if e.get('type') == 'pcb_smtpad')+    parts = []+    for key, holes in by_part.items():+        cid = key if not isinstance(key, tuple) else None+        c = first('pcb_component', 'pcb_component_id', cid) if cid is not None else None+        # The importer's lookups, including those of a hole without a component.+        sc = first('source_component', 'source_component_id', (c or {}).get('source_component_id'))+        cad = first('cad_component', 'pcb_component_id', (c or {}).get('pcb_component_id'))+        hint = json.dumps([(c or {}).get('metadata'), cad, (sc or {}).get('manufacturer_part_number')], separators=(',', ':'), ensure_ascii=False)+        url = next((v for k, v in (cad or {}).items() if k.startswith('model_') and k.endswith('_url') and isinstance(v, str)), '')+        meta = (((c or {}).get('metadata') or {}).get('kicad_footprint') or {}) if isinstance((c or {}).get('metadata'), dict) else {}+        desc = ((meta.get('properties') or {}).get('Description') or {}).get('value') if isinstance(meta.get('properties'), dict) else None+        model = PurePosixPath(url.split('?')[0]).name if url and not url.startswith('data:') else ''+        package = next((str(v) for v in (desc, PurePosixPath(model).stem if model else None, (sc or {}).get('manufacturer_part_number'), (sc or {}).get('ftype')) if v), '')+        pads = [{'number': str((h.get('port_hints') or ['1'])[-1]), 'drill': h['hole_diameter'] if isinstance(h.get('hole_diameter'), (int, float)) and not isinstance(h.get('hole_diameter'), bool) and math.isfinite(h['hole_diameter']) else None, 'oval': False} for h in holes]+        centre = (c or {}).get('center') or {'x': holes[0].get('x', 0), 'y': holes[0].get('y', 0)}+        parts.append({'designator': str((sc or {}).get('name') or ''), 'package': package.split(':')[-1], 'footprint': package, 'model': model, 'hint': hint,+                      'pads': pads + [{'number': '', 'drill': None, 'oval': False}] * smt.get(cid, 0) if cid is not None else pads,+                      'at': (centre.get('x', 0), centre.get('y', 0)), 'testpoint': None})+    # Components without plated holes count only as names (test points).+    named = {p['designator'] for p in parts}+    parts += [{'designator': str(e.get('name') or ''), 'package': '', 'model': '', 'hint': '', 'pads': [], 'at': (0, 0), 'testpoint': None, 'nameOnly': True}+              for e in a if e.get('type') == 'source_component' and str(e.get('name') or '') not in named]+    return parts+++def board_format(path):+    n = PurePosixPath(str(path).replace('\\', '/')).name.lower()+    if n == 'circuit.json' or n.endswith('.circuit.json'):+        return 'circuit_json'+    return {'.kicad_pcb': 'kicad_pcb', '.brd': 'brd', '.pcbdoc': 'pcbdoc', '.fbrd': 'fbrd'}.get(PurePosixPath(n).suffix)+++# ---------------------------------------------------------------- census++def _natural(name):+    return [int(t) if t.isdigit() else t.lower() for t in re.split(r'(\d+)', name)]+++def _list(names, show=6, order=True):+    names = sorted((n or '(unnamed)' for n in names), key=_natural) if order else [n or '(unnamed)' for n in names]+    return ', '.join(names) if len(names) <= show else ', '.join(names[:show]) + f' and {len(names) - show} more'+++def _say(rule, key, count, **values):+    """The message `key` of pins.json, in its singular form (key + 'One') when count is 1."""+    return rule.msg[key + 'One' if count == 1 and key + 'One' in rule.msg else key].format(count=count, **values)+++def _uniq(values):+    out = []+    for v in values:+        if v not in out:+            out.append(v)+    return out+++def _mm(d):+    return 'no' if d is None else f'{d:.2f}'+++def _cap(text, end=''):+    body = text if not end else text + ' ' + end+    if len(body) <= DETAIL_MAX:+        return body+    keep = DETAIL_MAX - (len(end) + 4 if end else 3)+    return text[:keep].rstrip() + '...' + (' ' + end if end else '')+++def read_pcbdoc(path):+    """The KiCad board text pcbdoc.py, beside this file, writes from the Altium board `path`."""+    spec = importlib.util.spec_from_file_location('pcbdoc', HERE / 'pcbdoc.py')+    if spec is None or not (HERE / 'pcbdoc.py').is_file():+        raise ValueError('pcbdoc.py, the Altium reader, is not beside names.py')+    mod = importlib.util.module_from_spec(spec)+    spec.loader.exec_module(mod)+    with tempfile.TemporaryDirectory() as d:+        out = Path(d) / 'board.kicad_pcb'+        mod.convert(str(path), str(out))+        return out.read_text(encoding='utf-8')+++def read_fbrd(path):+    """The EAGLE board text the Fusion .fbrd `path` holds: the one zip member+    electron.BlobParts/ExtFile.<id>.brd of a Fusion PCB document."""+    try:+        with zipfile.ZipFile(path) as z:+            hits = [n for n in z.namelist() if FBRD_BOARD.search(n)]+            if len(hits) != 1:+                kinds = sorted({n.split('/')[0] for n in z.namelist() if '/' in n})+                raise ValueError(f"it holds {len(hits)} EAGLE boards ({', '.join(kinds) or 'no Fusion asset'}), where a Fusion PCB document "+                                 'holds one; export the board from Fusion as an EAGLE .brd and push it beside the STEP')+            return z.read(hits[0]).decode('utf-8', errors='replace')+    except zipfile.BadZipFile as e:+        raise ValueError(f'it is not a zip, as Fusion saves a .fbrd: {e}') from None+++def census(path, route, rule, text=None, role=None, repo_path=None, kicad=None):+    """The census of the board file `path`. `route` ('circuit', 'board') is the page's; the+    rule is the same on both. An Altium board is read as the KiCad board `kicad` that+    pcbdoc.py wrote from it, or, without one, as the board read_pcbdoc() writes; a Fusion+    .fbrd as the EAGLE board read_fbrd() takes from it.++    Returns {report, checks, attachments, accepted, positions}: report is the census (report.names of+    the molecule report), checks are [{id, level, pass, detail}] with level fail, warn or+    info, in the order FAILS then warnings then info, attachments are the census's machine+    pins and contacts as [(kind, designator, package, hole)], kind 'machinePin' or+    'contact', one per pad the build keeps, and accepted is {machinePins, contacts,+    testPoints, lengths}: the designators the build keeps of each, in board order, and the+    lengths of kept pins taken from libraryModelLengths ({designator: length}), which+    importer_board() writes into the board the importer reads. positions is+    {pins, warned}: the board position [x, y] of each kept machine pin by designator, and+    [{designator, class, at}] for each one-pad machine pin or contact the census warns about and+    leaves out, at its board position; metadata.mjs maps the second into the importer's frame by+    the first.+    """+    fmt = board_format(path)+    src = {'role': role or ('circuit' if fmt == 'circuit_json' else 'board'), 'path': repo_path or PurePosixPath(str(path).replace('\\', '/')).name, 'format': fmt}+    base = {'rule': SCHEMA, 'ruleSha256': rule.sha256}+    none = {'machinePins': [], 'contacts': [], 'testPoints': [], 'lengths': {}}+    if fmt not in ('kicad_pcb', 'brd', 'circuit_json', 'pcbdoc', 'fbrd'):+        return {'report': {**base, 'applies': False, 'reason': 'no board file the build can read', 'source': src}, 'checks': [], 'attachments': [], 'accepted': none}+    end = rule.msg['refusalEnd']+    try:+        if fmt == 'pcbdoc':+            src['readAs'] = 'kicad_pcb'+            text = Path(kicad).read_bytes().decode('utf-8', errors='replace') if kicad else read_pcbdoc(path)+        elif fmt == 'fbrd':+            src['readAs'] = 'brd'+            text = read_fbrd(path) if text is None else text+        elif text is None:+            text = Path(path).read_bytes().decode('utf-8', errors='replace')+        parts = {'kicad_pcb': read_kicad, 'pcbdoc': read_kicad, 'brd': read_brd, 'fbrd': read_brd, 'circuit_json': read_circuit}[fmt](text)+    except (ValueError, ET.ParseError, RecursionError, OSError) as e:+        why = str(e).splitlines()[0][:200] if str(e) else type(e).__name__+        detail = _cap(rule.msg['boardRead'].format(file=src['path'], reason=why.rstrip('.')), end)+        return {'report': {**base, 'applies': True, 'source': src, 'error': detail}, 'checks': [{'id': 'board-read', 'level': 'fail', 'pass': False, 'detail': detail}], 'attachments': [], 'accepted': none}++    kicad_like = fmt in ('kicad_pcb', 'pcbdoc')+    hole = lambda group: None if not group or group[0][0]['oval'] else group[0][0]['drill']+    size = lambda group: 'large' if group[0][1] == 'largePin' else 'medium'+    rows, atts, non_attachments = [], [], []+    for part in parts:+        des, pkg = part['designator'], part['package']+        if part.get('nameOnly'):+            continue+        row = {'designator': des, 'package': pkg, 'holeMm': None, 'pads': len(part['pads']), 'class': None, 'result': None, 'at': part['at'], 'shown': part.get('footprint') or pkg}+        if part['testpoint']:+            named = bool(rule.tp.fullmatch(des))+            row.update(result='ignored' if part['testpoint'] == 'back' else 'ok' if named else 'warned', **{'class': 'test-point'})+            if row['result'] == 'warned':+                row['reason'] = 'not-named'+            rows.append(row)+            continue+        pins, contacts, dropped, off = [], [], [], []+        length, length_from = rule.length(part)+        furniture = rule.furniture(part)+        # A jumper is an ordinary component even when its old 0.81 mm holes are+        # outside the contact buckets. Its STEP contact body can sit at the part+        # origin; record that origin without publishing a machine attachment.+        jumper = bool(re.search(r'jumper', pkg, re.I) or re.fullmatch(r'JP[0-9]+', des))+        if jumper and not furniture and len(part['pads']) >= 2 and all(+                not p['oval'] and p['drill'] is not None and p['drill'] > 0 and+                rule.bucket(p['drill']) not in PIN_BUCKETS for p in part['pads']):+            non_attachments.append({'designator': des, 'class': 'jumper', 'at': list(part['at'])})+        for pad in part['pads']:+            b = rule.bucket(pad['drill'])+            if b in PIN_BUCKETS:+                (pins if length else dropped).append((pad, b))+            elif b:+                contacts.append((pad, b))+            elif pad['drill'] is not None or pad['oval']:+                off.append((pad, None))+        lower = bool(rule.near.fullmatch(des)) and des[:2] not in ('MP', 'MC')+        numbered = bool(rule.mpn.fullmatch(des))+        extra = bool(rule.ms.fullmatch(des))+        single = len(part['pads']) == 1+        if pins:+            row.update(holeMm=hole(pins), size=size(pins), length=length, **{'class': 'machine-pin'})+            if length_from == 'libraryModel':+                row['lengthFrom'] = length_from+            if rule.mp.fullmatch(des):+                row['result'] = 'ok'+            elif extra:+                row['result'] = 'extra'+            else:+                row.update(result='refused' if lower or numbered else 'warned', reason='lowercase' if lower else 'outside-mp1-mp4' if numbered else 'not-named')+        elif contacts and not single and not furniture:+            row.update(holeMm=hole(contacts), result='group', **{'class': 'group'})+        elif contacts:+            row.update(holeMm=hole(contacts), **{'class': 'machine-contact'})+            if rule.mc.fullmatch(des):+                row['result'] = 'ok'+            else:+                row.update(result='refused' if lower or numbered else 'warned', reason='lowercase' if lower else 'pin-name' if numbered else 'not-named')+        elif dropped and (furniture or numbered or lower or extra):+            row.update(holeMm=hole(dropped), size=size(dropped), result='warned', reason='no-length', **{'class': 'machine-pin'})+        elif dropped and single:+            row.update(holeMm=hole(dropped), size=size(dropped), result='warned', reason='not-named', **{'class': 'machine-pin'})+        elif dropped:+            row.update(holeMm=hole(dropped), result='ignored')+        elif furniture:+            # Named MP<n>, MC<n> or MS<n> on a round hole of no listed size (an older library drill):+            # refused. Its name is checked too (nameReason), so one export fixes both.+            pinlike = not (des.upper().startswith('MC') or 'contact' in f"{pkg} {part['model']}".lower())+            reason = 'no-hole' if not off else 'slot' if hole(off) is None else 'hole-off-table'+            refused = reason == 'hole-off-table' and bool(rule.near.fullmatch(des) or extra and pinlike)+            row.update(holeMm=hole(off), result='refused' if refused else 'warned', reason=reason,+                       **{'class': 'machine-pin' if pinlike else 'machine-contact'})+            if refused and (lower or numbered and not (pinlike and rule.mp.fullmatch(des))):+                row['nameReason'] = 'lowercase' if lower else 'outside-mp1-mp4' if pinlike else 'pin-name'+        else:+            continue+        if length_from == 'libraryModel' and row['class'] == 'machine-pin':+            row['inject'] = length+        if row['result'] == 'ok':+            kind, group = ('machinePin', pins) if row['class'] == 'machine-pin' else ('contact', contacts)+            atts += [(kind, des, row['shown'], p['drill']) for p, b in group]+        rows.append(row)++    kept = [r for r in rows if r['result'] in ('ok', 'extra') and r['class'] in ('machine-pin', 'machine-contact')]+    seen = collections.Counter(r['designator'] for r in kept)+    dups = collections.OrderedDict()+    for r in kept:+        if seen[r['designator']] > 1:+            dups.setdefault(r['designator'], []).append(r)+            r.update(result='refused', reason='duplicate')+    atts = [a for a in atts if a[1] not in dups]+    pin_rows = [r for r in rows if r['class'] == 'machine-pin']+    contact_rows = [r for r in rows if r['class'] == 'machine-contact']+    good_pins = [r for r in pin_rows if r['result'] == 'ok']+    extras = [r for r in pin_rows if r['result'] == 'extra']+    good_contacts = [r for r in contact_rows if r['result'] == 'ok']+    checks = []+    add = lambda id, level, ok, detail: checks.append({'id': id, 'level': level, 'pass': ok, 'detail': _cap(detail, end if level == 'fail' and not ok else '')})+    names_of = lambda rs: _list([r['designator'] for r in rs])+    because = lambda rs, reason: [r for r in rs if reason in (r.get('reason'), r.get('nameReason'))]++    # Refusals: names, the number of machine pins, repeated designators, mixed pins.+    case, outside = because(pin_rows, 'lowercase'), because(pin_rows, 'outside-mp1-mp4')+    said = ([_say(rule, 'pinNumber', len(outside), parts=names_of(outside))] if outside else []) + ([_say(rule, 'designatorCase', len(case), parts=names_of(case))] if case else [])+    add('pin-names', 'fail', not said, ' '.join(said) if said else f'{len(good_pins)} machine pins, each named MP1 to MP4')++    case, as_pin = because(contact_rows, 'lowercase'), because(contact_rows, 'pin-name')+    said = (([_say(rule, 'pinNameOnContact', len(as_pin), parts=names_of(as_pin), package=', '.join(_uniq(r['shown'] or '(none)' for r in as_pin)[:3]))] if as_pin else [])+            + ([_say(rule, 'designatorCase', len(case), parts=names_of(case))] if case else []))+    add('contact-names', 'fail', not said, ' '.join(said) if said else f'{len(good_contacts)} machine contacts, each named MC<n>')++    off = [r for r in rows if r['result'] == 'refused' and r.get('reason') == 'hole-off-table']+    sizes = lambda *ks: ' or '.join(f"{v:.2f} mm ({k.replace('Pin', '').replace('Contact', '')})" for k in ks for v in rule.doc['drillBucketsMm'][k])+    add('hole-sizes', 'fail', not off,+        _say(rule, 'holeSizes', len(off), parts=_list([f"{r['designator']} ({r['shown'] or 'no package'}: {_mm(r['holeMm'])} mm)" for r in off], 4),+             pins=sizes('mediumPin', 'largePin'), contacts=sizes('mediumContact', 'largeContact'), tol=f"{rule.tol:g}") if off+        else 'every part named as a machine pin or contact is drilled a standard size')++    n_pins = len(good_pins)+    if n_pins == 0:+        near = [r for r in pin_rows if r['result'] != 'ok']+        found = (f'{len(near)} parts look like machine pins and are not accepted: {names_of(near)}.' if near+                 else '0 parts in this board are named MP<n> or use a machine-pin footprint.')+        detail = rule.msg['pinNone'].format(found=found)+    elif n_pins not in rule.counts:+        fix = ('Add a second machine pin' if n_pins == 1 else 'Add a fourth machine pin, or remove one,' if n_pins == 3 else 'Remove the extra machine pins') + ' and export again.'+        detail = _say(rule, 'pinCount', n_pins, parts=names_of(good_pins), fix=fix)+    else:+        detail = f'{n_pins} machine pins'+    add('pin-count', 'fail', n_pins in rule.counts, detail)++    # MP1 to MP4 are the outermost corner pins: along each diagonal, no MS<n> pin further out than every MP<n> pin.+    beyond = collections.OrderedDict()+    for (dx, dy), corner in CORNERS if good_pins else ():+        reach = max(dx * r['at'][0] + dy * r['at'][1] for r in good_pins)+        for r in extras:+            if dx * r['at'][0] + dy * r['at'][1] > reach + rule.corner_tol:+                beyond.setdefault(r['designator'], []).append(corner)+    add('corner-pins', 'fail', not beyond,+        rule.msg['cornerPins'].format(parts='; '.join(f"{d} lies further out than {names_of(good_pins)} toward the {' and '.join(c)} corner{'s' if len(c) > 1 else ''}"+                                                      for d, c in list(beyond.items())[:4]) + (f'; and {len(beyond) - 4} more' if len(beyond) > 4 else ''))+        if beyond else 'no extra machine pins' if not extras else 'no machine pins to compare' if not good_pins+        else f'{n_pins} machine pins are the outermost, beside {len(extras)} extra machine pins')++    add('designators-unique', 'fail', not dups,+        ' '.join(_say(rule, 'duplicate', len(v), name=k, places=' and '.join(f"{round(r['at'][0], 2):g},{round(r['at'][1], 2):g}" for r in v[:4]))+                 for k, v in list(dups.items())[:6]) if dups+        else f'{len(kept)} machine pins and contacts, no designator repeated')++    kinds = collections.OrderedDict()+    for r in good_pins + extras:+        kinds.setdefault(f"{r['size']} {r['length']}", []).append(r['designator'])+    add('pins-uniform', 'fail', len(kinds) <= 1,+        rule.msg['pinsUniform'].format(groups='; '.join(f'{_list(v)} {"is" if len(v) == 1 else "are"} {k}' for k, v in kinds.items())) if len(kinds) > 1+        else f'every machine pin is {next(iter(kinds))}' if kinds else 'no machine pins to compare')++    # Warnings: parts that fit the standard only in part, groups, test points; then what the build leaves out.+    why = {'not-named': 'not named {want}', 'no-length': 'its footprint names no length', 'hole-off-table': 'its hole is {hole} mm', 'no-hole': 'it has no drilled hole', 'slot': 'its hole is a slot'}+    say_row = lambda r, want: f"{r['designator'] or '(unnamed)'} ({r['shown'] or 'no package'}: {why[r['reason']].format(want=want, hole=_mm(r['holeMm']))})"+    loose = [r for r in pin_rows if r['result'] == 'warned']+    if loose:+        sizes = {r.get('size', 'medium') for r in loose}+        one = next(iter(sizes)) if len(sizes) == 1 else None+        suggest = ' or '.join(n for n in rule.doc['adomParts'] if n.startswith('MachinePin') and (one is None or one.capitalize() in n))+        holes = ' or '.join(f'{v:.2f}' for k in PIN_BUCKETS if one is None or k.startswith(one) for v in rule.doc['drillBucketsMm'][k])+        add('not-machine-pins', 'warn', True, _say(rule, 'notPins', len(loose), parts=_list([say_row(r, 'MP1 to MP4') for r in loose], 4, order=False), suggest=suggest, holes=holes))+    loose = [r for r in contact_rows if r['result'] == 'warned']+    if loose:+        holes = ' or '.join(f'{v:.2f}' for k in ('mediumContact', 'largeContact') for v in rule.doc['drillBucketsMm'][k])+        add('not-machine-contacts', 'warn', True, _say(rule, 'notContacts', len(loose), parts=_list([say_row(r, 'MC<n>') for r in loose], 4, order=False), holes=holes))+    grouped = [r for r in rows if r['result'] == 'group']+    if grouped:+        shown, last = [], None+        for r in sorted(grouped, key=lambda r: _natural(r['designator'])):+            shown.append(r['designator'] + (f" ({r['pads']} pads)" if r['pads'] != last else ''))+            last = r['pads']+        add('groups', 'warn', True, _say(rule, 'groups', len(grouped), parts=_list(shown, order=False)))+    named_tp = [p for p in parts if rule.tp.fullmatch(p['designator'])] if not kicad_like else []+    unnamed_tp = [r for r in rows if r['class'] == 'test-point' and r['result'] == 'warned']+    if named_tp or unnamed_tp:+        add('test-points', 'warn', True, ' '.join(([_say(rule, 'testPoints', len(named_tp), parts=_list([p['designator'] for p in named_tp]), format=FORMATS[fmt])] if named_tp else [])+                                                 + ([_say(rule, 'testPointNames', len(unnamed_tp), parts=names_of(unnamed_tp))] if unnamed_tp else [])))+    if extras:+        add('extra-pins', 'info', True, _say(rule, 'extraPins', len(extras), parts=names_of(extras)))+    ignored = [r for r in rows if r['result'] == 'ignored' and r['class'] is None]+    if ignored:+        add('ignored', 'info', True, _say(rule, 'ignored', len(ignored), parts=_list([f"{r['designator'] or '(unnamed)'} ({r['shown'] or 'no package'}, {_mm(r['holeMm'])} mm)" for r in ignored], 4)))++    accepted = {'machinePins': [r['designator'] for r in good_pins], 'contacts': _uniq(r['designator'] for r in good_contacts),+                'testPoints': [r['designator'] for r in rows if r['class'] == 'test-point' and r['result'] == 'ok'],+                'lengths': {r['designator']: r['inject'] for r in good_pins if r.get('inject')}}+    positions = {'nonAttachments': non_attachments, 'pins': {r['designator']: list(r['at']) for r in good_pins},+                 'warned': [{'designator': r['designator'], 'class': r['class'], 'at': list(r['at'])} for r in rows+                            if r['result'] in ('warned', 'extra') and r['pads'] == 1 and r['class'] in ('machine-pin', 'machine-contact')]}+    for r in rows:+        r.pop('shown'); r.pop('at'); r.pop('size', None); r.pop('inject', None); r.pop('nameReason', None)+        r['holeMm'] = None if r['holeMm'] is None else round(r['holeMm'], 3)+    counts = {'machinePins': n_pins, 'extraMachinePins': len(extras), 'machineContacts': len(good_contacts), 'testPoints': len(accepted['testPoints']) if kicad_like else len(named_tp),+              'groups': len(grouped), 'ignored': len(ignored), 'warned': sum(r['result'] == 'warned' for r in rows), 'refused': sum(r['result'] == 'refused' for r in rows)}+    report = {**base, 'applies': True, 'source': src, 'anchorRule': None, 'testPointsImported': kicad_like, 'counts': counts, 'parts': rows}+    return {'report': report, 'checks': checks, 'attachments': atts, 'accepted': accepted, 'positions': positions}+++def _spans(text, head):+    """(start, end) of each top-level list `(head ...)` of the KiCad board `text`, read with the+    importer's tokenizer (a double quote toggles quoting, with no escapes)."""+    out, depth, quoted, start = [], 0, False, None+    for i, ch in enumerate(text):+        if ch == '"':+            quoted = not quoted+        elif quoted:+            continue+        elif ch == '(':+            depth += 1+            if depth == 2 and text.startswith(head, i + 1) and not text[i + 1 + len(head):i + 2 + len(head)].isalnum():+                start = i+        elif ch == ')':+            if depth == 2 and start is not None:+                out.append((start, i + 1))+                start = None+            depth -= 1+    return out+++def _same(a, b):+    return a is not None and b is not None and abs(a - b) < 1e-9+++def importer_board(path, accepted, text=None, kicad=None):+    """The board text the importer reads for the board file `path` and the census's accepted+    designators, or None when it is the board file's own text: for a kept pin whose length+    comes from libraryModelLengths, the length word added to its 3D model path (KiCad) or CAD+    record (circuit JSON), where the importer looks for it (accepted.lengths). An Altium board+    is the KiCad board `kicad`, a Fusion .fbrd the EAGLE board it holds; an EAGLE board names no+    3D model, so it is never rewritten."""+    lengths = accepted.get('lengths') or {}+    fmt = board_format(path)+    if not lengths or fmt in ('brd', 'fbrd'):+        return None+    if text is None:+        text = Path(kicad if fmt == 'pcbdoc' else path).read_bytes().decode('utf-8', errors='replace')+    if fmt in ('kicad_pcb', 'pcbdoc'):+        out, last = [], 0+        for a, b in _spans(text, 'footprint'):+            span = text[a:b]+            des = read_kicad(f'(kicad_pcb {span})')[0]['designator']+            if des in lengths:+                span = re.sub(r'\(model\s+(?:"([^"]*)"|([^\s()"]+))', lambda m: f'(model "{m.group(1) or m.group(2)} {lengths[des]}"', span, count=1)+            out += [text[last:a], span]+            last = b+        return ''.join(out + [text[last:]])+    a = json.loads(text)+    by_id = {e.get('source_component_id'): str(e.get('name') or '') for e in a if isinstance(e, dict) and e.get('type') == 'source_component'}+    owner = {e.get('pcb_component_id'): by_id.get(e.get('source_component_id'), '') for e in a if isinstance(e, dict) and e.get('type') == 'pcb_component'}+    for e in a:+        if not isinstance(e, dict):+            continue+        des = owner.get(e.get('pcb_component_id'))+        if e.get('type') == 'cad_component' and des in lengths:+            e['adom_length_hint'] = lengths[des]+    return json.dumps(a, separators=(',', ':'), ensure_ascii=False)+++def compare(attachments, board, rule):+    """census-matches-metadata: [] when the census's machine pins and contacts, by designator,+    are the importer's (board.machinePins and board.contacts by elementName), else the+    differences as sentences."""+    want = collections.Counter((k, d) for k, d, _, _ in attachments)+    have = collections.Counter([('machinePin', str(p.get('elementName'))) for p in board.get('machinePins') or []] ++                               [('contact', str(c.get('elementName'))) for c in board.get('contacts') or []])+    info = {(k, d): (p, h) for k, d, p, h in attachments}+    noun = {'machinePin': ('machine pin', 'machine pins'), 'contact': ('machine contact', 'contacts')}+    out = []+    for (k, d), n in (want - have).items():+        p, h = info[(k, d)]+        out.append(f"{d} (package {p or '(none)'}, hole {_mm(h)} mm) is a {noun[k][0]} in the census and missing from the importer's {noun[k][1]}" + (f' ({n} pads)' if n > 1 else ''))+    for (k, d), n in (have - want).items():+        out.append(f"{d} is one of the importer's {noun[k][1]} and not in the census" + (f' ({n} pads)' if n > 1 else ''))+    return out+++def census_detail(differences, rule):+    """The census-matches-metadata detail for compare()'s differences."""+    return _cap(_say(rule, 'census', len(differences), parts='; '.join(differences[:4]) + (f'; and {len(differences) - 4} more' if len(differences) > 4 else '')), rule.msg['refusalEnd'])+++# ---------------------------------------------------------------- command line++SKIP_DIRS = re.compile(r'(^|/)(node_modules|\.git)(/|$)')+++def source_pattern(pattern, slug=''):+    """A predicate over repo paths for one recipe source pattern, as the wiki's recipe engine+    reads it: {slug} is `slug`, '*' any run of characters within one segment, a segment '**'+    zero or more whole segments, case ignored; a pattern without '/' matches a file name at+    any depth, one with '/' the whole path."""+    parts = pattern.split('/')+    segs = [s for i, s in enumerate(parts) if not (s == '**' and i and parts[i - 1] == '**')]++    def seg(s):+        return ''.join(re.escape(slug) if p == '{slug}' else '[^/]*' if p == '*' else re.escape(p) for p in re.split(r'(\{slug\}|\*)', s))+    rx = ''+    for i, s in enumerate(segs):+        first, last = i == 0, i == len(segs) - 1+        if s != '**':+            rx += ('' if first or segs[i - 1] == '**' else '/') + seg(s)+        elif first and last:+            rx += '[^/]+(?:/[^/]+)*'+        elif last:+            rx += '(?:/[^/]+)*'+        else:+            rx += ('' if first else '/') + '(?:[^/]+/)*'+    m = re.compile(rx, re.I)+    whole = '/' in pattern+    return lambda path: m.fullmatch(path if whole else path.rsplit('/', 1)[-1]) is not None+++def board_source(paths, slug, recipes):+    """The board file a molecule page's build reads among its repo paths `paths`, as the+    recipes `recipes` (contract.json's) select it for the page slug `slug`. The recipes that+    apply to kind molecule are taken in order, each by its board file source (circuit on the+    circuit route, else board) and only that source: its exclude patterns remove files, its+    patterns are tried in order, the first that matches anything wins, and the shallowest of+    its matches is the file. Returns {recipe, role, route, pattern, path} for the first recipe+    whose source matches one file, {recipe, role, route, pattern, ambiguous: [paths]} when it+    matches two or more at that depth (the build refuses the page), or None when none matches.+    The recipes' other sources are not looked at, so a folder whose STEP is missing or+    ambiguous still has a board file here."""+    for r in recipes:+        if 'molecule' not in (r.get('applies') or {}).get('kinds', []):+            continue+        route = r['pipeline']['options']['route']+        role = 'circuit' if route == 'circuit' else 'board'+        spec = r['sources'].get(role)+        if not spec:+            continue+        excluded = [source_pattern(p, slug) for p in spec.get('exclude', [])]+        files = [f for f in paths if not any(m(f) for m in excluded)]+        for pattern in spec['match']:+            m = source_pattern(pattern, slug)+            hits = [f for f in files if m(f)]+            if not hits:+                continue+            depth = min(f.count('/') for f in hits)+            best = sorted(f for f in hits if f.count('/') == depth)+            out = {'recipe': f"{r['name']}/{r['version']}", 'role': role, 'route': route, 'pattern': pattern}+            return {**out, 'ambiguous': best} if len(best) > 1 else {**out, 'path': best[0]}+    return None+++def pick_board(folder, slug=None, contract=None):+    """The board file a molecule page's build reads when `folder` is its repository, by+    board_source() with the recipes of contract.json (contract_path(contract)) and the page+    slug `slug`, default the folder's name. Files under a .git or node_modules folder are left+    out. Returns (path, route), or raises ValueError when the source is ambiguous or no recipe's+    board file source matches."""+    root = Path(folder)+    slug = root.resolve().name if slug is None else slug+    recipes = json.loads(contract_path(contract).read_text(encoding='utf-8'))['recipes']+    files = sorted(p.relative_to(root).as_posix() for p in root.rglob('*') if p.is_file() and not SKIP_DIRS.search(p.relative_to(root).as_posix()))+    hit = board_source(files, slug, recipes)+    if hit is None:+        raise ValueError(f'no file in {folder} is the board file of a molecule recipe (circuit.json, *.circuit.json, *.kicad_pcb, *.brd, *.PcbDoc, *.fbrd outside library folders)')+    if 'ambiguous' in hit:+        raise ValueError(f"{hit['recipe']} source {hit['role']} ({hit['pattern']}): ambiguous: {', '.join(hit['ambiguous'])}; "+                         f"a board named for the slug ({slug!r}) is taken first, so pass --slug if the page's slug is another")+    return root / hit['path'], hit['route']+++def self_check(contract=None):+    out = {'namesPy': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), 'pins': hashlib.sha256(pins_path().read_bytes()).hexdigest()}+    print(json.dumps(out, indent=2))+    if contract:+        v = json.loads(Path(contract).read_text(encoding='utf-8')).get('versions', {})+        for k in out:+            if v.get(k) != out[k]:+                print(f'warning: {k} is {out[k]}, the contract names {v.get(k)}; this copy is older or newer than the contract', file=sys.stderr)+    return 0+++def main(argv):+    if argv[:1] in (['self-check'], ['--self-check']):+        return self_check(argv[1] if len(argv) > 1 else None)+    if argv[:1] != ['check'] or len(argv) < 2:+        print(__doc__.split('\n\n')[-1], file=sys.stderr)+        return 2+    opts = {argv[i]: argv[i + 1] for i in range(2, len(argv) - 1) if argv[i] in ('--route', '--pins', '--slug', '--contract')}+    rule = Rule(opts.get('--pins'))+    target = Path(argv[1])+    try:+        path, route = (pick_board(target, opts.get('--slug'), opts.get('--contract')) if target.is_dir()+                       else (target, 'circuit' if board_format(target) == 'circuit_json' else 'board'))+    except (ValueError, OSError) as e:+        print(f'error: {e}', file=sys.stderr)+        return 2+    route = opts.get('--route', route)+    result = census(path, route, rule, repo_path=path.relative_to(target).as_posix() if target.is_dir() else path.name)+    if '--json' in argv:+        print(json.dumps({'census': result['report'], 'checks': result['checks'], 'accepted': result['accepted']}, indent=2))+    else:+        print(json.dumps(result['report'], indent=2))+        for c in result['checks']:+            if not c['pass'] or c['level'] != 'fail':+                print(f"{'refused' if not c['pass'] else c['level']} {c['id']}: {c['detail']}")+    return 1 if any(not c['pass'] for c in result['checks']) else 0+++if __name__ == '__main__':+    sys.exit(main(sys.argv[1:]))
scripts/pins.jsonadded+107
@@ -0,0 +1,107 @@+{+  "schema": "adom.molecule-pins/2",+  "version": 2,+  "designators": {+    "machinePin": { "pattern": "^MP[1-4]$" },+    "machinePinNumbered": { "pattern": "^MP[0-9]+$" },+    "extraMachinePin": { "pattern": "^MS[1-9][0-9]*$" },+    "machineContact": { "pattern": "^MC[1-9][0-9]*$" },+    "testPoint": { "pattern": "^TP[1-9][0-9]*$" },+    "nearMiss": { "pattern": "^(MP|MC)[0-9]+$", "flags": "i" }+  },+  "machinePinCounts": [2, 4],+  "extraPinRule": "MP1 to MP4 are the outermost corner machine pins. Any other machine pin is named extraMachinePin (MS<n>, a tentative name): it is not one of the published machine pins, has the size and length of the others, and no MS<n> pin lies further out than the MP<n> pins toward any corner (compared along the four diagonals, within cornerToleranceMm).",+  "cornerToleranceMm": 0.01,+  "contactRule": "a single-pad through-hole part on a contact-bucket hole named MC<n> is a machine contact; one that fits the hole and not the name, or the name and not the hole, is not a contact and is warned about",+  "adomParts": ["MachinePinMediumShort", "MachinePinMediumStandard", "MachinePinLargeShort", "MachinePinLargeStandard", "MachineContactMedium", "MachineContactLarge"],+  "furniturePackages": ["MACH_PIN_*", "CONTACT_MED", "CONTACT_LRG", "PIN_MED*", "ADOM_*_PIN*", "ADOM_*_CONTACT*", "MpinContact*", "MachinePin*", "MachineContact*"],+  "furnitureMatch": "glob, case ignored, against the footprint name after its last ':' and against the file name of the KiCad 3D model path",+  "drillBucketsMm": { "mediumContact": [0.78], "mediumPin": [1.20], "largeContact": [2.62], "largePin": [3.45] },+  "drillToleranceMm": 0.001,+  "drillRule": "A hole is a pin or contact hole when it matches a drill bucket within drillToleranceMm, as the importer matches it; a looser match moves the machine pin. Older library drills (1.10, 1.12 and 1.0922 mm pins, 0.81 mm and 2.72 mm contacts) are not buckets. A part named MP<n> or MC<n> on a round hole that matches no bucket is refused (hole-sizes); a part packaged as a pin or contact and named otherwise, on such a hole, is warned about.",+  "lengthWords": { "short": ["short", "sht"], "standard": ["standard", "std"] },+  "libraryModelLengths": {+    "note": "Adom library 3D models whose file name carries no length word, by file name (case ignored), with the length the model itself names. A pin hole whose footprint hint has no length word takes its length from here when its 3D model file is listed.",+    "models": { "LargeMachinePin v3.step": "standard" }+  },+  "heightsMm": { "medium-short": 2.8, "medium-standard": 5.6, "large-short": 5.6, "large-standard": 8.4 },+  "step": {+    "note": "R1 and R2 as molecule_anchor.py in the toolchain image has them. The image does not read this block; test/registry/molecule-pins-copies.test.mjs holds it to the copy test/registry/fixtures/occt/molecule_anchor.py, extracted from the image by digest.",+    "marker": {+      "rule": "R1",+      "kind": "function",+      "source": "molecule_anchor.py:196-219 _is_marker_name, with _MARKER_PREFIX (40)",+      "text": "A node name, trimmed and lower-cased, is a marker when it holds no 'contact' and either starts with 'mp', has at most 5 characters and holds a digit, or its part after the last ':' starts with 'mp', has at most 4 characters and holds a digit while the part before that ':' holds 'pin'.",+      "prefix": "mp",+      "exclude": "contact",+      "nameMaxLength": 5,+      "suffixMaxLength": 4,+      "suffixBaseContains": "pin",+      "functionSha256": "8afa11f107ad2767b8b05fcc1a053051b23fd92ce29d3cd605b12d44fe4e10bd",+      "minMarkers": 3,+      "examples": {+        "MP1": true,+        "mp2:1": true,+        "MP101": true,+        "MP1000": false,+        "MACH_PIN_LRG_SHORT:MP3": true,+        "MachinePin:MP12": true,+        "U1:MP3": false,+        "CONTACT_MED:MP9": false,+        "MpinContact_Medium v6": false,+        "MC1": false,+        "MP": false+      }+    },+    "alias": {+      "rule": "R2",+      "kind": "regex",+      "source": "molecule_anchor.py:46-48 _ALIAS_RE, _ALIAS_EXCLUDE_RE, _ALIAS_PREFER_RE",+      "pattern": "machine[\\s_-]*pin|mach[\\s_-]*pin",+      "exclude": "contact|(^|[^a-z0-9])mc\\d",+      "prefer": "large|lrg",+      "flags": "i",+      "minMarkers": 3,+      "preferMinMarkers": 3+    }+  },+  "normalize": {+    "anchor": { "pattern": "(^|[^a-z0-9])MP[1-9][0-9]*($|[^a-z0-9])|machine\\s*pin|machinepin|mach_pin", "flags": "i" },+    "anchorExclude": { "pattern": "contact|(^|[^a-z0-9])MC[1-9]", "flags": "i" },+    "gold": { "pattern": "(^|[^a-z])m\\s*pin|(^|[^a-z])mach[\\s_-]*pin|machine[\\s_-]*(pin|contact)|(^|[^a-z0-9])M[PC][1-9][0-9]*($|[^a-z0-9])", "flags": "i" }+  },+  "messages": {+    "refusalEnd": "Until this is fixed the registry builds no model for this page.",+    "boardRead": "The board file {file} could not be read: {reason}.",+    "duplicate": "{count} parts are named {name} (at {places}). Designators must be unique.",+    "census": "The board census and the metadata importer disagree on {count} attachments: {parts}. This is a registry defect; report the page.",+    "censusOne": "The board census and the metadata importer disagree on 1 attachment: {parts}. This is a registry defect; report the page.",+    "groups": "{count} multi-pad parts have contact-sized holes and are not machine contacts: {parts}. A jumper or socket connects to the molecule through MC<n> contacts.",+    "groupsOne": "1 multi-pad part has contact-sized holes and is not a machine contact: {parts}. A jumper or socket connects to the molecule through MC<n> contacts.",+    "testPoints": "{count} test points are not imported: {parts}. Test points are read from KiCad boards only; this board is {format}.",+    "testPointsOne": "1 test point is not imported: {parts}. Test points are read from KiCad boards only; this board is {format}.",+    "ignored": "{count} parts have machine-pin-sized holes but are not named or packaged as machine pins, so the importer leaves them out: {parts}.",+    "ignoredOne": "1 part has a machine-pin-sized hole but is not named or packaged as a machine pin, so the importer leaves it out: {parts}.",+    "pinCount": "This board has {count} machine pins ({parts}). A molecule has two or four machine pins, named MP1 to MP4. {fix}",+    "pinCountOne": "This board has 1 machine pin ({parts}). A molecule has two or four machine pins, named MP1 to MP4. {fix}",+    "pinNone": "No machine pins found. A molecule has two or four machine pins: parts named MP1 to MP4 with a machine-pin footprint. {found}",+    "pinNumber": "{count} machine pins are numbered outside MP1 to MP4: {parts}. MP1 to MP4 are the outermost corner machine pins; name any other machine pin MS1, MS2, ... in the board and the schematic and export again.",+    "pinNumberOne": "1 machine pin is numbered outside MP1 to MP4: {parts}. MP1 to MP4 are the outermost corner machine pins; name any other machine pin MS1, MS2, ... in the board and the schematic and export again.",+    "cornerPins": "MP1 to MP4 must be the outermost corner machine pins: {parts}. Name the corner pins MP1 to MP4 and the others MS1, MS2, ... and export again.",+    "extraPins": "{count} extra machine pins are named MS<n> and are not published as machine pins: {parts}.",+    "extraPinsOne": "1 extra machine pin is named MS<n> and is not published as a machine pin: {parts}.",+    "designatorCase": "{count} designators are not in capitals: {parts}. Name machine pins MP<n> and machine contacts MC<n>, in capitals, and export again.",+    "designatorCaseOne": "1 designator is not in capitals: {parts}. Name machine pins MP<n> and machine contacts MC<n>, in capitals, and export again.",+    "pinNameOnContact": "{count} parts on machine-contact holes are named as machine pins: {parts} (package {package}). Machine contacts are named MC<n>: rename them MC1, MC2, ... in the board and the schematic and export again.",+    "pinNameOnContactOne": "1 part on a machine-contact hole is named as a machine pin: {parts} (package {package}). Machine contacts are named MC<n>: rename it to an unused MC<n> in the board and the schematic and export again.",+    "pinsUniform": "The machine pins differ: {groups}. Every machine pin on a molecule has the same size and length. Use one machine-pin part for all of them and export again.",+    "notPins": "{count} parts fit the machine-pin standard only in part and are not treated as machine pins: {parts}. A machine pin is named MP1 to MP4 (MS<n> beyond the four corner pins) and uses a machine-pin footprint ({suggest}) on a {holes} mm hole.",+    "notPinsOne": "1 part fits the machine-pin standard only in part and is not treated as a machine pin: {parts}. A machine pin is named MP1 to MP4 (MS<n> beyond the four corner pins) and uses a machine-pin footprint ({suggest}) on a {holes} mm hole.",+    "notContacts": "{count} parts fit the machine-contact standard only in part and are not treated as machine contacts: {parts}. A machine contact is a one-pad part named MC<n> on a {holes} mm hole.",+    "notContactsOne": "1 part fits the machine-contact standard only in part and is not treated as a machine contact: {parts}. A machine contact is a one-pad part named MC<n> on a {holes} mm hole.",+    "holeSizes": "{count} machine pins and contacts are drilled off the standard sizes: {parts}. Machine pins are drilled {pins} and machine contacts {contacts}, within {tol} mm. Change the drill in the board to the standard size and export again.",+    "holeSizesOne": "1 machine pin or contact is drilled off the standard sizes: {parts}. Machine pins are drilled {pins} and machine contacts {contacts}, within {tol} mm. Change the drill in the board to the standard size and export again.",+    "testPointNames": "{count} test-point footprints are not named TP<n> and are not imported: {parts}.",+    "testPointNamesOne": "1 test-point footprint is not named TP<n> and is not imported: {parts}."+  }+}
scripts/versions_check.pyadded+121
@@ -0,0 +1,121 @@+#!/usr/bin/env python3+"""The versions molecule-publish 3.0.0 needs, checked before its first registry step.++  versions_check.py [--json]++adom-wiki must be 1.8.0 or newer: older CLIs have no `model` verbs and no `--wait` on+`pkg publish`. The Hydrogen handoff is `adom-wiki model import`, so it needs no other+CLI. Each exporter installed in ~/.claude/skills/<name>/ must be at least the release that depends+on molecule-publish ^3.0.0; its version is read from the package.json its install script+copies there, and an installed exporter with no package.json there is older than that+release (the releases before it did not copy one). The messages are the ones the molecule+contract sets (section 8.2).++Exit 1 when adom-wiki is missing or too old (stop: nothing else in the skill works without+it). Update lines for the exporters are printed and exit 0: the publish can go ahead,+and the bundle check finds what an old exporter left in the folder.+Python 3.9 or newer, standard library only. It runs adom-wiki locally and reads no+network.+"""+import json+import re+import subprocess+import sys+from pathlib import Path++CLI_MINIMUM = "1.8.0"+# The release of each package that depends on adom/molecule-publish ^3.0.0.+EXPORTERS = {+    "kicad-export-molecule": "2.0.0",+    "fusion-export-molecule": "2.0.0",+    "altium-export-molecule": "3.0.0",+    "molecule-pipeline": "2.0.0",+}+VERSION = re.compile(r"(\d+)\.(\d+)\.(\d+)")+UNKNOWN_MODEL = "is not an adom-wiki command"+++def parse(text):+    """The first x.y.z in text, as a tuple, or None."""+    m = VERSION.search(text or "")+    return tuple(int(g) for g in m.groups()) if m else None+++def older(found, minimum):+    """True when found (a string or None) is missing or below minimum."""+    have = parse(found) if isinstance(found, str) else found+    return have is None or have < parse(minimum)+++def run(cmd):+    """stdout and stderr of a local command, or None when it cannot start."""+    try:+        p = subprocess.run(cmd, capture_output=True, text=True, timeout=60)+    except (OSError, subprocess.TimeoutExpired):+        return None+    return (p.stdout or "") + (p.stderr or "")+++def cli_message(found):+    return f"This skill needs adom-wiki {CLI_MINIMUM} or newer (found {found or 'none'}). Run: adom-wiki self-update"+++def update_line(name, minimum):+    return f"Update adom/{name} to {minimum}: adom-wiki pkg install adom/{name}"+++def check_cli(runner=run):+    out = runner(["adom-wiki", "--version"])+    if out is None:+        return {"ok": False, "found": None,+                "message": cli_message(None) + " (adom-wiki is not on PATH: install it from the adom/adom-wiki-cli page on wiki.adom.inc)"}+    found = ".".join(map(str, parse(out))) if parse(out) else out.strip()[:40] or None+    if older(out, CLI_MINIMUM):+        return {"ok": False, "found": found, "message": cli_message(found)}+    probe = runner(["adom-wiki", "model", "--help"]) or ""+    if UNKNOWN_MODEL in probe or "UNKNOWN_COMMAND" in probe:+        return {"ok": False, "found": found, "message": cli_message(found)}+    return {"ok": True, "found": found}+++def installed_version(skills, name):+    """(installed, version or None) for ~/.claude/skills/<name>/package.json."""+    folder = Path(skills) / name+    if not folder.is_dir():+        return False, None+    try:+        return True, str(json.loads((folder / "package.json").read_text(encoding="utf-8")).get("version") or "") or None+    except (OSError, ValueError, AttributeError):+        return True, None+++def check_exporters(skills):+    out = []+    for name, minimum in EXPORTERS.items():+        installed, version = installed_version(skills, name)+        if not installed:+            continue+        row = {"name": name, "found": version, "minimum": minimum, "ok": not older(version, minimum)}+        if not row["ok"]:+            row["message"] = update_line(name, minimum)+        out.append(row)+    return out+++def main(argv):+    skills = Path.home() / ".claude" / "skills"+    result = {"cli": check_cli(), "exporters": check_exporters(skills)}+    lines = [r["message"] for r in [result["cli"], *result["exporters"]] if not r["ok"]]+    if "--json" in argv:+        print(json.dumps(result, indent=2))+    else:+        print(f"adom-wiki {result['cli']['found'] or 'none'}")+        for r in result["exporters"]:+            print(f"  {r['name']} {r['found'] or '(no package.json)'}")+    for line in lines:+        print(line, file=sys.stderr)+    return 0 if result["cli"]["ok"] else 1+++if __name__ == "__main__":+    sys.exit(main(sys.argv[1:]))
tests/fixtures/ams1117-3v3_Molecule.PcbDocadded
⋯ 1 unchanged line ⋯
tests/test_bundle_check.pyadded+156
@@ -0,0 +1,156 @@+"""bundle_check.py against the recipe rules of the molecule contract (section 2.2); run with unittest."""+import importlib.util+import json+import tempfile+import unittest+from pathlib import Path++SCRIPT = Path(__file__).resolve().parents[1] / "scripts/bundle_check.py"+spec = importlib.util.spec_from_file_location("bundle_check", SCRIPT)+bc = importlib.util.module_from_spec(spec)+spec.loader.exec_module(bc)+++class BundleCheckTests(unittest.TestCase):+    def setUp(self):+        self.tmp = tempfile.TemporaryDirectory(dir=Path(__file__).resolve().parent)+        self.addCleanup(self.tmp.cleanup)+        self.root = Path(self.tmp.name)++    def files(self, *paths, record=None):+        for p in paths:+            f = self.root / p+            f.parent.mkdir(parents=True, exist_ok=True)+            f.write_bytes(b"x")+        if record is not None:+            (self.root / "export.json").write_text(json.dumps({"files": record}))++    def run_check(self, slug="foo", listing=None):+        return bc.check(self.root, slug, listing)++    def ids(self, out):+        return [p["id"] for p in out["problems"]]++    def test_kicad_bundle_takes_the_board_route(self):+        self.files("Foo.step", "Foo.kicad_pcb", "Foo.kicad_sch", "Foo.kicad_pro", "foo-fab.zip",+                   record=[{"path": "Foo.step", "role": "step"}, {"path": "Foo.kicad_pcb", "role": "board_kicad_pcb"}])+        out = self.run_check()+        self.assertEqual((out["recipe"], out["route"]), ("molecule-board/1", "board"))+        self.assertEqual({s["role"]: s["path"] for s in out["sources"]},+                         {"step": "Foo.step", "board": "Foo.kicad_pcb", "fab": "foo-fab.zip", "export": "export.json"})+        self.assertEqual(out["problems"], [])+        self.assertEqual(out["unread"], ["Foo.kicad_pro", "Foo.kicad_sch"])++    def test_kicad_wins_over_eagle_at_the_root(self):+        self.files("a.step", "a.kicad_pcb", "a.brd")+        out = self.run_check()+        self.assertEqual({s["role"]: s["path"] for s in out["sources"]}["board"], "a.kicad_pcb")++    def test_step_alone_is_refused_for_want_of_a_board_file(self):+        self.files("Foo.step", "README.md")+        out = self.run_check()+        self.assertEqual((out["recipe"], out["route"]), ("molecule-step/1", "step"))+        self.assertEqual(self.ids(out), ["board-file-required"])++    def test_altium_pcbdoc_with_step_takes_the_board_route(self):+        self.files("Foo.step", "Foo.PcbDoc", "foo-fab.zip",+                   record=[{"path": "Foo.step", "role": "step"}, {"path": "Foo.PcbDoc", "role": "board_altium_pcbdoc"}])+        out = self.run_check()+        self.assertEqual((out["recipe"], out["route"]), ("molecule-board/1", "board"))+        self.assertEqual({s["role"]: s["path"] for s in out["sources"]},+                         {"step": "Foo.step", "board": "Foo.PcbDoc", "fab": "foo-fab.zip", "export": "export.json"})+        self.assertEqual(out["problems"], [])++    def test_altium_record_naming_another_board_is_a_problem(self):+        self.files("Foo.step", "Foo.PcbDoc", "foo-fab.zip",+                   record=[{"path": "Foo.step", "role": "step"}, {"path": "Old.PcbDoc", "role": "board_altium_pcbdoc"}])+        self.assertEqual(self.ids(self.run_check()), ["export-record"])++    def test_a_board_without_a_step_gets_no_build(self):+        self.files("Foo.kicad_pcb", "Foo.kicad_sch")+        self.assertEqual(self.ids(self.run_check()), ["no-recipe"])++    def test_two_steps_at_the_root_are_ambiguous_unless_one_is_named_for_the_slug(self):+        self.files("a.step", "b.step", "a.kicad_pcb")+        self.assertEqual(self.ids(self.run_check()), ["ambiguous"])+        self.files("foo.step")+        out = self.run_check()+        self.assertEqual({s["role"]: s["path"] for s in out["sources"]}["step"], "foo.step")++    def test_library_and_preview_folders_are_not_sources(self):+        self.files("Foo.step", "Foo.kicad_pcb", "3d/part.step", "lib/x.step", "render/board.glb", "viewer/3d.glb", "x.3dshapes/y.step")+        out = self.run_check()+        self.assertEqual(out["route"], "board")+        self.assertEqual(out["problems"], [])++    def test_a_circuit_json_takes_the_circuit_route(self):+        self.files("Foo.step", "Foo.kicad_pcb", "viewer/circuit.json")+        self.assertEqual(self.run_check()["route"], "circuit")++    def test_renamed_page_still_finds_its_fab_zip(self):+        self.files("Old.step", "Old.kicad_pcb", "old-name-fab.zip",+                   record=[{"path": "Old.step", "role": "step"}, {"path": "Old.kicad_pcb", "role": "board_kicad_pcb"}])+        out = self.run_check(slug="new-name")+        self.assertEqual({s["role"]: s["path"] for s in out["sources"]}["fab"], "old-name-fab.zip")+        self.assertEqual(out["problems"], [])+        self.assertTrue(any("not named new-name-fab.zip" in n for n in out["notes"]))++    def test_two_fab_zips_at_one_depth_are_ambiguous(self):+        self.files("a.step", "a.kicad_pcb", "x-fab.zip", "y-fab.zip", "export.json")+        self.assertEqual(self.ids(self.run_check()), ["ambiguous"])++    def test_half_a_fabrication_pair_is_a_problem(self):+        self.files("a.step", "a.kicad_pcb", "foo-fab.zip")+        self.assertEqual(self.ids(self.run_check()), ["fab-pair"])++    def test_fabrication_pair_in_two_folders_is_a_problem(self):+        self.files("a.step", "a.kicad_pcb", "fab/foo-fab.zip", "export.json")+        self.assertEqual(self.ids(self.run_check()), ["fab-pair"])++    def test_record_naming_another_board_is_a_problem(self):+        self.files("a.step", "a.kicad_pcb", "foo-fab.zip",+                   record=[{"path": "a.step", "role": "step"}, {"path": "b.kicad_pcb", "role": "board_kicad_pcb"}])+        self.assertEqual(self.ids(self.run_check()), ["export-record"])++    def test_generated_files_in_the_folder_are_problems(self):+        self.files("Foo.step", "Foo.kicad_pcb", "foo.glb", "foo.web.glb", "Foo_footprint.json", "Foo_symbol.json", "foo.pipeline.json")+        out = self.run_check()+        self.assertEqual(self.ids(out), ["generated"])+        self.assertEqual(sorted(out["generated"]), ["Foo_footprint.json", "Foo_symbol.json", "foo.glb", "foo.pipeline.json", "foo.web.glb"])++    def test_footprint_json_is_not_generated_on_the_step_route(self):+        self.files("Foo.step", "Foo_footprint.json")+        out = self.run_check()+        self.assertEqual(out["route"], "step")+        self.assertEqual(out["generated"], [])+        self.assertEqual(self.ids(out), ["board-file-required"])++    def test_files_already_on_the_page_take_part(self):+        self.files("a.step", "a.kicad_pcb")+        listing = self.root.parent / f"{self.root.name}-listing.json"+        listing.write_text(json.dumps({"status": "ok", "data": {"files": [+            {"path": "old.step", "type": "blob"}, {"path": "docs", "type": "tree"}, {"path": "foo.glb", "type": "blob"}]}}))+        self.addCleanup(listing.unlink)+        out = self.run_check(listing=str(listing))+        self.assertEqual(self.ids(out), ["ambiguous"])+        self.assertEqual(out["generated"], [], "a file already on the page is not part of this write")++    def test_kind_other_than_molecule_is_a_problem(self):+        self.files("a.step", "a.kicad_pcb")+        (self.root / "package.json").write_text(json.dumps({"slug": "foo", "type": "component"}))+        self.assertEqual(self.ids(self.run_check()), ["kind"])+        (self.root / "package.json").write_text(json.dumps({"slug": "foo", "type": "component", "kind": "molecule"}))+        self.assertEqual(self.ids(self.run_check()), [])++    def test_pattern_grammar(self):+        m = bc.matcher("**/libraries/**", "s")+        self.assertTrue(m("libraries/a.step") and m("x/libraries/p/q.glb"))+        self.assertTrue(m("libraries"), "recipes.js: both ** may match zero segments")+        self.assertFalse(m("mylibraries/a.step"))+        self.assertTrue(bc.matcher("{slug}.step", "foo")("deep/FOO.STEP"))+        self.assertFalse(bc.matcher("3d/**", "s")("sub/3d/x.step"))+        self.assertFalse(bc.matcher("*.step", "s")("a.step.bak"))+++if __name__ == "__main__":+    unittest.main()
tests/test_component_graph.pyadded+98
@@ -0,0 +1,98 @@+"""component_graph.py reads an Altium .PcbDoc through pcbdoc.py beside it and takes machine+pins and contacts from the pin-name census of pin_names.py beside it; run with unittest.++fixtures/ams1117-3v3_Molecule.PcbDoc is a byte copy of git-wiki's+test/registry/fixtures/altium/ams1117-3v3_Molecule.PcbDoc (sha256 fbb53fd7...0a06546),+the Altium molecule page adom/ams1117-3v3-molecule.+"""+import importlib.util+import json+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"+FIXTURE = Path(__file__).resolve().parent / "fixtures" / "ams1117-3v3_Molecule.PcbDoc"+spec = importlib.util.spec_from_file_location("component_graph", SCRIPTS / "component_graph.py")+cg = importlib.util.module_from_spec(spec)+spec.loader.exec_module(cg)+++class PcbDocBomTests(unittest.TestCase):+    def test_parse_bom_reads_a_pcbdoc_as_its_kicad_board(self):+        rows = {r["ref"]: (r["footprint"], r["value"]) for r in cg.parse_bom(str(FIXTURE))}+        self.assertEqual(rows, {+            "U1": ("SOT229P700X180-4N", "AMS1117-3.3"),+            "C1": ("C0603", "C_10uF_0603"),+            "C2": ("C0805", "C_22uF_0805"),+            "J1": ("MachinePinMediumShort", "MachinePinMediumShort"),+            "J2": ("MachinePinMediumShort", "MachinePinMediumShort"),+            "J3": ("MachinePinMediumShort", "MachinePinMediumShort"),+            "J4": ("MachinePinMediumShort", "MachinePinMediumShort"),+        })++    def test_plan_on_a_pcbdoc(self):+        with tempfile.TemporaryDirectory() as d:+            out = Path(d) / "plan.json"+            run = subprocess.run([sys.executable, "-B", str(SCRIPTS / "component_graph.py"), "plan", str(FIXTURE),+                                  "--offline", "--out", str(out)], capture_output=True, text=True, timeout=60)+            plan = json.loads(out.read_text(encoding="utf-8"))+        self.assertEqual(run.returncode, 1, run.stderr)  # C1 and C2 carry value strings, not MPNs (#142)+        self.assertEqual(plan["board"], FIXTURE.name)+        parts = {p["ref"]: p for p in plan["parts"]}+        self.assertEqual((parts["U1"]["kind"], parts["U1"]["mpn"], parts["U1"]["status"]), ("electrical", "AMS1117-3.3", "create"))+        self.assertEqual({parts[r]["status"] for r in ("C1", "C2")}, {"flagged"})+        self.assertEqual(plan["counts"]["electrical"], 3)++    def test_machine_pins_come_from_the_census_even_when_it_refuses_the_board(self):+        # J1 to J4 sit on machine-pin holes with a machine-pin footprint but are not named+        # MP1 to MP4: the census warns (not-machine-pins) and refuses the board (pin-count),+        # and they are still machine furniture, not electrical parts.+        furniture, refused = cg.census_furniture(str(FIXTURE))+        self.assertEqual(furniture, {"J1", "J2", "J3", "J4"})+        self.assertEqual(refused, ["pin-count"])+        rows = {r["ref"]: r for r in cg.parse_bom(str(FIXTURE))}+        self.assertEqual({ref: cg.classify(r, furniture) for ref, r in rows.items()},+                         {"U1": "electrical", "C1": "electrical", "C2": "electrical",+                          "J1": "furniture", "J2": "furniture", "J3": "furniture", "J4": "furniture"})+        self.assertEqual(cg.classify(rows["J1"]), "electrical", "the designator rule alone misses them")+        with tempfile.TemporaryDirectory() as d:+            out = Path(d) / "plan.json"+            run = subprocess.run([sys.executable, "-B", str(SCRIPTS / "component_graph.py"), "plan", str(FIXTURE),+                                  "--offline", "--out", str(out)], capture_output=True, text=True, timeout=60)+            plan = json.loads(out.read_text(encoding="utf-8"))+        self.assertEqual(plan["furnitureRule"], {"source": "census", "furniture": ["J1", "J2", "J3", "J4"], "refused": ["pin-count"]})+        self.assertEqual(plan["counts"]["furniture"], 4)+        self.assertIn("the census refuses this board (pin-count)", run.stdout)++    def test_designator_rule_when_the_census_cannot_read_the_board(self):+        with tempfile.TemporaryDirectory() as d:+            fp = Path(d) / "pin.kicad_mod"+            fp.write_text('(footprint "MachinePinMediumShort" (property "Reference" "MP1") (property "Value" "x"))\n'+                          '(footprint "SOIC-8" (property "Reference" "U1") (property "Value" "LM358"))\n', encoding="utf-8")+            furniture, reason = cg.census_furniture(str(fp))+            self.assertIsNone(furniture)+            self.assertIn("no board file", reason)+            out = Path(d) / "plan.json"+            run = subprocess.run([sys.executable, "-B", str(SCRIPTS / "component_graph.py"), "plan", str(fp),+                                  "--offline", "--out", str(out)], capture_output=True, text=True, timeout=60)+            plan = json.loads(out.read_text(encoding="utf-8"))+        self.assertEqual(run.returncode, 0, run.stderr)+        self.assertEqual(plan["furnitureRule"]["source"], "designators")+        self.assertIn("by designator only", run.stdout)+        self.assertEqual({p["ref"]: p["kind"] for p in plan["parts"]}, {"MP1": "furniture", "U1": "electrical"})++    def test_an_unreadable_pcbdoc_is_a_usage_error(self):+        with tempfile.TemporaryDirectory() as d:+            board = Path(d) / "x.PcbDoc"+            board.write_bytes(b"not a compound file")+            run = subprocess.run([sys.executable, "-B", str(SCRIPTS / "component_graph.py"), "plan", str(board),+                                  "--offline", "--out", str(Path(d) / "plan.json")], capture_output=True, text=True, timeout=60)+        self.assertEqual(run.returncode, 2)+        self.assertIn("could not be read", run.stderr)+++if __name__ == "__main__":+    unittest.main()
tests/test_contract_copies.pyadded+74
@@ -0,0 +1,74 @@+"""The skill's copies of the molecule contract files match the contract release it names; run with unittest."""+import hashlib+import importlib.util+import json+import subprocess+import sys+import tempfile+import unittest+from pathlib import Path++SCRIPTS = Path(__file__).resolve().parents[1] / "scripts"+++def sha256(path):+    return hashlib.sha256(path.read_bytes()).hexdigest()+++def load(name):+    spec = importlib.util.spec_from_file_location(name, SCRIPTS / f"{name}.py")+    module = importlib.util.module_from_spec(spec)+    spec.loader.exec_module(module)+    return module+++class ContractCopyTests(unittest.TestCase):+    def setUp(self):+        self.contract = json.loads((SCRIPTS / "contract.json").read_text(encoding="utf-8"))+        self.versions = self.contract["versions"]++    def test_contract_is_the_molecule_contract(self):+        self.assertEqual(self.contract["schema"], "adom.molecule-contract/1")+        self.assertEqual([r["name"] for r in self.contract["recipes"]], ["molecule-circuit", "molecule-board", "molecule-step"])+        self.assertEqual(self.versions["publisherMinimum"], "3.0.0")+        self.assertEqual(self.versions["cliMinimum"], "1.8.0")++    def test_pin_names_is_the_programs_names_py(self):+        self.assertEqual(sha256(SCRIPTS / "pin_names.py"), self.versions["namesPy"])++    def test_pins_json_is_the_contracts(self):+        self.assertEqual(sha256(SCRIPTS / "pins.json"), self.versions["pins"])++    def test_fab_bundle_is_the_one_the_program_vendors(self):+        self.assertEqual(sha256(SCRIPTS / "fab_bundle.py"), self.versions["fabBundle"]["sha256"])++    def test_self_check_reports_no_drift(self):+        run = subprocess.run([sys.executable, "-B", str(SCRIPTS / "pin_names.py"), "--self-check", str(SCRIPTS / "contract.json")],+                             capture_output=True, text=True, timeout=60)+        self.assertEqual(run.returncode, 0, run.stderr)+        self.assertEqual(json.loads(run.stdout), {"namesPy": self.versions["namesPy"], "pins": self.versions["pins"]})+        self.assertNotIn("warning", run.stderr)++    def test_pin_names_reads_altium_boards_through_pcbdoc_beside_it(self):+        self.assertTrue((SCRIPTS / "pcbdoc.py").is_file())+        with tempfile.TemporaryDirectory() as d:+            board = Path(d) / "x.PcbDoc"+            board.write_bytes(b"not a compound file")+            run = subprocess.run([sys.executable, "-B", str(SCRIPTS / "pin_names.py"), "check", str(board), "--json"],+                                 capture_output=True, text=True, timeout=60)+        self.assertEqual(run.returncode, 1, run.stderr)+        checks = json.loads(run.stdout)["checks"]+        self.assertEqual([c["id"] for c in checks], ["board-read"])+        self.assertIn("not an OLE2 compound file", checks[0]["detail"])++    def test_component_graph_reads_the_furniture_rule_from_pins_json(self):+        graph = load("component_graph")+        near = json.loads((SCRIPTS / "pins.json").read_text(encoding="utf-8"))["designators"]["nearMiss"]+        self.assertEqual(graph.FURNITURE_REFS.pattern, near["pattern"])+        self.assertEqual(graph.classify({"ref": "mp3", "footprint": "MachinePinMediumShort"}), "furniture")+        self.assertEqual(graph.classify({"ref": "MC12", "footprint": "MachineContactMedium"}), "furniture")+        self.assertEqual(graph.classify({"ref": "U1", "footprint": "SOIC-8"}), "electrical")+++if __name__ == "__main__":+    unittest.main()
tests/test_versions_check.pyadded+82
@@ -0,0 +1,82 @@+"""versions_check.py: the 8.2 messages of the molecule contract; run with unittest."""+import contextlib+import importlib.util+import io+import json+import subprocess+import tempfile+import unittest+from pathlib import Path+from unittest import mock++SCRIPT = Path(__file__).resolve().parents[1] / "scripts/versions_check.py"+spec = importlib.util.spec_from_file_location("versions_check", SCRIPT)+vc = importlib.util.module_from_spec(spec)+spec.loader.exec_module(vc)+++def runner(outputs):+    return lambda cmd: outputs.get(" ".join(cmd))+++class VersionsCheckTests(unittest.TestCase):+    def test_cli_older_than_1_8_0_gets_the_contract_message(self):+        r = vc.check_cli(runner({"adom-wiki --version": "adom-wiki 1.7.72\n"}))+        self.assertFalse(r["ok"])+        self.assertEqual(r["message"], "This skill needs adom-wiki 1.8.0 or newer (found 1.7.72). Run: adom-wiki self-update")++    def test_cli_1_8_0_with_model_verbs_passes(self):+        r = vc.check_cli(runner({"adom-wiki --version": "adom-wiki 1.8.0", "adom-wiki model --help": "model: builds history plan"}))+        self.assertTrue(r["ok"])++    def test_unknown_command_model_counts_as_outdated(self):+        r = vc.check_cli(runner({"adom-wiki --version": "adom-wiki 1.8.0",+                                 "adom-wiki model --help": "error: 'model' is not an adom-wiki command"}))+        self.assertFalse(r["ok"])+        self.assertIn("found 1.8.0", r["message"])++    def test_missing_cli_stops(self):+        r = vc.check_cli(runner({}))+        self.assertFalse(r["ok"])+        self.assertTrue(r["message"].startswith("This skill needs adom-wiki 1.8.0 or newer (found none). Run: adom-wiki self-update"))++    def test_runs_only_adom_wiki(self):+        seen = []++        def fake_run(cmd, **kwargs):+            seen.append(cmd[0])+            out = "adom-wiki 1.8.0" if cmd[1:] == ["--version"] else "model: builds history plan"+            return subprocess.CompletedProcess(cmd, 0, out, "")++        with tempfile.TemporaryDirectory() as d, \+                mock.patch.object(vc.subprocess, "run", fake_run), \+                mock.patch.object(vc.Path, "home", return_value=Path(d)), \+                contextlib.redirect_stdout(io.StringIO()) as out:+            self.assertEqual(vc.main(["--json"]), 0)+        self.assertEqual(set(seen), {"adom-wiki"})+        self.assertEqual(set(json.loads(out.getvalue())), {"cli", "exporters"})++    def test_installed_exporters_older_than_their_release(self):+        with tempfile.TemporaryDirectory() as d:+            skills = Path(d)+            (skills / "kicad-export-molecule").mkdir()  # 1.2.0 installs no package.json+            (skills / "fusion-export-molecule").mkdir()+            (skills / "fusion-export-molecule" / "package.json").write_text(json.dumps({"version": "2.0.0"}))+            (skills / "altium-export-molecule").mkdir()+            (skills / "altium-export-molecule" / "package.json").write_text(json.dumps({"version": "2.4.0"}))+            rows = {r["name"]: r for r in vc.check_exporters(skills)}+        self.assertEqual(set(rows), {"kicad-export-molecule", "fusion-export-molecule", "altium-export-molecule"})+        self.assertEqual(rows["kicad-export-molecule"]["message"],+                         "Update adom/kicad-export-molecule to 2.0.0: adom-wiki pkg install adom/kicad-export-molecule")+        self.assertTrue(rows["fusion-export-molecule"]["ok"])+        self.assertEqual(rows["altium-export-molecule"]["message"],+                         "Update adom/altium-export-molecule to 3.0.0: adom-wiki pkg install adom/altium-export-molecule")++    def test_versions_compare_numerically(self):+        self.assertFalse(vc.older("1.10.0", "1.8.0"))+        self.assertTrue(vc.older("1.7.99", "1.8.0"))+        self.assertTrue(vc.older(None, "1.8.0"))+++if __name__ == "__main__":+    unittest.main()