by adom
The one-stop-shop for publishing a hardware component (or molecule/board) to the Adom Wiki. The whole lifecycle: page anatomy, the clone→edit→preview→push loop and its hard rules, making a great hero image (Hero Component Studio — 16:10, overlay-safe, datasheet-backed), the animated 3D composite, the interactive 3D viewer, ct thumbnails, the datasheet-accuracy audit, and every wiki push/pull gotcha we've hit. Now includes the worked Path B (board) pipeline: STEP-to-GLB, refdes tagging, layer de-
← Commit history
Publish 0.8.0
17 files changed
+2883
SKILL.md+1017docs/HERO.md+1docs/hero.pnginstall.sh+13package.json+65scripts/audit_checklist.md+45scripts/bake_board_glb.py+222scripts/board-viewer-template.html+489scripts/build_composite_cap.py+109scripts/build_composite_led.py+249scripts/kicad_board_geom.py+142scripts/kicad_board_map.py+138scripts/preview_readme/preview.html+69scripts/preview_readme/serve.py+17scripts/publish_wiki_page.py+279scripts/verify_seek_example.cjs+25uninstall.sh+3SKILL.mdadded+1017@@ -0,0 +1,1017 @@+---+name: adom-hardware-component-publish+description: >+ The one-stop-shop for publishing a HARDWARE COMPONENT (or molecule/board) to the Adom Wiki —+ everything you need in one place. Covers the whole lifecycle: what a component page is made of,+ the clone→edit→preview→push loop and its hard rules, how to make a great hero image (Hero+ Component Studio: a lit part on a procedural PCB or a molecule on a shadow ground, 16:10,+ overlay-safe, datasheet-backed), the animated 3D composite model, the interactive 3D viewer,+ ct thumbnails (symbol + footprint + 3D icons), the datasheet-accuracy audit, and every wiki+ push/pull gotcha we have hit. Use whenever someone wants to publish, update, or improve a+ component/molecule/board page on wiki.adom.inc. Trigger words: publish component, publish+ hardware, publish to wiki, component page, molecule page, board page, wiki page, hero image,+ component thumbnail, card art, 3d composite, insertion.glb, interactive viewer, ct thumbnails,+ datasheet audit, wiki push, wiki clone, page hero, set hero, land pattern, footprint viewer.+ PRIVATE — Adom only.+metadata:+ type: reference+---++# Publishing a Hardware Component to the Adom Wiki++**The single place to look when you want to put a hardware component on the wiki and have it look+right.** "Component" here means any physical thing that gets a wiki page: a discrete part+(resistor, MLCC, LED, inductor, connector, IC), a **molecule** (an assembled sub-board), or a full+**board**. The recipe is the same shape for all of them; the differences are called out inline.++> **Living document.** When you hit a new wiki issue or find a better recipe, add it to the right+> section, bump the version, and open a PR against `adom/adom-hardware-component-publish`. Never+> re-solve a problem that's already written here.++> **Private / Adom-only.** Published under the `adom` org, visibility private.++> **First decide which kind of page you're making** — a single **COMPONENT** (Path A) or a full+> **BOARD / MOLECULE** (Path B). The required contents differ (see "Two kinds of page" below). On a+> component page, the 3D viewer + cited datasheet content **stand in for the datasheet**: every fact+> is datasheet-accurate and **traceable to a specific figure/table/page** (cite your sources). A board+> page is the author's presentation of how their board works, not a cited datasheet.++---++## The lifecycle at a glance++```+1. Gather inputs datasheet (electrical + packing/tape&reel), CAD (STEP/GLB), KiCad sym/fp+2. Build the assets 3D composite (datasheet-accurate) · ct thumbnails · timeline viewer+3. Make the hero Hero Component Studio → 16:10, overlay-safe, datasheet-backed (§3)+4. Assemble ONE page README.html = datasheet content + full-page timeline viewer, self-sizing (§5.0)+5. Preview RENDERED preview via the readme-frame harness through the container proxy+6. Snapshot + approve save the pre-change files; get an explicit human go-ahead+7. Push clone fresh → README.html + viewer-config.json + hero → rm retired files+8. Verify live commit at HEAD · blobs 200 · /readme 200 · hero set · hard-refresh (cache)+```++Everything a page needs is below, section by section. If you only touch one thing (e.g. "make the+hero better"), jump to that section — but the **hard rules (§0)** and **push gotchas (§8)** apply to+every push.++---++## Two kinds of page — pick your path FIRST++A **single component** (a part: an LED, resistor, MLCC, IC, connector) and a **full board or+molecule** (an assembled sub-board) are different deliverables with different required contents.+Decide which you're publishing, build the required contents for that path, then use the shared+mechanics (hero §3, composite §4, viewer §5, wiki push §2/§8) to assemble and ship it. **Both paths+end as the one seamless full-page README (§5.0).**++### Path A — a COMPONENT page (a single part) · required contents++1. **Datasheet information — the whole point, and it must be COMPLETELY datasheet-accurate.**+ This is the former "characterization page", merged into the wiki page. **The datasheet PDF itself+ MUST be stored in the page repo** (Adom standard — every component page has a datasheet); it's the+ source of truth and every citation links to it. **Every single data point must be traceable to a+ specific place in that datasheet** — cite the revision + page/table/figure, linked into the stored+ PDF (e.g. "VF 2.1 V typ · 2.6 V max — [IN-S42AT V1.1 p.3]", "2θ½ 130° — [p.3 fig.4]"). See §7/§7a for+ the citation format, §7b for the "datasheet changes ⇒ citations change" rule AND the mandatory **datasheet revision+date line near the top of the page**, and §7c for how to read a datasheet. Charts are *redrawn+ to the datasheet curve*, not invented. If a value isn't in the datasheet, it does not go on the page+ — flag the gap, never estimate. (See [[feedback_never-fabricate-data]], [[feedback_characterization-pages-are-datasheets]].)+2. **Interactive viewer** (§5), with the modes the part warrants:+ - **Static** — the seated part with the standard Layers. If the component *does* something — a+ visual behaviour like emitting light or actuating — show it **cleanly and datasheet-backed**+ (e.g. an LED's glow colour from its λD, its FOV cone from 2θ½).+ - **Timeline** — a visual replacement for the *visually-explainable parts of the datasheet*+ (power-on, optical cone, reflow, tape & reel). Everything shown is datasheet-backed; the+ captions cite the datasheet (§5a datasheet-vs-measured rule).+ - **Pick & Place** — a **datasheet-accurate carrier tape & reel**, with either the standard+ drop-in **ghost nozzle** or a specific nozzle the user chooses.+3. **Solder joints** — either the default fillets, or (preferably) **the placement/shape the user+ specifies** (where and how the solder sits on the pads).+4. **The geometry carries the facts** — the viewer shows the real **pad size**, the **chip model**,+ and the correct **orientation** (cathode/pin-1), all datasheet-accurate.+5. **Symbol + footprint** — the schematic symbol and PCB footprint (inline `ct/` SVGs, since+ interactive symview/fpview iframes are sandbox-blocked, §8k).++### Path B — a BOARD / MOLECULE page · required contents++1. **Interactive viewer** (§5) — this is the centrepiece; a board/molecule is not a datasheet part,+ so it has **no characterization / tape&reel / pick-and-place** requirement. A board viewer has+ exactly **TWO modes** (an earlier draft split assembly/walkthrough/operation into three tabs —+ that was redundant; drop-in and explanation are ONE story, and an "operation" reel took the+ camera away from the user):+ - **Assembly — the groupings drop in together, and the caption explains each as it lands.**+ The board starts bare with an overview caption; then each functional grouping's parts **fall+ in as one beat** (all members of the power grouping together, then all the connectors, …) in+ the author's order, while a data-card caption (eyebrow / head / rows / note) explains what+ that grouping is and does. Camera frames each grouping — but **any drag/wheel yields it to+ the user for 5 s, then it eases back** (the exact convention of the single-component Timeline+ viewer; the viewer must never fight for control). If the board uses **molecules**, each drops+ in already populated and seats like a single component. Scrubber ticks mark group starts.+ - **Static — the seated board, and the camera is entirely the user's.** No timeline, no+ scripted moves, no caption sequence — hover tooltips, the section legend (click to isolate),+ section labels, and any **author-specified visual functions** as *toggles* (e.g. a "Power"+ button lighting the rail LEDs). Behaviours here are the author's call and must be labelled+ author-specified (§7B); nothing is invented. For rich animated behaviour (blink patterns, a+ scanning row, a display) use the LED-lighting / animated-emission method+ (`adom-basic-part-page-upgrade`, Caleb's playbook) — still as a user-triggered toggle, never+ a camera-stealing reel.+ - **ASK THE AUTHOR — this is their presentation, so collect (don't invent) exactly:**+ 1. **The groupings** — which parts belong together. Default straight from the schematic+ sheets (§5c.4 derives sheet membership automatically — e.g. the MCU sub-sheet is a+ grouping, Power is a grouping); the author refines via `blocks.json` (split a sheet,+ merge two, name them).+ 2. **How each grouping should be explained** — the caption content per group (what it is,+ the key parts/values, why it's there), plus the drop **order**.+ 3. **Static behaviours** — should anything light up or move? Which LEDs, what states, what+ the toggle is called. Explicitly ask; "none" is a fine answer.+ - **Choreography convention (the config, `adom-board-viewer-config/0.2`):** the **grouping is+ the unit of authorship**. `blocks[]` (id, label, colour, one-liner) ++ `modes.assembly{ order[], timing{fall_s, stagger_s, dwell_s, rest_s, drop_height_mm},+ intro{caption}, captions{<group-id>: {eyebrow, head, rows, note, d?}} }` ++ `modes.static{ blurb, functions{...author-specified toggles} }`. Per-group `d` overrides the+ default dwell. The author's whole input is one small JSON file; the geometry does the rest.+ Worked example: the feeder-reader mock's `viewer-config.json`; runnable viewer:+ `scripts/board-viewer-template.html`.+2. **Provenance per §7B** — every table generated from the design files, DNP honoured, and every+ claim labelled generated / author-asserted / illustrative.+3. **Board maps instead of symbol/footprint SVGs** (a board has no schematic symbol): top + bottom+ renders from the `.kicad_pcb` with pads coloured by functional section+ (`scripts/kicad_board_map.py`).+4. **`page.json` mapping for a board** (the schema is component-shaped; use this convention):+ `component.mpn` = the KiCad project name, `component.manufacturer` = the org (e.g. `Adom`),+ `component.category` = `board`, `component.model_3d_path` = the baked board GLB. Mandatory+ files (the Path B analogue of Path A's datasheet PDF): the **board GLB**, the **board maps**,+ and the **KiCad source** (or a pointer to where it lives).+5. **Any additional information the user wants to add** — a board page is theirs to compose.++Everything else — publishing mechanics, the **hero image and grid thumbnail** (§3), the wiki+clone→push loop (§2), and every gotcha (§8) — is **shared** by both paths and applies to each.++---++## The gold-standard page — what "done" looks like++The reference build is **`aravk/in-s42atr`** (Inolux red 0402 LED) — the **COMPONENT** (Path A) gold+standard. A **board/molecule** (Path B) shares the same *shape* (one seamless full-page README, the+viewer as the hero, the ADOM hero image + grid thumbnail) but its content is the viewer-as-presentation+plus whatever the author adds — not a cited datasheet. Aim a component page at this shape:++- **ONE seamless full-page.** The `README.html` IS the page. It is a single sandboxed iframe+ (`#readme-frame`) that grows to fit its content (§8k-0b) — no boxed 600px widget, no "click through+ to the datasheet". A visitor lands on the full-page 3D viewer and scrolls down through the entire+ datasheet in one continuous document.+- **The interactive 3D viewer is the hero of the page**, full-bleed and viewport-tall at the top+ (§5). Below it flows **everything a datasheet has**: spec cards, electrical table, operating+ conditions, package & land-pattern dims, the emission/IV/derating/brightness charts (redrawn to the+ datasheet), a live resistor calculator, environmental/handling, the symbol + footprint, pricing,+ and document links. The 3D viewer + these facts **replace the PDF for everyday reference**.+- **There is no separate characterization page.** The old `<MPN>.html` char blob is **merged into the+ README** and deleted — one canonical page, not two. (On in-s42atr the merge pulled the char content+ in and removed `IN-S42ATR.html`.)+- **Everything datasheet-backed**, tooltips split datasheet-vs-measured (§5), hero rendered in Hero+ Component Studio at 16:10 (§3).++The rest of this skill is how to build each piece. If you're making a new page, this is the target;+§5.0 is the assembly recipe for the single-page README.++---++## 0. Hard rules (never skip — this is why pages don't get clobbered)++1. **Always pull fresh before editing.** Someone else may have pushed since you last looked.+ `adom-wiki repo clone <owner>/<slug> --dir <fresh>` immediately before you edit.+2. **Snapshot before push.** Copy the pre-change files to a timestamped dir and **print the path**,+ so revert is a one-liner. (`adom-wiki repo clone` is NOT a git repo — see 8j; copy files by hand.)+3. **Preview before push, then get explicit human approval.** A *rendered* preview (pup/Hydrogen+ screenshot, or the served HTML), **NOT** `curl 200`. No preview → no push. Ever.+4. **Only push the files you changed** (`--files a b c`), and **only the page you're editing.** Never+ touch another page.+5. **Everything must trace to the datasheet.** Every electrical number, every hero glow colour,+ every tape/reel dimension, every chart curve. Cite the datasheet page. If it's a guess, remove it+ or flag it explicitly — never invent. Characterization pages ARE datasheets (§7).+6. **Real changelog required** (`WIKI_STRICT_AUTH` is on): `-m "<≥2 words, ≥10 chars, specific>"`.+ Placeholders (`update`, `release v1`) are 400-rejected.++---++## 1. Anatomy of a component page++A component page is a small file repo at `<owner>/<slug>`. Typical contents:++| File | What it is | Required? |+|---|---|---|+| `page.json` | metadata: `slug`, `type`, `description`, `component{mpn,manufacturer,category,model_3d_path}`, `hero{type,path}`, `dependencies` | **yes** |+| `README.html` | **the whole page** — the merged single-page document (viewer + full datasheet content), served in the self-sizing readme-frame (§5.0, 8k-0b). `.html` wins over `.md`; `.md` strips iframes. Keep a short `README.md` in the repo as source-of-record | **yes** |+| `screenshots/hero.png` | the **hero image** — one 16:10 image used for BOTH the page header and the grid card (§3) | **yes** |+| `<MPN>-datasheet.pdf` | the **datasheet** — MANDATORY on every component page (§7); source of truth + citation target | **yes (component)** |+| `viewer-config.json` | the timeline viewer's captions / tooltips / chapters config (§5) — push it alongside the README so the embedded viewer's text loads | interactive pages |+| `<MPN>.glb` | the canonical 3D model the viewer loads **by name** (see 8b) | for anything 3D |+| `<MPN>.insertion.glb` | the animated composite (part drops onto its footprint) — what the timeline viewer loads | composite pages |+| `<MPN>-viewer.html` | the **interactive 3D viewer** source (the timeline viewer, §5). Its content is inlined as `srcdoc` into the README; keep the file as the editable source | interactive pages |+| `adom-3d-viewer.min.js` | Colby's shipped viewer bundle (the viewer fetch-injects it by absolute URL) | interactive pages |+| `<MPN>.kicad_sym` / `.kicad_mod` | KiCad symbol / footprint source | if it has EDA |+| `ct/` | thumbnail bundle: 3D icons + **symbol SVG + footprint SVG** (used inline in the page, since interactive symview/fpview iframes are sandbox-blocked) + manifest (§6) | standard |++> **Note:** the standalone `<MPN>.html` characterization blob and the `<MPN>-symview/-fpview.html`+> iframe viewers are **retired** in the gold-standard build — the char content merges into the README+> and the symbol/footprint become the static `ct/` SVGs (interactive `src=` iframes are blocked in the+> readme sandbox, §8k). Old pages may still have them; new pages should not.++**`type`** in `page.json` is `component` for discrete parts and molecules alike (the BME690 and+USB3-Ethernet molecules both use `type: component`, category `Sensor` / `board`). There isn't a+separate "molecule" page type — a molecule is a component whose model happens to be a whole board.++**Served asset URL (memorise):** `https://wiki.adom.inc/blob/component/<slug>/<FILE>`. This is what+the page HTML and the 3D viewer fetch. It's also the URL your browser loads the hero from — not the+`/api/pages/...` path (see 8m).++---++## 2. The wiki CLI + publish lifecycle++One CLI over the whole git-wiki API: `adom-wiki`. Every call takes `--json`.++> **Prefer the runnable module** `scripts/publish_wiki_page.py` — stdlib-only wrappers around every+> step (`ensure_author`, `find_page_owner`, `clone_page`, `snapshot`, `push_files`, `set_hero`,+> `verify_asset`, `publish_new_package`) with the gotchas baked in. Read it top-to-bottom to learn+> the flow, or import it to drive a publish. The raw commands below are the ground truth.++```bash+# identity (once per container) — WIKI_STRICT_AUTH needs a real author + changelog+adom-wiki whoami+adom-wiki set-author # SSO your Adom identity into the wiki++# find the page and its OWNER (owner is not always `adom` — see 8a)+adom-wiki discover search -q "<mpn>" --limit 5+adom-wiki page stats <owner>/<slug> # 404 => not under that owner++# --- EXISTING page: clone → edit → preview → snapshot → approve → push ---+adom-wiki repo clone <owner>/<slug> --dir <fresh>+# ...edit locally, RENDERED preview, snapshot, get approval...+adom-wiki repo push <owner>/<slug> --files <f1> <f2> -m "<real changelog>"+adom-wiki repo log <owner>/<slug> --limit 5 # confirm ONLY your commit landed++# --- HERO (page card image) — takes a REPO-RELATIVE path, not a local file (see §3 / 8n) ---+adom-wiki repo push <owner>/<slug> --files screenshots/hero.png -m "hero: <what changed>"+adom-wiki page hero <owner>/<slug> --image screenshots/hero.png # NOTE: no --changelog on this verb++# --- NEW page: scaffold + publish ---+adom-wiki pkg init <slug> --type component+adom-wiki pkg publish --org adom --private -m "<changelog>" # from the pkg dir+```++**Verify a pushed asset authenticated** (private pages 403 unauthenticated — see 8h):+```bash+curl -s -H "Authorization: Bearer $(cat ~/.config/adom-wiki/token)" \+ "https://wiki.adom.inc/blob/component/<slug>/<FILE>" -o /tmp/x -w "%{http_code} %{size_download}\n"+```+The authoritative confirmation a push landed is `adom-wiki repo log` (your hash at HEAD); then+cross-check the served **byte count** equals what you pushed (a stable URL means HTTP 200 alone+doesn't prove the *new* bytes are live).++---++## 3. THE HERO IMAGE — do this well, it's the first thing anyone sees++Every browsable object gets **exactly one hero**: a single picture that lets a human identify the+thing in a fraction of a second, without reading the title. If you can't tell ten of these apart at a+glance in the grid, the design is broken. The hero is used in **two** places from **one** file —+the page header AND the landing-grid card. There is **no separate thumbnail asset**+(`page.hero_thumbnail` is always null; the grid renders the hero file directly).++### 3.1 Use Hero Component Studio++`~/project/hero-component-studio` (the `hero-component-studio` skill). A small web app + CLI that+frames a component in a studio scene, lets you tune every variable live, and renders headlessly at+full quality. **Every function has a CLI verb** — you never have to click.++```bash+hero-component-studio serve --detach # starts on 8872+hero-component-studio show # opens the Hydrogen webview tab+hero-component-studio mode component|molecule # pick the scene+hero-component-studio set part <MPN> # or: set molecule <name>+hero-component-studio list # every setting: value, range, what it does+hero-component-studio save <name> # save a preset; load <name> to reuse+hero-component-studio render --width 1344 --height 1200 # writes out/<subject>-hero.png+```++**Two scene modes:**+- **component** — one part standing on a **generated circuit board** (routed traces, flat under-mask+ vias, scattered scenery chips, a keep-out around the hero). This is the LED/passive path.+- **molecule** — a **finished assembly on its own**, no invented circuitry (a molecule IS a real+ board), sitting on an invisible shadow-catching ground.++Getting your own model in (validated + de-Draco'd on ingest):+```bash+hero-component-studio add-part ./<MPN>.glb+hero-component-studio add-molecule ./<name>.glb # wiki molecule: adom-wiki repo clone, point at its render/board.glb+```++### 3.2 The rules that make a hero good (each cost real iteration)++- **16:10 aspect, rendered natively — never scaled to fit.** The wiki grid slot is 16:10; a+ 1200×630 image **letterboxes** with bars top and bottom on the card. Render at **1920×1200**+ (canonical) — or the image panel at **1344×1200** if you composite a text block over the left 30%+ (see 3.3). If you must reshape an existing render, **crop, don't stretch**: `background-size:cover`+ scales uniformly and crops the overflow; scaling one axis distorts the part. The canonical+ hero-image spec (`adom/adom-wiki-hero-image`) actually wants **1600×1000 @ deviceScaleFactor 2 =+ 3200×2000** for retina crispness — render there if you want it razor sharp.+- **Shoot from the ISO view.** The hero camera is the classic isometric three-quarter:+ `camAzimuth` ≈ ±45–55°, `camElevation` ≈ 30° — the angle that shows the subject's top AND two+ sides at once, the way every CAD tool's "ISO" button frames a part. Straight-down reads like a+ board map, edge-on hides the body; the iso view is the standard for both component and board+ heroes (the feeder-reader hero is azimuth −52° / elevation 29°).+- **Overlay-safe framing.** The finished hero draws a title block over the lower band. Framing on the+ part's *centre* puts half of it under that band, clipping the pads. `autoClearOverlay` (on by+ default) **pans** the camera (never rotates — your angle survives) until the lowest projected corner+ of **body + pads** clears `overlayCutoff` (default 0.345 = bottom 34.5%). Hit the **Band** button to+ draw the reserved zone in the viewport.+- **Centre on the VISUAL mass, not the bounding box.** A board with pins hanging below reads "high"+ even when its bbox is perfectly centred. Measure the **luminance centroid** and correct with+ `panX` / `panY` (in units of the subject radius; right-click-drag in the viewport writes them). On+ the BME690 the bbox was centred to 0.6% but the visual centroid was off by ~3.7% vertically.+- **The hero renders at TRUE scale; the scenery is what you size.** In component mode the hero part is+ always 1:1 — the camera fits to it, so it dominates through framing (`fov` / `margin`), not by being+ scaled up. **`chipScale` sizes the scenery chips as real packages** (by body length: 0.6 = 0201,+ 1.0 = 0402, 1.6 = 0603, 2.0 = 0805) — so pick scenery that reads right next to your hero's package+ (a 0402 hero looks natural amid 0201–0603 scenery). `keepout` is the clear radius around the hero.+- **Every scenery component has a trace in AND out** (enforced in the generator). A chip with no+ routing reads as a part that does nothing; the router guarantees both terminals of every scenery+ chip connect outward to two different nodes. Vias and the hero's own pads join nearby nets too.+- **Everything datasheet-backed** (§0.5). An emitter's glow colour comes from its dominant wavelength+ λD (RGB → white; every other LED → its own λD colour), the FOV cone from 2θ½. Never reuse another+ part's numbers.+- **Mouse ⇄ sliders.** Orbit (left-drag) writes `camAzimuth/camElevation`, pan (right-drag) writes+ `panX/panY`, zoom (wheel) writes `margin` — so a view you find by dragging survives Save and renders+ identically. Save a look as a **preset** (`save <name>` / `load <name>`); the browser clipboard is+ blocked in the webview, so there's no "copy", only presets.+- **The render is NOT a screenshot.** It renders at 2× with SSAA + 4× MSAA and downsamples — that's+ what removes jagged edges. (`EffectComposer` silently discards the renderer's `antialias:true`, so+ the composer needs its own multisampled target — already handled in the app.)+- **Preview aids never render.** The light guide (`showLightHelper`) and the overlay band are tuning+ overlays; the renderer forces them off, so they never bake into the image.++### 3.3 The compositor (title block + branding)++The bare render is a part on a dark background. To get the ADOM-branded card (wordmark, title,+MPN + manufacturer, badge on a dark gradient), composite it through the Hero Studio compositor+(`hero-studio-local`, the local Node compositor in the led-hero scratchpad):++- Add a record to `hero-studio-local/data/components.json`: `name` (big title), `spec` (subtitle =+ MPN), `mfr` (trails the MPN), `badge` (**`ADOM BASIC PART`** for parts, **`ADOM MOLECULE`** for+ molecules), `family`, `owner`, `slug`. **All copy comes from the wiki `page.json` + README — never+ invent a title.**+- The compositor places the render panel in the right 70%, fades its left edge under the gradient,+ and draws the text block over the left 30%. Type is all in `cqw`, so it holds at 2000×1250.+- **Gotcha — `displayEntry()` drops unknown fields.** The compositor rebuilds a fresh object from the+ record; a new field (e.g. `badge`) won't reach the overlay until you thread it through+ `displayEntry()`. Symptom: your change to the data does nothing.+- The compositor **caches `components.json` at startup** — restart its Node server after editing data.+- Output at **1920×1200**; it verifies the bottom-third text column stays text-free.++### 3.4 Setting the hero on the page++`page hero --image` takes a **repo-relative path**, not a local file. So: clone fresh → copy the PNG+to `screenshots/hero.png` → `repo push --files screenshots/hero.png` → `page hero --image+screenshots/hero.png`. The wiki **warns** if the aspect isn't 16:10 ("crops left/right on the grid").++**Caching:** the served hero carries `cache-control: max-age=86400`. After a re-push the origin is+correct immediately (confirm with a cache-busted `curl ...?cb=$(date +%s)`), but a browser holds the+old image for 24 h — a **hard refresh** (Ctrl/Cmd+Shift+R) is the fix; closing/reopening a tab is+not. The page loads the hero from `/blob/component/<slug>/screenshots/hero.png`, so verify *that*+URL, not the `/api/pages/...` one.++### 3.5 Sharing a hero for review++To send a render to a teammate for feedback, `adom-google` DMs it as **you** (better than the+`adom-gchat` webhook, which only posts to shared spaces). Caveats learned the hard way: a human+account **cannot send a Chat card** (bot-only) and **`driveDataRef` attachments silently drop** — so+upload the PNG to Drive (`api --upload-file`, `--content-type image/png`), share it anyone-with-link+reader, and DM the **Drive link** as text (durable, unlike the container proxy URL which dies when+the container sleeps).++---++## 4. The 3D model / animated composite (`<MPN>.glb` / `<MPN>.insertion.glb`)++The centrepiece of a characterization page: the component drops onto its own footprint with a smooth+insert animation and a Layers toggle. See `scripts/build_composite_led.py` (LED, 3 materials + light)+and `scripts/build_composite_cap.py` (cap, 2 materials) for full worked builders. Key facts:++- **All metres, Z-up, 1:1 scale** (matches the wiki viewer + `machinecontactmedium`).+- **Node names the viewer recognises as Layers:** `fr4_board`, `pad_top`, `silk`, `solder_top`, plus+ `<MPN>` (the part). Board/pads/solder/silk are built from the part's `.kicad_mod`.+- **Insert animation** = translation channel on the `<MPN>` node, LINEAR, keyframes `[0, 1.2, 3.0,+ 4.2, 6.0]` s, Z `[0, 0, LIFT, LIFT, 0]`. **LIFT = 3 × the component's measured height**+ (`z.max − z.min` from geometry) — auto-scales per part.+- **Layers menu = FIXED vocabulary.** The shared viewer only turns a node into a toggle if its name+ is in a hardcoded map (`fr4_board, pad_top, pad_bottom, solder_top, solder_bottom, paste_top,+ paste_bottom, silk, silk_top, silk_bottom, barrel, pin1_marker`). Custom nodes (`LED_lit`, a FOV+ cone) and the part body do **not** appear — no `extras` escape hatch (only `extras.tooltip` is+ read). Custom toggles need the viewer owner (**Colby**) to add a key. Design GLBs to **degrade+ gracefully** when the toggle doesn't exist (e.g. the LED renders lit).+- **Real lights:** embed via `KHR_lights_punctual`. At mm scale, point-light intensity must be tiny+ (~4e-5) — inverse-square blows the board white at 0.3. Parent the light to `<MPN>` so it rides the+ animation. Red light on a green FR4 board reads warm/orange (green absorbs red — physics).+- **Emissive brightness:** boost with `KHR_materials_emissive_strength`.+- **Side embossing (part number/value):** cadquery boolean-cut the text into the STEP; auto-fit the+ font to the measured width×height taper so the whole string fits off the terminations.+- **Colouring a re-tessellated (embossed) mesh:** transfer material per-triangle by **densified+ nearest-neighbour** from the original colour GLB (a plane split only works for a clean 2-material+ boundary; 3-material parts need densified NN or you get zigzag artifacts).+- **Translucent overlays** (FOV cone, keep-out): build in world coords as their own top-level node,+ double-sided `BLEND` material, added to the insert animation's translation channel. Drive+ dimensions from a datasheet spec. Not in the fixed Layers vocabulary → renders always-on until+ Colby adds a toggle.+- **Height correction:** apply a node `scale=[1,1,h_target/h_model]` to `<MPN>` (and any glow node)+ to match a datasheet height — avoids re-plumbing the emboss/NN pipeline.++---++## 5. The interactive 3D viewer — the model somewhat *replaces* the datasheet++The single most valuable thing on a **single-component** page. The idea: a person should be able to+learn the part from the 3D viewer without opening the PDF. That only works if **every+datasheet-accurate fact is baked into the model and its tooltips** — the body dims, the pad/land+pattern, the optical cone, the tape & reel, the electricals — each either measured live off the+geometry or shown as a datasheet-cited row. If a number isn't in the model or a tooltip, it isn't in+the viewer, so put it there (§4 builds the geometry; the tooltips below carry the rest).++> **Both paths use Timeline, but they mean different things** (this supersedes an earlier note that+> said Timeline was component-only):+> - **Component (Path A) Timeline** = the *part's* visual datasheet story — power on → optical cone →+> lift → solder reflow → tape & reel. Every beat is datasheet-backed. This is what the `viewer-config.json`+> captions/tooltips below describe.+> - **Board/molecule (Path B) Timeline** = the *author's presentation of the board* — a walkthrough of+> its functional sections the user defines (power: ESD → fuse → LDO; user input: buttons; …). It's a+> narrative, not a fixed lifecycle. It also has **no tape&reel / pick-and-place** (a board isn't reeled).+> Its Static mode is components (and pre-populated molecules) dropping into place, choreographed by the+> author.++An interactive viewer (`<MPN>-viewer.html`) built on **Colby's shipped bundle** (`window.Adom3DViewer`+/ `adom-3d-viewer.min.js`, already in the page repo). Our logic is all host-page code on top of his+**unmodified** bundle — so it's purely additive and could be offered back to Colby. The full worked+reference is the `adom-basic-part-page-upgrade` skill (`assets/viewer-template.html`).++### 5.0 Assembling the single-page README (the gold-standard build)++The whole page is one `README.html` = the datasheet content with the viewer as a full-page `srcdoc`+at the top. To build (or rebuild) it:++1. **Start from the characterization content** (the spec cards / tables / charts / calculator). If a+ standalone `<MPN>.html` exists, its body is the base; then **delete `<MPN>.html`** (one canonical+ page). If not, author the content directly.+2. **Embed the timeline viewer as a full-bleed `srcdoc`** at the top (§5a below). Full-width (break+ out of the text column), viewport-tall.+3. **Convert every nested `src=` iframe** — they are sandbox-blocked (§8k): the 3D viewer → the+ `srcdoc` viewer; symbol/footprint viewers → inline **`ct/` SVG `<img>`s**; any molecule/board+ viewer → a link.+4. **Absolute-URL everything the srcdoc fetches** — the bundle, the GLB, `viewer-config.json`, and any+ `<img>` — to `https://wiki.adom.inc/blob/component/<slug>/…` (relative 404s in the readme sandbox).+5. **Fix stale URLs** — old pages often reference a dead host (`wiki-ufypy5dpx93o.adom.cloud/static/+ libraries/…`); rewrite to the current blob host.+6. **Add the self-sizing script** (§8k-0b): size the viewer to `screen.availHeight − ~200`, then+ `parent.postMessage({type:"readme-height", height: document.documentElement.scrollHeight}, "*")` on+ load/resize so the readme-frame grows to fit — no box-in-box scrollbar.+7. **Push together:** `README.html` + `viewer-config.json` + `screenshots/hero.png`. Then `repo rm`+ the retired `<MPN>.html` / `-symview.html` / `-fpview.html`.++Preview by mirroring the wiki's readme-frame + resize handler locally and loading through the+container proxy (headless puppeteer in the container reaches `127.0.0.1`; pup can't). Verify the+frame grows and the viewer renders before pushing.++### 5a. Timeline mode + the config-driven text (viewer-cli)++> **The Timeline viewer is the PRIMARY, canonical viewer — and it is under active development.**+> Not the old Static/PnP-only one. It lives in a work dir (`/home/adom/project/in-s42atr-work/…` for+> in-s42atr). **Pull it FRESH before every embed/push** — the copy on the wiki goes stale the moment+> it's edited. Never re-embed a cached copy. Regeneration is mechanical (steps 4→7 above); the viewer+> already ships the sandbox storage shim + bundle fetch-inject, so no other adaptation is needed.++The viewer has three modes via a segmented control: **Timeline** (a ~56 s narrated explainer reel —+chapters: the part → powered on → viewing angle → lift off → solder → tape & reel → rest), **Static**+(inspect the seated part), and **Pick & Place** (a nozzle lifts the part from a datasheet-exact+carrier tape and seats it). Every scripted camera move, caption, and tooltip is **data**, not code:++- **`viewer-config.json`** is the editable source of truth for the Timeline **captions** (the+ data-point cards + `t0/t1` timing = when each appears), the **hover tooltips**, the **chapter+ marks**, and the swappable **tape/nozzle** GLBs. The viewer merges it over built-in defaults, so it+ works standalone but every bit of text is authorable.+- **`./viewer-cli`** authors it (adom-cli conventions — `OK:/ERROR:/Hint:` + `--json`):+ `caption list|set|add|rm`, `tooltip list|set|add|rm|enable|disable`, `chapter list|set`,+ `assets set-tape|set-nozzle`, `verify` (headless load + config⇄viewer check), `doctor`. It+ validates timing (`t0<t1`) and validates a swapped GLB against the loader (rejects Draco / external+ buffers, warns on node transforms, reports the bbox).+- **The datasheet-vs-measured rule (non-negotiable).** A tooltip's rows are either **datasheet+ rows** — editable via `viewer-cli tooltip set --row` — or **measured rows** computed live from the+ model geometry, which are **never** edited. Every stated spec stays datasheet-cited; every+ measurement stays honest. `tooltip list` tags which tooltips also append measured rows. Do NOT add+ a way to hand-type a measured value.++### 5b. Load-sequence gotchas (building the host page on Colby's bundle)++- **Storage shim BEFORE the bundle loads.** Wiki blobs render sandboxed (no `allow-same-origin`) →+ `localStorage`/`sessionStorage` throw on *access* → Colby's `SceneBuilder` aborts (no lights/IBL/+ shadows/skybox). Shim both with no-ops first.+- **Fetch-inject the bundle** (don't `<script src>` it): blob `.js` is `application/octet-stream ++ nosniff` → refused as a script src. `fetch().text()` → inline `<script>`.+- **Null the model's `rotationQuaternion`** after load: glTF sets a quaternion that overrides the+ Euler `rotation.z` we animate.+- **Harvest classes not on the bundle's `B`:** `V.BABYLON` exposes only `MeshBuilder,+ StandardMaterial, Vector3, Color3, DynamicTexture`; get others from live instances' `.constructor`.+ Notably **`Matrix` is absent** and `Vector3.Project` needs one (any DOM label pinned over the 3D+ scene) — harvest it as `const Matrix = scene.getTransformMatrix().constructor`, and wrap the+ projection in try/catch so a bad frame can't kill the render loop.+- **Camera:** `frameModel()` frames the 5000-unit skybox (mm part → sub-pixel). Run it for its light/+ ground setup, then set an explicit mm-scale camera (`cam.target.copyFromFloats(...)`, `cam.radius`+ ~0.006 static / ~0.026 P&P).+- **Verify render** with `gl.readPixels` across a row after an explicit `scene.render()` — pup+ screenshots read blank (no `preserveDrawingBuffer`). Drive via `adom-desktop` pup against the+ container proxy URL (`$VSCODE_PROXY_URI`; `127.0.0.1` is refused — pup runs on the user's machine).+- **Verify a TIME-BASED viewer by SEEKING, never by waiting.** Headless swiftshader renders a heavy+ scene (a board is ~400k faces) at **well under 1 fps**, so "wait 10 s then screenshot" samples+ `t ≈ 0` and every animation looks broken when it isn't — an invitation to "fix" working code.+ Give the viewer a debug handle (`window.__dbg` with a `t` setter that also resets caption state,+ `setMode`, `pause`, and a `snap()` that jumps the eased camera straight to its goal), then drive+ it: set mode → pause → seek `t` → wait 2 frames → snap → screenshot. Sample the moments that+ matter (mid-drop, each chapter, end state) in ONE browser session. On a real GPU (the user's+ webview) the same page runs at full speed — headless slowness is a harness artifact, not a bug.+- **Match Colby's ground/sky** by inspecting his LIVE native scene (the vendored bundle is older):+ `clearColor` `#2a3340`, `environmentIntensity` 1.0, disable `/^Background/` meshes (no skybox),+ ground = a `groundFadeTex` radial-fade circle at alpha 0.2. Re-apply after every re-frame AND in+ the Ground toggle handler (`setGroundVisible` rebuilds the ground opaque).++Embedding the viewer on the page (§8k) is the other half — README.html + srcdoc for the landing page,+an `<iframe>` hero section for the characterization page.++**Bake the datasheet into the 3D model (§4 + §5 checklist):** body dims → the composite geometry+(height-corrected to the datasheet); land pattern → pads built from the `.kicad_mod`; optical cone →+the FOV overlay at the datasheet 2θ½; glow colour → the dominant wavelength λD; tape & reel → the+datasheet packing table; electricals (VF, IV, λD/λP) → tooltip datasheet rows. When all of that is in+the model + tooltips, the viewer stands in for the datasheet for everyday reference.++### 5c. Path B build pipeline — board STEP → tagged, viewer-ready GLB++Worked end-to-end on the Feeder Reader (130×50 mm, 4-layer, 143 footprints, 303 solids). Every+number below was measured on that build. The runnable step is+**`scripts/bake_board_glb.py`** (its docstring repeats this section); the viewer that consumes the+output is **`scripts/board-viewer-template.html`**.++**1. STEP → GLB.** Two blessed converters, chosen by consumer:+- **`step2glb`** (the Adom skill/CLI; OCCT XCAF on a shared service container). Run+ `step2glb health` FIRST — the CLI does nothing locally, and fail fast if the service is down.+ A 32 MB board is a gzip upload + async job + polling: ~2.5 min wall, so give Bash ≥5 min.+ Output is 44% smaller (KHR_mesh_quantization, in `extensionsRequired`) — **fine for+ three.js/Babylon/Colby's viewer, but trimesh/pygltflib misread quantized positions by 32767×**.+ If it must feed a trimesh pipeline, `gltf-transform dequantize` first. Also ~19k primitives+ (one per B-rep face region) vs cascadio's ~300 — merge if draw calls matter.+- **`cascadio`** (pip-installable OCCT wheel, runs locally in a venv, no service): plain float32,+ ~300 primitives — **use this for the bake step below** (it's trimesh-based).+Both produce the SAME scene graph: root = board name, per-component nodes named by **refdes**,+meshes named by footprint/3D-model name, board layers as `<Board>_PCB/_copper/_soldermask/+_silkscreen`. Units are **metres**, and Y is **negated** vs the `.kicad_pcb`+(`glb_y = −pcb_y/1000`) — get this wrong and the board mirrors silently.++**2. Tag solids by REFDES from the node hierarchy — not by position.** KiCad's STEP export+names each component's assembly node with its refdes; geometry-bearing leaf nodes are OCCT tags+(`=>[0:1:1:41]`), so walk UP the parents to the first name matching a refdes that exists in the+`.kicad_pcb` (297/297 solids resolved on the reference board). Do NOT use nearest-centroid as+the primary method — on the same board it provably mistagged 4/297: a big IC's pin-1 dimple+solid sits closer to a neighbouring 0402 than to its own footprint origin, and stale geometry+(see 3) lands wherever the part was when the STEP was exported. Name the baked meshes+`section|REFDES|i` — that one convention is what makes isolate/dim, per-section cameras,+drop-in choreography, and hover tooltips possible downstream.++**3. Cross-check positions → STALE-GEOMETRY report.** For each refdes, compare its solids'+centroid against the footprint position in the `.kicad_pcb`. A distance beyond ~2 mm means the+board was edited AFTER the STEP export (on the reference board D15 had moved 7.3 mm). Keep the+refdes tag (it's correct), but flag it in the coverage report and SAY IT ON THE PAGE — the model+shows that part where it used to be. The fix is re-exporting the STEP, not the pipeline.++**4. Sections come from the SCHEMATIC by default.** The `.kicad_pcb` carries+`(path "/<sheet-uuid>/<symbol-uuid>")` per footprint and the ROOT `.kicad_sch` declares each+sub-sheet's uuid + Sheetname — so **sheet membership is derivable from files you already have**+(the sub-sheet .kicad_sch files are not needed). Use sheet-derived sections as the automatic+default; an author-supplied `blocks.json` (finer groupings, e.g. splitting "MCU sheet" into+mcu/usb/comms) overrides it. This is the answer to "how does the author communicate sections":+they usually don't have to — the schematic already says.++**5. Bake node transforms, recenter, verify.** KiCad places every solid purely by node+transform, and the Adom viewer bundle does NOT apply node transforms — unbaked, the entire BOM+renders collapsed at the origin. Bake world matrices into vertex data, recentre X/Y on the+board-outline centre (keep Z), and **assert** every exported node matrix is identity.++**6. De-fight the layers (the "layers clip each other" shimmer).** Measured root causes on the+reference board, all fixed at bake + one viewer-side line:+- The exporter emits mask/silk as **zero-thickness sheets** 10–15 µm off the copper, and+ components seat 10 µm above the top silk. The bundle's camera sets `minZ = radius/1000`,+ making one 24-bit depth step ≈ 10 µm at board-viewing distance — so those gaps are ~1 depth+ step: guaranteed z-fighting.+- **Bake offsets** (defaults in `bake_board_glb.py`, preserving silk>mask>copper order): top+ MASK +15 µm, top SILK +15 µm, components +30 µm (skip parts that wrap the board edge, e.g. a+ USB shell — detected by z-extent below board mid); mirrored negative on the bottom sheets.+- **PCB material must be OPAQUE.** Exporters emit the FR-4 solid at alpha 0.98 BLEND; it+ re-blends over the *exactly coplanar* buried copper faces every frame — the worst clip of+ all, and unfixable by offsets (one copper mesh carries both slabs). Force baseColor alpha 1 ++ `alphaMode OPAQUE` at bake.+- **Viewer-side:** `cam.minZ = max(cam.radius/100, 2e-4)` per frame (≈1 µm depth steps; near+ plane still 0.3 mm out at closest zoom). In the template already.++**7. Coverage report → the page.** Real parts with NO solid (they are simply invisible in the+viewer — on the reference board 11 of them, incl. the DIP switch and the crystal) vs+legitimately-bodiless footprints (solder pads, mounting holes, jumpers), plus DNP refs and the+stale-geometry list. `bake_board_glb.py --report` emits it; the README build should render this+section FROM the report (provenance rule §7B — never hand-type it; a hand-typed copy of this+list was off by one within a day).++**8. Verify by seeking** (§5b) — the board runs at <1 fps in headless swiftshader; screenshot by+driving the debug handle, not by waiting.++---++## 6. ct/ thumbnail bundle (standard on every page)++```bash+# stage the part's STEP into the chip-fetcher library, then:+adom-chip-thumbnailer once <MPN> # 3D icons + outlines + manifest+adom-symbol render --file <MPN>.kicad_sym --out ct/<MPN>-symbol.svg+adom-footprint render --file <MPN>.kicad_mod --out ct/<MPN>-footprint.svg+```++Put them in `ct/`, add a README "Thumbnails" section with a **provenance** blockquote (who/what+produced each artifact), and — for a basic part — the page hero can be `ct/<MPN>-3d-iso-icon.png`.+But a proper **Hero Component Studio** hero (§3) beats the plain 3D icon for the card.++**Boards (Path B) have no schematic symbol** — the `ct/` equivalent is a pair of **board maps**:+top + bottom SVG renders straight from the `.kicad_pcb` (outline, copper, silkscreen, vias, pads+coloured by functional section). Two shipped scripts, stdlib-only, no KiCad needed:+```bash+python3 scripts/kicad_board_geom.py <board.kicad_pcb> geom.json # parse (cached)+python3 scripts/kicad_board_map.py geom.json F ct/<slug>-top.svg blocks.json+python3 scripts/kicad_board_map.py geom.json B ct/<slug>-bottom.svg blocks.json+```++---++## 7. Datasheet-accuracy audit — for COMPONENT pages, this is non-negotiable++**MANDATE: every component page MUST include its datasheet, stored in the page repo.** Push the PDF+alongside the page (`<MPN>-datasheet.pdf`, or the manufacturer's filename) — it is the source of truth+the page is verified against and the target every citation links to. No datasheet in the repo → the+page is not publishable. (This is an Adom standard: every component page has a datasheet.)++**Every number and every curve must be traceable to a specific place in that datasheet, and cited so a+reader can verify it.** Not "roughly right" — *exactly* right, with the page / table / figure named+next to it. The page stands in for the datasheet, so it must be at least as trustworthy: if someone+can't check a value against the datasheet in seconds, the page has failed. This applies to the merged+datasheet content, the viewer tooltips (§5a), the Timeline captions, and every rendered chart. If a+value isn't in the datasheet, it does **not** appear — flag the gap, never estimate. (Boards/molecules,+Path B, carry no cited datasheet — this section is Path-A only.)++### 7a. Citation format — cite to a page in the stored datasheet++Every citation names the **datasheet revision + the specific page** (and table/figure where useful),+and **links into the stored PDF at that page**: `<a href="<MPN>-datasheet.pdf#page=3">p.3</a>`. The+revision matters — **page numbers move between datasheet revisions**, so the citation is `IN-S42AT V1.1+· p.3`, never a bare "p.3". This is the same `src` vocabulary the viewer tooltips already use+(`Inolux IN-S42AT V1.1 · p.3 electro-optical table`), so the whole page cites one way.++**Granularity — PER-ROW `src` (the chosen convention).** Every data row carries its own citation: a+small muted, clickable `src` naming the datasheet revision + page (and table/figure), deep-linked into+the stored PDF — exactly like a viewer tooltip row's `src`. This is the most informative and the most+verifiable: a reader can check *any single value* against its exact datasheet location without+guessing which section-level citation covers it. Yes it repeats when a table is all one page — that's+the point; keep it muted (small, dim text in a trailing `src` cell/line) so it's present but quiet.+Charts cite the figure they were redrawn from (`p.5 fig.6`) in the chart footer. Render the `src` as+`IN-S42AT V1.1 · p.3` linking to `<MPN>-datasheet.pdf#page=3`. (Section-only / footnote styles were+considered and rejected: coarser or a scroll-hunt to verify.)++### 7b. RULE — datasheet changes ⇒ citations change; show the datasheet's date+revision on the page++The datasheet is versioned. **Whenever the datasheet is updated (new revision) OR you change a value,+re-run the audit and update the citations** — page numbers, table names, and even values shift between+revisions, so a stale `p.3` silently points at the wrong place. On any page update: confirm the stored+PDF is the revision the citations name; if the revision changed, re-verify **every** cited value and+fix the page references. Bump the datasheet revision in every `src` string when you swap the PDF.++**The page MUST show, near the top, which datasheet it's built from — revision AND date.** A short+line under the title, e.g. *"Datasheet: IN-S42AT V1.1 · 25 Apr 2017"* (link it to the stored PDF).+This lets an engineer see at a glance whether the datasheet is current and go pull a newer one if it's+stale. The date + revision usually live in the datasheet's **page footer** (Inolux: "April 25, 2017"+on every page). Both is ideal; date is the minimum.++### 7c. How to READ a datasheet (methodology — from ds2sf / the ds-extract parser)++Getting the numbers right is the hard part. The distilled method (see `ds2sf`, the `datasheet-parser`+skill, and `process-datasheets`):++1. **Find the official PDF.** Prefer the manufacturer's own site over aggregators (ti.com,+ bosch-sensortec.com, st.com, nxp.com, microchip.com, analog.com, inolux-corp.com). `WebSearch` if+ you don't have a URL. Store it in the repo (§7 mandate) and note its revision + date (footer).+2. **`pdftotext -layout` first — as a MAP, not the truth.** It gives you a rough index of what's on+ each page (which page has the electrical table, the curves, the packing figure). Its reading order,+ tables, and figures are mangled — expected. **When text and the rendered image disagree, trust the+ image.**+3. **Render pages and READ THE IMAGE.** `pdftoppm -png -r 300 <ds.pdf> <out>` → Claude vision reads+ each page accurately. **Downscale before Reading** — a 300-dpi page is ~2480×3508 px and the Read+ tool caps ~2000 px/side in multi-image turns; make a ≤1500-px-long-edge mirror to read from, keep+ the full-res original for figure crops.+4. **Tables:** reconstruct with correct alignment; watch **min / typ / max** columns, **units**, and+ **footnote markers** (a value is often "@ 20 mA" or "note 3"). Cite the row's page.+5. **Figures are where the machine-unreadable data hides.** The **packing / tape & reel** table and the+ **dimension drawings** are usually *images* (`pdftotext` returns nothing) — rasterize the page and+ read the figure directly (in-s42at: p.9). Same for any **curve** — crop the figure and **redraw the+ chart to the actual curve**, never to invented points (§7 "charts redrawn").+6. **Cross-check against standards**, not just the sheet: **EIA-481 / IEC 60286-3** for carrier tape+ (§7 tape validation), **IPC-7351** for land patterns, package-family norms for body dims. A datasheet+ figure transcribed by eye + a standard agreeing is far stronger than either alone.+7. **Let tools do the deterministic part.** `ds2sf extract <MPN>` reads the datasheet → symbol ++ footprint + **provenance JSON** (each pad/pin cites where it came from); `ds2sf normalize` resolves+ the package string against the KiCad standard library. The `ds-extract` service (docling + pdfplumber+ + PyMuPDF, confidence-routed) does bulk table/figure extraction and only escalates ambiguous crops to+ vision — reuse it rather than reading 14 pages by hand when you can.+8. **Every extracted number keeps its source** all the way to the page's `src` citation (§7a) — the+ provenance from ds2sf and the page/table you read it from are the citation.++```bash+# 1. render the page's claims to plain text+python3 -c "import re,html;t=open('<MPN>.html').read();t=re.sub(r'<(script|style).*?</\\1>','',t,flags=re.S);print(html.unescape(re.sub(r'<[^>]+>',' ',t)))"+# 2. datasheet text + FIGURES (charts/dims are images — render them)+pdftotext -layout DS.pdf - # tables (Vf, wavelengths, ratings)+pdftoppm -png -r 300 -f <pg> -l <pg> -x <X> -y <Y> -W <W> -H <H> DS.pdf /tmp/crop # zoom a figure+# (ImageMagick is NOT installed — crop with pdftoppm's -x -y -W -H at high DPI, then Read the PNG)+# 3. compare EACH value + EACH chart curve; cite the datasheet page for every finding+```++**Charts must be redrawn to the datasheet, not just re-captioned** — an SVG curve path can plot the+wrong numbers under a corrected caption. **Common LED-page discrepancies found in the wild:**+land-pattern "center-to-center" that's actually the edge-to-edge gap (c-c = pad_width + gap);+brightness-vs-current/temperature curves drawn to invented numbers; FWHM stated when the datasheet's+Δλ is blank; footprint pad W/H swapped; 3D model height = generic KiCad body (0.5 mm) vs datasheet+(0.45 mm).++**Carrier-tape / reel dims (for the interactive viewer's tape):** on many datasheets the packing+table is an **image**, so `pdftotext` can't pull it and the numbers get transcribed from the figure+— treat those as *not yet validated* and say so. Cross-check against **EIA-481 / IEC 60286-3** (8 mm+tape is standardised: W 8.0, Po 4.0, Do 1.5, E 1.75, F 3.5, T 0.2–0.4; only Ao/Bo/Ko pocket + P1+pitch are part-specific), distributor packaging data (`adom-mouser`/`adom-digikey`/+`adom-parts-search`), OCR (tesseract), or the manufacturer's packing spec.++---++## 7B. Provenance for BOARD pages (Path B) — the analogue of §7++A board carries no cited datasheet — but that does NOT mean a board page needs no provenance. It+means the provenance comes from somewhere else: **the design files.** The rule (proven on the+feeder-reader build):++1. **Generate every table from the design files — never hand-type them.** The BOM (grouped by+ value+footprint, designators listed), the board outline/stack-up/layer count, the+ footprint→section membership, the board maps, and the 3D model all derive mechanically from+ `.kicad_pcb` / `.kicad_sch` / the STEP export. A generated page cannot drift from the design;+ a hand-typed one already has.+2. **Honour DNP.** KiCad marks do-not-populate as `(attr … dnp)` on the footprint (NOT a+ `(dnp yes)` node — grep for the attr). DNP parts change the effective BOM and usually encode+ intent (bus termination fitted only at the ends, etc.); tag them visibly in the BOM and say+ what they're for. A generated BOM that ignores DNP is wrong.+3. **Label every claim's provenance class, on the page.** Three classes:+ - **Generated** — mechanically derived from the design files (the tables above).+ - **Author-asserted** — design intent from the board's author: poll rates, baud rates, system+ topology, scope notes. True because the author says so, not because a file proves it.+ - **Illustrative** — anything shown to demonstrate behaviour that isn't captured data (example+ IDs in a scan animation, sample bus traffic). Must be labelled as such wherever it appears.+ The page gets a dedicated "how this page was built, and what is *not* verified" section making+ the split explicit — including that part-level values are **as-drawn from the schematic, not+ verified against each part's datasheet** (that's what the parts' own Path A pages are for).+4. **Print the 3D coverage report** (see the Path B pipeline, §5c): which real parts have no solid+ in the STEP export, vs footprints that are legitimately bodiless.++---++## 8. Wiki push/pull gotchas — ADD TO THIS when you hit new ones++**8a. Owner is not always `adom`.** Basic-parts pages are under `aravk/` (e.g. `aravk/in-s42atr`).+A `adom/<slug>` stats check 404s even though the page exists. Confirm via `discover search` first.++**8b. The 3D viewer loads `<slug>.glb` BY NAME.** Hardcoded as `/blob/component/<slug>/<MPN>.glb`+inside the `/viewer/3d/component/<slug>` iframe; it **ignores** `page.json`+`component.model_3d_path`. To change the 3D model, make the canonical `<MPN>.glb` itself the new+content (keep an identical `<MPN>.insertion.glb` sibling).++**8c. Assets are CDN/browser-cached by URL.** After overwriting `<MPN>.glb`, bust the page HTML with+`?v=$(date +%s)` in a fresh pup session; confirm the new bytes with a direct `curl` of the blob URL.++**8d. Same-origin iframe control.** Page and its `/viewer/3d/...` iframe are both on `wiki.adom.inc`,+so a parent `browser_eval` can reach in: `document.querySelector("iframe").contentWindow.BABYLON...`+— use it to pause the animation at a frame for a clean verification screenshot.++**8e. `page hero` takes no `--changelog`** (unlike `repo push`). Passing it errors.++**8f. Derived viewers embed geometry — regenerate them.** `<MPN>-fpview.html` / `-symview.html` bake+in pad/pin geometry; changing the `.kicad_mod` leaves them stale until regenerated (§9). Same for the+`ct/` footprint SVG.++**8g. `http.server` cleanup footgun.** A `pkill -f "http.server <port>"` compound line can SIGKILL+the shell (exit 144). Start preview servers with `setsid python3 -m http.server <port> --directory+<dir> --bind 0.0.0.0 >log 2>&1 </dev/null &` and kill by real PID (`lsof -ti:<port>` / `fuser+<port>/tcp`), never a broad `pkill -f` (it also matches VS Code Server → kills the container).++**8h. Verifying a served asset needs auth — private pages 403 unauthenticated.** Send the bearer+(`~/.config/adom-wiki/token`): `-H "Authorization: Bearer $(cat ~/.config/adom-wiki/token)"`. The+authoritative "did it land" is `adom-wiki repo log` (your hash at HEAD) + matching served byte count.++**8i. Reaching a container preview from desktop Chrome (pup).** pup runs on the user's desktop, so it+can't reach the container's `127.0.0.1`. Bind the preview server to `0.0.0.0` and open the proxied+URL from `$VSCODE_PROXY_URI` (`https://<host>/proxy/<port>/…`), not `localhost`.++**8j. `adom-wiki repo clone` is a plain file checkout, NOT a git repo.** No `.git`; `git show+HEAD:<file>` returns nothing (a snapshot built that way is 0 bytes). Snapshot by **copying the file+from the fresh clone BEFORE you edit it**.++**8k. Embedding a live interactive viewer in a page.** On-page `<canvas>`/iframe viewers load assets+blob-relative (`/blob/component/<slug>/…`). To embed a self-contained viewer, push the host HTML ++any bundle it needs into the page repo and reference them blob-relative. Sub-points:+- **8k-i. Blob `.js` won't run via `<script src>`** (`octet-stream + nosniff`). Load it via+ `fetch().text()` → inline `<script>` (`s.textContent = code; document.head.appendChild(s)`).+- **8k-0. `README.md` STRIPS raw `<iframe>`; push a `README.html` to embed on the page.** The wiki+ renders `README.md` as *sanitized* markdown (keeps its native `/viewer/3d|symbol|footprint` embeds,+ removes user `<iframe>`s). A pushed `README.html` is auto-detected+ (`page.readme_variants_json.bareHtml`), **wins over `README.md`**, and serves at+ `/readme/<owner>/component/<slug>?variant=public` inside a sandboxed iframe (`#readme-frame`,+ `sandbox="allow-scripts allow-downloads"`).+- **8k-0b. The readme-frame RESIZES — you can make it fill the page.** It ships `min-height:600px`+ with no height set (so it *defaults* to 600px), but the parent (`app.js`) listens for a message+ from the README and grows it: `postMessage({ type:"readme-height", height:<px> }, "*")` →+ `frame.style.minHeight="0"; frame.style.height = clamp(height, 120, 16000)`. So a README that posts+ its own `document.documentElement.scrollHeight` fits exactly (no box-in-box scrollbar), and a viewer+ sized near the viewport reads as a **seamless full-page** part of the wiki. Height caveat: the+ sandbox (no `allow-same-origin`) can't read the parent's viewport, so proxy it from+ `screen.availHeight` minus chrome (~200px). Full-bleed width: break the viewer out of your centered+ text column. **This corrects an earlier note that called the frame "fixed 600px, no auto-resize" —+ it is not.** Verified live-shape against `aravk/in-s42atr`.+ Tradeoff still stands: `README.md` text is native/full-width but can't hold the viewer; `README.html`+ puts ALL its content (text + viewer) inside the readme-frame — no mixing native markdown with it.+- **8k-ii. Wiki blobs render SANDBOXED (no `allow-same-origin`)** → `localStorage`/`sessionStorage`+ throw on access → the shared viewer's `SceneBuilder` aborts (dark, unlit). Shim both storages with+ no-ops before loading the bundle.+- **8k-iii. `frameModel()` mis-frames the embed → "blank."** It frames the 5000-unit skybox (camera+ ~2500 m from a mm part). Set the camera explicitly to mm scale after load; verify with+ `gl.readPixels` after a `scene.render()` with the render loop stopped (no `preserveDrawingBuffer`).+- **8k-iv. Embedding the viewer IN the README (`README.html` + `srcdoc`).** The readme-frame is+ sandboxed with CSP `sandbox allow-scripts allow-downloads; script-src 'unsafe-inline' https:;+ connect-src 'self' data:; frame-src https:; base-uri 'none'`. So: a nested `<iframe src="/blob/…">`+ is **blocked** (no `allow-same-origin`) — embed via **`<iframe srcdoc="…">`** with the viewer HTML+ inlined; **relative** asset paths 404 (they resolve against `/readme/…`) — use **absolute**+ `https://wiki.adom.inc/blob/component/<slug>/<file>` (`'self'` = `wiki.adom.inc`, blobs serve CORS);+ srcdoc-escape the HTML `.replace('&','&').replace('"','"')` (that order). The storage shim+ still runs inside the srcdoc child. Preview by mirroring the byte-exact CSP locally, loaded via the+ container proxy; bridge the child's render status out with `postMessage` (separate opaque origin).+ Verified live on `aravk/in-s42atr`.+- **8k-v. CORS: the srcdoc viewer is an OPAQUE ORIGIN — every fetch it makes is cross-origin.**+ Because the readme-frame sandbox has no `allow-same-origin`, the srcdoc document has no origin at+ all, so even a fetch to the very host serving the page is cross-origin and **requires+ `Access-Control-Allow-Origin` on the response**. The real blob host sends it; a plain local+ preview server (python `http.server`, `npx serve`) does NOT — the bundle fetch dies with+ `net::ERR_FAILED` and the viewer never boots, which looks exactly like a broken viewer. Any local+ preview server must send `Access-Control-Allow-Origin: *` (the shipped+ `scripts/preview_readme/serve.py` does).++**8k-vi. Publishing an APP/SKILL package: the hero gate (learned publishing this very skill).**+Component pages take any hero image, but **new app/skill pages** hard-reject at publish+(`HERO_STUDIO_REQUIRED`) unless BOTH of these hold:+- The manifest `hero` field is the **image form** `{"type":"image","path":"docs/hero.png"}`. The+ old billboard descriptor `{headline, subhead, screenshot}` is what actually trips+ "the auto-composed billboard hero is retired" — the server reads the SHAPE of the manifest+ field, so no PNG will ever pass while the manifest still asks for a billboard. (Three publish+ attempts went down this hole while the error message pointed at the image.)+- The PNG itself is generated through **Hero Studio's pose gate by a human**:+ `hero-studio pose <owner>/<slug> --title … --brief …` blocks until the human ratifies the+ checklist and clicks Generate; never `POST /generate` yourself. The studio stamps provenance+ into the PNG. Posing aids (state POSTs, injecting a vitrine screenshot as a data URL) are fine;+ the CLICK must be human. If the studio webview looks frozen, check the tab's **proxy mode**+ (`adom-cli hydrogen webview set-proxy false --name …`) — proxy mode silently blocks page JS.++**8l. `WIKI_STRICT_AUTH`** rejects a push without a real author (`set-author`) + a changelog+(≥2 words / ≥10 chars, specific).++**8m. The hero's cache + which URL the page uses.** Served with `cache-control: max-age=86400`; the+page loads `/blob/component/<slug>/screenshots/hero.png` (not `/api/pages/...`). After a re-push,+verify the blob URL cache-busted; the viewer's browser needs a hard refresh. `page.hero_thumbnail` is+always null — one 16:10 file serves both header and card, so there's nothing else to regenerate.++**8n. `page hero --image` wants a REPO-RELATIVE path**, not a local file (a local path 404s+"No such file in the repo"). Push the file into the repo first, then set the hero to its repo path.+The verb also pins the hero to `screenshots/hero.png` regardless of the filename you pass, so put the+content there.++---++## 9. Regenerating derived viewers++When the `.kicad_mod` changes, regenerate the footprint viewer (Node ESM, gallia):++```bash+node -e 'import("/home/adom/gallia/viewer/kicad-footprint-viewer.js").then(async m=>{+ const html=await m.generateFootprintViewer("<dir>/<MPN>.kicad_mod","<MPN>",+ {manufacturer:"<mfr>",partName:"<MPN>",datasheetUrl:"<url>"});+ await (await import("fs/promises")).writeFile("<dir>/<MPN>-fpview.html",html);+})'+```+Renders via the KiCad service, or a local fallback SVG from the parsed footprint — either way it+reflects the corrected pads.++---++## 10. Environment / tools++- **cadquery** in a venv (system Python is externally-managed):+ `python3 -m venv venv && venv/bin/pip install cadquery pygltflib trimesh numpy`.+- **Non-uniform STEP scaling** (height fix) via OCP: `BRepBuilderAPI_GTransform` with+ `gp_GTrsf().SetVectorialPart(gp_Mat(1,0,0, 0,1,0, 0,0,s))`.+- **Do NOT `step2glb` a cadquery-cut STEP** — malformed GLB (accessors with no `bufferView`).+ Tessellate in cadquery (`shape.tessellate(tol, ang)`) instead.+- **Do NOT tessellate a raw imported STEP compound before a boolean** — segfaults. Measure the taper+ from the original colour GLB's vertices instead.+- CLIs used: `adom-wiki`, `hero-component-studio`, `adom-chip-thumbnailer`, `adom-symbol`,+ `adom-footprint`, `step2glb`, `adom-desktop` (pup preview), `adom-google` (share a render).++---++## 11. Reference scripts (in `scripts/`)++| file | what |+|---|---|+| `publish_wiki_page.py` | **The programmatic publish reference.** Stdlib-only wrapper around `adom-wiki`: auth → locate owner → clone → snapshot → push → verify, plus new-page publish. Start here. |+| `build_composite_led.py` | Full LED composite builder: emboss (auto-fit taper), densified-NN 3-material colour, red lens + `LED_lit` glow + `KHR_lights_punctual` light, insert animation, node Z-scale height correction. |+| `build_composite_cap.py` | Cap composite builder: plane-split 2-material colour, top+side emboss. Simpler start. |+| `audit_checklist.md` | The datasheet-accuracy audit checklist + common-discrepancy list. |++---++## Related skills++- **`hero-component-studio`** — the hero-image app (§3). The tool you actually drive to make the card.+- **`adom-basic-part-page-upgrade`** — the full interactive-viewer + tape/reel + hero treatment for+ basic parts (the deep §5 reference, with `assets/viewer-template.html`).+- **`adom-wiki-cli`** — the wiki CLI itself (every pillar/verb).+- **`adom-wiki-hero-image`** (`adom/adom-wiki-hero-image`) — the canonical hero spec (16:10,+ 1600×1000@2×, midnight theme, one-app-one-screenshot).+- **`adom-basic-parts`** — the basic-parts inventory + per-MPN slugs.++## Status — what's PROVEN vs still to build (read before trusting a section)++Be honest about maturity so nobody assumes a section is turnkey when it isn't.++**Proven end-to-end** (built and shipped live on `aravk/in-s42atr`):+- The full **COMPONENT (Path A)** page: merged datasheet content + cited tooltips, the single seamless+ full-page README, the full-page **Timeline viewer** embed, static symbol/footprint SVGs, the hero+ from Hero Component Studio, the readme-frame self-sizing, the whole wiki push/rm flow.++**Proven as a LOCAL mock** (built end-to-end on the **Feeder Reader** board — 130×50 mm, 4-layer,+143 footprints — viewed in the wiki-faithful preview harness; not yet pushed to the wiki):+- **The Path B pipeline (§5c):** STEP→GLB (step2glb service verified; cascadio for trimesh-bound+ bakes), refdes tagging from the node hierarchy (297/297), stale-geometry detection (caught a+ real 7.3 mm post-export move), sheet-derived sections, transform baking, layer de-fighting,+ coverage report. Runnable: `scripts/bake_board_glb.py`.+- **A board viewer** (`scripts/board-viewer-template.html`): the two-mode spec — **Assembly**+ (groupings drop in together while their captions explain them; scripted camera yields to the+ user for 5 s on input) and **Static** (free camera, hover tooltips, legend isolate,+ author-specified toggles like Power) — config-driven via `adom-board-viewer-config/0.2`+ (`blocks[]` + `modes.assembly` + `modes.static`, see §Path B).+- **Board maps** (`scripts/kicad_board_geom.py` + `kicad_board_map.py`) and the **preview+ harness** (`scripts/preview_readme/` — real sandbox flags + the readme-height handler + CORS).++**Still to build for Path B:**+- **A `board-viewer-cli`** — the config shape exists and is authorable as JSON, but the "never+ hand-edit, go through a CLI" rule has no CLI yet for board viewer configs.+- **Publishing an actual board page to the wiki** (the mock proved the content pipeline and the+ sandbox behaviour locally; the push itself is the standard §2 flow but hasn't been exercised+ for a board).+- **Board visual functions** (LEDs blinking, indicators). The LED-lighting method is referenced+ (Caleb's playbook) but not built into our tooling; the data-HUD path (§Path B) is the proven+ alternative for non-visual boards.++**Underspecified even for Path A** (decide + document a convention):+- ~~Citation FORMAT~~ **DECIDED (§7a):** cite to the datasheet revision + page, deep-linked into the+ stored PDF (`<MPN>-datasheet.pdf#page=N`); per-table by default, per-row where a row's source differs;+ charts cite their figure. The datasheet is now MANDATORY in the repo (§7), and datasheet changes must+ update citations (§7b). Still to do: apply this format to the in-s42atr merged content (it currently+ carries the values but not yet the per-row deep-links).+- **Non-emitter components** (resistors, MLCCs, inductors) — the emit/actuate visual path is LED-proven;+ passives get the viewer + tape/reel + symbol/footprint but no glow/cone. The passive path is less worked.+- **The preview harness** (readme-frame + resize handler mirror) is ad-hoc per session, not a shipped+ script. Worth turning into a reusable `preview-readme` tool.+- **Tape/reel dimensions:** VALIDATED for IN-S42ATR (read from datasheet p.9 figure at 220 dpi ++ cross-checked against EIA-481 — every value matches). The **other 10 LED tapes are still+ transcribed-not-verified**; validate each by rasterizing its datasheet p.9 the same way+ (`pdftoppm -png -r 220 -f 9 -l 9 <ds.pdf>` → read). See [[project_tape-dims-need-validation]].+- ~~The Timeline viewer + `viewer-cli` config are component-specific~~ **RESOLVED for the viewer+ side:** the board viewer template + config shape exist (§5c, §Path B); what remains is the+ `board-viewer-cli` (see "Still to build"). The original note for context: a board Timeline+ (functional-section narrative) needs a different config shape / authoring flow.++## Contributing++Hit a new wiki issue, a viewer quirk, or a better hero recipe? Add it to the right section (usually+§8 gotchas, §3 hero, or §4 composite), bump the version, and open a PR against+`adom/adom-hardware-component-publish`. Keep findings **specific and cited**.
docs/HERO.mdadded+1@@ -0,0 +1 @@+Put a 1200x630 `hero.png` in this folder. It is the billboard reused on the page header, the homepage, and the screensaver. Until it exists, `adom-wiki pkg lint` reports the hero as the one outstanding item.
docs/hero.pngadded⋯ 1 unchanged line ⋯
install.shadded+13@@ -0,0 +1,13 @@+#!/bin/sh+# adom-hardware-component-publish — install the skill (+ its runnable scripts) for this user.+set -e+# Adom convention: SYMLINK install targets back into the module dir, so edits propagate and+# reinstalls don't clobber.+DEST="$HOME/.claude/skills/adom-hardware-component-publish"+mkdir -p "$DEST"+ln -sfn "$PWD/SKILL.md" "$DEST/SKILL.md"+# the worked scripts the skill references (bake_board_glb, board maps, viewer template,+# preview harness, seek-verify example) — linked so §5c/§6 commands work as written+ln -sfn "$PWD/scripts" "$DEST/scripts"+echo "installed: adom-hardware-component-publish -> $DEST"+echo "entry point: SKILL.md (the publish lifecycle); scripts/ holds the runnable pieces"
package.jsonadded+65@@ -0,0 +1,65 @@+{+ "slug": "adom-hardware-component-publish",+ "title": "Publish a Hardware Component to the Adom Wiki",+ "type": "skill",+ "version": "0.8.0",+ "description": "The one-stop-shop for publishing a hardware component (or molecule/board) to the Adom Wiki. The whole lifecycle: page anatomy, the clone\u2192edit\u2192preview\u2192push loop and its hard rules, making a great hero image (Hero Component Studio \u2014 16:10, overlay-safe, datasheet-backed), the animated 3D composite, the interactive 3D viewer, ct thumbnails, the datasheet-accuracy audit, and every wiki push/pull gotcha we've hit. Now includes the worked Path B (board) pipeline: STEP-to-GLB, refdes tagging, layer de-fighting, two-mode board viewer (Assembly merged with explanation + free-camera Static) template, board maps, preview harness. A living, refinable skill \u2014 add gotchas via PR. Private, Adom-only.",+ "tags": [+ "skill",+ "wiki",+ "publish",+ "hardware",+ "component",+ "molecule",+ "hero-image",+ "3d-composite",+ "interactive-viewer",+ "datasheet",+ "adom",+ "reference"+ ],+ "dependencies": {},+ "scripts": {+ "install": "./install.sh",+ "uninstall": "./uninstall.sh"+ },+ "hero": {+ "type": "image",+ "path": "docs/hero.png"+ },+ "visibility": "private",+ "org": "adom",+ "sample_prompts": [+ "Publish a hardware component|Publish the wiki page for <MPN> (a <category>) end-to-end using adom-hardware-component-publish",+ "Make a great hero image|Render an overlay-safe 16:10 hero for <MPN>/<molecule> in Hero Component Studio and set it as the page hero",+ "Update an existing component page|Clone <owner>/<slug> fresh, fix <thing>, preview, snapshot, and push with a real changelog",+ "Build the 3D composite|Build the animated insertion.glb for <MPN> (part drops onto its footprint, Layers toggle)",+ "Audit a page against its datasheet|Compare the <MPN> characterization page to its datasheet and list discrepancies with page citations",+ "Add ct thumbnails|Generate the ct/ bundle (3D icons + symbol + footprint) for <MPN>"+ ],+ "discovery_triggers": [+ "publish component",+ "publish hardware",+ "publish to wiki",+ "component page",+ "molecule page",+ "board page",+ "wiki page",+ "hero image",+ "component thumbnail",+ "card art",+ "3d composite",+ "insertion.glb",+ "interactive viewer",+ "ct thumbnails",+ "datasheet audit",+ "wiki push",+ "wiki clone",+ "page hero",+ "set hero",+ "land pattern",+ "footprint viewer",+ "adom-hardware-component-publish"+ ],+ "discovery_pitch": "The one-stop-shop for putting a hardware component on the Adom Wiki and having it look right \u2014 the push loop, a great hero image, the 3D composite/viewer, and every gotcha, in one place."+}
scripts/audit_checklist.mdadded+45@@ -0,0 +1,45 @@+# Datasheet-accuracy audit checklist++A characterization page **is** a datasheet. Every value and every chart must trace+to a specific datasheet figure/table. **Cite the page number for every finding.**++## Procedure+1. Extract the page's claims to plain text (strip HTML tags).+2. Get the datasheet: `pdftotext -layout DS.pdf -` for the tables; render figures+ with `pdftoppm -png -r 300 -f <pg> -l <pg>` and, for a specific curve, crop with+ `-x -y -W -H` at high DPI then Read the PNG. (ImageMagick is NOT installed.)+3. For the target part specifically (a series datasheet covers many variants — pick+ the right row: colour/value/voltage), compare EACH value and EACH chart curve.++## Value checklist (per component type)+- **LED:** Vf typ/max, λD (dominant), λP (peak), IV (mcd) @ test current, IF max,+ IFP (pulse note), VR, Pd, viewing angle 2θ½, material (AlInGaP/InGaN), lens,+ operating/storage temp. Package L×W×H + tolerance. Solder pattern (pad W, H, gap).+- **MLCC / cap:** capacitance, tolerance, rated voltage, dielectric, package L×W×T+ + termination band, dissipation factor, insulation resistance, temp range, reflow.+- **Resistor:** value, tolerance, power rating, TCR, package, derating curve.++## Charts — verify the CURVE, not just the caption+An SVG `<path>` can plot the wrong numbers even with a corrected caption. For each+chart: read the datasheet curve at several points, convert to the chart's pixel+coords (`x = x0 + (v-v0)*scale`, `y = y0 - value*scale`), and redraw the path.++## Common discrepancies found in the wild+- **Land pattern "center-to-center" that is actually the edge-to-edge GAP.** The+ datasheet solder-pattern dimension between two pads is usually the gap. c-c =+ pad_width + gap. (Seen on IN-S42ATR: page said c-c 0.6mm; Fig 1's 0.6 is the gap,+ real c-c = 0.4 + 0.6 = 1.0mm.)+- **Brightness-vs-current / vs-temperature curves drawn to invented numbers**+ (e.g. "+55% at 40mA" when the datasheet curve reads +70%; "−30% at 70°C" when it's+ ~−40%). Redraw from the datasheet curve.+- **FWHM / spectral width stated as a value** when the datasheet's Δλ column is blank+ for that colour — remove it (it's a guess, not a spec).+- **Footprint pad size not matching the datasheet solder pattern** (e.g. width/height+ swapped: 0.6×0.5 where Fig 1 says 0.4×0.6). Fix the `.kicad_mod` AND regenerate the+ fpview + ct footprint SVG + the composite pads.+- **3D model height = the generic KiCad body** (0402 LED_0402 is 0.5mm) vs the+ datasheet (0.45mm). Scale the STEP + composite to the datasheet height.+- **Derating curve values that look wrong but are actually right** — verify against+ the datasheet's own curve before "fixing". (IN-S42ATR: the derating curve peaks at+ 30mA even though the abs-max table says 25mA — the datasheet is internally+ inconsistent; the page correctly reproduced the curve.)
scripts/bake_board_glb.pyadded+222@@ -0,0 +1,222 @@+#!/usr/bin/env python3+"""bake_board_glb.py — turn a KiCad board STEP-derived GLB into a viewer-ready, tagged model.++The Path B model-prep step (see SKILL.md §5c). What it does, and why each step exists:++1. TAG every solid `section|REFDES|i` — **refdes comes from the GLB node hierarchy**: KiCad's+ STEP export names each component's assembly node with its refdes (R39, U2 …); both converters+ (step2glb, cascadio) preserve it. Geometry-bearing LEAF nodes are OCCT tags (`=>[0:1:1:41]`),+ so walk UP the parent chain to the first node matching a refdes that exists in the .kicad_pcb.+ Verified 297/297 solids on a 143-footprint board — no positional guessing.+ (Do NOT match by nearest centroid as the primary method: on the same board it provably+ mistagged 4/297 — a big IC's pin-1 dimple sits closer to a neighbouring 0402 than to its own+ origin, and stale geometry lands wherever it was when the STEP was exported.)+2. CROSS-CHECK each solid's centroid against its refdes's .kicad_pcb position → a distance over+ ~2 mm means the STEP predates a component move (**stale geometry**). Keep the (correct) refdes+ tag, but flag it in the report — the page must say the model is stale for those refs.+3. SECTION each refdes. Default: **derive sheet membership from the design files** — the PCB's+ `(path "/<sheet-uuid>/<symbol-uuid>")` entries against the root .kicad_sch's sheet+ declarations (works without the sub-sheet files). An explicit blocks.json (author's finer+ sections) overrides; refs in neither get "other".+4. BAKE node transforms into vertex data (KiCad places purely by node transform; the Adom viewer+ bundle does NOT apply node transforms — unbaked, the whole BOM collapses at the origin), then+ RECENTER on the board-outline centre. Verified after export: every node matrix is identity.+ Coordinate convention: STEP is METRES with Y NEGATED vs the PCB (glb_y = -pcb_y/1000).+5. DE-FIGHT the layers (measured on a real board: mask sheet sits 10-15 µm off copper, silk 10 µm+ under component bottoms — about ONE depth-buffer step at viewing distance, i.e. guaranteed+ shimmer): lift top MASK +15 µm, top SILK +15 µm, components +30 µm (skip parts that wrap the+ board edge); mirror negative on the bottom. Order (silk above mask above copper) is preserved.+ Also force the PCB material OPAQUE — exporters emit it at alpha 0.98 BLEND, which re-blends+ the exactly-coplanar buried copper faces every frame (the worst clip of all, unfixable by+ offsets since one copper mesh carries both slabs). Viewer-side, also raise the camera's+ near plane (minZ = radius/100) — see the board-viewer template.+6. COVERAGE REPORT: real parts with NO solid (invisible in the viewer!) vs legitimately-bodiless+ footprints, plus DNP refs and stale-geometry refs. Print it and put it on the page (§7B.4).++Usage:+ bake_board_glb.py <raw.glb> <board.kicad_pcb> <out.glb>+ [--sch root.kicad_sch] [--blocks blocks.json]+ [--report coverage.json] [--index board-index.json]+ [--silk-um 15] [--mask-um 15] [--comp-um 30]++NOTE: feed this a **cascadio/float32 GLB**. step2glb output is KHR_mesh_quantization-compressed,+which trimesh misreads by 32767x — dequantize first (gltf-transform dequantize) or convert with+cascadio for the bake and keep step2glb for direct-to-viewer uses.+Requires: trimesh + numpy.+"""+import re, json, collections, argparse+import numpy as np+import trimesh++BODILESS_FP = ('SolderPad', 'SolderPads', 'MountingHole', 'SolderJumper', 'TestPoint',+ 'Fiducial', 'LOGO', 'Logo', 'Feeder_Pins')+REFPAT = re.compile(r'^([A-Z]{1,4}[0-9]+)(?:[ _].*)?$')++ap = argparse.ArgumentParser()+ap.add_argument('raw_glb'); ap.add_argument('kicad_pcb'); ap.add_argument('out_glb')+ap.add_argument('--sch'); ap.add_argument('--blocks')+ap.add_argument('--report'); ap.add_argument('--index')+ap.add_argument('--silk-um', type=float, default=15.0)+ap.add_argument('--mask-um', type=float, default=15.0)+ap.add_argument('--comp-um', type=float, default=30.0)+ap.add_argument('--stale-mm', type=float, default=2.0)+A = ap.parse_args()++# ---------------- footprints (refdes, value, fp name, position, layer, dnp, sheet path)+s = open(A.kicad_pcb, encoding='utf8', errors='replace').read()+fps = []+for b in s.split('\n\t(footprint ')[1:]:+ g = lambda k: (re.search(r'\(property "%s" "([^"]*)"' % k, b) or [None, None])[1]+ at = re.search(r'\(at (-?[\d.]+) (-?[\d.]+)(?: (-?[\d.]+))?\)', b)+ lay = re.search(r'\(layer "([^"]+)"\)', b)+ head = b[:b.find('(pad ')] if '(pad ' in b else b+ pth = re.search(r'\(path "([^"]*)"\)', head)+ fps.append(dict(ref=g('Reference'), val=g('Value'),+ fp=re.match(r'"([^"]+)"', b).group(1).split(':')[-1],+ x=float(at.group(1)), y=float(at.group(2)),+ rot=float(at.group(3)) if at.group(3) else 0.0,+ layer=lay.group(1) if lay else '?',+ dnp=bool(re.search(r'\(attr[^)]*\bdnp\b', head)),+ path=pth.group(1) if pth else ''))+fps = [f for f in fps if f['ref'] and not f['ref'].startswith('G*')]+REFS = {f['ref'] for f in fps}+F = {f['ref']: f for f in fps}++# ---------------- sections: sheet-derived default, blocks.json override+sheet_of = {}+if A.sch:+ sch = open(A.sch, encoding='utf8', errors='replace').read()+ sheets = {} # uuid -> sheet name+ for m in re.finditer(r'\(sheet\s(.*?)\n\t\)', sch, re.S):+ u = re.search(r'\(uuid "([^"]+)"\)', m.group(1))+ n = re.search(r'\(property "Sheetname" "([^"]+)"', m.group(1))+ if u and n:+ sheets[u.group(1)] = n.group(1)+ for f in fps:+ parts = [p for p in f['path'].split('/') if p]+ f['sheet'] = sheets.get(parts[0], 'root') if parts else 'root'+ sheet_of[f['ref']] = f['sheet']+BLK = {}+if A.blocks:+ BL = json.load(open(A.blocks))+ BLK = {r: k for k, v in BL.items() for r in v}+def section(ref):+ return BLK.get(ref) or sheet_of.get(ref, 'other') if (BLK or sheet_of) else 'other'++# ---------------- board outline centre+xs, ys = [], []+for m in re.finditer(r'\(gr_(?:line|arc|rect|circle|poly)\s(.*?)\n\t\)', s, re.S):+ if '"Edge.Cuts"' not in m.group(1):+ continue+ for x, y in re.findall(r'\((?:start|end|mid|center|xy)\s+(-?[\d.]+)\s+(-?[\d.]+)\)', m.group(1)):+ xs.append(float(x)); ys.append(float(y))+CX, CY = (min(xs) + max(xs)) / 2 / 1000.0, -(min(ys) + max(ys)) / 2 / 1000.0+W = (max(xs) - min(xs)) / 1000.0++# ---------------- load + refdes from node ancestry+sc = trimesh.load(A.raw_glb)+parent = {c: p for p, c, _ in sc.graph.to_edgelist()}+def refdes_of(node):+ cur = node+ while True:+ m = REFPAT.match(str(cur))+ if m and m.group(1) in REFS:+ return m.group(1)+ if cur not in parent:+ return None+ cur = parent[cur]++SUBKIND = [('PCB', 'PCB'), ('copper', 'COPPER'), ('soldermask', 'MASK'), ('silkscreen', 'SILK')]+insts = []+z_top = 0.0+for node in sc.graph.nodes_geometry:+ T, gname = sc.graph[node]+ m = sc.geometry[gname].copy(); m.apply_transform(T)+ kind = None+ if (m.bounds[1][0] - m.bounds[0][0]) > W * 0.9:+ base = gname.rsplit('_', 1)[0] if gname.rsplit('_', 1)[-1].isdigit() else gname+ for key, tag in SUBKIND:+ if key in base:+ kind = tag+ if kind == 'PCB':+ z_top = float(m.bounds[1][2])+ insts.append((node, gname, m, kind))++out = trimesh.Scene(); counts = collections.Counter(); idx = {}+stale = {}; unmatched = []+zmid = z_top / 2+for node, gname, m, kind in insts:+ if kind: # substrate+ blk, ref = 'substrate', kind+ zc = float((m.bounds[0][2] + m.bounds[1][2]) / 2)+ if kind in ('MASK', 'SILK'): # de-fight the zero-thickness sheets+ d = (A.silk_um if kind == 'SILK' else A.mask_um) * 1e-6+ m.apply_translation([0, 0, d if zc > zmid else -d])+ if kind == 'PCB': # kill the BLEND-over-buried-copper fight+ mat = getattr(m.visual, 'material', None)+ if mat is not None:+ if getattr(mat, 'baseColorFactor', None) is not None:+ bcf = list(mat.baseColorFactor); bcf[3] = 255+ mat.baseColorFactor = bcf+ mat.alphaMode = 'OPAQUE'+ else:+ ref = refdes_of(node)+ if ref is None:+ unmatched.append(gname); continue+ blk = section(ref)+ c = (m.bounds[0] + m.bounds[1]) / 2+ f = F[ref]+ d_mm = float(np.hypot(c[0] - f['x'] / 1000.0, c[1] - -f['y'] / 1000.0)) * 1000+ # big packages have sub-solids far from the origin; only flag if the WHOLE part drifts,+ # so track the minimum distance per ref and decide after the loop+ stale.setdefault(ref, []).append(d_mm)+ # lift components clear of the raised silk — except parts that wrap the board edge+ if m.bounds[0][2] < zmid:+ pass # e.g. a USB shell / through-hole pins: leave alone+ else:+ m.apply_translation([0, 0, A.comp_um * 1e-6])+ m.apply_translation([-CX, -CY, 0.0])+ name = f"{blk}|{ref}|{counts[(blk, ref)]}"; counts[(blk, ref)] += 1+ out.add_geometry(m, node_name=name, geom_name=name)+ b = m.bounds; k = f"{blk}|{ref}"+ e = idx.setdefault(k, {'blk': blk, 'ref': ref, 'lo': b[0].tolist(), 'hi': b[1].tolist(), 'n': 0})+ e['lo'] = np.minimum(e['lo'], b[0]).tolist(); e['hi'] = np.maximum(e['hi'], b[1]).tolist()+ e['n'] += 1++data = out.export(file_type='glb'); open(A.out_glb, 'wb').write(data)+r = trimesh.load(A.out_glb)+bad = [n for n in r.graph.nodes_geometry if not np.allclose(r.graph[n][0], np.eye(4), atol=1e-9)]+assert not bad, f'bake failed - nodes still carry transforms: {bad[:5]}'++# ---------------- coverage + staleness+stale_refs = {ref: round(min(ds), 2) for ref, ds in stale.items() if min(ds) > A.stale_mm}+tagged = {v['ref'] for v in idx.values() if v['blk'] != 'substrate'}+missing_real, bodiless = [], []+for f in fps:+ if f['ref'] in tagged:+ continue+ (bodiless if any(k in f['fp'] for k in BODILESS_FP) else missing_real).append(+ dict(ref=f['ref'], val=f['val'], fp=f['fp']))+report = dict(solids=sum(1 for i in insts), refs_tagged=len(tagged),+ missing_real=missing_real, bodiless_ok=bodiless,+ stale_geometry=stale_refs, unmatched_solids=unmatched,+ dnp=[f['ref'] for f in fps if f['dnp']],+ sections=dict(collections.Counter(section(f['ref']) for f in fps)))+print(f"baked {len(insts)} solids -> {A.out_glb} ({len(data)/1e6:.1f} MB); identity verified")+print(f"tagged {len(tagged)} refs | REAL parts with NO body ({len(missing_real)}): "+ f"{[m['ref'] for m in missing_real]}")+print(f"STALE geometry (moved after STEP export): {stale_refs}")+print(f"bodiless-ok {len(bodiless)} | unmatched {unmatched} | DNP {report['dnp']}")+if A.report:+ json.dump(report, open(A.report, 'w'), indent=1); print('report ->', A.report)+if A.index:+ FI = {f['ref']: dict(ref=f['ref'], val=f['val'], fp=f['fp'], layer=f['layer'], rot=f['rot'],+ x=f['x'] / 1000.0 - CX, y=-f['y'] / 1000.0 - CY,+ blk=section(f['ref']), sheet=f.get('sheet'), dnp=f['dnp'],+ stale_mm=stale_refs.get(f['ref']),+ has3d=(f"{section(f['ref'])}|{f['ref']}") in idx)+ for f in fps}+ json.dump({'groups': idx, 'fps': FI, 'centre_mm': [CX * 1000, -CY * 1000],+ 'coverage': report},+ open(A.index, 'w'), indent=0)+ print('index ->', A.index)
scripts/board-viewer-template.htmladded+489@@ -0,0 +1,489 @@+<meta charset="utf-8">+<title>Feeder Reader — interactive board viewer</title>+<meta name="viewport" content="width=device-width, initial-scale=1">+<style>+ :root{ --bg:#2a3340; --ink:#e8eef5; --dim:#9fb0c3; --line:rgba(255,255,255,.14); }+ *{box-sizing:border-box}+ html,body{margin:0;height:100%;background:var(--bg);color:var(--ink);+ font-family:ui-sans-serif,-apple-system,"Segoe UI",Inter,system-ui,sans-serif;overflow:hidden}+ #app{position:absolute;inset:0}+ canvas{outline:none;display:block;width:100%;height:100%;touch-action:none}+ #status{position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);color:var(--dim);+ font-size:13px;letter-spacing:.02em;text-align:center;pointer-events:none}+ .panel{position:absolute;background:rgba(16,22,31,.82);backdrop-filter:blur(9px);+ border:1px solid var(--line);border-radius:12px}++ /* mode switch */+ #modes{top:14px;left:50%;transform:translateX(-50%);display:flex;gap:2px;padding:3px;z-index:6}+ #modes button{appearance:none;background:transparent;border:0;color:var(--dim);cursor:pointer;+ font:600 12px/1 inherit;padding:8px 14px;border-radius:9px;letter-spacing:.02em}+ #modes button.on{background:rgba(255,255,255,.13);color:#fff}++ /* caption card */+ #caption{left:20px;bottom:64px;max-width:min(430px,42vw);padding:14px 16px;z-index:5;+ opacity:0;transition:opacity .45s ease;pointer-events:none}+ #caption.show{opacity:1}+ #caption .eyebrow{font:700 10px/1 inherit;letter-spacing:.14em;text-transform:uppercase;color:var(--dim);margin-bottom:7px}+ #caption .head{font:650 17px/1.3 inherit;margin-bottom:9px;color:#fff}+ #caption .rows{display:grid;grid-template-columns:auto 1fr;gap:3px 12px;font-size:12px;margin-bottom:9px}+ #caption .rows b{color:var(--dim);font-weight:500;white-space:nowrap}+ #caption .rows span{color:#dce6f2;font-variant-numeric:tabular-nums}+ #caption .note{font-size:12px;line-height:1.5;color:#b9c7d7}+ #caption .chip{display:inline-block;width:8px;height:8px;border-radius:2px;margin-right:7px;vertical-align:1px}+++ /* legend + layers */+ #legend{left:20px;top:64px;padding:11px 13px;z-index:5;font-size:11.5px}+ #legend h3{margin:0 0 8px;font:700 10px/1 inherit;letter-spacing:.14em;text-transform:uppercase;color:var(--dim)}+ #legend .row{display:flex;align-items:center;gap:8px;padding:3px 0;cursor:pointer;color:#c6d3e1}+ #legend .row:hover{color:#fff}+ #legend .row.off{opacity:.38}+ #legend .sw{width:9px;height:9px;border-radius:2px;flex:none}+ #legend .n{margin-left:auto;color:#7f92a6;font-variant-numeric:tabular-nums;font-size:10.5px}++ /* buttons + scrubber */+ .btn-row{position:absolute;right:20px;bottom:20px;display:flex;gap:7px;z-index:6}+ .btn{appearance:none;background:rgba(16,22,31,.82);border:1px solid var(--line);color:var(--dim);+ border-radius:9px;padding:8px 12px;font:600 11.5px/1 inherit;cursor:pointer;backdrop-filter:blur(9px)}+ .btn:hover{color:#fff}+ .btn.on{background:rgba(255,255,255,.15);color:#fff}+ #topbar{position:absolute;left:0;right:0;top:0;height:3px;background:rgba(255,255,255,.08);cursor:pointer;z-index:7}+ #topbar-fill{height:100%;width:0;background:linear-gradient(90deg,#3b82f6,#22c55e)}+ /* ticks only — the chapter NAME already leads the caption card, so labels here just+ collided with the mode switch */+ #marks{position:absolute;left:0;right:0;top:3px;height:6px;z-index:7;pointer-events:none}+ #marks i{position:absolute;top:0;width:1px;height:6px;background:rgba(255,255,255,.32)}+ #tip{position:absolute;pointer-events:none;z-index:8;padding:8px 10px;max-width:230px;+ background:rgba(10,15,22,.94);border:1px solid var(--line);border-radius:9px;+ font-size:11.5px;line-height:1.45;color:#dce6f2;opacity:0;transition:opacity .12s}+ #tip .t{font-weight:650;color:#fff;margin-bottom:3px}+ #tip .m{color:#8fa2b6;font-size:10.5px;font-variant-numeric:tabular-nums}+ @media (max-width:760px){ #legend{display:none!important} #caption{max-width:calc(100vw - 40px);bottom:58px} }+ /* embedded in a short frame the legend (top-left) and the caption (bottom-left) collide —+ the caption is the one that carries the narrative, so the legend yields */+ @media (max-height:640px){ #legend{display:none} }+</style>++<div id="app"></div>+<div id="status">loading board…</div>+<div id="topbar"><div id="topbar-fill"></div></div>+<div id="marks"></div>+<div class="panel" id="modes"></div>+<div class="panel" id="legend"><h3>Sections</h3><div id="legend-list"></div></div>+<div class="panel" id="caption"><div class="eyebrow"></div><div class="head"></div><div class="rows"></div><div class="note"></div></div>+<div class="btn-row">+ <button class="btn" id="btn-power" style="display:none">⏻ Power</button>+ <button class="btn on" id="btn-play">⏸ Pause</button>+ <button class="btn" id="btn-replay">↺ Replay</button>+ <button class="btn on" id="btn-ground">Ground</button>+ <button class="btn on" id="btn-labels">Labels</button>+</div>+<div id="tip"></div>++<script>+(async () => {+const statusEl = document.getElementById('status');++// Wiki blobs render SANDBOXED (no allow-same-origin) → localStorage/sessionStorage throw on+// ACCESS, which aborts the bundle's SceneBuilder (no lights/IBL/shadows). Shim before load.+for (const k of ['localStorage','sessionStorage']) {+ try { window[k] && window[k].getItem('x'); }+ catch (e) { try { Object.defineProperty(window,k,{configurable:true,value:{getItem:()=>null,setItem:()=>{},removeItem:()=>{},clear:()=>{},key:()=>null,length:0}}); } catch(_){} }+}+// Blob storage serves .js as application/octet-stream + nosniff → <script src> is refused.+// Fetch as text, inject inline.+if (!window.Adom3DViewer) {+ try {+ const code = await (await fetch('./adom-3d-viewer.min.js')).text();+ const s = document.createElement('script'); s.textContent = code; document.head.appendChild(s);+ } catch (e) { statusEl.textContent = 'viewer bundle fetch failed: ' + e.message; return; }+}+const V = window.Adom3DViewer;+if (!V) { statusEl.textContent = 'Adom3DViewer bundle failed to load'; return; }+const B = V.BABYLON;++try {+// ---------------------------------------------------------------- config + index+const CFG = await (await fetch('./viewer-config.json',{cache:'no-store'})).json();+const IDX = await (await fetch('./board-index.json',{cache:'no-store'})).json();+const BLOCKS = CFG.blocks;+const BCOL = Object.fromEntries(BLOCKS.map(b => [b.id, b.color]));+const BLAB = Object.fromEntries(BLOCKS.map(b => [b.id, b.label]));++// ---------------------------------------------------------------- scene+const viewer = V.init(document.getElementById('app'), { zUp:true, showViewCube:true, showGround:true });+await viewer.loadModel('./feeder-reader.board.glb');+const scene = viewer.getScene();+scene.animationGroups.slice().forEach(g => g.dispose()); // we drive all motion++// Match Colby's current native viewer: flat #2a3340, no skybox mesh, soft radial ground.+const bgBot = new B.Color3(0.165,0.200,0.251);+const Color4 = scene.clearColor && scene.clearColor.constructor;+let _fade=null;+const groundFadeTex = () => {+ if (_fade) return _fade;+ const t=new B.DynamicTexture('groundFadeTex',256,scene,true), c=t.getContext();+ const g=c.createRadialGradient(128,128,6,128,128,128);+ g.addColorStop(0,'rgba(255,255,255,1)'); g.addColorStop(.55,'rgba(255,255,255,.6)'); g.addColorStop(1,'rgba(255,255,255,0)');+ c.fillStyle=g; c.fillRect(0,0,256,256); t.update(); t.hasAlpha=true; _fade=t; return t;+};+const matchColby = () => {+ if (Color4) scene.clearColor = new Color4(bgBot.r,bgBot.g,bgBot.b,1);+ scene.environmentIntensity = 1.0;+ scene.meshes.filter(m=>/^Background/.test(m.name)).forEach(m=>m.setEnabled(false));+ const gnd = scene.getMeshByName('shadowGround');+ if (gnd && gnd.material) {+ const m = gnd.material;+ if (!(m.baseTexture && m.baseTexture.name==='groundFadeTex')) {+ if ('baseTexture' in m) m.baseTexture = groundFadeTex();+ m.alpha=0.2; m.transparencyMode=2; m.backFaceCulling=false;+ }+ gnd.receiveShadows = true;+ }+};+matchColby();++// ---------------------------------------------------------------- group meshes+// Every mesh is named "<block>|<ref>|<i>" (transforms baked at export, so a plain+// position offset is a rigid move — see bake2.py).+const parts = new Map(); // ref -> {ref, blk, meshes[], home:Vector3, centre}+const byBlock = new Map(); // blk -> [part]+for (const m of scene.meshes) {+ const nm = (m.name||'').split('_primitive')[0];+ if (nm.indexOf('|') < 0) continue;+ const [blk, ref] = nm.split('|');+ m.rotationQuaternion = null; // glTF quaternion would override Euler+ let p = parts.get(ref);+ if (!p) { p = { ref, blk, meshes:[], home:m.position.clone() }; parts.set(ref, p); (byBlock.get(blk)||byBlock.set(blk,[]).get(blk)).push(p); }+ p.meshes.push(m);+}+for (const p of parts.values()) {+ let lo=null, hi=null;+ for (const m of p.meshes) {+ m.computeWorldMatrix(true);+ const bb = m.getBoundingInfo().boundingBox;+ lo = lo ? B.Vector3.Minimize(lo, bb.minimumWorld) : bb.minimumWorld.clone();+ hi = hi ? B.Vector3.Maximize(hi, bb.maximumWorld) : bb.maximumWorld.clone();+ }+ p.lo=lo; p.hi=hi; p.centre=lo.add(hi).scale(0.5); p.size=hi.subtract(lo);+}+const blockBox = blk => {+ let lo=null,hi=null;+ for (const p of (byBlock.get(blk)||[])) {+ lo = lo ? B.Vector3.Minimize(lo,p.lo) : p.lo.clone();+ hi = hi ? B.Vector3.Maximize(hi,p.hi) : p.hi.clone();+ }+ // fold in footprints that have no 3D body (feeder pads, switches, jumpers…)+ for (const f of Object.values(IDX.fps)) {+ if (f.blk!==blk || f.has3d) continue;+ const v=new B.Vector3(f.x,f.y,0.0015);+ lo = lo ? B.Vector3.Minimize(lo,v) : v.clone(); hi = hi ? B.Vector3.Maximize(hi,v) : v.clone();+ }+ return lo ? {lo,hi,c:lo.add(hi).scale(.5),s:hi.subtract(lo)} : null;+};+const SUB = ['PCB','COPPER','MASK','SILK'].map(r=>parts.get(r)).filter(Boolean);+const COMPONENTS = [...parts.values()].filter(p => p.blk!=='substrate');+statusEl.textContent = '';++// ---------------------------------------------------------------- camera+const cam = scene.activeCamera;+const home = { a:-Math.PI/2 - 0.55, b:0.92, r:0.165, t:new B.Vector3(0,0,0.004) };+const setCam = (o,ease) => {+ const tgt = { alpha:o.a, beta:o.b, radius:o.r, target:o.t };+ if (!ease) { cam.alpha=tgt.alpha; cam.beta=tgt.beta; cam.radius=tgt.radius; cam.target.copyFrom(tgt.target); return; }+ camGoal = tgt;+};+let camGoal = null, userHold = 0;+setCam(home,false);+cam.lowerRadiusLimit = 0.03; cam.upperRadiusLimit = 1.2; cam.wheelDeltaPercentage = 0.02;+// Depth-precision fix: the bundle's camera sets minZ = radius/1000, which makes one 24-bit+// depth step ~10 um at board-viewing distance — exactly the gap between mask/silk/copper+// sheets, so coplanar-ish layers shimmer. radius/100 gives ~1 um steps and the near plane is+// still only 0.3 mm out at the closest zoom. (Bake-side the layers are also nudged apart.)+scene.onBeforeRenderObservable.add(() => { cam.minZ = Math.max(cam.radius / 100, 2e-4); });+cam.panningSensibility = 6000;+// The camera is "yours for 5 s": any drag/wheel pauses the scripted chase (assembly only),+// which then eases back — same convention as the single-component Timeline viewer. In static+// mode there is no scripted camera at all, so input is simply never fought.+['pointerdown','wheel'].forEach(ev => scene.getEngine().getRenderingCanvas()+ .addEventListener(ev, () => { userHold = 5; }, {passive:true}));++// ---------------------------------------------------------------- helpers+const emissive = (col, alpha) => {+ const m = new B.StandardMaterial('em'+Math.random(), scene);+ m.emissiveColor = col; m.diffuseColor = new B.Color3(0,0,0); m.specularColor = new B.Color3(0,0,0);+ m.disableLighting = true; m.alpha = alpha==null?1:alpha; if (alpha!=null) m.alphaMode = 1;+ return m;+};+const hex2c3 = h => new B.Color3(parseInt(h.slice(1,3),16)/255, parseInt(h.slice(3,5),16)/255, parseInt(h.slice(5,7),16)/255);++// Section outline boxes (wireframe) — one per block, hidden by default.+const outlines = new Map();+for (const b of BLOCKS) {+ const bb = blockBox(b.id); if (!bb) continue;+ const pad = 0.0018;+ const box = B.MeshBuilder.CreateBox('outline_'+b.id, {+ width: Math.max(bb.s.x,0.002)+pad*2, height: Math.max(bb.s.y,0.002)+pad*2, depth: Math.max(bb.s.z,0.002)+pad*2 }, scene);+ box.position.copyFrom(bb.c);+ const mt = emissive(hex2c3(b.color)); mt.wireframe = true; mt.alpha = .45; mt.alphaMode = 1;+ box.material = mt; box.isPickable = false; box.setEnabled(false);+ outlines.set(b.id, box);+}++// Static-mode visual function (AUTHOR-SPECIFIED, see viewer-config): e.g. the rail LEDs+// lighting when "Power" is toggled. Purely illustrative of the powered state.+const FN = (CFG.modes.static && CFG.modes.static.functions && CFG.modes.static.functions.power_leds) || null;+const glows = new Map();+let powerOn = !!(FN && FN.default);+for (const ref of (FN ? FN.refs : [])) {+ const f = IDX.fps[ref]; if (!f) continue;+ const d = B.MeshBuilder.CreateBox('glow_'+ref, {width:.0028,height:.0028,depth:.0009}, scene);+ d.position.set(f.x, f.y, 0.0022); d.material = emissive(hex2c3(FN.color), .95); d.isPickable=false; d.setEnabled(false);+ glows.set(ref, d);+}++// DOM labels for sections+const labelLayer = document.createElement('div');+labelLayer.style.cssText = 'position:absolute;inset:0;pointer-events:none;z-index:4';+document.body.appendChild(labelLayer);+const labels = new Map();+for (const b of BLOCKS) {+ const bb = blockBox(b.id); if (!bb) continue;+ const el = document.createElement('div');+ el.style.cssText = 'position:absolute;transform:translate(-50%,-50%);font:650 10.5px/1 ui-sans-serif,system-ui;'++ 'letter-spacing:.03em;padding:3px 7px;border-radius:6px;white-space:nowrap;opacity:0;transition:opacity .3s;'++ 'background:rgba(10,15,22,.82);border:1px solid '+b.color+'66;color:'+b.color;+ el.textContent = b.label;+ labelLayer.appendChild(el); labels.set(b.id, {el, pos:bb.c.clone()});+}+let labelsOn = true;+// Only ONE section label is drawn at a time — the block the current chapter is about.+// (Blocks overlap heavily in plan view: feeder-io alone spans the whole board, so every+// centroid lands near the middle and all eight labels stack on top of each other.)+let focusBlk = null, hoverBlk = null;++// ---------------------------------------------------------------- visibility control+const setPartVis = (p, v) => { for (const m of p.meshes) m.visibility = v; };+const showAllComponents = v => COMPONENTS.forEach(p => setPartVis(p, v));+const layerOn = { PCB:true, COPPER:true, SILK:true, MASK:true };+const blockOn = Object.fromEntries(BLOCKS.map(b=>[b.id,true]));+const applyLayers = () => {+ for (const p of SUB) { const on = layerOn[p.ref]!==false; p.meshes.forEach(m=>m.setEnabled(on)); }+ for (const p of COMPONENTS) { const on = blockOn[p.blk]!==false; p.meshes.forEach(m=>m.setEnabled(on)); }+};++// ---------------------------------------------------------------- legend+const legendList = document.getElementById('legend-list');+const counts = {};+for (const f of Object.values(IDX.fps)) counts[f.blk] = (counts[f.blk]||0)+1;+for (const b of BLOCKS) {+ const row = document.createElement('div'); row.className='row';+ row.innerHTML = `<span class="sw" style="background:${b.color}"></span><span>${b.label}</span><span class="n">${counts[b.id]||0}</span>`;+ row.onclick = () => { blockOn[b.id] = !blockOn[b.id]; row.classList.toggle('off', !blockOn[b.id]); applyLayers(); };+ row.onmouseenter = () => { hoverBlk = b.id; outlines.get(b.id)?.setEnabled(true); };+ row.onmouseleave = () => { hoverBlk = null; if (focusBlk!==b.id) outlines.get(b.id)?.setEnabled(false); };+ legendList.appendChild(row);+}+const subRow = document.createElement('div'); subRow.className='row';+subRow.innerHTML = `<span class="sw" style="background:#b78227"></span><span>Copper & silkscreen</span><span class="n">4</span>`;+subRow.onclick = () => { const on = !(layerOn.COPPER && layerOn.SILK); layerOn.COPPER=layerOn.SILK=on; subRow.classList.toggle('off',!on); applyLayers(); };+legendList.appendChild(subRow);++// ---------------------------------------------------------------- caption+const capEl = document.getElementById('caption');+const showCap = (c) => {+ if (!c) { capEl.classList.remove('show'); return; }+ const dot = c.block ? `<span class="chip" style="background:${BCOL[c.block]}"></span>` : '';+ capEl.querySelector('.eyebrow').innerHTML = dot + (c.eyebrow||'');+ capEl.querySelector('.head').textContent = c.head||'';+ capEl.querySelector('.rows').innerHTML = (c.rows||[]).map(r=>`<b>${r[0]}</b><span>${r[1]}</span>`).join('');+ capEl.querySelector('.note').textContent = c.note||'';+ capEl.classList.add('show');+};+let lastCapKey = null;+const showCapOnce = (key,c) => { if (key!==lastCapKey) { lastCapKey=key; showCap(c); } };++// ---------------------------------------------------------------- modes+const A = CFG.modes.assembly, S = CFG.modes.static;+// Assembly schedule — the GROUP is the unit: all of a grouping's parts fall together+// (tiny in-group stagger for texture) while that grouping's caption explains it.+const T = A.timing;+const sched = []; // {p, t, blk} — individual part drops+const groups = []; // {id, t0, t1} — caption/camera windows+let tA = (A.intro && A.intro.d) || 6;+for (const bid of A.order) {+ const ps = (byBlock.get(bid)||[]).slice().sort((p,q)=>p.centre.x-q.centre.x);+ ps.forEach((p,i)=> sched.push({p, t: tA + i*T.stagger_s, blk:bid}));+ const dwell = (A.captions[bid] && A.captions[bid].d) || T.dwell_s;+ groups.push({ id: bid, t0: tA, t1: tA + dwell });+ tA += dwell;+}+const A_LEN = tA + T.rest_s;+const LEN = { assembly: A_LEN, static: 1 }; // static has NO timeline++let mode = 'assembly', t = 0, playing = true;++const modesEl = document.getElementById('modes');+for (const k of ['assembly','static']) {+ const b = document.createElement('button'); b.textContent = CFG.modes[k].label; b.dataset.k = k;+ b.onclick = () => setMode(k);+ modesEl.appendChild(b);+}+const marksEl = document.getElementById('marks');+function drawMarks() {+ marksEl.innerHTML = '';+ if (mode!=='assembly') return;+ for (const g of groups) marksEl.insertAdjacentHTML('beforeend', `<i style="left:${100*g.t0/A_LEN}%"></i>`);+}+function setMode(k) {+ mode = k; t = 0; lastCapKey = null; camGoal = null; userHold = 0; focusBlk = null;+ [...modesEl.children].forEach(b => b.classList.toggle('on', b.dataset.k===k));+ outlines.forEach(o => o.setEnabled(false));+ COMPONENTS.forEach(p => { setPartVis(p, k==='assembly' ? 0 : 1);+ p.meshes.forEach(m => m.position.copyFrom(p.home)); });+ // static: no timeline, no scripted camera — the camera is entirely the user's+ const isA = k==='assembly';+ document.getElementById('topbar').style.display = isA ? 'block' : 'none';+ document.getElementById('btn-play').style.display = isA ? '' : 'none';+ document.getElementById('btn-replay').style.display = isA ? '' : 'none';+ document.getElementById('btn-power').style.display = (!isA && FN) ? '' : 'none';+ glows.forEach(g => g.setEnabled(!isA && powerOn));+ setCam(home,false);+ drawMarks(); applyLayers(); showCap(null);+ if (!isA && S.blurb) showCap({ eyebrow:'Static', head:'Inspect the board', note:S.blurb });+}++// ---------------------------------------------------------------- render loop+// B exposes only MeshBuilder/StandardMaterial/Vector3/Color3/DynamicTexture — Matrix is NOT+// on it (§5b). Harvest it from a live instance instead of reaching for B.Matrix.+const Matrix = scene.getTransformMatrix().constructor;+const IDM = Matrix.Identity();+const worldToScreen = (v) => {+ try {+ const e = scene.getEngine();+ return B.Vector3.Project(v, IDM, scene.getTransformMatrix(),+ cam.viewport.toGlobal(e.getRenderWidth(), e.getRenderHeight()));+ } catch (_) { return null; }+};+let last = performance.now();+scene.onBeforeRenderObservable.add(() => {+ const now = performance.now(); const dt = Math.min((now-last)/1000, .05); last = now;+ if (playing) t = (t + dt) % LEN[mode];+ if (userHold > 0) userHold -= dt;++ // camera easing — assembly only; static never steers+ if (mode==='assembly' && camGoal && userHold <= 0 &&+ Number.isFinite(camGoal.alpha) && Number.isFinite(camGoal.beta) && Number.isFinite(camGoal.radius)) {+ const k = 1 - Math.pow(0.0016, dt);+ cam.alpha += (camGoal.alpha - cam.alpha) * k;+ cam.beta += (camGoal.beta - cam.beta) * k;+ cam.radius += (camGoal.radius - cam.radius) * k;+ cam.target.x += (camGoal.target.x - cam.target.x) * k;+ cam.target.y += (camGoal.target.y - cam.target.y) * k;+ cam.target.z += (camGoal.target.z - cam.target.z) * k;+ }+ if (mode==='assembly' && userHold <= 0) cam.alpha += dt * 0.005; // gentle drift++ if (mode === 'assembly') {+ // drops+ for (const d of sched) {+ const u = (t - d.t) / T.fall_s;+ if (u < 0) { setPartVis(d.p, 0); continue; }+ const k = Math.min(u, 1), e = 1 - Math.pow(1-k, 3); // easeOutCubic+ setPartVis(d.p, Math.min(1, k*2.2));+ const dz = (1-e) * T.drop_height_mm/1000;+ for (const m of d.p.meshes) { m.position.copyFrom(d.p.home); m.position.z += dz; }+ }+ // caption + focus + camera per GROUP window (intro before, rest after)+ const g = groups.find(g => t>=g.t0 && t<g.t1);+ if (t < groups[0].t0) {+ showCapOnce('a-intro', A.intro); focusBlk = null;+ outlines.forEach((o,id)=>o.setEnabled(id===hoverBlk));+ camGoal = { alpha:home.a, beta:home.b, radius:home.r, target:home.t };+ } else if (g) {+ const c = A.captions[g.id] || {};+ showCapOnce('a'+g.id, { ...c, block:g.id });+ focusBlk = g.id;+ outlines.forEach((o,id)=>o.setEnabled(id===g.id || id===hoverBlk));+ const bb = blockBox(g.id);+ if (bb) camGoal = { alpha: home.a + 0.25*Math.sin(t*0.12), beta: 0.86,+ radius: Math.max(0.105, Math.min(0.24, bb.s.length()*2.6)),+ target: bb.c };+ } else { // rest: whole board seated+ showCapOnce('a-rest', null); focusBlk = null;+ outlines.forEach((o,id)=>o.setEnabled(id===hoverBlk));+ camGoal = { alpha:home.a, beta:home.b, radius:home.r, target:home.t };+ }+ }+ // static mode: nothing per-frame — no timeline, no captions changing, no camera goals.+ // Hover tooltips, legend isolate, labels and the Power toggle all work event-driven.++ // scrub + labels+ if (mode==='assembly') document.getElementById('topbar-fill').style.width = (100*t/A_LEN) + '%';+ for (const [id, L] of labels) {+ const vis = labelsOn && blockOn[id]!==false && (id===focusBlk || id===hoverBlk);+ if (!vis) { L.el.style.opacity = 0; continue; }+ const p = worldToScreen(L.pos);+ if (!p || p.z > 1 || p.z < 0) { L.el.style.opacity = 0; continue; }+ L.el.style.left = p.x+'px'; L.el.style.top = p.y+'px'; L.el.style.opacity = 0.92;+ }+});++// ---------------------------------------------------------------- hover tooltip+const tipEl = document.getElementById('tip');+scene.getEngine().getRenderingCanvas().addEventListener('pointermove', ev => {+ const pick = scene.pick(scene.pointerX, scene.pointerY, m => (m.name||'').indexOf('|')>=0);+ if (!pick || !pick.hit) { tipEl.style.opacity = 0; return; }+ const nm = pick.pickedMesh.name.split('_primitive')[0];+ const [blk, ref] = nm.split('|');+ const f = IDX.fps[ref];+ const p = parts.get(ref);+ const mm = v => (v*1000).toFixed(2);+ if (blk === 'substrate') {+ tipEl.innerHTML = `<div class="t">Bare board</div><div class="m">130.00 × 50.00 mm · 1.6 mm · 4 layers<br>`++ `${{PCB:'FR-4 substrate',COPPER:'copper (all 4 layers)',MASK:'soldermask',SILK:'silkscreen'}[ref]||ref}</div>`;+ } else if (f) {+ tipEl.innerHTML = `<div class="t">${ref} · ${f.val}</div>`++ `<div class="m">${f.fp}<br>${BLAB[blk]||blk} · ${f.layer==='F.Cu'?'top':'bottom'} · ${f.rot?f.rot+'°':'0°'}`++ (p? `<br>extent ${mm(p.size.x)} × ${mm(p.size.y)} × ${mm(p.size.z)} mm` : '')+`</div>`;+ } else return;+ tipEl.style.opacity = 1;+ tipEl.style.left = Math.min(ev.clientX+14, innerWidth-244)+'px';+ tipEl.style.top = Math.min(ev.clientY+14, innerHeight-90)+'px';+});+scene.getEngine().getRenderingCanvas().addEventListener('pointerleave', ()=> tipEl.style.opacity=0);++// ---------------------------------------------------------------- controls+document.getElementById('btn-play').onclick = e => { playing=!playing; e.target.classList.toggle('on',playing); e.target.textContent = playing?'⏸ Pause':'▶ Play'; };+document.getElementById('btn-replay').onclick = () => { t=0; lastCapKey=null; if(mode==='assembly') COMPONENTS.forEach(p=>setPartVis(p,0)); };+document.getElementById('btn-ground').onclick = e => {+ const g = scene.getMeshByName('shadowGround'); if (!g) return;+ const on = !g.isEnabled(); g.setEnabled(on); e.target.classList.toggle('on',on); matchColby();+};+document.getElementById('btn-labels').onclick = e => { labelsOn=!labelsOn; e.target.classList.toggle('on',labelsOn); };+document.getElementById('btn-power').onclick = e => {+ powerOn = !powerOn; e.target.classList.toggle('on', powerOn);+ glows.forEach(g => g.setEnabled(mode!=='assembly' && powerOn));+};+document.getElementById('topbar').onclick = ev => { if (mode==='assembly') { t = A_LEN * (ev.clientX/innerWidth); lastCapKey=null; } };++// debug handle (harmless; also handy from the console)+window.__dbg = { parts, COMPONENTS, byBlock, sched, groups, outlines, labels, cam,+ get t(){return t}, set t(v){t=v; lastCapKey=null;},+ get mode(){return mode}, get focus(){return focusBlk},+ setMode, A_LEN, LEN,+ // jump the camera straight to its goal — the eased chase needs many frames,+ // and headless swiftshader renders this board at well under 1 fps.+ snap(){ if (camGoal) { cam.alpha=camGoal.alpha; cam.beta=camGoal.beta;+ cam.radius=camGoal.radius; cam.target.copyFrom(camGoal.target); } },+ pause(){ playing=false; }, play(){ playing=true; } };++setMode('assembly');+addEventListener('resize', () => scene.getEngine().resize());++} catch (err) {+ statusEl.textContent = 'viewer error: ' + (err && err.message ? err.message : err);+ console.error(err);+}+})();+</script>
scripts/build_composite_cap.pyadded+109@@ -0,0 +1,109 @@+# Worked example — cap emboss + 2-material (plane-split) colour, swapped into a composite (0603B104J500CT).+# ADAPT paths. Companion to build_insertion_glb-style board/animation assembly.++"""+v2 emboss + clean swap:+ - PART NUMBER 0603B104J500CT → sunken into the TOP (+Z), brown region only+ - VALUE 100nF → sunken into a long SIDE (+Y), brown region only, LARGE+ - silver/brown split at |x| >= 0.5 mm (the REAL termination boundary from the+ original chip mesh) → no triangular color artifacts+ - text kept within |x| <= 0.46 mm so it never touches the silver terminations+"""+import struct, json+import numpy as np+import cadquery as cq+import pygltflib++STEP_IN = "/tmp/claude-1001/-home-adom-project/7572280e-1088-44ed-9829-35fccaaabecb/scratchpad/wiki-fresh-0603b104j500ct/0603B104J500CT.step"+BACKUP = "/tmp/claude-1001/-home-adom-project/7572280e-1088-44ed-9829-35fccaaabecb/scratchpad/wiki-work-0603b104j500ct/_backup-working-composite.glb"+OUT = "/tmp/claude-1001/-home-adom-project/7572280e-1088-44ed-9829-35fccaaabecb/scratchpad/wiki-work-0603b104j500ct/0603B104J500CT.glb"+INSERTION = "/tmp/claude-1001/-home-adom-project/7572280e-1088-44ed-9829-35fccaaabecb/scratchpad/wiki-work-0603b104j500ct/0603B104J500CT.insertion.glb"++DEPTH = 0.06+FONT, FONT_PATH = "DejaVu Sans", "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"+ORIG_GLB = "/tmp/claude-1001/-home-adom-project/7572280e-1088-44ed-9829-35fccaaabecb/scratchpad/wiki-fresh-0603b104j500ct/0603B104J500CT.glb"+TOL, ANG = 0.02, 0.35 # tessellation++# ---- Reference colours straight from the actual STEP (via its color-preserving GLB) ----+def load_ref():+ f=open(ORIG_GLB,'rb'); f.read(12); ln=struct.unpack('<I',f.read(4))[0]; f.read(4)+ j=json.loads(f.read(ln)); bl=struct.unpack('<I',f.read(4))[0]; f.read(4); bd=f.read(bl)+ CT={5123:'H',5125:'I',5126:'f'}; SZ={5123:2,5125:4,5126:4}; NC={'SCALAR':1,'VEC3':3}+ def acc(i):+ a=j['accessors'][i]; bv=j['bufferViews'][a['bufferView']]+ off=bv.get('byteOffset',0)+a.get('byteOffset',0); n=a['count']*NC[a['type']]+ v=struct.unpack(f'<{n}'+CT[a['componentType']], bd[off:off+n*SZ[a['componentType']]])+ return np.array(v).reshape(a['count'],NC[a['type']])+ cents=[]; silver=[]+ silver_mat = [m['name'] for m in j['materials']].index('mat_0')+ for pr in j['meshes'][0]['primitives']:+ pos=acc(pr['attributes']['POSITION']); idx=acc(pr['indices']).reshape(-1,3)+ c=pos[idx].mean(axis=1)+ cents.append(c); silver.append(np.full(len(c), pr.get('material')==silver_mat))+ return np.vstack(cents).astype(np.float32), np.concatenate(silver)+REF_C, REF_SILVER = load_ref()+print(f"ref mesh: {len(REF_C)} tris ({REF_SILVER.sum()} silver / {(~REF_SILVER).sum()} brown)")++body = cq.importers.importStep(STEP_IN)++# ---- PART NUMBER on TOP (+Z), reading world -X + letter-tops toward -Y so it+# reads upright/consistent with the side value when the +Y face is toward you ----+pn = (cq.Workplane("XY").workplane(offset=0.8)+ .text("0603B104J500CT", 0.10, -DEPTH, font=FONT, fontPath=FONT_PATH,+ halign="center", valign="center", combine=False)+ .rotate((0,0,0),(0,0,1), 180))++# ---- VALUE on +Y SIDE, LARGE, reads correctly when viewed from +Y ----+# Plane on the +Y face: local +X = world -X (so a +Y viewer reads left→right),+# local +Y = world +Z (upright), normal +Y; extrude -DEPTH cuts into the body.+side_plane = cq.Plane(origin=(0, 0.40, 0.40), xDir=(-1, 0, 0), normal=(0, 1, 0))+val = (cq.Workplane(side_plane)+ .text("100nF", 0.28, -DEPTH, font=FONT, fontPath=FONT_PATH,+ halign="center", valign="center", combine=False))++for nm, t in (("PN(top)", pn), ("100nF(side)", val)):+ bb = t.val().BoundingBox()+ print(f" {nm:12s} X[{bb.xmin:.3f},{bb.xmax:.3f}] Y[{bb.ymin:.3f},{bb.ymax:.3f}] Z[{bb.zmin:.3f},{bb.zmax:.3f}]")++embossed = body.cut(pn).cut(val)++# ---- tessellate + flat normals ----+vmm, tris = embossed.val().tessellate(TOL, ANG)+P = np.array([[v.x,v.y,v.z] for v in vmm]) * 0.001+tris = np.array(tris, dtype=np.int64)+tp = P[tris]+fn = np.cross(tp[:,1]-tp[:,0], tp[:,2]-tp[:,0]); L=np.linalg.norm(fn,axis=1,keepdims=True); L[L==0]=1; fn/=L+V = tp.reshape(-1,3).astype(np.float32); N = np.repeat(fn,3,axis=0).astype(np.float32)+# The actual STEP's silver/brown boundary is a clean plane at |x| = 0.5 mm (verified+# from the reference mesh: silver tris all |x|>=0.5, brown all <=0.5). Split there.+TERM_X = float(np.abs(REF_C[REF_SILVER][:,0]).min()) # inner edge of silver in the real STEP (m)+print(f"real silver inner edge |x| = {TERM_X*1000:.4f} mm (brown reaches {np.abs(REF_C[~REF_SILVER][:,0]).max()*1000:.4f} mm)")+cx = tp.mean(axis=1)[:,0]+term = np.abs(cx) >= TERM_X - 1e-6+ids = np.arange(len(tris)*3).reshape(-1,3)+term_idx = ids[term].reshape(-1).astype(np.uint32)+body_idx = ids[~term].reshape(-1).astype(np.uint32)+print(f"tessellated {len(tris)} tris → silver {term.sum()} / brown {(~term).sum()} (clean split at STEP boundary)")++# ---- splice into composite (2 prims: silver mat_0, brown mat_1) ----+def swap(path_in, path_out):+ g = pygltflib.GLTF2().load(path_in); blob = bytearray(g.binary_blob())+ chip = next(n for n in g.nodes if n.name=="0603B104J500CT"); mesh = g.meshes[chip.mesh]+ names=[m.name for m in g.materials]; ms=names.index("mat_0"); mb=names.index("mat_1")+ def av(d,t):+ nonlocal blob+ while len(blob)%4: blob+=b"\x00"+ o=len(blob); blob+=d; g.bufferViews.append(pygltflib.BufferView(buffer=0,byteOffset=o,byteLength=len(d),target=t)); return len(g.bufferViews)-1+ pbv=av(V.tobytes(),34962); nbv=av(N.tobytes(),34962)+ pa=len(g.accessors); g.accessors.append(pygltflib.Accessor(bufferView=pbv,componentType=5126,count=len(V),type="VEC3",min=V.min(0).tolist(),max=V.max(0).tolist()))+ na=len(g.accessors); g.accessors.append(pygltflib.Accessor(bufferView=nbv,componentType=5126,count=len(N),type="VEC3"))+ def ia(a):+ bv=av(a.tobytes(),34963); i=len(g.accessors); g.accessors.append(pygltflib.Accessor(bufferView=bv,componentType=5125,count=len(a),type="SCALAR",min=[int(a.min())],max=[int(a.max())])); return i+ ta,ba=ia(term_idx),ia(body_idx)+ mesh.primitives=[+ pygltflib.Primitive(attributes=pygltflib.Attributes(POSITION=pa,NORMAL=na),indices=ta,material=ms,mode=4),+ pygltflib.Primitive(attributes=pygltflib.Attributes(POSITION=pa,NORMAL=na),indices=ba,material=mb,mode=4)]+ g.buffers[0].byteLength=len(blob); g.set_binary_blob(bytes(blob)); g.save(path_out)+ print(f"OK: {path_out} ({len(blob):,} B)")+swap(BACKUP, OUT)+import shutil; shutil.copy(OUT, INSERTION); print("mirrored → insertion.glb")
scripts/build_composite_led.pyadded+249@@ -0,0 +1,249 @@+# Worked example — LED animated composite builder (IN-S42ATR).+# ADAPT the absolute paths at the top for your part. Requires the cadquery venv (see SKILL §7).+# Does: emboss (auto-fit taper) + densified-NN 3-material colour + board/pads/solder/silk+# + insert animation + red lens + LED_lit glow + KHR_lights_punctual light + node Z-scale height fix.++"""+Build IN-S42ATR.insertion.glb — the animated LED-on-footprint composite:+ fr4_board / pad_top / silk (cathode mark) / solder_top / IN-S42ATR (LED) + LED_lit glow+ + smooth `insert` animation on the LED node.++LED mesh = embossed (IN-S42ATR + RED on the sides) + 3 original materials via densified+NN + a red lens (top) + a toggleable emissive LED_lit child (on/off via Layers menu).+All meters, Z-up (matches the cap composite the wiki viewer already renders).+"""+import struct, json+import numpy as np+import cadquery as cq+import trimesh+import pygltflib++STEP_IN = "/tmp/claude-1001/-home-adom-project/7572280e-1088-44ed-9829-35fccaaabecb/scratchpad/wiki-fresh-in-s42atr/IN-S42ATR.step"+ORIG_GLB = "/tmp/claude-1001/-home-adom-project/7572280e-1088-44ed-9829-35fccaaabecb/scratchpad/wiki-fresh-in-s42atr/IN-S42ATR.glb"+OUT = "/tmp/claude-1001/-home-adom-project/7572280e-1088-44ed-9829-35fccaaabecb/scratchpad/wiki-edit-in-s42atr/IN-S42ATR.glb"+INSERTION = "/tmp/claude-1001/-home-adom-project/7572280e-1088-44ed-9829-35fccaaabecb/scratchpad/wiki-edit-in-s42atr/IN-S42ATR.insertion.glb"++DEPTH=0.05; FONT,FP="DejaVu Sans","/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"; TOL,ANG=0.015,0.35+ZS=0.90 # datasheet height 0.45mm / model 0.50mm+LIGHT_INT=0.00004; LIGHT_RNG=0.004 # red point-light intensity (candela) + range (m) — tuned for mm scale (brighter)++# ===== 1. Emboss + tessellate =====+body=cq.importers.importStep(STEP_IN)++# GENERAL taper check: measure the body's X-width vs height straight from the+# component's own mesh vertices (the color-preserving GLB = the tessellated STEP),+# so this works for ANY tapered / domed / stepped component (nothing hardcoded).+def _load_positions_mm(glb_path):+ import struct as _st+ fp=open(glb_path,'rb'); fp.read(12); L=_st.unpack('<I',fp.read(4))[0]; fp.read(4); jj=_st.loads=json.loads(fp.read(L))+ b2=_st.unpack('<I',fp.read(4))[0]; fp.read(4); bb=fp.read(b2)+ pts=[]+ for mm in jj['meshes']:+ for pr in mm['primitives']:+ a=jj['accessors'][pr['attributes']['POSITION']]; bvv=jj['bufferViews'][a['bufferView']]+ off=bvv.get('byteOffset',0)+a.get('byteOffset',0); n=a['count']*3+ vals=_st.unpack(f'<{n}f',bb[off:off+n*4]); pts.append(np.array(vals).reshape(a['count'],3))+ return np.vstack(pts)*1000.0 # m → mm+_BP=_load_positions_mm(ORIG_GLB)+# Build a width-vs-height profile from the mesh's distinct Z "rings", then interpolate+# (mesh vertices only exist at geometry rings, so a thin slice between them is empty).+_zr=np.unique(np.round(_BP[:,2],3))+_levels=[]+for _z in _zr:+ _sl=_BP[np.abs(_BP[:,2]-_z)<0.006]+ if len(_sl): _levels.append((float(_z), float(_sl[:,0].max()-_sl[:,0].min())))+_levels.sort(); _ZL=np.array([l[0] for l in _levels]); _WL=np.array([l[1] for l in _levels])+print(f"taper profile: {len(_BP)} verts, width-by-height rings={list(zip(np.round(_ZL,2),np.round(_WL,2)))}")+def face_w(z):+ return float(np.interp(z,_ZL,_WL))++# Auto-fit: largest font so the WHOLE string fits the usable face width AND the band+# height (with margin). Prevents the part number / value from being clipped.+def fit_font(txt,max_w,max_h,mf=0.90):+ bb=cq.Workplane("XY").text(txt,1.0,0.01,font=FONT,fontPath=FP,halign="center",valign="center",combine=False).val().BoundingBox()+ return min(max_w/bb.xlen, max_h/bb.ylen)*mf++MARGIN=0.05+Zc_pn,H_pn = 0.28,0.12+uw_pn=face_w(Zc_pn+H_pn/2)-2*MARGIN; f_pn=fit_font("IN-S42ATR",uw_pn,H_pn)+Zc_red,H_red = 0.29,0.20+uw_red=face_w(Zc_red+H_red/2)-2*MARGIN; f_red=fit_font("RED",uw_red,H_red)+print(f"fit: IN-S42ATR font={f_pn:.3f} (usable_w={uw_pn:.3f}) RED font={f_red:.3f} (usable_w={uw_red:.3f})")++pn=cq.Workplane(cq.Plane(origin=(0,0.25,Zc_pn),xDir=(-1,0,0),normal=(0,1,0))).text("IN-S42ATR",f_pn,-DEPTH,font=FONT,fontPath=FP,halign="center",valign="center",combine=False)+red=cq.Workplane(cq.Plane(origin=(0,-0.25,Zc_red),xDir=(1,0,0),normal=(0,-1,0))).text("RED",f_red,-DEPTH,font=FONT,fontPath=FP,halign="center",valign="center",combine=False)++# Hard check: the placed text must fit inside the usable width and stay off the gold+# terminations (|x| < 0.5 minus margin). Fail loudly if not.+for nm,t,uw in (("IN-S42ATR",pn,uw_pn),("RED",red,uw_red)):+ bb=t.val().BoundingBox()+ assert bb.xlen<=uw+1e-6, f"{nm} width {bb.xlen:.3f} > usable {uw:.3f}"+ assert max(abs(bb.xmin),abs(bb.xmax))<0.48, f"{nm} reaches x={max(abs(bb.xmin),abs(bb.xmax)):.3f} into termination zone"+ print(f" check {nm}: width={bb.xlen:.3f}<= {uw:.3f}, x_extent=±{max(abs(bb.xmin),abs(bb.xmax)):.3f} OK")++embossed=body.cut(pn).cut(red)+vmm,tris=embossed.val().tessellate(TOL,ANG)+P=np.array([[v.x,v.y,v.z] for v in vmm])*0.001; tris=np.array(tris,dtype=np.int64)+tp=P[tris]; fn=np.cross(tp[:,1]-tp[:,0],tp[:,2]-tp[:,0]); Ln=np.linalg.norm(fn,axis=1,keepdims=True); Ln[Ln==0]=1; fn/=Ln+Vled=tp.reshape(-1,3).astype(np.float32); Nled=np.repeat(fn,3,axis=0).astype(np.float32)+EC=tp.mean(axis=1).astype(np.float32)++# ===== 2. Densified NN colour transfer =====+f=open(ORIG_GLB,'rb'); f.read(12); ln=struct.unpack('<I',f.read(4))[0]; f.read(4); j=json.loads(f.read(ln))+bl=struct.unpack('<I',f.read(4))[0]; f.read(4); bd=f.read(bl)+CTM={5123:'H',5125:'I',5126:'f'}; SZ={5123:2,5125:4,5126:4}; NCc={'SCALAR':1,'VEC3':3}+def acc(i):+ a=j['accessors'][i]; bv=j['bufferViews'][a['bufferView']]; off=bv.get('byteOffset',0)+a.get('byteOffset',0); n=a['count']*NCc[a['type']]+ v=struct.unpack(f'<{n}'+CTM[a['componentType']],bd[off:off+n*SZ[a['componentType']]]); return np.array(v).reshape(a['count'],NCc[a['type']])+bary=np.array([(i/6,k/6,1-i/6-k/6) for i in range(7) for k in range(7-i)])+RP=[]; RM=[]+for m in j['meshes']:+ for pr in m['primitives']:+ mt=pr.get('material'); pos=acc(pr['attributes']['POSITION']); idx=acc(pr['indices']).reshape(-1,3)+ for tr in idx: RP.append(bary@pos[tr]); RM.append(np.full(len(bary),mt))+REF=np.vstack(RP).astype(np.float32); RMAT=np.concatenate(RM)+mat_of=np.empty(len(EC),dtype=np.int64)+for s in range(0,len(EC),2000):+ ec=EC[s:s+2000]; mat_of[s:s+2000]=RMAT[(((ec[:,None,:]-REF[None,:,:])**2).sum(-1)).argmin(1)]++# top lens = pale tris that face up near the top+topmask=(mat_of==0)&(fn[:,2]>0.8)&(EC[:,2]>0.00042)+cat=np.where(topmask,4,mat_of) # 4 = lens_red+ids=np.arange(len(tris)*3).reshape(-1,3)+groups={k:ids[cat==k].reshape(-1).astype(np.uint32) for k in (0,1,2,4)}+print("LED tri split:",{k:len(v)//3 for k,v in groups.items()})++# glow geometry = the top-lens tris, nudged up 4µm+glow_tris=tris[topmask]+gtp=P[glow_tris]+np.array([0,0,0.000004])+Vglow=gtp.reshape(-1,3).astype(np.float32)+gfn=np.cross(gtp[:,1]-gtp[:,0],gtp[:,2]-gtp[:,0]); gL=np.linalg.norm(gfn,axis=1,keepdims=True); gL[gL==0]=1; gfn/=gL+Nglow=np.repeat(gfn,3,axis=0).astype(np.float32)+print(f"glow tris: {len(glow_tris)}")++# ===== 3. Footprint layer meshes (trimesh) =====+def box(sx,sy,sz,cx=0,cy=0,cz=0,color=(200,200,200,255)):+ b=trimesh.creation.box(extents=[sx,sy,sz]).apply_translation([cx,cy,cz])+ b.visual=trimesh.visual.ColorVisuals(b,face_colors=color); return b+BL,BW,BT=0.0032,0.0024,0.0016+board=box(BL,BW,BT,cz=-BT/2,color=(10,60,30,255))+padL=box(0.0004,0.0006,0.000035,cx=-0.0005,cz=0.0000175); padR=box(0.0004,0.0006,0.000035,cx=0.0005,cz=0.0000175)+pads=trimesh.util.concatenate([padL,padR]); pads.visual=trimesh.visual.ColorVisuals(pads,face_colors=(210,160,60,255))+# cathode silk bar on -Y edge, -X side (from footprint fp_line -0.7,-0.5 .. -0.2,-0.5)+silk=box(0.0005,0.00012,0.00003,cx=-0.00045,cy=-0.0005,cz=0.000045); silk.visual=trimesh.visual.ColorVisuals(silk,face_colors=(220,220,220,255))+def dot(x):+ d=trimesh.creation.icosphere(subdivisions=2,radius=0.00013); d.apply_scale([1,1,0.6]); d.apply_translation([x,0,0.000035]); return d+solder=trimesh.util.concatenate([dot(-0.0005),dot(0.0005)]); solder.visual=trimesh.visual.ColorVisuals(solder,face_colors=(190,195,205,255))++# ===== 4. Assemble GLB with pygltflib =====+g=pygltflib.GLTF2(); g.asset=pygltflib.Asset(version="2.0"); blob=bytearray()+def av(d,t):+ global blob+ while len(blob)%4: blob+=b"\x00"+ o=len(blob); blob+=d; g.bufferViews.append(pygltflib.BufferView(buffer=0,byteOffset=o,byteLength=len(d),target=t)); return len(g.bufferViews)-1+def vec3acc(A):+ bv=av(A.astype(np.float32).tobytes(),34962); i=len(g.accessors)+ g.accessors.append(pygltflib.Accessor(bufferView=bv,componentType=5126,count=len(A),type="VEC3",min=A.min(0).tolist(),max=A.max(0).tolist())); return i+def idxacc(A):+ A=A.astype(np.uint32); bv=av(A.tobytes(),34963); i=len(g.accessors)+ g.accessors.append(pygltflib.Accessor(bufferView=bv,componentType=5125,count=len(A),type="SCALAR",min=[int(A.min())],max=[int(A.max())])); return i+def mat(name,color,met=0.0,rough=0.6,emis=None,alpha=None,emis_str=None):+ pbr=pygltflib.PbrMetallicRoughness(baseColorFactor=color,metallicFactor=met,roughnessFactor=rough)+ m=pygltflib.Material(name=name,pbrMetallicRoughness=pbr)+ if emis: m.emissiveFactor=emis+ if emis_str is not None:+ m.extensions={"KHR_materials_emissive_strength":{"emissiveStrength":emis_str}}+ if "KHR_materials_emissive_strength" not in (g.extensionsUsed or []):+ g.extensionsUsed=(g.extensionsUsed or [])+["KHR_materials_emissive_strength"]+ if alpha is not None: m.alphaMode="BLEND"+ g.materials.append(m); return len(g.materials)-1++def tm_prim(tm, material):+ v=np.array(tm.vertices,dtype=np.float32); faces=np.array(tm.faces).reshape(-1)+ # flat normals+ fnv=tm.face_normals; nv=np.repeat(fnv,3,axis=0).astype(np.float32)+ vexp=v[np.array(tm.faces).reshape(-1)].astype(np.float32)+ pa=vec3acc(vexp); na=vec3acc(nv); ia=idxacc(np.arange(len(vexp)))+ return pygltflib.Primitive(attributes=pygltflib.Attributes(POSITION=pa,NORMAL=na),indices=ia,material=material,mode=4)++# materials+m_board=mat("board",[0.04,0.24,0.12,1],0,0.75); m_pad=mat("pad",[0.82,0.63,0.24,1],0.6,0.4)+m_silk=mat("silk",[0.87,0.87,0.87,1],0,0.8); m_sold=mat("solder",[0.75,0.76,0.80,1],0.85,0.35)+m_pale=mat("mat_0",[0.80,0.79,0.66,1],0.25,0.55); m_gold=mat("mat_1",[0.71,0.50,0.21,1],0.7,0.35)+m_green=mat("mat_2",[0.09,0.42,0.17,1],0,0.6)+m_lens=mat("lens_red",[0.40,0.02,0.02,1],0,0.75,emis=[0.40,0.01,0.01],emis_str=1.4) # brighter deep-red lens+m_glow=mat("led_glow",[0.85,0.02,0.02,1],0,0.70,emis=[1.0,0.04,0.04],alpha=0.9,emis_str=1.6) # brighter deep-red glow++def add_node(name,prims,children=None,scale=None,trans=None):+ g.meshes.append(pygltflib.Mesh(name=name,primitives=prims)); mi=len(g.meshes)-1+ nd=pygltflib.Node(name=name,mesh=mi)+ if children is not None: nd.children=children+ if scale: nd.scale=scale+ if trans: nd.translation=trans+ g.nodes.append(nd); return len(g.nodes)-1++# layer nodes+n_board=add_node("fr4_board",[tm_prim(board,m_board)])+n_pad=add_node("pad_top",[tm_prim(pads,m_pad)])+n_silk=add_node("silk",[tm_prim(silk,m_silk)])+n_sold=add_node("solder_top",[tm_prim(solder,m_sold)])++# LED mesh prims (share LED pos/normal accessors)+pa=vec3acc(Vled); na=vec3acc(Nled)+led_prims=[]+for k,mi in ((0,m_pale),(1,m_gold),(2,m_green),(4,m_lens)):+ if len(groups[k])==0: continue+ led_prims.append(pygltflib.Primitive(attributes=pygltflib.Attributes(POSITION=pa,NORMAL=na),indices=idxacc(groups[k]),material=mi,mode=4))+# glow mesh+gpa=vec3acc(Vglow); gna=vec3acc(Nglow)+glow_prim=pygltflib.Primitive(attributes=pygltflib.Attributes(POSITION=gpa,NORMAL=gna),indices=idxacc(np.arange(len(Vglow))),material=m_glow,mode=4)+# LED_lit is TOP-LEVEL (so the wiki Layers menu lists it) and gets its own animation+# channel so it still rides the LED during the insert animation.+n_glow=add_node("LED_lit",[glow_prim],trans=[0.0,0.0,0.0],scale=[1.0,1.0,ZS])+n_led=add_node("IN-S42ATR",led_prims,trans=[0.0,0.0,0.0],scale=[1.0,1.0,ZS])++# REAL red light: embed a KHR_lights_punctual point light at the emitter so the lit LED+# actually casts red onto the board/pads (Babylon renders it), not just a flat rectangle.+LIGHT_INTENSITY=LIGHT_INT # candela — tuned for the mm-scale scene+LIGHT_RANGE=LIGHT_RNG # metres+g.extensionsUsed=(g.extensionsUsed or [])+["KHR_lights_punctual"]+g.extensions={"KHR_lights_punctual":{"lights":[{+ "type":"point","name":"led_emitter","color":[1.0,0.03,0.015],+ "intensity":LIGHT_INTENSITY,"range":LIGHT_RANGE}]}}+n_light=len(g.nodes)+g.nodes.append(pygltflib.Node(name="LED_light",translation=[0.0,0.0,0.00060],+ extensions={"KHR_lights_punctual":{"light":0}}))+g.nodes[n_led].children=[n_light] # rides the LED via parent transform++g.scenes=[pygltflib.Scene(nodes=[n_board,n_pad,n_silk,n_sold,n_led,n_glow])]; g.scene=0++# ===== 5. insert animation on the LED node =====+# STANDARD for basic-parts animated composites: lift = 3 x the component's own height+# (measured from its geometry, so it scales to any part).+COMP_H=(_BP[:,2].max()-_BP[:,2].min())*0.001 # component height, m+LIFT=3.0*COMP_H*ZS+print(f"lift = 3 x component height ({COMP_H*1000:.3f}mm) = {LIFT*1000:.3f}mm")+times=[0.0,1.2,3.0,4.2,6.0]+outs=[(0,0,0),(0,0,0),(0,0,LIFT),(0,0,LIFT),(0,0,0)]+tb=struct.pack(f'<{len(times)}f',*times); ob=struct.pack(f'<{len(outs)*3}f',*[c for o in outs for c in o])+while len(blob)%4: blob+=b"\x00"+tin=len(blob); blob+=tb+while len(blob)%4: blob+=b"\x00"+oin=len(blob); blob+=ob+tbv=len(g.bufferViews); g.bufferViews.append(pygltflib.BufferView(buffer=0,byteOffset=tin,byteLength=len(tb)))+obv=len(g.bufferViews); g.bufferViews.append(pygltflib.BufferView(buffer=0,byteOffset=oin,byteLength=len(ob)))+tacc=len(g.accessors); g.accessors.append(pygltflib.Accessor(bufferView=tbv,componentType=5126,count=len(times),type="SCALAR",min=[times[0]],max=[times[-1]]))+oacc=len(g.accessors); g.accessors.append(pygltflib.Accessor(bufferView=obv,componentType=5126,count=len(outs),type="VEC3",min=[min(o[i] for o in outs) for i in range(3)],max=[max(o[i] for o in outs) for i in range(3)]))+g.animations=[pygltflib.Animation(name="insert",+ samplers=[pygltflib.AnimationSampler(input=tacc,output=oacc,interpolation="LINEAR")],+ channels=[+ pygltflib.AnimationChannel(sampler=0,target=pygltflib.AnimationChannelTarget(node=n_led,path="translation")),+ pygltflib.AnimationChannel(sampler=0,target=pygltflib.AnimationChannelTarget(node=n_glow,path="translation")),+ ])]++g.buffers=[pygltflib.Buffer(byteLength=len(blob))]; g.set_binary_blob(bytes(blob))+import os; os.makedirs(os.path.dirname(OUT),exist_ok=True)+g.save(OUT)+import shutil; shutil.copy(OUT,INSERTION)+print(f"OK: wrote {OUT} ({len(blob):,} B) + insertion.glb")+print("nodes:",[n.name for n in g.nodes]); print("materials:",[m.name for m in g.materials])
scripts/kicad_board_geom.pyadded+142@@ -0,0 +1,142 @@+#!/usr/bin/env python3+"""kicad_board_geom.py - parse a .kicad_pcb into geom.json (outline, footprints+pads with+transforms applied, silkscreen, tracks, vias). Stdlib-only s-expression parse; no KiCad needed.+Feeds kicad_board_map.py (SVG board maps) and the Path B README builder.++Usage: python3 kicad_board_geom.py <board.kicad_pcb> [out_geom.json]+"""+import re,json,math,sys+SRC=sys.argv[1]+OUT=sys.argv[2] if len(sys.argv)>2 else 'geom.json'+s=open(SRC,encoding='utf8',errors='replace').read()++def toks(txt,i):+ """return (list, next_index) parsing one s-expr starting at txt[i]=='('"""+ assert txt[i]=='('+ out=[];i+=1;cur=''+ while i<len(txt):+ c=txt[i]+ if c=='(':+ sub,i=toks(txt,i); + if cur: out.append(cur); cur=''+ out.append(sub); continue+ if c==')':+ if cur: out.append(cur)+ return out,i+1+ if c=='"':+ j=i+1;buf=''+ while txt[j]!='"' or txt[j-1]=='\\':+ buf+=txt[j];j+=1+ if cur: out.append(cur);cur=''+ out.append(('STR',buf)); i=j+1; continue+ if c.isspace():+ if cur: out.append(cur);cur=''+ i+=1;continue+ cur+=c;i+=1+ return out,i++def find_all(node,name):+ for c in node:+ if isinstance(c,list) and c and c[0]==name: yield c+def get(node,name):+ for c in find_all(node,name): return c+ return None+def sval(x): return x[1] if isinstance(x,tuple) else x+def nums(node,n=2,start=1):+ return [float(sval(v)) for v in node[start:start+n]]++print('parsing…',file=sys.stderr)+root,_=toks(s,s.index('(kicad_pcb'))+print('top-level children:',len(root),file=sys.stderr)++def xf(px,py,ox,oy,rot):+ a=math.radians(rot)+ return (ox+px*math.cos(a)+py*math.sin(a), oy-px*math.sin(a)+py*math.cos(a))++edges=[];silk=[];pads=[];fabtext=[];courts=[]+def layer_of(n):+ l=get(n,'layer')+ return sval(l[1]) if l else ''+def layers_of(n):+ l=get(n,'layers')+ return [sval(v) for v in l[1:]] if l else []++def arc_pts(x1,y1,xm,ym,x2,y2,steps=16):+ # circle through 3 points+ ax,ay,bx,by,cx,cy=x1,y1,xm,ym,x2,y2+ d=2*(ax*(by-cy)+bx*(cy-ay)+cx*(ay-by))+ if abs(d)<1e-9: return [(x1,y1),(x2,y2)]+ ux=((ax*ax+ay*ay)*(by-cy)+(bx*bx+by*by)*(cy-ay)+(cx*cx+cy*cy)*(ay-by))/d+ uy=((ax*ax+ay*ay)*(cx-bx)+(bx*bx+by*by)*(ax-cx)+(cx*cx+cy*cy)*(bx-ax))/d+ r=math.hypot(ax-ux,ay-uy)+ a1=math.atan2(ay-uy,ax-ux);am=math.atan2(by-uy,bx-ux);a2=math.atan2(cy-uy,cx-ux)+ def norm(a,b):+ while b-a>math.pi: b-=2*math.pi+ while b-a<-math.pi: b+=2*math.pi+ return b+ am=norm(a1,am); a2=norm(am,a2)+ return [(ux+r*math.cos(a1+(a2-a1)*t/steps), uy+r*math.sin(a1+(a2-a1)*t/steps)) for t in range(steps+1)]++# ---- board graphics+for n in root:+ if not isinstance(n,list) or not n: continue+ t=n[0]+ if t in ('gr_line','gr_arc','gr_rect','gr_circle','gr_poly'):+ if layer_of(n)!='Edge.Cuts': continue+ if t=='gr_line': edges.append(('L',nums(get(n,'start'))+nums(get(n,'end'))))+ elif t=='gr_arc': edges.append(('A',nums(get(n,'start'))+nums(get(n,'mid'))+nums(get(n,'end'))))+ elif t=='gr_rect': edges.append(('R',nums(get(n,'start'))+nums(get(n,'end'))))+ elif t=='gr_circle': edges.append(('C',nums(get(n,'center'))+nums(get(n,'end'))))+ elif t=='gr_poly':+ pts=get(n,'pts'); edges.append(('P',[nums(p) for p in find_all(pts,'xy')]))++fps=[]+for n in find_all(root,'footprint'):+ at=get(n,'at'); ox,oy=nums(at); rot=float(sval(at[3])) if len(at)>3 else 0.0+ ref=''+ for p in find_all(n,'property'):+ if sval(p[1])=='Reference': ref=sval(p[2])+ lay=layer_of(n)+ fp={'ref':ref,'x':ox,'y':oy,'rot':rot,'layer':lay,'pads':[],'silk':[],'court':[]}+ for pd in find_all(n,'pad'):+ pat=get(pd,'at'); px,py=nums(pat); prot=float(sval(pat[3])) if len(pat)>3 else 0.0+ sz=get(pd,'size'); w,h=nums(sz) if sz else (0.5,0.5)+ shape=sval(pd[3]) if len(pd)>3 else 'rect'+ lys=layers_of(pd)+ gx,gy=xf(px,py,ox,oy,rot)+ fp['pads'].append({'x':gx,'y':gy,'w':w,'h':h,'rot':rot+prot,'shape':shape,'layers':lys,+ 'drill':bool(get(pd,'drill'))})+ for g in n:+ if not isinstance(g,list) or not g: continue+ gt=g[0]+ if gt in ('fp_line','fp_arc','fp_rect','fp_circle','fp_poly'):+ L=layer_of(g)+ tgt = fp['silk'] if L in ('F.SilkS','B.SilkS') else (fp['court'] if L in ('F.CrtYd','B.CrtYd') else None)+ if tgt is None: continue+ if gt=='fp_line':+ a=nums(get(g,'start'));b=nums(get(g,'end'))+ tgt.append(('L',[*xf(*a,ox,oy,rot),*xf(*b,ox,oy,rot)]))+ elif gt=='fp_arc':+ a=nums(get(g,'start'));m=nums(get(g,'mid'));b=nums(get(g,'end'))+ tgt.append(('A',[*xf(*a,ox,oy,rot),*xf(*m,ox,oy,rot),*xf(*b,ox,oy,rot)]))+ elif gt=='fp_rect':+ a=nums(get(g,'start'));b=nums(get(g,'end'))+ c=[(a[0],a[1]),(b[0],a[1]),(b[0],b[1]),(a[0],b[1])]+ tgt.append(('P',[xf(*p,ox,oy,rot) for p in c]))+ elif gt=='fp_circle':+ c=nums(get(g,'center'));e=nums(get(g,'end'))+ tgt.append(('C',[*xf(*c,ox,oy,rot),math.dist(c,e)]))+ elif gt=='fp_poly':+ pts=get(g,'pts'); tgt.append(('P',[xf(*nums(p),ox,oy,rot) for p in find_all(pts,'xy')]))+ fps.append(fp)++# ---- tracks+tracks=[]+for n in find_all(root,'segment'):+ tracks.append((nums(get(n,'start'))+nums(get(n,'end')), float(sval(get(n,'width')[1])), layer_of(n)))+vias=[]+for n in find_all(root,'via'):+ vias.append(nums(get(n,'at'))+[float(sval(get(n,'size')[1]))/2])+print(f'edges={len(edges)} fps={len(fps)} tracks={len(tracks)} vias={len(vias)}',file=sys.stderr)+json.dump({'edges':edges,'fps':fps,'tracks':tracks,'vias':vias},open(OUT,'w'))+print('wrote',OUT)
scripts/kicad_board_map.pyadded+138@@ -0,0 +1,138 @@+#!/usr/bin/env python3+"""kicad_board_map.py - render geom.json (from kicad_board_geom.py) as an SVG board map:+outline, copper, silkscreen, vias, pads coloured by functional section.++Usage: python3 kicad_board_map.py <geom.json> <F|B> <out.svg> [blocks.json]+blocks.json: {"section-id": ["R1","U2",...], ...} - optional; palette assigned in key order.+"""+import json,math,sys,itertools+G=json.load(open(sys.argv[1]))+side=sys.argv[2] if len(sys.argv)>2 else 'F'+out=sys.argv[3] if len(sys.argv)>3 else f'board-{side}.svg'+B=json.load(open(sys.argv[4])) if len(sys.argv)>4 else {}+BLK={r:k for k,v in B.items() for r in v}+PALETTE=['#f5a524','#f97316','#3b82f6','#a855f7','#06b6d4','#22c55e','#ef4444','#64748b',+ '#eab308','#14b8a6','#8b5cf6','#f43f5e']+COL={k:PALETTE[i%len(PALETTE)] for i,k in enumerate(B.keys())}+mode='map' if B else 'bare' ++xs=[];ys=[]+for k,d in G['edges']:+ if k=='L': xs+=[d[0],d[2]];ys+=[d[1],d[3]]+ elif k=='A': xs+=[d[0],d[2],d[4]];ys+=[d[1],d[3],d[5]]+ elif k=='R': xs+=[d[0],d[2]];ys+=[d[1],d[3]]+ elif k=='P': xs+=[p[0] for p in d];ys+=[p[1] for p in d]+X0,X1,Y0,Y1=min(xs),max(xs),min(ys),max(ys)+PAD=3; W=X1-X0+2*PAD; H=Y1-Y0+2*PAD+S=8 # px per mm+mir = (side=='B')+def T(x,y):+ X = (X1-x) if mir else (x-X0)+ return ((X+PAD)*S, (y-Y0+PAD)*S)++o=[]+o.append(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W*S:.1f} {H*S:.1f}" width="{W*S:.0f}" height="{H*S:.0f}" font-family="ui-sans-serif,system-ui,sans-serif">')+o.append('<defs><linearGradient id="fr4" x1="0" y1="0" x2="0" y2="1">'+ '<stop offset="0" stop-color="#0f3d2e"/><stop offset="1" stop-color="#0a2d22"/></linearGradient>'+ '<filter id="sh" x="-20%" y="-20%" width="140%" height="140%">'+ '<feDropShadow dx="0" dy="3" stdDeviation="4" flood-color="#000" flood-opacity=".45"/></filter></defs>')++# --- board outline path+def edge_path():+ segs=[]+ for k,d in G['edges']:+ if k=='L': segs.append([(d[0],d[1]),(d[2],d[3])])+ elif k=='A':+ ax,ay,mx,my,bx,by=d+ dd=2*(ax*(my-by)+mx*(by-ay)+bx*(ay-my))+ if abs(dd)<1e-9: segs.append([(ax,ay),(bx,by)]); continue+ ux=((ax*ax+ay*ay)*(my-by)+(mx*mx+my*my)*(by-ay)+(bx*bx+by*by)*(ay-my))/dd+ uy=((ax*ax+ay*ay)*(bx-mx)+(mx*mx+my*my)*(ax-bx)+(bx*bx+by*by)*(mx-ax))/dd+ r=math.hypot(ax-ux,ay-uy)+ a1=math.atan2(ay-uy,ax-ux);am=math.atan2(my-uy,mx-ux);a2=math.atan2(by-uy,bx-ux)+ while am-a1>math.pi: am-=2*math.pi+ while am-a1<-math.pi: am+=2*math.pi+ while a2-am>math.pi: a2-=2*math.pi+ while a2-am<-math.pi: a2+=2*math.pi+ N=14; segs.append([(ux+r*math.cos(a1+(a2-a1)*t/N), uy+r*math.sin(a1+(a2-a1)*t/N)) for t in range(N+1)])+ elif k=='R':+ x0,y0,x1,y1=d; segs.append([(x0,y0),(x1,y0),(x1,y1),(x0,y1),(x0,y0)])+ elif k=='P': segs.append([tuple(p) for p in d]+[tuple(d[0])])+ # chain segments into a loop+ used=[False]*len(segs); chain=list(segs[0]); used[0]=True+ for _ in range(len(segs)):+ best=None;bd=1e9+ for i,sg in enumerate(segs):+ if used[i]: continue+ for endp,pts in ((sg[0],sg),(sg[-1],list(reversed(sg)))):+ dd=math.dist(chain[-1],endp)+ if dd<bd: bd=dd;best=(i,pts)+ if best is None or bd>0.6: break+ used[best[0]]=True; chain+=best[1][1:]+ return 'M'+' L'.join(f'{T(*p)[0]:.2f},{T(*p)[1]:.2f}' for p in chain)+' Z'+EP=edge_path()+o.append(f'<path d="{EP}" fill="url(#fr4)" stroke="#134e37" stroke-width="1.2" filter="url(#sh)"/>')+o.append(f'<clipPath id="brd"><path d="{EP}"/></clipPath><g clip-path="url(#brd)">')++# --- tracks+tl = 'F.Cu' if side=='F' else 'B.Cu'+for (d,w,L) in G['tracks']:+ if L!=tl: continue+ a=T(d[0],d[1]);b=T(d[2],d[3])+ o.append(f'<line x1="{a[0]:.2f}" y1="{a[1]:.2f}" x2="{b[0]:.2f}" y2="{b[1]:.2f}" stroke="#b78227" stroke-opacity=".55" stroke-width="{w*S:.2f}" stroke-linecap="round"/>')+for v in G['vias']:+ p=T(v[0],v[1]); o.append(f'<circle cx="{p[0]:.2f}" cy="{p[1]:.2f}" r="{v[2]*S:.2f}" fill="#8a6420" fill-opacity=".6"/>')+o.append('</g>')++# --- block wash+if mode=='map':+ import collections+ bb=collections.defaultdict(lambda:[1e9,1e9,-1e9,-1e9])+ for f in G['fps']:+ k=BLK.get(f['ref'])+ if not k: continue+ for pd in f['pads']:+ r=max(pd['w'],pd['h'])/2+ b=bb[k]+ b[0]=min(b[0],pd['x']-r);b[1]=min(b[1],pd['y']-r);b[2]=max(b[2],pd['x']+r);b[3]=max(b[3],pd['y']+r)++# --- pads+for f in G['fps']:+ if f['layer']!=('F.Cu' if side=='F' else 'B.Cu') and not any(pd['drill'] for pd in f['pads']): continue+ k=BLK.get(f['ref']); c=COL.get(k,'#c9a227')+ for pd in f['pads']:+ if not (tl in pd['layers'] or '*.Cu' in pd['layers']): continue+ x,y=T(pd['x'],pd['y']); w,h=pd['w']*S,pd['h']*S+ rot=-pd['rot'] if not mir else pd['rot']+ rx = min(w,h)*0.22 if pd['shape'] in('roundrect','rect') else min(w,h)/2+ if pd['shape']=='circle': rx=min(w,h)/2+ o.append(f'<rect x="{-w/2:.2f}" y="{-h/2:.2f}" width="{w:.2f}" height="{h:.2f}" rx="{rx:.2f}" '+ f'fill="{c}" fill-opacity="{0.95 if mode=="map" else 0.85}" transform="translate({x:.2f},{y:.2f}) rotate({rot:.1f})"/>')++# --- silkscreen+sl='F.SilkS' if side=='F' else 'B.SilkS'+o.append('<g stroke="#e9eef2" stroke-opacity=".7" fill="none" stroke-width="0.9" stroke-linecap="round">')+for f in G['fps']:+ for k,d in f['silk']:+ if k=='L':+ a=T(d[0],d[1]);b=T(d[2],d[3]); o.append(f'<path d="M{a[0]:.2f},{a[1]:.2f}L{b[0]:.2f},{b[1]:.2f}"/>')+ elif k=='P':+ pts=' '.join(f'{T(*p)[0]:.2f},{T(*p)[1]:.2f}' for p in d); o.append(f'<polygon points="{pts}" fill="#e9eef2" fill-opacity=".5" stroke="none"/>')+ elif k=='C':+ p=T(d[0],d[1]); o.append(f'<circle cx="{p[0]:.2f}" cy="{p[1]:.2f}" r="{d[2]*S:.2f}"/>')+ elif k=='A':+ a=T(d[0],d[1]);m=T(d[2],d[3]);b=T(d[4],d[5])+ o.append(f'<path d="M{a[0]:.2f},{a[1]:.2f}Q{m[0]:.2f},{m[1]:.2f} {b[0]:.2f},{b[1]:.2f}"/>')+o.append('</g>')++# --- refdes labels for the map+if mode=='map':+ o.append('<g font-size="7" text-anchor="middle" fill="#eaf2ee" font-weight="600">')+ BIG={'U2','U1','U3','U4','U5','U6','J1','J2','J3','J6','J16','J23','SW1','SW2','SW3','Y1','F1','F2','D15','D16','C9'}+ for f in G['fps']:+ if f['ref'] in BIG or f['ref'].startswith('J') and f['ref'][1:].isdigit() and 7<=int(f['ref'][1:])<=13:+ x,y=T(f['x'],f['y']); o.append(f'<text x="{x:.1f}" y="{y-6:.1f}" stroke="#07231a" stroke-width="2" paint-order="stroke">{f["ref"]}</text>')+ o.append('</g>')+o.append('</svg>')+open(out,'w').write('\n'.join(o))+print('wrote',out, f'{W*S:.0f}x{H*S:.0f}px ({X1-X0:.1f}x{Y1-Y0:.1f} mm)')
scripts/preview_readme/preview.htmladded+69@@ -0,0 +1,69 @@+<meta charset="utf-8">+<title>Feeder Reader — wiki page preview (readme-frame mirror)</title>+<meta name="viewport" content="width=device-width, initial-scale=1">+<!--+ Mirrors how wiki.adom.inc actually hosts a README:+ · the page body is ONE iframe (#readme-frame)+ · sandboxed "allow-scripts allow-downloads" — NO allow-same-origin, so the document+ inside is an opaque origin: relative URLs 404, storage throws, nested src= iframes+ are blocked (publish skill §8k)+ · the host listens for postMessage({type:"readme-height"}) and grows the frame,+ which is what makes the page one seamless scroll (§8k-0b)+ If it looks right here, it will look right on the wiki.+-->+<style>+ :root{ --bg:#0f141a; --ink:#e8eef5; --dim:#8fa2b6; --line:rgba(255,255,255,.10); }+ *{box-sizing:border-box}+ body{margin:0;background:var(--bg);color:var(--ink);+ font-family:ui-sans-serif,-apple-system,"Segoe UI",Inter,system-ui,sans-serif}+ header{position:sticky;top:0;z-index:10;display:flex;align-items:center;gap:14px;+ padding:9px 18px;background:rgba(15,20,26,.92);backdrop-filter:blur(10px);+ border-bottom:1px solid var(--line);font-size:12.5px}+ header b{font-weight:650}+ header .path{color:var(--dim);font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:11.5px}+ header .spacer{margin-left:auto}+ header .badge{background:rgba(34,197,94,.14);border:1px solid rgba(34,197,94,.3);+ color:#8fe6b0;border-radius:6px;padding:3px 8px;font-size:11px;font-weight:600}+ header .warn{background:rgba(245,165,36,.13);border:1px solid rgba(245,165,36,.32);+ color:#f0cf9a;border-radius:6px;padding:3px 8px;font-size:11px;font-weight:600}+ #hero{display:block;width:100%;height:auto}+ #readme-frame{display:block;width:100%;border:0;min-height:600px;background:#151b23}+ #hud{position:fixed;right:14px;bottom:14px;z-index:11;background:rgba(10,15,22,.9);+ border:1px solid var(--line);border-radius:9px;padding:8px 11px;font-size:11px;color:var(--dim);+ font-family:ui-monospace,SFMono-Regular,Menlo,monospace}+ #hud b{color:#dce6f2}+</style>++<header>+ <b>Adom Wiki</b>+ <span class="path">aravk / feeder-reader</span>+ <span class="badge">readme-frame mirror</span>+ <span class="spacer"></span>+ <span class="warn">LOCAL MOCK — not published</span>+</header>++<!-- the page hero: rendered in Hero Component Studio, composited in Hero Studio.+ On the wiki this is set with `adom-wiki page hero` and drawn by the page chrome,+ not by README.html — so it lives here in the mirror, above the frame. -->+<img id="hero" src="screenshots/hero.png" alt="Feeder Reader hero">++<iframe id="readme-frame" src="README.html"+ sandbox="allow-scripts allow-downloads"+ title="Feeder Reader page"></iframe>++<div id="hud">frame height: <b id="h">—</b> · resize msgs: <b id="n">0</b></div>++<script>+ // This is the wiki's app.js behaviour, reproduced: grow the frame to the height the+ // README reports, clamped 120–16000px.+ var frame = document.getElementById('readme-frame'), n = 0;+ addEventListener('message', function (ev) {+ var d = ev.data;+ if (!d || (d.type !== 'readme-height' && d.type !== 'resize')) return;+ var h = Math.max(120, Math.min(16000, +d.height || 0));+ frame.style.minHeight = '0';+ frame.style.height = h + 'px';+ document.getElementById('h').textContent = h + 'px';+ document.getElementById('n').textContent = ++n;+ });+</script>
scripts/preview_readme/serve.pyadded+17@@ -0,0 +1,17 @@+import http.server, socketserver, functools, sys++class H(http.server.SimpleHTTPRequestHandler):+ def log_message(self, *a): pass+ def end_headers(self):+ self.send_header('Cache-Control', 'no-store')+ # The README embeds the viewer as a srcdoc iframe sandboxed WITHOUT allow-same-origin,+ # so it runs at an opaque origin and every fetch it makes is cross-origin. The wiki's+ # blob host sends permissive CORS; mirror that here or the bundle fetch ERR_FAILEDs.+ self.send_header('Access-Control-Allow-Origin', '*')+ super().end_headers()++socketserver.ThreadingTCPServer.allow_reuse_address = True+d = sys.argv[1]; p = int(sys.argv[2])+with socketserver.ThreadingTCPServer(('127.0.0.1', p), functools.partial(H, directory=d)) as s:+ print('serving', d, 'on', p, flush=True)+ s.serve_forever()
scripts/publish_wiki_page.pyadded+279@@ -0,0 +1,279 @@+#!/usr/bin/env python3+"""+publish_wiki_page.py — programmatic reference for publishing to the Adom Wiki.++WHY THIS FILE EXISTS+--------------------+So a new AI session (or teammate) does NOT have to re-figure-out how to publish a+wiki page on the fly. Read these functions top-to-bottom and you understand the whole+lifecycle: auth → locate → clone → edit → snapshot → (preview+approve) → push → verify,+plus publishing a brand-new page. Every non-obvious step has a comment explaining the+"why" and the gotcha that bit us the first time.++HOW IT WORKS+------------+The Adom Wiki has ONE CLI: `adom-wiki` (a Rust binary, every call prints JSON). This+module is a thin, documented wrapper around it — there is no separate REST SDK to learn;+`adom-wiki api <url>`-style access exists but the pillar verbs below are the supported+surface. Everything here shells out to `adom-wiki` and parses the JSON, so the behaviour+is identical to what you'd type by hand — this file just makes the sequence copy-pasteable+and encodes the rules from the SKILL (pull-before-edit, snapshot, real changelog, verify).++USAGE+-----+ from publish_wiki_page import (+ ensure_author, find_page_owner, clone_page, snapshot, push_files,+ set_hero, verify_asset, publish_new_package,+ )++ # --- update an existing page ---+ owner = find_page_owner("in-s42atr") # pages may live under aravk/, not adom/+ work = clone_page(owner, "in-s42atr", "/tmp/edit-in-s42atr")+ snap = snapshot(work) # revert insurance+ # ... edit files under `work` ...+ # ... render a PREVIEW and get EXPLICIT human approval (NOT done here) ...+ push_files(owner, "in-s42atr", ["IN-S42ATR.html"],+ "Fix brightness-vs-temp curve to match datasheet page 5")+ verify_asset("in-s42atr", "IN-S42ATR.html") # confirm the blob is live++ # --- publish a brand-new page/skill/component ---+ publish_new_package("/path/to/pkg", org="adom", private=True,+ changelog="Initial <slug> v0.1.0 — <what it is>")++This file is deliberately dependency-free (stdlib only) so it runs anywhere the+`adom-wiki` binary is on PATH.+"""++from __future__ import annotations+import json+import os+import shutil+import subprocess+import sys+import time+import urllib.request+import urllib.error++TOKEN_PATH = os.path.expanduser("~/.config/adom-wiki/token") # set by `adom-wiki set-author`++WIKI_HOST = "https://wiki.adom.inc" # public path — verify assets here, not localhost+BLOB = WIKI_HOST + "/blob/component/{slug}/{file}" # the URL the page + 3D viewer fetch+++# --------------------------------------------------------------------------- #+# Low-level: run the adom-wiki CLI and parse its JSON envelope.+# --------------------------------------------------------------------------- #+def wiki(*args: str, check: bool = True) -> dict | list | str:+ """Run `adom-wiki <args>` and return parsed JSON (or raw text if not JSON).++ Every adom-wiki verb prints a JSON envelope to stdout. We parse it. On a+ non-zero exit we raise with the stderr so failures are loud, not silent.+ """+ proc = subprocess.run(["adom-wiki", *args], capture_output=True, text=True)+ if check and proc.returncode != 0:+ raise RuntimeError(f"adom-wiki {' '.join(args)} failed:\n{proc.stderr or proc.stdout}")+ out = proc.stdout.strip()+ try:+ return json.loads(out)+ except json.JSONDecodeError:+ return out+++# --------------------------------------------------------------------------- #+# Auth — WIKI_STRICT_AUTH is ON: real author identity + real changelog required.+# --------------------------------------------------------------------------- #+def whoami() -> dict:+ """Who will publishes be attributed to? (server-controlled, from the bearer token)."""+ return wiki("whoami")+++def ensure_author() -> None:+ """Make sure we publish under a real Adom identity, not the shared 'Developer' token.++ The CLI hard-blocks publishing as the shared identity. `set-author` SSOs the+ container's Adom identity into the wiki (writes a token to ~/.config/adom-wiki/).+ Idempotent — safe to call every run.+ """+ me = whoami()+ user = (me or {}).get("user", {}) if isinstance(me, dict) else {}+ if not user.get("email"):+ wiki("set-author")+++# --------------------------------------------------------------------------- #+# Locate — a page's OWNER is not always `adom`. Basic-parts live under `aravk/`.+# --------------------------------------------------------------------------- #+def page_exists(owner: str, slug: str) -> bool:+ """True if <owner>/<slug> resolves. A 404 here does NOT mean the page doesn't+ exist — only that it doesn't exist UNDER THAT OWNER (see find_page_owner)."""+ res = wiki("page", "stats", f"{owner}/{slug}", check=False)+ if isinstance(res, dict):+ return res.get("http_status") not in (404, "404") and "PAGE_NOT_FOUND" not in json.dumps(res)+ return False+++def find_page_owner(slug: str, candidates: list[str] | None = None) -> str | None:+ """Find which owner a component page lives under. GOTCHA: the basic-parts pages+ are owned by `aravk`, not `adom` — a naive `adom/<slug>` check 404s. We also+ fall back to full-text discovery to catch any other owner."""+ for owner in (candidates or ["aravk", "adom"]):+ if page_exists(owner, slug):+ return owner+ # last resort: search and read the owner off the first exact-slug hit+ res = wiki("discover", "search", "--query", slug, "--limit", "10", check=False)+ for hit in (res.get("results", []) if isinstance(res, dict) else []):+ if hit.get("slug") == slug:+ return hit.get("owner")+ return None+++# --------------------------------------------------------------------------- #+# Clone / snapshot — ALWAYS pull fresh before editing; ALWAYS snapshot before push.+# --------------------------------------------------------------------------- #+def clone_page(owner: str, slug: str, dest: str) -> str:+ """Pull the page's repo fresh into `dest`. RULE: do this immediately before you+ edit — someone else may have pushed since your last pull, and a stale local copy+ will clobber their work on push."""+ if os.path.exists(dest):+ shutil.rmtree(dest)+ wiki("repo", "clone", f"{owner}/{slug}", "--dir", dest)+ return dest+++def snapshot(work_dir: str, stamp: str | None = None) -> str:+ """Copy the pristine pulled state to a timestamped folder so revert is a one-liner.+ Pass `stamp` explicitly (Date.now-style calls are unavailable in some sandboxes)."""+ stamp = stamp or str(int(time.time()))+ snap = f"{work_dir.rstrip('/')}-snapshot-{stamp}"+ shutil.copytree(work_dir, snap)+ print(f"snapshot: {snap} (revert with: cp -r {snap}/* {work_dir}/ && push)")+ return snap+++# --------------------------------------------------------------------------- #+# Push — only the files you changed, only this page, with a REAL changelog.+# --------------------------------------------------------------------------- #+def push_files(owner: str, slug: str, files: list[str], changelog: str) -> dict:+ """Commit + push `files` (paths RELATIVE to the page repo root) to <owner>/<slug>.++ RULES enforced by the server (WIKI_STRICT_AUTH):+ - changelog must be >=10 chars, >=2 words, and NOT a placeholder ('update',+ 'release v1', ...). Make it describe the actual change (cite the datasheet+ page for characterization edits).+ - only the files you list are pushed. Never push files you didn't change and+ never touch another page.+ Run this from inside the page's working dir, or pass repo-relative paths.+ """+ if len(changelog.split()) < 2 or len(changelog) < 10:+ raise ValueError(f"changelog too weak (needs >=2 words, >=10 chars): {changelog!r}")+ return wiki("repo", "push", "--files", *files, "-m", changelog, f"{owner}/{slug}")+++def repo_log(owner: str, slug: str, limit: int = 5) -> dict:+ """Like `git log` for the page — confirm ONLY your commit landed after a push."""+ return wiki("repo", "log", f"{owner}/{slug}", "--limit", str(limit))+++# --------------------------------------------------------------------------- #+# Hero — the page card image. GOTCHA: this verb takes NO --changelog.+# --------------------------------------------------------------------------- #+def set_hero(owner: str, slug: str, image_rel_path: str) -> dict:+ """Set the page hero/billboard image (path relative to the page repo)."""+ return wiki("page", "hero", f"{owner}/{slug}", "--image", image_rel_path)+++# --------------------------------------------------------------------------- #+# Verify — fetch the served blob (the path the page + viewer actually fetch),+# NOT localhost. GOTCHA: private pages return 403 to UNAUTHENTICATED requests, so+# we send the same bearer token adom-wiki uses. Comparing the returned byte_count+# to the file you pushed is the real proof (a stable URL means a 200 alone doesn't+# tell you the *new* bytes are live — an in-place overwrite keeps the URL).+# --------------------------------------------------------------------------- #+def verify_asset(slug: str, filename: str, timeout: int = 15) -> tuple[int, int]:+ """GET the served blob (authenticated) and return (http_status, byte_count).+ Cross-check byte_count against the local file's size. If this still 403s, the+ push still landed — confirm with `repo_log(...)` that your commit is at HEAD."""+ req = urllib.request.Request(BLOB.format(slug=slug, file=filename))+ if os.path.exists(TOKEN_PATH):+ with open(TOKEN_PATH) as fh:+ req.add_header("Authorization", "Bearer " + fh.read().strip())+ try:+ with urllib.request.urlopen(req, timeout=timeout) as r:+ return r.status, len(r.read())+ except urllib.error.HTTPError as e:+ return e.code, 0+++# --------------------------------------------------------------------------- #+# New page — scaffold + publish a fresh page/skill/component/app.+# --------------------------------------------------------------------------- #+def init_package(slug: str, ptype: str = "component", title: str | None = None) -> dict:+ """Scaffold a new package dir (package.json + README + SKILL/skeleton) in ./<slug>/.+ ptype ∈ {app, skill, component, bootstrap}."""+ args = ["pkg", "init", slug, "--type", ptype]+ if title:+ args += ["--title", title]+ return wiki(*args)+++def lint_package(pkg_dir: str) -> dict:+ """Pre-publish linter. errors[] must be empty to publish (hero image is a common+ blocker); warnings[] (e.g. no README screenshots) do not block."""+ cwd = os.getcwd()+ try:+ os.chdir(pkg_dir)+ return wiki("pkg", "lint")+ finally:+ os.chdir(cwd)+++def publish_new_package(pkg_dir: str, org: str | None = None, private: bool = False,+ changelog: str = "") -> dict:+ """Publish the package in `pkg_dir` (contains package.json). For an org-owned+ private page: org='adom', private=True. Lints first and refuses on hard errors."""+ lint = lint_package(pkg_dir)+ if isinstance(lint, dict) and lint.get("errors"):+ raise RuntimeError(f"lint errors block publish: {lint['errors']}")+ args = ["pkg", "publish"]+ if org:+ args += ["--org", org]+ args += ["--private"] if private else ["--public"]+ if changelog:+ args += ["-m", changelog]+ cwd = os.getcwd()+ try:+ os.chdir(pkg_dir)+ return wiki(*args)+ finally:+ os.chdir(cwd)+++# --------------------------------------------------------------------------- #+# Worked flows — read these to see the full sequence. Guarded so importing or+# running with no args does nothing destructive.+# --------------------------------------------------------------------------- #+def _demo_update_existing(slug: str, changed_files: list[str], changelog: str) -> None:+ """The canonical 'edit an existing component page' flow. This function does the+ SAFE steps automatically (auth, locate, clone, snapshot) and STOPS before push so+ a human can preview + approve — publishing is never silent."""+ ensure_author()+ owner = find_page_owner(slug)+ if not owner:+ raise SystemExit(f"no page found for slug {slug!r}")+ work = clone_page(owner, slug, f"/tmp/edit-{slug}")+ snapshot(work)+ print(f"\nPulled {owner}/{slug} into {work}.")+ print("NEXT (do by hand): edit the files, render a PREVIEW, get EXPLICIT approval, then:")+ print(f' push_files("{owner}", "{slug}", {changed_files!r}, "{changelog}")')+ print(f' verify_asset("{slug}", "{changed_files[0]}")')+++if __name__ == "__main__":+ if len(sys.argv) >= 2 and sys.argv[1] == "whoami":+ print(json.dumps(whoami(), indent=2))+ elif len(sys.argv) >= 3 and sys.argv[1] == "owner":+ print(find_page_owner(sys.argv[2]))+ else:+ print(__doc__)+ print("Quick checks: python3 publish_wiki_page.py whoami")+ print(" python3 publish_wiki_page.py owner <slug>")
scripts/verify_seek_example.cjsadded+25@@ -0,0 +1,25 @@+const puppeteer=require('puppeteer');+const S=[['assembly',4.0,'a1'],['assembly',9.5,'a2'],['assembly',26.0,'a3'],+ ['walkthrough',14,'w1'],['walkthrough',40,'w2'],+ ['operation',3,'o1'],['operation',9,'o2'],['operation',20,'o3']];+(async()=>{+ const out=process.argv[2];+ const b=await puppeteer.launch({headless:'new',args:['--no-sandbox','--enable-webgl','--use-gl=swiftshader','--enable-unsafe-swiftshader','--disable-dev-shm-usage']});+ const p=await b.newPage(); await p.setViewport({width:1280,height:800});+ p.on('pageerror',e=>console.log('PAGEERROR:',e.message));+ await p.goto('http://127.0.0.1:8891/feeder-reader-viewer.html',{waitUntil:'domcontentloaded',timeout:90000});+ await p.waitForFunction(()=>!!window.__dbg,{timeout:180000});+ for (const [m,t,tag] of S){+ await p.evaluate((m,t)=>{ const d=window.__dbg; d.setMode(m); d.pause(); d.t=t; },m,t);+ await new Promise(r=>setTimeout(r,2500)); // a few frames so the loop applies state+ await p.evaluate(()=>window.__dbg.snap());+ await new Promise(r=>setTimeout(r,2500));+ const info=await p.evaluate(()=>({t:+window.__dbg.t.toFixed(1),focus:window.__dbg.focus,+ vis:window.__dbg.COMPONENTS.filter(x=>x.meshes[0].visibility>0.5).length,+ cap:document.querySelector('#caption .head').textContent.slice(0,44),+ shown:document.getElementById('caption').classList.contains('show')}));+ console.log(tag,m,JSON.stringify(info));+ await p.screenshot({path:`${out}/s-${tag}.png`});+ }+ await b.close();+})().catch(e=>{console.error('FAIL',e.message);process.exit(1)});
uninstall.shadded+3@@ -0,0 +1,3 @@+#!/bin/sh+rm -rf "$HOME/.claude/skills/adom-hardware-component-publish"+echo "uninstalled: adom-hardware-component-publish"