by adom
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.
← Commit history
Publish 3.1.0
9 files changed
+804−134
SKILL.md+137−41@@ -16,8 +16,8 @@ EDA export skill THIS SKILL adom- (kicad/fusion/altium) -> check -> publish private -> wait for build -> hero -> public -> Hydrogen ``` -**Sources only.** On a molecule page the registry builds (program-`molecule/8`), the registry writes these files, and a write that adds or+**Sources only.** On a molecule page the registry builds, the registry+writes these files, and a write that adds or changes one of them is refused with `REGISTRY_MODEL_FILE_REFUSED`, nothing written: @@ -28,6 +28,7 @@ written: | footprint | `<slug>_footprint.json` | circuit, board | | symbol | `<slug>_symbol.json` | circuit, board | | report | `<slug>.pipeline.json` | all |+| cad (a STEP for CAD apps) | `<slug>.cad.step` | board, and circuit given a STEP | The refusal also covers the root names `<slug>.render.glb` and `<slug>.metadata.json`, and, on a route with footprint and symbol slots, any@@ -96,8 +97,8 @@ 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. -**The roles** (recipes tried in this order: `molecule-circuit`,-`molecule-board`, `molecule-step`):+**The roles** (recipes tried in this order: `molecule-circuit-step`,+`molecule-circuit`, `molecule-board`, `molecule-step`): | Role | Patterns, first hit wins | Excluded | |---|---|---|@@ -107,12 +108,16 @@ matches nothing rules out only its own recipe. | `fab` (optional) | `{slug}-fab.zip`, `*-fab.zip` | none | | `export` (optional) | `export.json` | `render/**`, `viewer/**` | +`molecule-circuit-step` is `molecule-circuit` with a `step` role of its own+(`eda/*.step`, `eda/*.stp`, `{slug}.step`, `{slug}.stp`, `3d.step`, nothing+excluded); a circuit page that has one also gets `cad`.+ **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 |+| KiCad, Fusion/EAGLE | `step`, `board` (`.kicad_pcb` or `.brd`), `fab` and `export` | board (`molecule-board/1`) | model, web, footprint, symbol, report, cad |+| Altium | `step`, `board` (`.PcbDoc`), `fab` and `export` | board (`molecule-board/1`) | model, web, footprint, symbol, report, cad | 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@@ -198,7 +203,8 @@ python3 scripts/bundle_3d.py check <folder>/<board>.kicad_pcb --page <owner>/<sl 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+ `export-record`, `export-stackup` (a stackup the build's fabrication check+ refuses, item 3), `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.@@ -228,9 +234,26 @@ python3 scripts/bundle_3d.py check <folder>/<board>.kicad_pcb --page <owner>/<sl 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.+ 1.2.0, the one `molecule/11` builds with). 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. It also+ checks `export.json`'s `stackup` (docs/fabrication.md):+ - refused (exit 1): a shape no build can read, such as `"maskColor":+ "green"` where `{"top": "green", "bottom": "green"}` belongs, a+ thickness or layer count that is not a positive number, or a misspelled+ key. The error gives the shape to write. Write the record again with+ `fab_bundle.py create` and a corrected `--stackup` file. (Builds before+ `molecule/11` failed such a record later, in `normalize`, with+ `'str' object has no attribute 'get'`.)+ - warned (exit 0, a `warnings` list in its output): a colour or finish+ name the board look does not know, or a key no build reads. Names match+ exactly, in any case. The warning says which known name is closest+ ("Did you mean ...?") and lists the names; the build draws the default+ there and warns `stackup-values`. Fix a typo to the name it suggests,+ or give a colour as `#rrggbb` for the exact colour. A finish KiCad+ names that the board look has no colour for (Immersion nickel, User+ defined) is right as written: it stays in the record. Show each warning+ to the user. 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@@ -273,7 +296,8 @@ and `README.md`: ``` Nothing generated goes in the folder: no `<slug>.glb`, `<slug>.web.glb`,-`*_footprint.json`, `*_symbol.json` or `<slug>.pipeline.json`, and no+`*_footprint.json`, `*_symbol.json`, `<slug>.pipeline.json` or+`<slug>.cad.step`, 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.@@ -289,6 +313,7 @@ publishing, and never mint a page keyed on a value string. ```json { "slug": "<slug>", "version": "1.0.0", "type": "component", "kind": "molecule",+ "org": "<org>", "description": "<at least 20 characters>", "tags": ["molecule", "..."], "component": { "mpn": "<name>", "manufacturer": "", "category": "other" }, "dependencies": {}@@ -297,13 +322,21 @@ publishing, and never mint a page keyed on a value string. - `"kind": "molecule"` is required: the recipes, the refusal and the build key on the page's kind after the write.+- `org` is the org that owns the page (`adom` for an Adom page). `pkg+ publish` publishes to `<org>/<slug>`; without `org` it publishes to+ `<you>/<slug>`, which is a different page (#21). Leave it out only for a+ page in your own namespace. A person's page you hold a write grant on has+ no manifest key: pass `--owner <handle>` to `pkg publish` (Stage 3.2). - 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 `hero` block: the hero is set in Stage 4 from the built model, which+ does not exist before the first build. A private publish of a molecule+ page needs no hero (the publish answers with the hint+ `HARDWARE_HERO_PENDING`); a public hardware page needs a 16:10 PNG hero,+ which Stage 4 sets before Stage 5. A wiki older than that rule refuses+ the private publish with `HERO_REQUIRED` (Stage 3.3). - No `visibility` field: a value there would override the page's visibility on every publish. - Bump `version` on every publish.@@ -316,14 +349,48 @@ 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+# 1. plan: parse the BOM and the schematic's MPNs, classify, probe the global namespace by MPN+python3 scripts/component_graph.py plan <folder>/<board.kicad_pcb|.brd|.PcbDoc|.fbrd> \+ [--sch <folder>/<root .kicad_sch or .sch>] --out <work>/component-plan.json+# 2. build or reuse component pages per the plan (Stage 2.6), wire deps on the board;+# mark parts whose page is on its way as pending (below) # 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 ``` +**MPNs come from the board and its schematic.** `plan` reads each part's+MPN from the board file and from the schematic, matched by designator: by+default the schematic the EDA keeps beside the board (`<stem>.kicad_sch` for+a `.kicad_pcb`, `<stem>.sch` for an EAGLE `.brd`), or the one `--sch` names.+A KiCad schematic's sheets are followed, and a sheet placed twice gives each+placement its own designators. The plan records each part's `mpnSource`+(`board`, `schematic` or `board+schematic`) and prints how many MPNs only the+schematic had: those boards were not updated from the schematic after the+MPN fields were added. A board and schematic that disagree on a part's MPN+flag it: update the PCB from the schematic (or fix the schematic) and plan+again. `--sch` reads only KiCad `.kicad_sch` and EAGLE `.sch`, and refuses a+file it cannot read (exit 2), sheets included; an Altium or Fusion board's+MPNs come from the board alone.++**Pending parts.** A part whose component page is on its way (held for a+footprint review, requested) has no page to depend on yet. Mark it, with+what it waits for and where that is tracked:++```bash+python3 scripts/component_graph.py pend <work>/component-plan.json <REF or MPN>... \+ --why "page held for footprint review" --ref "part request 1240"+```++An MPN marks every part with that MPN. The gate then passes with a warning+that names each pending part, its reason and its reference, and fails again+once its page exists (`--resolve` probes it by MPN) while the board still+does not depend on it. A part with no MPN cannot be pending; neither can a+part whose page exists. A new `plan` of the same board keeps the marks while+each part keeps its designator and MPN. Never create a second, unreviewed+page to get past the gate, and never use `--allow-no-components` for a board+that has components. Report every pending part to the user.+ 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):@@ -336,8 +403,8 @@ pages directly). The gate enforces two separate properties (#17): 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+code or value string (#142), a stale plan from a different board, and a+`--plan` that does not exist. 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@@ -399,9 +466,9 @@ it), and report created, reused and flagged parts: - **adom-lbr JSON**: `adom-lbr import-kicad --sym <f> --fp <f> --mpn <MPN>`; also ship the Fusion `.lbr` from `adom-lbr generate`. - **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.+ designer's local library, mark the part pending (Stage 2.5, `pend`, with+ `--why` naming 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).@@ -438,11 +505,21 @@ source and `export.json` together, and the registry queues one build from it. ```bash # first publish of a new page-adom-wiki --json pkg publish --private --wait --timeout 1200 [--org <org>]+adom-wiki --json pkg publish --private --wait --timeout 1200 # 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+adom-wiki --json pkg publish --wait --timeout 1200 [--owner <handle>] ``` +The publish lands on `<org>/<slug>` when `package.json` names `org`+(Stage 2), on `<handle>/<slug>` with `--owner <handle>` (another person's+page you hold a write grant on), and otherwise on your own `<you>/<slug>`.+For an update it must be the page 3.1 read: an org's page needs `org` in+`package.json`; without it the publish creates a new page in your own+namespace. A wiki with the namespace check refuses that with+`NAMESPACE_CONFLICT` (3.3) when a page with that slug that you can see exists+under another owner, and a CLI with the matching check asks the wiki before+it uploads anything. Do not count on either: check the target yourself.+ 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.@@ -460,7 +537,17 @@ The server's code is `data.response.code`: 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`.+ public with no model. Publish with `--private`. On an update this means+ the publish was about to create a new page: check where it lands (3.2).+- `NAMESPACE_CONFLICT`: the publish would create `<you>/<slug>` while+ `<owner>/<slug>` exists (`data.response.data` names it). Point the publish+ at that page (`org` in `package.json`, or `--owner <handle>`) and publish+ again. Never `--allow-fork` a molecule page.+- `HERO_REQUIRED` on a private publish of a molecule page: the wiki does not+ yet let private hardware pages publish without a hero. Declare a 16:10+ PNG at least 1600 px wide as `"hero": {"path": "<file>"}` in+ `package.json` (a render of the board from the EDA will do), ship the+ file in the folder, and publish again; Stage 4 replaces it. - Any other code: show the error and its hints, and stop. **3.4 The write landed** (`status: "ok"`). `data.model` is the build's@@ -552,15 +639,23 @@ 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.+from a pre-rendered `render/` folder, and the page's own Schematics section+shows `render/sheet-*.svg` by `render/manifest.json`; without the folder 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>+adom-wiki pkg install adom/adom-project-manager # once per machine; installs adom-project-manager+adom-project-manager --render-board <owner>/<slug> ``` +APM 0.14.0 renamed the command back from `adom-nucleus`, which its install+removes. It renders through the hosted KiCad service and pushes with+`adom-wiki repo push` under the bare slug, so the push fails (`upload+FAILED`, exit 1) when another owner has a page with the same slug; report+that on adom/adom-project-manager rather than pushing `render/` by hand.+ 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@@ -568,7 +663,8 @@ 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);+ (`manifest.json`, `pcb.svg`, `sheet-NNN.svg`, and `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@@ -580,14 +676,13 @@ Verify after the run: `render/manifest.json` is on the page, parses, and 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-`` 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.+**The README.** The page shows the schematic sheets itself (its Schematics+section, adom/wiki#72), so the README embeds no sheets; remove a+`## Schematics` section an older run added. Nothing else on the page shows+`render/pcb.svg`: the README carries a `## Board layout` section with+``, added once. 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@@ -652,8 +747,9 @@ Stages 2.5, 2.6 and 6 apply as for molecules. (`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+- [ ] every referenced component page exists (Stage 2.6), or its parts are+ pending in the plan (`pend`, with why and a reference) and the user+ was told - [ ] 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)
docs/fabrication.md+40−7@@ -33,10 +33,41 @@ unreleased) drafts a bridge-side writer for the same schema. - 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`. 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.+- `stackup`: what is known of the board's stackup, every key optional.+ Unknown values stay null or absent; never turn a viewer's default into+ claimed design data. The shape:++ ```json+ {"thicknessMm": 1.6, "copperLayers": 2,+ "maskColor": {"top": "green", "bottom": "green"},+ "silkColor": {"top": "white", "bottom": "white"},+ "finish": "ENIG"}+ ```++ `thicknessMm` is a positive number, `copperLayers` a positive whole+ number. `maskColor` and `silkColor` are per side, each a colour name or+ `#rrggbb` (`#rrggbbaa` too); the British spelling (`maskColour`,+ `silkColour`) is accepted, not both. `finish` is text. `null`, an empty+ value, `"None"` (what KiCad writes when no finish was chosen) and `"Not+ specified"` state nothing.++ `fab_bundle.py` refuses (in `create` before it writes anything, in `check`,+ and in the build's `fab-bundle` check) a shape no reader can take: a+ colour given as one string, a side other than `top` or `bottom`, a number+ given as text, a misspelled key such as `maskcolor`, a malformed+ `#rrggbb`. It warns, and the build draws its default there and warns+ `stackup-values`, about a well-formed value the board look has no colour+ or finish for, and about a key no build reads. The board look draws these+ mask colours: green, light green, saturated green, red, light red,+ red/orange, blue, light blue 1, light blue 2, green/blue, black, matte+ black, white, yellow, purple, light purple; silk colours white, black,+ yellow, blue, red, grey (KiCad's names, any case); and the finishes ENIG+ (also ENEPIG, hard gold, immersion gold), HASL (HAL SnPb, HAL lead-free,+ HASL lead-free, lead-free HASL, LF HASL), OSP (HT_OSP), immersion silver+ and immersion tin. Names match exactly, in any case; a near miss gets the+ closest known name in the warning ("Did you mean ...?"). KiCad's Immersion+ nickel and User defined are finishes the board look has no colour for:+ the warning says so, and the record keeps them. - `gerbers.included` is true. `drill.plating` says `split`, `mixed`, `plated` (no unplated drill file) or `unplated`. A drill file's role comes from its X2 `FileFunction` when it has one, else from whole words of its@@ -60,7 +91,8 @@ python3 scripts/fab_bundle.py check /path/to/bundle --slug my-board Use the versions actually installed, not the example values. `--fab` also accepts an EDA-produced zip. `--stackup` is optional; pass the data the EDA-provides. Repeat `--source` for every exported source, including every+provides, in the shape above. Its output lists `warnings` when the stackup+holds a value the board look does not draw. Repeat `--source` for every exported source, including every schematic sheet. The helper writes the canonical zip name without changing its members' bytes, with one exception: a Gerber job file loses its `Owner` field, where Fusion writes the EDA account's name and email, because the@@ -93,8 +125,9 @@ The registry's molecule recipes read the pair on the board route - 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+- The build runs fab_bundle, the same file as `scripts/fab_bundle.py`+ (1.2.0 from `molecule/11`; 1.1.0 before, without the stackup check), 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
package.json+1−1@@ -1,6 +1,6 @@ { "slug": "molecule-publish",- "version": "3.0.0",+ "version": "3.1.0", "type": "skill", "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": [
page.json+1−1@@ -1,6 +1,6 @@ { "slug": "molecule-publish",- "version": "3.0.0",+ "version": "3.1.0", "type": "skill", "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": [
scripts/bundle_check.py+23−4@@ -25,10 +25,12 @@ Problems (exit 1): no-recipe, ambiguous, overflow (no build would run); board-fi 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+other than the one the build selects); export-stackup (export.json's stackup has a shape the+build's fab-bundle check refuses, by fab_bundle.py beside this script; a value the board look+does not draw is a note); 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 importlib.util import json import re import sys@@ -40,6 +42,17 @@ SKIP_FILES = {".adomignore", ".pkgignore", ".DS_Store", "Thumbs.db"} IGNORE_FILES = (".gitignore", ".adomignore", ".pkgignore") +def _fab_bundle():+ """fab_bundle.py beside this script: the export record's rules, the ones the build runs."""+ spec = importlib.util.spec_from_file_location("fab_bundle", HERE / "fab_bundle.py")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++stackup_problems = _fab_bundle().stackup_problems++ 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] == "**")]@@ -188,9 +201,15 @@ def check(root, slug, listing=None, contract=None): elif exp and exp in mine: base = PurePosixPath(exp).parent try:- files = json.loads((root / exp).read_text(encoding="utf-8")).get("files") or []+ record = json.loads((root / exp).read_text(encoding="utf-8"))+ files = record.get("files") or [] except (ValueError, OSError, AttributeError):- files = None+ record, files = None, None+ if isinstance(record, dict):+ errors, warnings = stackup_problems(record.get("stackup"))+ for e in errors:+ problems.append({"id": "export-stackup", "detail": f"{e}. The build refuses it (fab-bundle); write the record again with fab_bundle.py create"})+ notes.extend(warnings) if not isinstance(files, list): problems.append({"id": "export-record", "detail": f"{exp} has no files list; export again"}) else:
scripts/component_graph.py+364−59@@ -18,16 +18,23 @@ 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 (.kicad_pcb, .brd, .PcbDoc or .fbrd)- -> classify -> probe the wiki- namespace -> emit plan.json + a table- of reused / create / FLAGGED parts+ plan <board> [--sch S] parse BOM (.kicad_pcb, .brd, .PcbDoc or .fbrd)+ and the MPNs of its schematic -> classify+ -> probe the wiki namespace -> emit+ plan.json + a table of reused / create /+ pending / FLAGGED parts+ pend <plan.json> <REF|MPN>... --why W --ref R+ mark parts whose component page is on its+ way (in review, requested) as pending gate <package.json> [--plan P] HARD GATE, non-zero exit on failure: - electrical BOM rows but no deps - electrical parts not covered by any dep- (DECLARED check, #17)+ (DECLARED check, #17); a pending part+ warns instead, naming why and its ref - a declared dep that resolves to no page (RESOLVED check, #17; needs --resolve)+ - a pending part whose page exists now+ and is still not a dependency - any slug keyed on an LCSC code or a value string instead of an MPN (#142) opt out ONLY with --allow-no-components@@ -42,7 +49,7 @@ import re import subprocess import sys import tempfile-import time+import xml.etree.ElementTree as ET from pathlib import Path # ── identity rules (#142: key by MPN, never by value or distributor code) ──@@ -106,55 +113,205 @@ def read_fbrd(board_path): return mod.read_fbrd(board_path) +# Field names a part's MPN and distributor code are written under, compared without case.+MPN_FIELDS = ("mpn", "manufacturer part number", "manufacturer_part_number", "mfr#")+LCSC_FIELDS = ("lcsc", "lcsc part", "jlcpcb")+++def field(props, names):+ """The first non-empty value among `names` in a {name: value} map, names without case."""+ low = {k.strip().lower(): v for k, v in props.items()}+ return next((low[n].strip() for n in names if (low.get(n) or "").strip()), "")+++def sexpr(text):+ """A KiCad S-expression file as nested lists of atoms (strings unquoted)."""+ tokens = re.finditer(r'\(|\)|"((?:[^"\\]|\\.)*)"|[^\s()"]+', text)+ stack, cur = [], []+ for t in tokens:+ tok = t.group(0)+ if tok == "(":+ stack.append(cur)+ cur = []+ elif tok == ")":+ if not stack:+ raise ValueError("unbalanced parentheses")+ done, cur = cur, stack.pop()+ cur.append(done)+ elif t.group(1) is not None:+ cur.append(re.sub(r'\\(.)', r'\1', t.group(1)))+ else:+ cur.append(tok)+ if stack:+ raise ValueError("unbalanced parentheses")+ return cur+++def kids(node, head):+ return [c for c in node if isinstance(c, list) and c and c[0] == head]+++def props_of(node):+ return {p[1]: p[2] for p in kids(node, "property") if len(p) >= 3 and isinstance(p[1], str) and isinstance(p[2], str)}+++def eagle_attrs(el):+ """{name: value} of an EAGLE <element> or <part>: its own attributes, then its <attribute> children."""+ out = {k: v for k, v in el.attrib.items()}+ for a in el.findall("attribute"):+ if a.get("name") and a.get("value") is not None:+ out[a.get("name")] = a.get("value")+ return out++ def parse_bom(board_path): """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."""- kicad = board_path.lower().endswith((".kicad_pcb", ".kicad_mod", ".pcbdoc"))- if board_path.lower().endswith(".pcbdoc"):+ .kicad_pcb that pcbdoc.py writes from it), an EAGLE .brd (XML elements and+ their attributes) or a Fusion .fbrd (the EAGLE board it holds).+ Returns [{ref, value, footprint, lcsc, mpn, dnp}] with whatever the file carries.+ Raises ValueError for a board it cannot read."""+ low = board_path.lower()+ if low.endswith(".pcbdoc"): txt = read_pcbdoc(board_path)- elif board_path.lower().endswith(".fbrd"):+ elif low.endswith(".fbrd"): txt = read_fbrd(board_path) else:- txt = open(board_path, encoding="utf-8", errors="replace").read()+ txt = Path(board_path).read_text(encoding="utf-8", errors="replace") rows = []- if kicad:- for m in re.finditer(r'\(footprint "([^"]+)"', txt):- start = m.start()- depth, i = 0, start- while i < len(txt):- if txt[i] == '(':- depth += 1- elif txt[i] == ')':- depth -= 1- if depth == 0:- break- i += 1- blk = txt[start:i + 1]- def prop(name):- mm = re.search(r'\(property "%s" "([^"]*)"' % name, blk)- return mm.group(1) if mm else ""+ if low.endswith((".kicad_pcb", ".kicad_mod", ".pcbdoc")):+ try:+ forms = [f for f in sexpr(txt) if isinstance(f, list) and f]+ except ValueError as e:+ raise ValueError(f"not a readable KiCad board: {e}")+ footprints = [f for f in forms if f[0] == "footprint"] + [fp for f in forms if f[0] == "kicad_pcb" for fp in kids(f, "footprint")]+ for fp in footprints:+ props = props_of(fp)+ dnp_prop = field(props, ("dnp",)).lower() rows.append({- "ref": prop("Reference"),- "value": prop("Value"),- "footprint": m.group(1),- "lcsc": prop("LCSC") or prop("LCSC Part") or prop("JLCPCB"),- "mpn": prop("MPN") or prop("Manufacturer Part Number") or prop("MFR#"),- "dnp": "(dnp" in blk or '"dnp"' in blk,+ "ref": props.get("Reference", ""),+ "value": props.get("Value", ""),+ "footprint": fp[1] if len(fp) > 1 and isinstance(fp[1], str) else "",+ "lcsc": field(props, LCSC_FIELDS),+ "mpn": field(props, MPN_FIELDS),+ "dnp": (any(a == "dnp" for attr in kids(fp, "attr") for a in attr[1:])+ or any(d[1:2] == ["yes"] for d in kids(fp, "dnp"))+ or dnp_prop not in ("", "no", "false", "0")), })- else: # EAGLE .brd XML- for m in re.finditer(r'<element\s+([^>]*?)/?>', txt):- attrs = dict(re.findall(r'(\w+)="([^"]*)"', m.group(1)))+ else: # EAGLE .brd XML (a Fusion .fbrd holds the same)+ try:+ root = ET.fromstring(txt.encode("utf-8"))+ except ET.ParseError as e:+ raise ValueError(f"not readable EAGLE XML: {e}")+ for el in root.iter("element"):+ attrs = eagle_attrs(el) rows.append({ "ref": attrs.get("name", ""), "value": attrs.get("value", ""), "footprint": attrs.get("package", ""),- "lcsc": "", "mpn": "", "dnp": False,+ "lcsc": field(attrs, LCSC_FIELDS), "mpn": field(attrs, MPN_FIELDS), "dnp": False, }) return [r for r in rows if r["ref"]] +def schematic_mpns(sch_path):+ """{designator: MPN} from a schematic and every sheet under it: a KiCad .kicad_sch+ (hierarchical sheets followed by their file names, each placed instance by the+ reference KiCad gives it there) or an EAGLE .sch. Symbols whose reference starts+ with '#' (power, flags) are left out. A designator whose units carry different+ MPNs raises ValueError, as does a file that cannot be read."""+ low = sch_path.lower()+ found = {}++ def put(ref, mpn, where):+ if not ref or ref.startswith("#") or not mpn:+ return+ if found.get(ref, (mpn,))[0] != mpn:+ raise ValueError(f"{ref} has MPN {found[ref][0]!r} in {found[ref][1]} and {mpn!r} in {where}")+ found[ref] = (mpn, where)++ if low.endswith(".sch"):+ try:+ root = ET.parse(sch_path).getroot()+ except (ET.ParseError, OSError) as e:+ raise ValueError(f"{sch_path} is not a readable EAGLE schematic: {e}")+ for part in root.iter("part"):+ attrs = eagle_attrs(part)+ put(attrs.get("name", ""), field(attrs, MPN_FIELDS), os.path.basename(sch_path))+ return {r: m for r, (m, _) in found.items()}+ if not low.endswith(".kicad_sch"):+ raise ValueError(f"--sch reads a KiCad .kicad_sch or an EAGLE .sch; {os.path.basename(sch_path)} is neither")++ base = os.path.dirname(os.path.abspath(sch_path))+ root_tree = None+ visited = set()++ def walk(path):+ real = os.path.abspath(path)+ if real in visited: # a sheet placed twice is read once; its instances list every reference+ return+ visited.add(real)+ try:+ text = Path(real).read_text(encoding="utf-8", errors="replace")+ tree = sexpr(text)[0]+ except (OSError, ValueError, IndexError) as e:+ raise ValueError(f"{os.path.relpath(real, base)} is not a readable KiCad schematic: {e}")+ if not tree or tree[0] != "kicad_sch":+ raise ValueError(f"{os.path.relpath(real, base)} is not a KiCad schematic")+ nonlocal root_tree+ if root_tree is None:+ root_tree = tree+ where = os.path.relpath(real, base)+ for sym in kids(tree, "symbol"): # placed symbols; lib_symbols holds the definitions+ props = props_of(sym)+ mpn = field(props, MPN_FIELDS)+ refs = [r[1] for inst in kids(sym, "instances") for proj in kids(inst, "project")+ for p in kids(proj, "path") for r in kids(p, "reference") if len(r) > 1]+ uuid = next((u[1] for u in kids(sym, "uuid") if len(u) > 1), None)+ if not refs and uuid and root_tree is not None: # KiCad 6: the root's symbol_instances+ refs = [r[1] for si in kids(root_tree, "symbol_instances") for p in kids(si, "path")+ if isinstance(p[1], str) and p[1].endswith("/" + uuid) for r in kids(p, "reference") if len(r) > 1]+ for ref in refs or [props.get("Reference", "")]:+ put(ref, mpn, where)+ for sheet in kids(tree, "sheet"):+ props = props_of(sheet)+ name = props.get("Sheetfile") or props.get("Sheet file")+ if not name:+ raise ValueError(f"a sheet in {where} names no file")+ walk(os.path.join(os.path.dirname(real), name))++ walk(sch_path)+ return {r: m for r, (m, _) in found.items()}+++def own_schematic(board_path):+ """The schematic beside a board that its EDA keeps with it: <stem>.kicad_sch for a+ .kicad_pcb, <stem>.sch for an EAGLE .brd; None when there is none."""+ stem, ext = os.path.splitext(board_path)+ sch = {".kicad_pcb": ".kicad_sch", ".brd": ".sch"}.get(ext.lower())+ return stem + sch if sch and os.path.isfile(stem + sch) else None+++def merge_mpns(rows, sch, sch_name):+ """Each row's MPN and where it came from (mpnSource: board, schematic, both, or None),+ the schematic's MPN by designator. A board and schematic that disagree on a part's MPN+ leave it with no MPN and a `conflict` naming both. Returns the designators the+ schematic gives an MPN that the board has no footprint for."""+ by_ref = {r["ref"]: r for r in rows}+ for r in rows:+ b, s = r.get("mpn") or "", sch.get(r["ref"], "")+ if b and s and b.lower() != s.lower():+ r["mpn"], r["mpnSource"] = "", None+ r["conflict"] = (f"the board says {b!r} and {sch_name} says {s!r}: update the PCB from the "+ "schematic (or fix the schematic), then plan again")+ elif b and s:+ r["mpnSource"] = "board+schematic"+ elif s:+ r["mpn"], r["mpnSource"] = s, "schematic"+ else:+ r["mpnSource"] = "board" if b else None+ return sorted(ref for ref in sch if ref not in by_ref)++ 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@@ -200,6 +357,8 @@ def classify(row, furniture=None): def identity(row): """(mpn, problem). An LCSC code or a value string is NOT an identity (#142)."""+ if row.get("conflict"):+ return None, row["conflict"] mpn = (row.get("mpn") or "").strip() if mpn: return mpn, None@@ -275,12 +434,57 @@ def page_exists(ref, offline=False): return any((r.get("slug") or "").lower() == slug for r in res) +PENDING_FIELDS = ("why", "ref")+++def pending_problem(part):+ """Why a part's pending mark is not usable, or None."""+ mark = part.get("pending")+ if not isinstance(mark, dict) or any(not str(mark.get(k) or "").strip() for k in PENDING_FIELDS):+ return (f"{part['ref']} is pending without a reason and a reference "+ '(pending: {"why": "...", "ref": "..."}); mark it with `component_graph.py pend`')+ if not part.get("mpn"):+ return f"{part['ref']} is pending but has no MPN; a pending part is one whose page is on its way"+ return None++ def cmd_plan(a): 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+ sch_path = a.sch or own_schematic(a.board)+ sch_note = None+ if sch_path:+ try:+ sch = schematic_mpns(sch_path)+ except ValueError as e:+ print(f"error: {e}", file=sys.stderr)+ return 2+ sch_name = os.path.basename(sch_path)+ extra = merge_mpns(rows, sch, sch_name)+ took = sorted(r["ref"] for r in rows if r.get("mpnSource") == "schematic")+ sch_note = (f"MPNs from the board and {sch_name}" + ("" if a.sch else " (the board's own schematic; --sch names another)")+ + (f"; {len(took)} only in the schematic ({', '.join(took[:8])}{' ...' if len(took) > 8 else ''}):"+ " the board was not updated from the schematic after their MPNs were added" if took else ""))+ if extra:+ sch_note += (f"\n {len(extra)} schematic part(s) with an MPN have no footprint on the board: "+ + ", ".join(extra[:8]) + (" ..." if len(extra) > 8 else ""))+ else:+ sch_name = None+ for r in rows:+ r["mpnSource"] = "board" if r.get("mpn") else None+ # Pending marks of an earlier plan of this board carry over, part by part, while+ # the part keeps its designator and MPN and its page has not appeared.+ earlier = {}+ if a.out and os.path.exists(a.out):+ try:+ old = json.loads(Path(a.out).read_text(encoding="utf-8"))+ if old.get("board") == os.path.basename(a.board):+ earlier = {p["ref"]: p for p in old.get("parts", []) if p.get("status") == "pending"}+ except (ValueError, OSError, KeyError, TypeError):+ earlier = {} furniture, census = census_furniture(a.board) if furniture is None: rule = {"source": "designators", "detail": census}@@ -293,10 +497,11 @@ def cmd_plan(a): 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": [],+ plan = {"board": os.path.basename(a.board), "schematic": sch_name, "furnitureRule": rule, "parts": [], "counts": {"electrical": 0, "furniture": 0, "skip": 0,- "reuse": 0, "create": 0, "flagged": 0}}- print(note + "\n")+ "reuse": 0, "create": 0, "pending": 0, "flagged": 0}}+ print(note + ("\n" + sch_note if sch_note else "") + "\n")+ carried, dropped = [], [] for row in rows: kind = classify(row, furniture) plan["counts"][kind] = plan["counts"].get(kind, 0) + 1@@ -305,31 +510,89 @@ def cmd_plan(a): mpn, problem = identity(row) existing = probe_wiki(mpn, a.offline) status = ("flagged" if problem else "reuse" if existing else "create")+ part = {"ref": row["ref"], "kind": kind, "mpn": mpn, "mpnSource": row.get("mpnSource"),+ "value": row.get("value"), "footprint": row.get("footprint"),+ "status": status, "page": existing, "problem": problem}+ old = earlier.get(row["ref"])+ if old and kind == "electrical" and mpn and (old.get("mpn") or "").lower() == mpn.lower():+ if status == "create":+ part["status"], part["pending"] = "pending", old.get("pending")+ carried.append(row["ref"])+ elif status == "reuse":+ dropped.append(f"{row['ref']} ({existing})") if kind == "electrical":- plan["counts"][status] += 1- plan["parts"].append({"ref": row["ref"], "kind": kind, "mpn": mpn,- "value": row.get("value"), "footprint": row.get("footprint"),- "status": status, "page": existing, "problem": problem})+ plan["counts"][part["status"]] += 1+ plan["parts"].append(part) w = max([len(p["ref"]) for p in plan["parts"]] + [4])- print(f"{'REF'.ljust(w)} {'STATUS'.ljust(8)} {'KIND'.ljust(10)} IDENTITY")+ print(f"{'REF'.ljust(w)} {'STATUS'.ljust(8)} {'KIND'.ljust(10)} {'MPN FROM'.ljust(15)} IDENTITY") for p in sorted(plan["parts"], key=lambda x: (x["status"] != "flagged", x["ref"])): ident = p["page"] or p["mpn"] or (p["problem"] or "")- print(f"{p['ref'].ljust(w)} {p['status'].ljust(8)} {p['kind'].ljust(10)} {ident}")+ if p["status"] == "pending":+ ident += f" (pending: {p['pending'].get('why')}; {p['pending'].get('ref')})"+ print(f"{p['ref'].ljust(w)} {p['status'].ljust(8)} {p['kind'].ljust(10)} {(p['mpnSource'] or '-').ljust(15)} {ident}") c = plan["counts"] print(f"\nelectrical={c['electrical']} furniture={c['furniture']} skipped={c['skip']}"- f" -> reuse={c['reuse']} create={c['create']} FLAGGED={c['flagged']}")+ f" -> reuse={c['reuse']} create={c['create']} pending={c['pending']} FLAGGED={c['flagged']}")+ if carried:+ print(f"\npending kept from the earlier plan: {', '.join(carried)}")+ if dropped:+ print(f"\nno longer pending, the page exists now (add the dependency): {', '.join(dropped)}") if c["flagged"]: print("\nFLAGGED parts have no resolvable MPN. Resolve them (or explicitly drop\n" "them from the graph) before publishing - the gate refuses them.") if a.out:- json.dump(plan, open(a.out, "w"), indent=2)+ with open(a.out, "w", encoding="utf-8") as f:+ json.dump(plan, f, indent=2) print(f"\nplan -> {a.out}") return 1 if c["flagged"] else 0 +def cmd_pend(a):+ """Mark parts whose component page is on its way (held for review, requested) as+ pending: the gate then warns about their missing dependency instead of failing,+ until the page exists."""+ why, ref = (a.why or "").strip(), (a.ref or "").strip()+ if not why or not ref:+ print("error: --why and --ref are both required (what the page waits for, and where: "+ "a part request, a review, an issue)", file=sys.stderr)+ return 2+ try:+ plan = json.loads(Path(a.plan).read_text(encoding="utf-8"))+ except (OSError, ValueError) as e:+ print(f"error: {a.plan} could not be read: {e}", file=sys.stderr)+ return 2+ errors, marked = [], []+ for want in a.parts:+ hits = [p for p in plan.get("parts", []) if p["ref"] == want+ or (p.get("mpn") and p["mpn"].lower() == want.lower())]+ if not hits:+ errors.append(f"{want}: no part of the plan has this designator or MPN")+ for p in hits:+ if p["kind"] != "electrical":+ errors.append(f"{p['ref']}: a {p['kind']} part is not in the dependency graph")+ elif p["status"] == "flagged":+ errors.append(f"{p['ref']}: has no MPN ({p['problem']}); resolve it first")+ elif p["status"] == "reuse":+ errors.append(f"{p['ref']}: its page exists ({p['page']}); add the dependency instead")+ else:+ p["status"], p["pending"] = "pending", {"why": why, "ref": ref}+ marked.append(p["ref"])+ for e in errors:+ print(f"error: {e}", file=sys.stderr)+ if errors:+ return 2+ counts = plan.setdefault("counts", {})+ for k in ("reuse", "create", "pending", "flagged"):+ counts[k] = sum(1 for p in plan["parts"] if p["kind"] == "electrical" and p["status"] == k)+ with open(a.plan, "w", encoding="utf-8") as f:+ json.dump(plan, f, indent=2)+ print(f"pending ({why}; {ref}): {', '.join(sorted(set(marked)))}")+ return 0++ def cmd_gate(a):- pkg = json.load(open(a.package))+ pkg = json.loads(Path(a.package).read_text(encoding="utf-8")) deps = pkg.get("dependencies") or {} slug = pkg.get("slug", "") fails, warns = [], []@@ -355,7 +618,18 @@ def cmd_gate(a): if VALUE_NAMED_RE.match(slug) or VALUE_RE.match(slug): fails.append(f"slug '{slug}' is a value string, not an MPN (#142)") - plan = json.load(open(a.plan)) if a.plan and os.path.exists(a.plan) else None+ plan_path = a.plan+ if plan_path is None and os.path.exists("component-plan.json"):+ plan_path = "component-plan.json"+ print("plan: component-plan.json (the default; --plan names another)")+ if plan_path is not None and not os.path.exists(plan_path):+ print(f"error: --plan {plan_path} does not exist; run `component_graph.py plan` first", file=sys.stderr)+ return 2+ try:+ plan = json.loads(Path(plan_path).read_text(encoding="utf-8")) if plan_path else None+ except ValueError as e:+ print(f"error: {plan_path} is not a plan: {e}", file=sys.stderr)+ return 2 # A plan from a DIFFERENT board silently "passes" a board it never inspected - # the exact class of mistake this gate exists to stop. Compare stems. if plan and a.expect_board:@@ -375,8 +649,9 @@ def cmd_gate(a): if not deps: fails.append("board publishes with dependencies:{} and no plan to justify it") else:- if electrical and not deps:- fails.append(f"{len(electrical)} electrical BOM parts but dependencies:{{}} - "+ needed = [p for p in electrical if p["status"] != "pending"]+ if needed and not deps:+ fails.append(f"{len(needed)} electrical BOM parts but dependencies:{{}} - " "APM/Nucleus will show an empty BOM panel (molecule-pipeline #4)") if flagged: fails.append(f"{len(flagged)} part(s) have no resolved MPN: "@@ -386,21 +661,43 @@ def cmd_gate(a): # dependency naming it. board -> components directly (#18): the expected # dep slug is the part's MPN slug (or the slug of the page probe found). dep_slugs = {dep_slug(d) for d in deps}- uncovered = []+ uncovered, waiting = [], [] for p in electrical: if p["status"] == "flagged": continue # already failed above; no identity to match on+ if p["status"] == "pending":+ problem = pending_problem(p)+ if problem:+ fails.append(problem)+ continue want = {slugify(p["mpn"])} if p.get("mpn") else set() if p.get("page"): want.add(dep_slug(p["page"])) if want and not (want & dep_slugs):- uncovered.append(p)+ (waiting if p["status"] == "pending" else uncovered).append(p) if uncovered: fails.append( f"{len(uncovered)} electrical part(s) are NOT covered by any dependency " "(declared-coverage, #17): " + ", ".join(f"{p['ref']}={p['mpn'] or p.get('value')}" for p in uncovered[:5]) + " - add a dependency on each part's component page")+ # PENDING: a part whose page is on its way (held for review, requested) has no page+ # to depend on yet. It warns, naming why, until its page exists; then a missing+ # dependency fails like any other (checked by MPN with --resolve).+ by_mpn = {}+ for p in waiting:+ by_mpn.setdefault(p["mpn"].lower(), []).append(p)+ for parts in by_mpn.values():+ refs = ", ".join(p["ref"] for p in parts)+ mark = parts[0]["pending"]+ page = probe_wiki(parts[0]["mpn"], a.offline) if a.resolve else None+ if page:+ fails.append(f"{refs} ({parts[0]['mpn']}) was pending ({mark['why']}; {mark['ref']}), "+ f"and its page exists now: {page}. Add the dependency")+ else:+ warns.append(f"{refs} ({parts[0]['mpn']}) pending: {mark['why']} ({mark['ref']}); "+ "no dependency until its page exists"+ + ("" if a.resolve else " (not probed: pass --resolve to check whether it exists now)")) # ── RESOLVED (existence, #17): every declared dep must resolve to a real # page. Skipped unless --resolve (it hits the network); a probe that@@ -444,15 +741,23 @@ def main(): p = sub.add_parser("plan", help="parse the BOM, classify, probe the wiki namespace") p.add_argument("board")- p.add_argument("--sch")- p.add_argument("--owner")+ p.add_argument("--sch", help="the schematic whose MPNs count with the board's, by designator: a KiCad "+ ".kicad_sch (its sheets are followed) or an EAGLE .sch. Default: <board stem>.kicad_sch "+ "or .sch beside the board, when there is one") p.add_argument("--out", default="component-plan.json") p.add_argument("--offline", action="store_true", help="skip wiki namespace probing") p.set_defaults(fn=cmd_plan) + q = sub.add_parser("pend", help="mark parts whose component page is on its way as pending")+ q.add_argument("plan", help="the plan written by `plan`")+ q.add_argument("parts", nargs="+", help="designators (U3) or MPNs (every part with that MPN)")+ q.add_argument("--why", help="what the page waits for, e.g. 'page held for footprint review'")+ q.add_argument("--ref", help="where that is tracked, e.g. 'part request 1240'")+ q.set_defaults(fn=cmd_pend)+ g = sub.add_parser("gate", help="HARD GATE before publish (non-zero exit = do not publish)") g.add_argument("package", help="the board's package.json")- g.add_argument("--plan", default="component-plan.json")+ g.add_argument("--plan", help="the plan (default: component-plan.json when it exists)") g.add_argument("--expect-board", help="board filename this package should match " "(guards against passing a stale plan from another board)") g.add_argument("--allow-no-components", action="store_true",
scripts/contract.json+103−14@@ -3,6 +3,26 @@ "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-step",+ "version": 1,+ "description": "A tscircuit molecule with a STEP of the board: circuit.json, the model files it references, and the STEP the CAD STEP is written from.",+ "applies": { "kinds": ["molecule"] },+ "sources": {+ "circuit": { "match": ["circuit.json", "*.circuit.json"], "exclude": ["**/node_modules/**"] },+ "assets": { "match": ["**/libraries/**"], "exclude": ["**/node_modules/**"], "optional": true, "many": 200 },+ "step": { "match": ["eda/*.step", "eda/*.stp", "{slug}.step", "{slug}.stp", "3d.step"] }+ },+ "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" },+ "cad": { "from": "cad", "path": "{slug}.cad.step" }+ }+ }, { "name": "molecule-circuit", "version": 1,@@ -44,7 +64,8 @@ "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" }+ "report": { "from": "report", "path": "{slug}.pipeline.json" },+ "cad": { "from": "cad", "path": "{slug}.cad.step" } } }, {@@ -70,7 +91,7 @@ ], "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"],+ "rootNames": ["{slug}.glb", "{slug}.web.glb", "{slug}.render.glb", "{slug}.pipeline.json", "{slug}.metadata.json", "{slug}.cad.step"], "rootSuffixes": ["_footprint.json", "_symbol.json"], "suffixSlots": ["footprint", "symbol"], "allowed": ["render/**", "3d/**", "viewer/**", "libraries/**", "**/*.3dshapes/**"]@@ -210,7 +231,7 @@ "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"+ "note": "the STEP is placed on the board file's machine pins by shape; a turn the board contacts, the pin names or the pins alone prove is turned back about Z (model-turned), and a mirrored fit, or turned fits nothing tells apart, are refused" }, { "stage": "convert-anchor", "id": "anchor-rule", "level": "info", "routes": ["board"] }, {@@ -220,6 +241,13 @@ "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": "model-turned",+ "level": "warn",+ "routes": ["board"],+ "note": "the STEP was turned against the board file; the build turned it back about Z into the board file's frame, the origin pin at the origin"+ }, { "stage": "convert-anchor", "id": "anchor-matches-metadata", "level": "fail", "routes": ["board"] }, { "stage": "fabrication",@@ -228,7 +256,13 @@ "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-bundle",+ "level": "fail",+ "routes": ["board"],+ "note": "fab_bundle's check of the zip against export.json, and of the record's stackup: a shape no reader can take is refused, naming the shape to write"+ }, { "stage": "fabrication", "id": "fab-layers", "level": "fail", "routes": ["circuit", "board"] }, { "stage": "fabrication", "id": "fab-tier", "level": "fail", "routes": ["circuit", "board"] }, {@@ -340,24 +374,78 @@ "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",+ "note": "the board artwork registers turned or mirrored against the model and normalize did not turn it back: mirrored, an outline-only or tied fit, a score under registration.accept, or a turn after the anchor's own", "routes": ["circuit", "board"] },+ {+ "stage": "normalize",+ "id": "model-turned",+ "level": "warn",+ "routes": ["circuit", "board"],+ "note": "the drill holes proved a turn and normalize turned the model about Z into the board file's frame (orient design)"+ },+ {+ "stage": "normalize",+ "id": "origin-pin",+ "level": "fail",+ "routes": ["circuit", "board"],+ "note": "after a turn: the board's origin pin, the one the footprint and the metadata name, is at the origin and every machine pin where the board file has it, unturned"+ },+ {+ "stage": "normalize",+ "id": "stackup-values",+ "level": "warn",+ "routes": ["circuit", "board"],+ "note": "the stackup (export.json, or a KiCad board's own) names a colour or finish the board look has no colour for; the model draws the default there"+ }, { "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": "board-layers", "id": "layer-geometry", "level": "info", "routes": ["circuit", "board"] },+ { "stage": "board-layers", "id": "distance-fields", "level": "info", "routes": ["circuit", "board"] },+ {+ "stage": "board-layers",+ "id": "texture-look",+ "level": "warn",+ "routes": ["circuit", "board"],+ "note": "the board faces keep the texture look, with the reason: no registered fabrication layers, no field within the texel limit at the base texture's resolution, or a board-layers tool failed"+ },+ { "stage": "optimize-canonical", "id": "board-layers-packed", "level": "info", "routes": ["circuit", "board"] },+ {+ "stage": "optimize-canonical",+ "id": "texture-look",+ "level": "warn",+ "routes": ["circuit", "board"],+ "note": "pack.mjs could not add the fields to this model; both models keep the texture look"+ }, { "stage": "optimize-canonical", "id": "preservation", "level": "fail", "routes": ["circuit", "board"] },+ {+ "stage": "optimize-canonical",+ "id": "hover-labels",+ "level": "warn",+ "routes": ["circuit", "board"],+ "note": "never raised here: the canonical model keeps every node and gets no hover labels; main.py records both models' optimizer stages in one loop"+ }, { "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": "board-layers-packed", "level": "info", "routes": ["circuit", "board"] },+ {+ "stage": "optimize-render",+ "id": "texture-look",+ "level": "warn",+ "routes": ["circuit", "board"],+ "note": "pack.mjs could not add the fields to this model; both models keep the texture look"+ }, { "stage": "optimize-render", "id": "preservation", "level": "fail", "routes": ["circuit", "board"] },+ {+ "stage": "optimize-render",+ "id": "hover-labels",+ "level": "warn",+ "routes": ["circuit", "board"],+ "note": "parts the render model has no hover label for, and machine pins or contacts the STEP names no node after, by designator; hovering one shows a CAD part name"+ }, { "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"] },@@ -365,6 +453,7 @@ { "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": "cad-step", "id": "cad-step", "level": "warn", "routes": ["circuit", "board"] }, { "stage": "outputs", "id": "outputs-written", "level": "fail", "routes": ["circuit", "board"] }, { "stage": "pipeline",@@ -375,13 +464,13 @@ ] }, "versions": {- "program": "molecule/8",+ "program": "molecule/11", "toolchain": "sha256:eea7c5d640ed5112a4c308ee1d22b0bd398cb0ffd53ed1d6d8c58e276726a6ec",- "fabBundle": { "version": "1.1.0", "sha256": "3d22b1d4e98ddb16f5e7d3202e85ffeee2dd45ed120de1cdf8de5aff5837b132" },+ "fabBundle": { "version": "1.2.0", "sha256": "4680db19ff23dff641bb68257c96e0995e3967b2af4aa2f512ce1728f13eb2c8" }, "importer": "1e045f7", "normalizeSpec": "0.6", "pins": "f1404942e79e3e83f550f70199344b7e86b20e1f07a93cca13a1b8bb3b32d39a",- "namesPy": "cfdde56176749f36291777741f65fd823dfa841e247fc8ec0a1f1ff107e56fee",+ "namesPy": "8889df488b90a2cdf198df9ebd17ca00dd60f369d06631cba0552556960a32ab", "anchorFixture": "92d82a583a13a5c4f7fc4e9ae0fa308d8ecd3f209d98caacf1eb2b7fd04c73d3", "tscircuitLedger": [ "https://registry-api.tscircuit.com/package_files/get?package_file_id=f9f26d61-1970-4336-8aad-2c4292790e44",
scripts/fab_bundle.py+130−4@@ -1,6 +1,7 @@ #!/usr/bin/env python3 """Pack and verify fabrication sources. Standard library only; never publishes.""" import argparse+import difflib import hashlib import json import re@@ -8,7 +9,7 @@ import sys import zipfile from pathlib import Path, PurePosixPath -VERSION = "1.1.0"+VERSION = "1.2.0" REQUIRED = {"copper_top", "copper_bottom", "mask_top", "mask_bottom", "silk_top", "silk_bottom", "outline"} DRILLS = {"drill_plated", "drill_unplated", "drill_mixed"}@@ -22,6 +23,117 @@ READER_EXT = re.compile(r"\.(gbr|gtl|gbl|gts|gbs|gto|gbo|gko|gm1|gml|gm|cmp|sol| ZIP_BUDGET = (2000, 512 * 1024 ** 2) EMAIL = re.compile(rb"[\w.+-]+@[\w-]+(?:\.[\w-]+)+") +# The stackup of adom.export/1. The colour names and finishes are the ones Board Look's normalize+# draws (board-look.json mask.colors, silk.colors and finish.aliases), which are KiCad's names; the+# registry's test keeps the two lists equal. A name matches exactly, in any case. A colour may also be+# given as #rrggbb (or #rrggbbaa).+STACKUP_SHAPE = ('{"thicknessMm": 1.6, "copperLayers": 2, "maskColor": {"top": "green", "bottom": "green"}, '+ '"silkColor": {"top": "white", "bottom": "white"}, "finish": "ENIG"}')+STACKUP_KEYS = ("thicknessMm", "copperLayers", "maskColor", "silkColor", "finish")+BRITISH = {"maskColour": "maskColor", "silkColour": "silkColor"}+COLOURS = {+ "maskColor": ("green", ("green", "light green", "saturated green", "red", "light red", "red/orange",+ "blue", "light blue 1", "light blue 2", "green/blue", "black", "matte black",+ "white", "yellow", "purple", "light purple")),+ "silkColor": ("white", ("white", "black", "yellow", "blue", "red", "grey")),+}+FINISHES = {"enig": "ENIG", "enepig": "ENIG", "hard gold": "ENIG", "immersion gold": "ENIG", "hasl": "HASL",+ "hal snpb": "HASL", "hal lead-free": "HASL", "hasl lead-free": "HASL", "lead-free hasl": "HASL",+ "lf hasl": "HASL",+ "osp": "OSP", "ht_osp": "OSP", "immersion silver": "ImmersionSilver",+ "immersion tin": "ImmersionTin"}+# KiCad finishes the board look has no colour for: real names, so a build draws the default+# there without a "did you mean" (board-look.json finish.notDrawn).+FINISHES_NOT_DRAWN = ("immersion nickel", "user defined")+FINISH_DEFAULT = "HASL"+# Values that state nothing: KiCad writes "None" for a finish nobody chose.+NOT_STATED = {"", "none", "not specified"}+HEX = re.compile(r"#[0-9a-fA-F]{6}(?:[0-9a-fA-F]{2})?")+++def did_you_mean(value, names):+ """' Did you mean "<name>"?' for the known name closest to `value`, or "" when none is close."""+ near = difflib.get_close_matches(value.strip().lower(), list(names), n=1, cutoff=0.6)+ return f' Did you mean "{near[0]}"?' if near else ""+++def _flat(key):+ return re.sub(r"[^a-z]", "", key.lower()).replace("colour", "color")+++def stackup_problems(stackup):+ """(errors, warnings) of an export.json stackup.++ An error is a record whose shape no reader can take: a stackup that is not an object, a key+ written two ways or misspelled, a colour that is not {"top": ..., "bottom": ...}, a thickness or+ layer count that is not a positive number, a finish that is not text, a malformed #rrggbb. A+ warning is a well-formed value the board look has no colour or finish for (a build draws its+ default there and says so), or a key no build reads. A null value, an empty one, "None" or+ "Not specified" states nothing and is neither."""+ errors, warnings = [], []+ if stackup is None:+ return errors, warnings+ if not isinstance(stackup, dict):+ return [f"export.json stackup must be an object like {STACKUP_SHAPE}; it is {json.dumps(stackup)[:80]}"], warnings+ seen = {}+ for key in stackup:+ name = BRITISH.get(key, key)+ if name in STACKUP_KEYS:+ if name in seen:+ errors.append(f"export.json stackup has both {seen[name]} and {key}; give one")+ seen[name] = key+ continue+ near = next((k for k in STACKUP_KEYS if _flat(k) == _flat(key)), None)+ if near:+ errors.append(f"export.json stackup.{key} is misspelled: write {near}")+ else:+ warnings.append(f"export.json stackup.{key} is not read by any build (known keys: {', '.join(STACKUP_KEYS)})")+ for name, key in seen.items():+ value, at = stackup[key], f"export.json stackup.{key}"+ if value is None:+ continue+ if name in ("thicknessMm", "copperLayers"):+ whole = name == "copperLayers"+ ok = (isinstance(value, int) if whole else isinstance(value, (int, float))) and not isinstance(value, bool)+ if not ok or not 0 < value < float("inf"):+ what = "whole number of copper layers" if whole else "number of millimetres"+ errors.append(f"{at} must be a positive {what}; it is {json.dumps(value)[:40]}")+ elif name == "finish":+ if not isinstance(value, str):+ errors.append(f'{at} must be text such as "ENIG"; it is {json.dumps(value)[:40]}')+ elif value.strip().lower() in FINISHES_NOT_DRAWN:+ warnings.append(f"{at} {value!r} is a finish the board look has no colour for, so a build draws {FINISH_DEFAULT} there. "+ f"The name is right; nothing to change.")+ elif value.strip().lower() not in NOT_STATED and value.strip().lower() not in FINISHES:+ warnings.append(f"{at} {value!r} is not a finish name the board look knows, so a build draws {FINISH_DEFAULT} there."+ f"{did_you_mean(value, FINISHES)} Names it knows (any case): {', '.join(sorted(FINISHES))}")+ else:+ default, palette = COLOURS[name]+ if not isinstance(value, dict) or set(value) - {"top", "bottom"}:+ errors.append(f'{at} must be {{"top": "<colour>", "bottom": "<colour>"}}, for example '+ f'{{"top": "{default}", "bottom": "{default}"}}; it is {json.dumps(value)[:80]}')+ continue+ for side, colour in value.items():+ if colour is None:+ continue+ if not isinstance(colour, str):+ errors.append(f"{at}.{side} must be a colour name or #rrggbb; it is {json.dumps(colour)[:40]}")+ elif colour.strip().startswith("#"):+ if not HEX.fullmatch(colour.strip()):+ errors.append(f"{at}.{side} {colour!r} is not #rrggbb")+ elif colour.strip().lower() not in NOT_STATED and colour.strip().lower() not in palette:+ warnings.append(f"{at}.{side} {colour!r} is not a colour name the board look knows, so a build draws {default} there."+ f"{did_you_mean(colour, palette)} Give the exact colour as #rrggbb, or one of (any case): {', '.join(palette)}")+ return errors, warnings+++def check_stackup(stackup):+ """The warnings of stackup_problems; its errors raise one ValueError naming them all."""+ errors, warnings = stackup_problems(stackup)+ if errors:+ raise ValueError("; ".join(errors))+ return warnings+ def safe_path(name): p = PurePosixPath(name)@@ -195,6 +307,7 @@ def check(root, slug): zips = [e for e in entries if e["role"] == "fab_zip"] if len(zips) != 1 or zips[0]["path"] != f"{slug}-fab.zip": raise ValueError(f"exactly one fab_zip named {slug}-fab.zip is required")+ check_stackup(rec.get("stackup")) files = read_zip(root / zips[0]["path"]) stripped = without_owner(files) owned = [n for n in sorted(files) if stripped[n] != files[n]]@@ -225,6 +338,15 @@ def create(args): root = Path(args.root).resolve() if (root / "export.json").exists(): raise ValueError("export.json already exists; verify it or use a fresh export folder")+ stackup = {}+ if args.stackup:+ try:+ stackup = json.loads(Path(args.stackup).read_text(encoding="utf-8"))+ except ValueError as e:+ raise ValueError(f"--stackup {args.stackup} is not JSON: {e}")+ if not isinstance(stackup, dict):+ raise ValueError(f"--stackup {args.stackup} must hold one object like {STACKUP_SHAPE}")+ check_stackup(stackup) source = Path(args.fab) if source.is_dir(): files = {}@@ -253,7 +375,6 @@ def create(args): fab = fingerprint(target.name, "fab_zip", target.read_bytes()) fab["entries"] = layers entries.append(fab)- stackup = json.loads(Path(args.stackup).read_text(encoding="utf-8")) if args.stackup else {} rec = {"schema": "adom.export/1", "tool": args.tool, "toolVersion": args.tool_version, "exporter": args.exporter, "exporterVersion": args.exporter_version, "design": args.slug, "files": entries, "stackup": stackup,@@ -277,13 +398,18 @@ def main(): q.add_argument("--exporter", required=True) q.add_argument("--exporter-version", required=True) q.add_argument("--source", action="append", required=True, help="ROLE=relative/path (repeat)")- q.add_argument("--stackup", help="JSON with known thicknessMm, maskColor, silkColor, finish")+ q.add_argument("--stackup", help="a JSON file holding what is known of the stackup, every key optional: "+ + STACKUP_SHAPE.replace("%", "%%") + "; colours per side, by name or #rrggbb") args = p.parse_args() try: if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", args.slug): raise ValueError("slug must be lowercase words separated by hyphens") rec = create(args) if args.command == "create" else check(args.root, args.slug)- print(json.dumps({"ok": True, "files": [e["path"] for e in rec["files"]] + ["export.json"]}))+ out = {"ok": True, "files": [e["path"] for e in rec["files"]] + ["export.json"]}+ warnings = check_stackup(rec.get("stackup"))+ if warnings:+ out["warnings"] = warnings+ print(json.dumps(out)) except (ValueError, OSError, KeyError, TypeError, zipfile.BadZipFile) as e: print(json.dumps({"ok": False, "error": str(e)}), file=sys.stderr) return 1
scripts/pin_names.py+5−3@@ -353,7 +353,7 @@ def census(path, route, rule, text=None, role=None, repo_path=None, kicad=None): 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+ Returns {report, checks, attachments, accepted, positions, designators}: 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@@ -364,7 +364,8 @@ def census(path, route, rule, text=None, role=None, repo_path=None, kicad=None): {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.+ the first. designators is every part's designator on the board, in natural order; it is+ missing when the board was not read. """ 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}@@ -587,7 +588,8 @@ def census(path, route, rule, text=None, role=None, repo_path=None, kicad=None): 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}+ designators = sorted({p['designator'] for p in parts if p['designator']}, key=_natural)+ return {'report': report, 'checks': checks, 'attachments': atts, 'accepted': accepted, 'positions': positions, 'designators': designators} def _spans(text, head):