← Commit history
Merge PR #586: AI Flow 0.2.100: components table (#238, #239), model fit (#240), KiCad focus rule (release-0.2.100 -> main) merge
Showing changes introduced by the merge (against its first parent).
16 files changed
+374−25
Cargo.lock+10−10Cargo.toml+1−1SKILL.md+1−1bin/adom-aiflowcrates/adom-aiflow/src/main.rs+27−3crates/adom-aiflow/src/model_fit.rs+72crates/aiflow-bridge/src/focus.rs+45crates/aiflow-bridge/src/lib.rs+22docs/isolated-kicad-read-socket.md+1−1docs/release-0.2.100.md+18package.json+1−1page.json+1−1skills/adom-aiflow/SKILL.md+1−1skills/aiflow-project-page/SKILL.md+1tests/page-build-components.py+68tools/page-build.py+105−6Cargo.lock+10−10@@ -4,7 +4,7 @@ version = 4 [[package]] name = "adom-aiflow"-version = "0.2.99"+version = "0.2.100" dependencies = [ "aiflow-analyze", "aiflow-board",@@ -25,7 +25,7 @@ dependencies = [ [[package]] name = "aiflow-analyze"-version = "0.2.99"+version = "0.2.100" dependencies = [ "aiflow-board", "serde",@@ -35,7 +35,7 @@ dependencies = [ [[package]] name = "aiflow-board"-version = "0.2.99"+version = "0.2.100" dependencies = [ "roxmltree", "serde",@@ -44,7 +44,7 @@ dependencies = [ [[package]] name = "aiflow-bridge"-version = "0.2.99"+version = "0.2.100" dependencies = [ "aiflow-board", "serde",@@ -53,7 +53,7 @@ dependencies = [ [[package]] name = "aiflow-copper"-version = "0.2.99"+version = "0.2.100" dependencies = [ "aiflow-board", "aiflow-grid",@@ -63,7 +63,7 @@ dependencies = [ [[package]] name = "aiflow-grid"-version = "0.2.99"+version = "0.2.100" dependencies = [ "aiflow-board", "serde",@@ -72,7 +72,7 @@ dependencies = [ [[package]] name = "aiflow-place"-version = "0.2.99"+version = "0.2.100" dependencies = [ "aiflow-board", "serde",@@ -81,7 +81,7 @@ dependencies = [ [[package]] name = "aiflow-pours"-version = "0.2.99"+version = "0.2.100" dependencies = [ "aiflow-board", "aiflow-copper",@@ -91,7 +91,7 @@ dependencies = [ [[package]] name = "aiflow-router"-version = "0.2.99"+version = "0.2.100" dependencies = [ "aiflow-board", "aiflow-grid",@@ -101,7 +101,7 @@ dependencies = [ [[package]] name = "aiflow-run"-version = "0.2.99"+version = "0.2.100" dependencies = [ "serde", "serde_json",
Cargo.toml+1−1@@ -14,7 +14,7 @@ members = [ ] [workspace.package]-version = "0.2.99"+version = "0.2.100" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
SKILL.md+1−1@@ -323,7 +323,7 @@ Deterministic checks that report, each an OK or FINDINGS with suggestions (never - **`netlist check [--sch design.kicad_sch] [--board B] [--net exported.net]`**: exports the schematic's netlist with kicad-cli (`sch export netlist --format kicadsexpr`, through `ADOM_AIFLOW_KICAD_CLI`; `adom-aiflow-kicad-cli-remote` does it on a desktop's KiCad 10 and carries the sub-sheets, lib tables and `${KIPRJMOD}` symbol libraries) and compares it pin by pin with the board's pads: missing and extra references, and every pin whose net differs (`/VIN` equals `VIN`; unlabelled `Net-(...)` nets compare by their pins). In a run it is recorded; `finish` re-checks the stored netlist against the board it finishes on and asks again when the schematic changed. - **`molecule check [--board B --spec S]`**, and inside `place check`, `gate` and `finish` whenever the spec has `"molecule": {...}`: MP1 to MP4 are MachinePin footprints (MediumShort 1.6 mm pad / 1.2 mm drill, or large 5.2 / 3.45), MP1 is the front-left pin and MP2 to MP4 follow counterclockwise seen from above (back left, back right, front right), the four sit on a rectangle whose sides are whole grid steps (a warning when not 4 mm multiples, which a LrgMed scaffold needs), every MachineContact (medium 1.3 / 0.78) sits on the grid from MP1, pins and contacts keep the edge margin, `molecule.fixed` positions hold, and `fixedRefs` are where the start board had them. Corner-pin class (0.2.17, issue #87): an error when the pins are medium but the board needs large ones (seats in the base scaffold, over 100 g with its parts, a motor, actuator, heatsink over 20 g, cabled connector or hard-pressed button, longest side over 100 mm, or a pin net over 3.5 A in `spec.loads`); a warning when the mass is unknown or a part looks like an undeclared mechanical load; large pins with no reason are fine. The rule, its data and the spec fields are in skill aiflow-molecule. Spec: `"molecule": {"gridMm": 2, "edgeMarginMm": 2, "cornerPinsNet": "GND", "contacts": [...], "fixed": {"J1": [0, 12]}, "seat": "base|lrgmed|board", "massG": 42, "mechanicalLoads": [{"ref": "M1", "kind": "motor"}], "pinCurrentA": 1.2}` (mm from MP1, y up; all optional); `--bom <csv>` (default: the run's BOM) gives a `mass_g` column. - **Fab rules**: `"fab": {"rules": "fab" | "jlcpcb"}` in the spec. `fab` (the 3rd party fab) requires the project's own `.kicad_dru` beside the board; those rules are private and never shipped or restated. `jlcpcb` requires the JLCPCB pack for the board's copper layer count: on 2 layers the shipped profile, installed with `rules install --profile jlcpcb --layers 2` (JLCPCB's published 2-layer capabilities, cited in the file; `--force` replaces another rules file, keeps it as `.kicad_dru.bak` and says what it replaced); on 4, 6 or more layers `rules use --profile jlcpcb --layers <n>` loads the pack from adom/pcb-design-rules (`rules install` refuses a layer count it does not ship). A layer suffix pins the count: `"rules": "jlcpcb-6L"`. When the spec has no `fab.rules`, the gate, finish and `rules check` use what `rules use` recorded in run.json `fabRules` (an intake run has no spec yet), and warn when the spec and `fabRules` disagree. `rules check` says whether the board matches; the gate and finish refuse when it does not.-- **3D models right way up**: `models` (and `models --offline`, no bridge) takes every bound model's bbox from `step2glb features` on the shared service (paced, cached per file in the run; the STEP file's own points when the service gives nothing), applies the footprint's rotate/offset as KiCad does, and warns when a flat SMD chip's thinnest axis is not Z or an SMD body's bottom is off the board. Fix the binding and look in the native 3D viewer; when a model is right as it is, `models --ack R1,C2 --why "<what you saw>"`. `finish` refuses while any warning is open. Never adom-chipsmith.+- **3D models right way up**: `models` (and `models --offline`, no bridge) takes every bound model's bbox from `step2glb features` on the shared service (paced, cached per file in the run; the STEP file's own points when the service gives nothing), applies the footprint's rotate/offset as KiCad does, and warns when a flat SMD chip's thinnest axis is not Z or an SMD body's bottom is off the board. Fix the binding and look in the native 3D viewer; when a model is right as it is, `models --ack R1,C2 --why "<what you saw>"`. `finish` refuses while any warning is open. Never adom-chipsmith. `models` also compares each top-side model with its footprint's body outline (F.Fab, else the courtyard) and, when its centre is off or it lies across the body, notes the offset or quarter turn that would centre it (issue #240): advisory, look in the native 3D viewer and fix the footprint's model or leave it. - **Pads are real copper in every board GLB**: after `step2glb convert`, `board-glb copper --glb <kicad.glb> --board <design>.kicad_pcb --out <board>.glb [--finish copper|enig|hasl] [--paste none|solder]` makes them so by construction from the footprints' layers (pad/via/track meshes by KiCad layer name get a copper material with explicit metal and roughness; the mask is rebuilt as the outline minus every F.Mask/B.Mask aperture; solder only on F.Paste/B.Paste apertures of fitted parts; test points stay bare copper), then runs the gate. `board-glb check` alone refuses grey or default-metal pads, a mask over any exposed pad centre, solder on a pad without paste, or a board file whose pads do not line up with the GLB. A board file with no pads and no F.Mask/B.Mask apertures has no exposed copper: the GLB is still written (substrate and silkscreen opaque, mask whole) and the gate passes with the note "no exposed copper on this board". In a run the result is recorded (`boardGlb`). Rule and details: aiflow-molecule. Never hand-recolour a material index or lift pads through the mask. ## The rules behind the stages
bin/adom-aiflow⋯ 1 unchanged line ⋯
crates/adom-aiflow/src/main.rs+27−3@@ -2,6 +2,7 @@ //! Every reply starts with OK: or ERROR: and carries Hint: lines that depend on this board and run. mod bare_lands; mod continuation;+mod model_fit; mod fields_versions; mod winpath; mod host_machine;@@ -3597,8 +3598,19 @@ fn netlist_gate(r: &Run) -> Result<String, String> { /// (warnings as [{ref, model, finding}], notes on what could not be checked). Bboxes are cached per /// file (path, size, mtime) in the run directory so reruns do not call the shared service again. fn model_orientation(board: &Board, project_dir: &Path, cache_path: Option<&Path>) -> (Vec<Value>, Vec<String>) {+ let (w, n, _) = model_orientation_fit(board, project_dir, cache_path);+ (w, n)+}++/// The orientation pass plus issue #240's in-plane fit: (warnings, notes, fit suggestions). The fit compares each+/// top-side model with its footprint's body outline (F.Fab, else the courtyard) and never blocks.+fn model_orientation_fit(board: &Board, project_dir: &Path, cache_path: Option<&Path>) -> (Vec<Value>, Vec<String>, Vec<Value>) { let mut cache: serde_json::Map<String, Value> = cache_path.and_then(|p| std::fs::read(p).ok()).and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default(); let (mut warnings, mut notes, mut calls) = (Vec::new(), Vec::new(), 0usize);+ let mut fits: Vec<Value> = Vec::new();+ let bodies: BTreeMap<String, (f64, f64, f64, f64)> = board.root.find_all("footprint")+ .filter(|fp| fp.find("layer").and_then(|l| l.value()) != Some("B.Cu"))+ .filter_map(|fp| Some((aiflow_board::reference_of(fp)?, mechanical::local_box(fp, &["F.Fab"]).or_else(|| mechanical::local_box(fp, &["F.CrtYd"]))?))).collect(); let mut unresolved: BTreeMap<String, Vec<String>> = BTreeMap::new(); for m in checks::model_refs(board) { let Some(file) = checks::resolve_model(&m.path, project_dir) else { unresolved.entry(m.path.clone()).or_default().push(m.reference.clone()); continue };@@ -3617,10 +3629,15 @@ fn model_orientation(board: &Board, project_dir: &Path, cache_path: Option<&Path for finding in checks::orientation_findings(&m, &placed) { warnings.push(json!({"ref": m.reference, "model": file.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default(), "rotate": m.rotate, "offset": m.offset, "bboxSource": src, "finding": finding})); }+ if let Some(mut f) = bodies.get(&m.reference).and_then(|b| model_fit::fit(&placed, *b, m.offset)) {+ f["ref"] = json!(m.reference);+ f["model"] = json!(file.file_name().map(|f| f.to_string_lossy().to_string()).unwrap_or_default());+ fits.push(f);+ } } for (p, refs) in unresolved { notes.push(format!("not checked here (path does not resolve in this container): {p} ({})", refs.join(","))); } if let Some(p) = cache_path { let _ = std::fs::write(p, serde_json::to_string_pretty(&Value::Object(cache)).unwrap_or_default()); }- (warnings, notes)+ (warnings, notes, fits) } /// Orientation warnings the AI has not acknowledged (run.data.modelAcks: {ref: why}).@@ -6951,7 +6968,7 @@ fn main() { ok(&format!("board open in the run's own KiCad editor (hwnd {}, pid {}), pipe {}; every live call of this run goes to it", iso.hwnd.map(|h| h.to_string()).unwrap_or("?".into()), iso.pid.map(|p| p.to_string()).unwrap_or("?".into()), iso.socket), &["Next: declare your first step (`step intake`, `step placement`); its clip starts by itself.".into(), "Edit live; after an offline edit to the file use `capture reload`, never a relaunch. Before closing: `capture close` (saves, then closes only this editor).".into(),- if raise { String::new() } else { "If KiCad comes in front on the human's screen, `adom-bridge kicad_set_settings '{\"backgroundGuard\":true}'` has the bridge push it behind once (off by default).".into() }]);+ if raise { String::new() } else { "On a hands-off machine AI Flow sends KiCad behind the person's window once when the open says they are working and KiCad came in front (KiCad Bridge 1.1.7+); nobody at the machine, it stays.".into() }]); } "open" => { let raise = screen_mode(&mut r).may_raise();@@ -8017,9 +8034,16 @@ fn main() { r.log("models-ack", json!({"refs": refs, "why": why})); } // the orientation pass: offline, every model bound on the board, right way up- let (orient, orient_notes) = model_orientation(&board_of(&r), &project_dir_of(&r), Some(&dir.join("model-bbox-cache.json")));+ let (orient, orient_notes, fits) = model_orientation_fit(&board_of(&r), &project_dir_of(&r), Some(&dir.join("model-bbox-cache.json"))); let unacked = unacked_orientation(&r, &orient); r.outcome("models-orientation", json!({"warnings": orient, "notChecked": orient_notes, "unacknowledged": unacked}));+ // issue #240: in-plane fit suggestions, advisory: a note now and in the outcome, never a stop+ r.outcome("models-fit", json!({"suggestions": fits}));+ if !fits.is_empty() {+ note(&format!("{} 3D model(s) may sit off their footprint in the board plane (advisory):\n{}", fits.len(),+ fits.iter().map(|f| format!(" {} {}: {}", f["ref"].as_str().unwrap_or(""), f["model"].as_str().unwrap_or(""), f["finding"].as_str().unwrap_or(""))).collect::<Vec<_>>().join("\n")),+ &["Look at each in the native 3D viewer: when the leads miss their holes or the body overlaps a neighbour, set the suggested offset (or turn) in the footprint's model and run `models` again. A body drawn off-centre on purpose (a connector mouth) is fine as it is.".into()]);+ } let orient_lines: Vec<String> = orient.iter().map(|w| format!(" {} {}: {}{}", w["ref"].as_str().unwrap_or(""), w["model"].as_str().unwrap_or(""), w["finding"].as_str().unwrap_or(""), if r.data["modelAcks"].get(w["ref"].as_str().unwrap_or("")).is_some() { " (acknowledged)" } else { "" })).collect(); let orient_hint = if unacked.is_empty() { String::new() } else { format!("3D orientation warnings to fix or acknowledge ({}): correct the model's rotate/offset in the footprint and look at it in the native 3D viewer, then `models` again; when the model is right as it is, `models --ack {} --why \"<what you saw>\"`. finish refuses while any stays open.", unacked.join(","), unacked.join(",")) }; if *offline {
crates/adom-aiflow/src/model_fit.rsadded+72@@ -0,0 +1,72 @@+//! Issue #240: does a bound 3D model sit on its footprint in the board plane? The up-axis and seating checks+//! (`checks::orientation_findings`) pass a model that is shifted across its pads: a trimmer STEP centred on its+//! body bound to a pin-1-origin footprint lands 2.54 mm off its holes. This compares the placed model's XY box+//! with the footprint's own body outline (F.Fab, else the courtyard) and suggests the offset (and a quarter+//! turn) that would centre it, with the residual. Advisory: imperfect catalog CAD never stops a run.+use crate::checks::BBox;+use serde_json::{json, Value};++/// The suggestion for one model, or None when it sits within tolerance: `placed` is the model's box after its+/// footprint offset, scale and rotation (model frame: Y up), `body` the footprint's body box in its own board+/// frame (Y down), `offset` the model's current offset.+pub fn fit(placed: &BBox, body: (f64, f64, f64, f64), offset: [f64; 3]) -> Option<Value> {+ let (mx0, mx1, my0, my1) = (placed[0][0], placed[0][1], -placed[1][1], -placed[1][0]);+ let (mw, mh) = (mx1 - mx0, my1 - my0);+ let (bw, bh) = (body.2 - body.0, body.3 - body.1);+ if mw <= 0.0 || mh <= 0.0 || bw <= 0.0 || bh <= 0.0 { return None; }+ let (mc, bc) = (((mx0 + mx1) / 2.0, (my0 + my1) / 2.0), ((body.0 + body.2) / 2.0, (body.1 + body.3) / 2.0));+ let (dx, dy) = (bc.0 - mc.0, bc.1 - mc.1);+ let residual = dx.hypot(dy);+ let tol = 0.5_f64.max(0.15 * bw.min(bh));+ // a quarter turn: both long, the long sides across each other, and the sizes match once turned+ let long = |w: f64, h: f64| w.max(h) / w.min(h) > 1.3;+ let close = |a: f64, b: f64| (a - b).abs() <= 0.25 * a.max(b);+ let turn = long(mw, mh) && long(bw, bh) && ((mw > mh) != (bw > bh)) && close(mw, bh) && close(mh, bw);+ if residual <= tol && !turn { return None; }+ let r3 = |v: f64| (v * 1000.0).round() / 1000.0;+ // the model offset is in the footprint's frame with Y up: a board-frame shift (dx, dy) is (dx, -dy) there+ let suggested = [r3(offset[0] + dx), r3(offset[1] - dy), offset[2]];+ let mut what = Vec::new();+ if residual > tol { what.push(format!("its centre is {:.2} mm from the body's ({:+.2}, {:+.2} mm on the board): offset ({:.3}, {:.3}) instead of ({:.3}, {:.3}) would centre it", residual, dx, dy, suggested[0], suggested[1], offset[0], offset[1])); }+ if turn { what.push(format!("it lies across the body ({:.2} x {:.2} mm against {:.2} x {:.2} mm): a 90 degree turn about Z would line it up", mw, mh, bw, bh)); }+ Some(json!({"dxMm": r3(dx), "dyMm": r3(dy), "residualMm": r3(residual), "toleranceMm": r3(tol), "offsetNow": offset, "offsetSuggested": suggested,+ "quarterTurn": turn, "finding": what.join("; ")}))+}++#[cfg(test)]+mod tests {+ use super::*;++ /// John's trimmer: three leads 2.54 mm apart, the footprint's origin pin 1, the body (F.Fab) centred on pin 2;+ /// the STEP is centred on its body, so bound with no offset it sits 2.54 mm left of its holes.+ #[test]+ fn a_body_centred_model_on_a_pin_one_footprint_is_told_its_offset() {+ let placed: BBox = [[-4.75, 4.75], [-2.5, 2.5], [0.0, 5.0]];+ let body = (-2.21, -2.5, 7.29, 2.5);+ let f = fit(&placed, body, [0.0, 0.0, 0.0]).expect("off by 2.54 mm");+ assert_eq!(f["dxMm"], 2.54);+ assert_eq!(f["offsetSuggested"][0], 2.54);+ assert_eq!(f["quarterTurn"], false);+ // with that offset the model sits on the body+ let moved: BBox = [[-2.21, 7.29], [-2.5, 2.5], [0.0, 5.0]];+ assert!(fit(&moved, body, [2.54, 0.0, 0.0]).is_none());+ }++ /// A model off in board Y: the suggestion flips the sign for the model frame (Y up).+ #[test]+ fn a_shift_in_board_y_becomes_the_opposite_model_offset() {+ let placed: BBox = [[-1.0, 1.0], [-1.0, 1.0], [0.0, 1.0]];+ let body = (-1.0, 1.0, 1.0, 3.0); // the body 2 mm further down the board+ let f = fit(&placed, body, [0.0, 0.0, 0.0]).unwrap();+ assert_eq!((f["dyMm"].as_f64(), f["offsetSuggested"][1].as_f64()), (Some(2.0), Some(-2.0)));+ }++ #[test]+ fn a_model_across_its_body_gets_a_quarter_turn_and_a_good_fit_gets_nothing() {+ let across: BBox = [[-1.0, 1.0], [-3.0, 3.0], [0.0, 1.0]];+ let f = fit(&across, (-3.0, -1.0, 3.0, 1.0), [0.0, 0.0, 0.0]).unwrap();+ assert_eq!(f["quarterTurn"], true);+ let good: BBox = [[-3.0, 3.0], [-1.0, 1.0], [0.0, 1.0]];+ assert!(fit(&good, (-3.1, -1.1, 3.1, 1.1), [0.0, 0.0, 0.0]).is_none());+ }+}
crates/aiflow-bridge/src/focus.rsadded+45@@ -0,0 +1,45 @@+//! KiCad Bridge 1.1.7 (kicad-lane): every verb that opens a KiCad window answers `userActivity {idleSeconds,+//! active}` (input within 60 s), `kicadInFront {hwnd, title}` or null. Colby's rule for a hands-off run: if the+//! person is working, keep KiCad behind (`kicad_send_to_back` once); if nobody is at the machine, in front is+//! fine. Never a loop.+use serde_json::Value;++#[derive(Debug, PartialEq)]+pub enum Action {+ /// The person is working and KiCad is in front: send this window behind once.+ SendBack(i64),+ /// Nothing to do, and why.+ Leave(String),+}++/// What the rule says for an open's reply, or None when the reply predates KiCad Bridge 1.1.7.+pub fn send_back_target(reply: &Value) -> Option<Action> {+ let d = reply.get("data").filter(|d| d.is_object() && d.get("userActivity").is_some()).unwrap_or(reply);+ let ua = d.get("userActivity").filter(|u| u.is_object())?;+ let active = ua["active"].as_bool() == Some(true);+ let front = d.get("kicadInFront").and_then(|k| k["hwnd"].as_i64()).filter(|h| *h != 0);+ Some(match (active, front) {+ (true, Some(h)) => Action::SendBack(h),+ (true, None) => Action::Leave("the person is working and KiCad stayed behind".into()),+ (false, Some(_)) => Action::Leave(format!("nobody at the machine (idle {} s): KiCad left in front", ua["idleSeconds"].as_u64().unwrap_or(0))),+ (false, None) => Action::Leave("nobody at the machine and KiCad behind".into()),+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn send_back_only_when_the_person_is_working_and_kicad_is_in_front() {+ let r = |active: bool, front: Value| json!({"success": true, "userActivity": {"idleSeconds": if active { 3 } else { 900 }, "active": active}, "kicadInFront": front});+ assert_eq!(send_back_target(&r(true, json!({"hwnd": 42, "title": "b — PCB Editor"}))), Some(Action::SendBack(42)));+ assert!(matches!(send_back_target(&r(true, Value::Null)), Some(Action::Leave(_))));+ assert!(matches!(send_back_target(&r(false, json!({"hwnd": 42}))), Some(Action::Leave(w)) if w.contains("idle 900 s")));+ // an older bridge says nothing: the caller keeps its own handling+ assert_eq!(send_back_target(&json!({"success": true, "hwnd": 42})), None);+ // the fields inside "data" too+ assert_eq!(send_back_target(&json!({"data": {"userActivity": {"active": true}, "kicadInFront": {"hwnd": 7}}})), Some(Action::SendBack(7)));+ }+}
crates/aiflow-bridge/src/lib.rs+22@@ -10,6 +10,7 @@ use serde_json::{json, Value}; pub mod altium; pub mod eda; pub mod fusion;+pub mod focus; pub mod isolated; pub mod landing; pub mod recorder;@@ -538,6 +539,13 @@ impl Bridge { let before = self.foreground(); let r = self.call("kicad_open_board", &json!({"filePath": remote_board, "foreground": false})); let Some(hwnd) = r.get("hwnd").and_then(|h| h.as_i64()).or_else(|| self.wait_board_window(remote_board, &r)) else { return Err(r) };+ // KiCad Bridge 1.1.7: the open says whether the person is working and whether KiCad came in front;+ // the bridge's own rule then (once, never a loop), no foreground guessing of ours+ if let Some(said) = self.follow_focus_rule(&r) {+ std::thread::sleep(std::time::Duration::from_secs(40));+ self.call("kicad_send_key", &json!({"hwnd": hwnd, "menu": "Zoom to Fit"}));+ return Ok((hwnd, format!("opened in the background, not maximised (screen hands-off), zoomed to fit; {said}")));+ } let mut done: Vec<String> = self.keep_behind(hwnd, before.as_ref()).into_iter().collect(); std::thread::sleep(std::time::Duration::from_secs(40)); // KiCad can come forward again when the board finishes loading@@ -564,6 +572,7 @@ impl Bridge { pub fn open_isolated(&self, remote_board: &str, reason: &str, raise: bool) -> Result<isolated::Isolated, isolated::Refusal> { let r = self.call("kicad_open_board", &json!({"filePath": remote_board, "isolated": true, "foreground": false, "reason": reason})); let mut iso = isolated::isolated_of(&r)?;+ if !raise { let _ = self.follow_focus_rule(&r); } if iso.hwnd.is_none() { iso.hwnd = self.wait_board_window(remote_board, &json!({"success": true})); } if let (true, Some(h)) = (raise, iso.hwnd) { self.call("desktop_ui_window", &json!({"hwnd": h, "action": "maximize", "reason": "aiflow capture: fill the monitor"}));@@ -572,6 +581,19 @@ impl Bridge { Ok(iso) } + /// KiCad Bridge 1.1.7's rule for a hands-off open: when the reply says the person is active and KiCad is in+ /// front, `kicad_send_to_back` once; otherwise leave it. None when the reply predates 1.1.7 (no+ /// `userActivity`), so the caller keeps its older handling; else what was done.+ pub fn follow_focus_rule(&self, reply: &Value) -> Option<String> {+ match focus::send_back_target(reply)? {+ focus::Action::SendBack(h) => {+ let r = self.call("kicad_send_to_back", &json!({"hwnd": h}));+ Some(if Self::ok(&r) { "KiCad came in front while the person was working: sent behind their window once".into() } else { format!("KiCad came in front while the person was working; kicad_send_to_back answered {}", r["errorCode"].as_str().or(r["error"].as_str()).unwrap_or("?")) })+ }+ focus::Action::Leave(why) => Some(why),+ }+ }+ /// The OS foreground window: {hwnd, pid, title}, None when there is none or it cannot be read. pub fn foreground(&self) -> Option<Value> { let r = self.raw_call("desktop_get_foreground", &json!({}));
docs/isolated-kicad-read-socket.md+1−1@@ -18,7 +18,7 @@ A task-owned instance can be launched with a process-local TEMP/TMP directory to - A board another KiCad has open is refused with `board_locked`: work on a copy (with its `.kicad_pro` and `.kicad_dru`), never close the other editor. - After an offline edit to the file, `capture reload` runs KiCad's own Revert over IPC: no prompt, no relaunch. It answers the revision, whether copper, parts or the outline changed (silkscreen and text reload but are not counted) and whether the editor matches the file. With unsaved edits in the editor it refuses (`unsaved_changes`): save first, or `capture reload --discard`. - `capture close` saves the board (`kicad_save_board {filePath, socketPath}`) and then closes only that editor (`kicad_close_document {path}`); `--discard` closes without saving. Closing discards whatever was not saved, so never close an editor with `kicad_close_document` yourself before saving.-- Focus: the bridge opens it behind the human's window. If KiCad still comes in front, `kicad_set_settings {"backgroundGuard": true}` has the bridge push it behind once (off by default).+- Focus (KiCad Bridge 1.1.7+): every open answers `userActivity {idleSeconds, active}` and `kicadInFront`. On a hands-off run, when the person is active and KiCad came in front, AI Flow calls `kicad_send_to_back` once (their window takes the activation back, nothing is minimised); when nobody is at the machine it leaves KiCad where it is. Never a loop. An older bridge keeps AI Flow's own foreground handling. An older KiCad bridge ignores `isolated` and answers no pipe; AI Flow then says so and changes nothing. Until the bridge is updated, on a `screen: hands-off` run work in the editor the bridge opened, use `kicad-cli` file checks for what needs no live editor, and ask the human, without waiting, to close the other session's KiCad or to allow the screen (`capture screen allowed`).
docs/release-0.2.100.mdadded+18@@ -0,0 +1,18 @@+# AI Flow 0.2.100++- **Components table grouped by part number, with price tiers** (#238, John). `project-page` writes one buy row+ per manufacturer and MPN: every reference kept, quantities summed, the line cost the quantity times the unit+ price. It reads 1-piece and 10-piece prices, their date and the distributor from the BOM's columns (`Price @1`,+ `Price @10`, `Price date`, `Source` and the usual variants), names the part numbers with no 10-piece price,+ adds a bold totals row, and links the per-reference BOM for assembly.+- **Chip thumbnails in the Components table** (#239, John). Each part's picture is its component page's own chip+ thumbnail: the roll-up icon `artwork/<MPN>-3d-iso-named-icon.png`, else the `chip-shaded` asset its+ `<MPN>-thumbs.json` manifest lists; the page hero and a STEP render only when it has neither.+- **3D model fit in the board plane** (#240, John). `models` compares each top-side model with its footprint's body+ outline (F.Fab, else the courtyard) and, when its centre is off by more than 0.5 mm (or 15 % of the body) or it+ lies across the body, notes the offset or quarter turn that would centre it, with the residual. Advisory: a+ note and the `models-fit` outcome, never a stop.+- **KiCad in front of a person** (KiCad Bridge 1.1.7, kicad-lane). On a hands-off run, after `capture open` (shared+ or `--isolated`), AI Flow follows the bridge's rule: when the open says the person is working and KiCad came+ in front, `kicad_send_to_back` once; when nobody is at the machine, leave it. An older bridge keeps AI Flow's own+ foreground handling.
package.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.99",+ "version": "0.2.100", "title": "AI Flow", "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.", "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
page.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.99",+ "version": "0.2.100", "title": "AI Flow", "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.", "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
skills/adom-aiflow/SKILL.md+1−1@@ -409,7 +409,7 @@ Deterministic checks that report, each an OK or FINDINGS with suggestions (never - **`netlist check [--sch design.kicad_sch] [--board B] [--net exported.net]`**: exports the schematic's netlist with kicad-cli (`sch export netlist --format kicadsexpr`, through `ADOM_AIFLOW_KICAD_CLI`; `adom-aiflow-kicad-cli-remote` does it on a desktop's KiCad 10 and carries the sub-sheets, lib tables and `${KIPRJMOD}` symbol libraries) and compares it pin by pin with the board's pads: missing and extra references, and every pin whose net differs (`/VIN` equals `VIN`; unlabelled `Net-(...)` nets compare by their pins). In a run it is recorded; `finish` re-checks the stored netlist against the board it finishes on and asks again when the schematic changed. - **`molecule check [--board B --spec S]`**, and inside `place check`, `gate` and `finish` whenever the spec has `"molecule": {...}`: MP1 to MP4 are MachinePin footprints (MediumShort 1.6 mm pad / 1.2 mm drill, or large 5.2 / 3.45), MP1 is the front-left pin and MP2 to MP4 follow counterclockwise seen from above (back left, back right, front right), the four sit on a rectangle whose sides are whole grid steps (a warning when not 4 mm multiples, which a LrgMed scaffold needs), every MachineContact (medium 1.3 / 0.78) sits on the grid from MP1, pins and contacts keep the edge margin, `molecule.fixed` positions hold, and `fixedRefs` are where the start board had them. Corner-pin class (0.2.17, issue #87): an error when the pins are medium but the board needs large ones (seats in the base scaffold, over 100 g with its parts, a motor, actuator, heatsink over 20 g, cabled connector or hard-pressed button, longest side over 100 mm, or a pin net over 3.5 A in `spec.loads`); a warning when the mass is unknown or a part looks like an undeclared mechanical load; large pins with no reason are fine. The rule, its data and the spec fields are in skill aiflow-molecule. Spec: `"molecule": {"gridMm": 2, "edgeMarginMm": 2, "cornerPinsNet": "GND", "contacts": [...], "fixed": {"J1": [0, 12]}, "seat": "base|lrgmed|board", "massG": 42, "mechanicalLoads": [{"ref": "M1", "kind": "motor"}], "pinCurrentA": 1.2}` (mm from MP1, y up; all optional); `--bom <csv>` (default: the run's BOM) gives a `mass_g` column. - **Fab rules**: `"fab": {"rules": "fab" | "jlcpcb"}` in the spec. `fab` (the 3rd party fab) requires the project's own `.kicad_dru` beside the board; those rules are private and never shipped or restated. `jlcpcb` requires the JLCPCB pack for the board's copper layer count: on 2 layers the shipped profile, installed with `rules install --profile jlcpcb --layers 2` (JLCPCB's published 2-layer capabilities, cited in the file; `--force` replaces another rules file, keeps it as `.kicad_dru.bak` and says what it replaced); on 4, 6 or more layers `rules use --profile jlcpcb --layers <n>` loads the pack from adom/pcb-design-rules (`rules install` refuses a layer count it does not ship). A layer suffix pins the count: `"rules": "jlcpcb-6L"`. When the spec has no `fab.rules`, the gate, finish and `rules check` use what `rules use` recorded in run.json `fabRules` (an intake run has no spec yet), and warn when the spec and `fabRules` disagree. `rules check` says whether the board matches; the gate and finish refuse when it does not.-- **3D models right way up**: `models` (and `models --offline`, no bridge) takes every bound model's bbox from `step2glb features` on the shared service (paced, cached per file in the run; the STEP file's own points when the service gives nothing), applies the footprint's rotate/offset as KiCad does, and warns when a flat SMD chip's thinnest axis is not Z or an SMD body's bottom is off the board. Fix the binding and look in the native 3D viewer; when a model is right as it is, `models --ack R1,C2 --why "<what you saw>"`. `finish` refuses while any warning is open. Never adom-chipsmith.+- **3D models right way up**: `models` (and `models --offline`, no bridge) takes every bound model's bbox from `step2glb features` on the shared service (paced, cached per file in the run; the STEP file's own points when the service gives nothing), applies the footprint's rotate/offset as KiCad does, and warns when a flat SMD chip's thinnest axis is not Z or an SMD body's bottom is off the board. Fix the binding and look in the native 3D viewer; when a model is right as it is, `models --ack R1,C2 --why "<what you saw>"`. `finish` refuses while any warning is open. Never adom-chipsmith. `models` also compares each top-side model with its footprint's body outline (F.Fab, else the courtyard) and, when its centre is off or it lies across the body, notes the offset or quarter turn that would centre it (issue #240): advisory, look in the native 3D viewer and fix the footprint's model or leave it. - **Pads are real copper in every board GLB**: after `step2glb convert`, `board-glb copper --glb <kicad.glb> --board <design>.kicad_pcb --out <board>.glb [--finish copper|enig|hasl] [--paste none|solder]` makes them so by construction from the footprints' layers (pad/via/track meshes by KiCad layer name get a copper material with explicit metal and roughness; the mask is rebuilt as the outline minus every F.Mask/B.Mask aperture; solder only on F.Paste/B.Paste apertures of fitted parts; test points stay bare copper), then runs the gate. `board-glb check` alone refuses grey or default-metal pads, a mask over any exposed pad centre, solder on a pad without paste, or a board file whose pads do not line up with the GLB. A board file with no pads and no F.Mask/B.Mask apertures has no exposed copper: the GLB is still written (substrate and silkscreen opaque, mask whole) and the gate passes with the note "no exposed copper on this board". In a run the result is recorded (`boardGlb`). Rule and details: aiflow-molecule. Never hand-recolour a material index or lift pads through the mask. Publish only the `board-glb copper` output, never the raw step2glb GLB. ## The rules behind the stages
skills/aiflow-project-page/SKILL.md+1@@ -56,6 +56,7 @@ Every board, molecule or project README (and readme.html) follows **wiki-readme* Before building the table, make sure every component page has the `::adom-chip-thumbnail` widget, that icon, and a hero image rendered from its hero GLB with footprint and silkscreen (**wiki-component**, "Every component page"). Fix any page that falls short first, so the table never shows a broken or copied icon. - **No schematic sheets inline.** Link the schematic PDF and sources once. Explain how the system works with high-level **animated** diagrams instead: signal flow, power, control and the physics, as animated SVGs in `docs/diagrams/` (SMIL/CSS inside the SVG, no scripts). - Check both in pup on the live page: the icons load, the totals add up, and the diagrams animate and are readable.+- `project-page --molecule-bundle` builds this table itself (issues #238, #239): one row per manufacturer and MPN with every reference and the summed quantity, the 1-piece and 10-piece prices with their date and source from the BOM's columns (`Price @1`, `Price @10`, `Price date`, `Source`), the lines with no 10-piece price named, a totals row, a link to the per-reference BOM, and each part's picture from its component page's chip thumbnail (`artwork/<MPN>-3d-iso-named-icon.png`, else the `chip-shaded` asset in `<MPN>-thumbs.json`), its hero only when it has neither. ## The page build: every board, after export (issues #131, #164, #197, #198, #200)
tests/page-build-components.pyadded+68@@ -0,0 +1,68 @@+"""page-build's Components table (issues #238, #239): one row per manufacturer and MPN with every reference and the+summed quantity, the 1-piece and 10-piece prices, their date and source read from the BOM, and the component+page's chip thumbnail looked up before its hero.++ python3 tests/page-build-components.py+"""+import importlib.util, os, tempfile, unittest+from pathlib import Path++SCRIPT = Path(__file__).resolve().parents[1] / "tools" / "page-build.py"+spec = importlib.util.spec_from_file_location("page_build", SCRIPT)+pb = importlib.util.module_from_spec(spec); spec.loader.exec_module(pb)++BOM = """Reference,Qty,Value,Manufacturer,MPN,Price @1,Price @10,Price date,Source+C1,1,1uF,Murata,GRM188R61E105KA12D,0.10,0.05,2026-11-22,Mouser+C2,1,1uF,Murata,GRM188R61E105KA12D,0.10,0.05,2026-11-22,Mouser+C10 C3,2,1uF,Murata,grm188r61e105ka12d,0.10,,2026-11-22,Mouser+U1,1,LDO,TI,TPS7A0233PDBVR,0.42,,2026-11-22,DigiKey+TP1,1,,,,,,,+"""+++class Components(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.bom = os.path.join(self.tmp.name, "bom.csv")+ open(self.bom, "w").write(BOM)++ def tearDown(self):+ self.tmp.cleanup()++ def test_rows_group_by_mpn_with_every_reference_and_the_tiers(self):+ lines, info = pb.bom_lines(self.bom, {"parts": {}}, {})+ self.assertEqual(info["price10Column"], "Price @10")+ self.assertEqual(info["priceColumn"], "Price @1")+ g = pb.group_lines(lines)+ parts = [l for l in g if not l["feature"]]+ self.assertEqual(len(parts), 2)+ cap = parts[0]+ self.assertEqual(cap["refs"], ["C1", "C2", "C3", "C10"])+ self.assertEqual(cap["qty"], 4)+ self.assertEqual((cap["unit"], cap["price10"], cap["line"]), (0.10, 0.05, 0.4))+ self.assertEqual((cap["priceDate"], cap["source"]), ("2026-11-22", "Mouser"))+ ldo = parts[1]+ self.assertIsNone(ldo["price10"])+ self.assertEqual(ldo["line"], 0.42)+ self.assertEqual(len([l for l in g if l["feature"]]), 1, "the test point is a board feature, kept apart")++ def test_the_chip_thumbnail_comes_before_the_hero(self):+ calls = []+ def fake(page, path, out):+ calls.append(path)+ if path.endswith("-3d-iso-named-icon.png"):+ open(out, "wb").write(b"png")+ return True+ return False+ real = pb._wiki_file+ pb._wiki_file = fake+ try:+ got = pb.chip_thumbnail("adom/x", "ABC1", self.tmp.name)+ finally:+ pb._wiki_file = real+ self.assertTrue(got and got.endswith(".icon.png"))+ self.assertEqual(calls, ["artwork/ABC1-3d-iso-named-icon.png"])+++if __name__ == "__main__":+ unittest.main()
tools/page-build.py+105−6@@ -1583,7 +1583,11 @@ def bom_lines(bom_path, design, run): c_wiki = col(fields, r"wiki", r"page", r"wiki ?page") c_role = col(fields, r"role", r"function", r"purpose", r"use") c_note = col(fields, r"notes?", r"comments?")- c_price = col(fields, r"unit[ _-]?price.*", r"price[ _-]?(usd|each|1|unit)?", r"(mouser|digikey|lcsc)[ _-]?price.*", r"cost")+ # issue #238: quantity tiers, "price_1" / "unit price (1)" / "price@10" / "mouser price 10" and the like+ c_p1 = col(fields, r"(unit[ _-]?)?price[ _@(x-]*(qty[ _-]?)?1\)?(pc|pcs)?", r"(mouser|digikey|lcsc)[ _-]?price[ _@(x-]*1\)?", r"(qty|q)[ _-]?1[ _-]?price")+ c_p10 = col(fields, r"(unit[ _-]?)?price[ _@(x-]*(qty[ _-]?)?10\)?(pc|pcs)?", r"(mouser|digikey|lcsc)[ _-]?price[ _@(x-]*10\)?", r"(qty|q)[ _-]?10[ _-]?price")+ c_pdate = col(fields, r"(price[ _-]?)?(lookup|checked|price)[ _-]?date", r"date[ _-]?(checked|looked[ _-]?up)?", r"as[ _-]?of")+ c_price = c_p1 or col(fields, r"unit[ _-]?price.*", r"price[ _-]?(usd|each|1|unit)?", r"(mouser|digikey|lcsc)[ _-]?price.*", r"cost") c_stock = col(fields, r"stock.*", r".*stock.*") c_src = col(fields, r"source", r"supplier", r"distributor") stock_date = None@@ -1605,6 +1609,8 @@ def bom_lines(bom_path, design, run): continue qty = int(money(r.get(c_qty)) or len(refs) or 1) if c_qty else (len(refs) or 1) unit = money(r.get(c_price)) if c_price else None+ p10 = money(r.get(c_p10)) if c_p10 else None+ pdate = (r.get(c_pdate) or "").strip() if c_pdate else "" if unit is None: unit = prices.get(mpn.upper()) dp = next((design["parts"][x] for x in refs if x in design["parts"]), {})@@ -1622,8 +1628,48 @@ def bom_lines(bom_path, design, run): "wiki": ((r.get(c_wiki) or "").strip() if c_wiki else "") or dp.get("page") or "", "role": role, "unit": unit, "line": round(unit * qty, 4) if unit is not None else None, "stock": (r.get(c_stock) or "").strip() if c_stock else "", "stockDate": stock_date,+ "price10": p10, "priceDate": pdate or stock_date or "", "source": (r.get(c_src) or "").strip() if c_src else "", "buy": "https://www.mouser.com/c/?q=" + urllib.parse.quote(mpn)})- return out, {"priceColumn": c_price, "stockColumn": c_stock, "file": bom_path}+ return out, {"priceColumn": c_price, "price10Column": c_p10, "priceDateColumn": c_pdate, "stockColumn": c_stock, "file": bom_path}+++def _ref_key(r):+ m = re.match(r"([A-Za-z_]*)(\d*)(.*)", r)+ return (m.group(1), int(m.group(2)) if m.group(2) else -1, m.group(3))+++def group_lines(lines):+ """Issue #238: one buy row per orderable part: the lines with the same manufacturer and MPN (case and spaces+ ignored) become one, every reference kept (sorted), quantities summed, the line cost the quantity times the+ unit price. A part whose lines carry different unit prices keeps the first and says so. Board features (no+ MPN) are left as they are."""+ out, by = [], {}+ for l in lines:+ if l.get("feature"):+ out.append(l)+ continue+ key = (re.sub(r"\s+", "", (l.get("mfr") or "")).upper(), re.sub(r"\s+", "", l["mpn"]).upper())+ g = by.get(key)+ if g is None:+ g = dict(l, refs=list(l["refs"]), lines=1)+ by[key] = g+ out.append(g)+ continue+ g["refs"] = sorted(set(g["refs"]) | set(l["refs"]), key=_ref_key)+ g["qty"] += l["qty"]+ g["lines"] += 1+ for k in ("value", "role", "wiki", "stock", "source", "priceDate"):+ if not g.get(k) and l.get(k):+ g[k] = l[k]+ for k in ("unit", "price10"):+ if g.get(k) is None and l.get(k) is not None:+ g[k] = l[k]+ elif g.get(k) is not None and l.get(k) is not None and abs(g[k] - l[k]) > 1e-9:+ g.setdefault("priceNotes", []).append(f"{k} {l[k]} on {' '.join(l['refs'])} differs; {g[k]} kept")+ for g in out:+ if not g.get("feature"):+ g["line"] = round(g["unit"] * g["qty"], 4) if g.get("unit") is not None else None+ return out def slugify(s):@@ -1686,6 +1732,37 @@ def salient_crop(im): return im.crop((int(cx - side / 2), int(cy - side / 2), int(cx + side / 2), int(cy + side / 2))) +def _wiki_file(page, path, out):+ """One file of a wiki page into `out` (adom-wiki repo show), True when it came and is not empty."""+ if not os.path.isfile(out):+ subprocess.run(["adom-wiki", "repo", "show", page, path, "--out", out], capture_output=True, stdin=subprocess.DEVNULL, timeout=120)+ return os.path.isfile(out) and os.path.getsize(out) > 0+++def chip_thumbnail(page, mpn, cache):+ """Issue #239: the component page's chip thumbnail as a local file, or None. The roll-up icon+ artwork/<MPN>-3d-iso-named-icon.png (wiki-component), else the first chip-shaded PNG the page's+ artwork/<MPN>-thumbs.json manifest (adom/chip-artwork-cache@1) lists."""+ key = re.sub(r"[^A-Za-z0-9_.-]", "_", page)+ for m in dict.fromkeys([mpn, mpn.upper()]):+ out = os.path.join(cache, f"{key}.{m}.icon.png")+ if _wiki_file(page, f"artwork/{m}-3d-iso-named-icon.png", out):+ return out+ man = os.path.join(cache, f"{key}.{m}.thumbs.json")+ if _wiki_file(page, f"artwork/{m}-thumbs.json", man):+ try:+ d = json.load(open(man))+ except ValueError:+ continue+ assets = [a for a in d.get("assets") or [] if isinstance(a, dict) and a.get("kind") == "chip-shaded" and re.search(r"\.png$", a.get("path") or "", re.I)]+ assets.sort(key=lambda a: 0 if "iso-named-icon" in a["path"] else 1)+ for a in assets:+ out = os.path.join(cache, f"{key}.{os.path.basename(a['path'])}")+ if _wiki_file(page, a["path"], out):+ return out+ return None++ def part_image(line, cache, out_dir, bundle, offline): """docs/parts/<slug>.png: the part's wiki page hero, else a step2glb thumbnail of its STEP in the bundle's 3d/, else None (the page draws a placeholder). Returns (file, source)."""@@ -1709,6 +1786,15 @@ def part_image(line, cache, out_dir, bundle, offline): return dst, how page = line.get("wiki")+ # issue #239: the component page's own chip thumbnail first (artwork/<MPN>-3d-iso-named-icon.png, else the+ # chip-shaded asset its adom/chip-artwork-cache@1 manifest names), then the page hero, then a STEP render+ if page and not offline:+ icon = chip_thumbnail(page, line["mpn"], cache)+ if icon:+ try:+ return finish(icon, f"chip thumbnail of {page}")+ except Exception:+ pass if page and not offline: ck = os.path.join(cache, re.sub(r"[^A-Za-z0-9_.-]", "_", page) + ".hero") if not os.path.isfile(ck):@@ -2044,13 +2130,15 @@ def bom_section(S, url_of): rows.append([f'<div class="part">{pic}<div>{name}<br><span class="muted">{esc(l["mfr"])}</span>{src}</div></div>', str(l["qty"]), f'<div class="refs">{esc(" ".join(l["refs"]))}</div>', esc(l["value"]), esc(l["role"]), usd(l["unit"]) if l["unit"] is not None else '<span class="muted">not recorded</span>',+ usd(l["price10"]) if l.get("price10") is not None else '<span class="muted">not recorded</span>', usd(l["line"]) if l["line"] is not None else '<span class="muted">not recorded</span>', stock,+ (esc(l["source"] or "") + (f'<br><span class="muted">{esc(l["priceDate"])}</span>' if l.get("priceDate") else "")) or '<span class="muted">not recorded</span>', f'<a href="{esc(l["buy"])}" target="_blank" rel="noopener">Mouser</a>']) total = sum(l["line"] for l in priced)- head = ["Part", "Qty", "Refs", "Value", "Role", "Unit", "Line", "Stock" + (f" ({lines[0]['stockDate']})" if lines[0].get("stockDate") else ""), "Buy"]- tbl = table(head, rows, cls="bom", nums=(1, 5, 6, 7))+ head = ["Part", "Qty", "Refs", "Value", "Role", "1 pc", "10 pc", "Line", "Stock" + (f" ({lines[0]['stockDate']})" if lines[0].get("stockDate") else ""), "Source", "Buy"]+ tbl = table(head, rows, cls="bom", nums=(1, 5, 6, 7, 8)) if priced and len(priced) == len(lines):- tbl = tbl.replace("</tbody>", f'<tr class="total"><td colspan="6">Board total, {sum(l["qty"] for l in lines)} parts</td><td class="num">{usd(total)}</td><td colspan="2"></td></tr></tbody>')+ tbl = tbl.replace("</tbody>", f'<tr class="total"><td colspan="7"><strong>Board total, {sum(l["qty"] for l in lines)} parts, {len(lines)} part numbers</strong></td><td class="num"><strong>{usd(total)}</strong></td><td colspan="3"></td></tr></tbody>') lead = f"<p>Unit prices from the BOM's <code>{esc(info.get('priceColumn') or 'sourcing')}</code> column, at the quantity one board needs.</p>" elif priced: lead = (f"<p>Prices are recorded for {len(priced)} of {len(lines)} lines (the BOM's <code>{esc(info.get('priceColumn') or 'sourcing')}</code> column): "@@ -2058,11 +2146,19 @@ def bom_section(S, url_of): else: lead = ("<p>No prices are recorded for this board: the BOM has no price column and the sourcing check recorded none, so this table shows none " "and no board total. Add a <code>unit_price</code> column from a parts search (adom-parts-search) and build the page again.</p>")+ # issue #238: what the grouping did, which tiers are missing, and where the per-reference BOM is+ grouped = f"<p class=\"muted\">{len(lines)} part numbers from {info.get('placements', sum(len(l['refs']) for l in lines))} placements ({info.get('rowsBefore', len(lines))} BOM rows), one row per manufacturer and MPN.</p>"+ no10 = [l["mpn"] for l in lines if l.get("price10") is None]+ if priced and no10:+ grouped += f"<p class=\"muted\">No 10-piece price recorded for {len(no10)} of {len(lines)} part numbers" + (f" ({esc(', '.join(no10[:8]))}{', ...' if len(no10) > 8 else ''})" if len(no10) < len(lines) else "") + ".</p>"+ if info.get("file") and os.path.isfile(os.path.join(S["bundle"], os.path.basename(info["file"]))):+ grouped += f'<p class="muted">The per-reference BOM for assembly: <a href="{esc(S["filesUrl"](os.path.basename(info["file"])))}" target="_blank" rel="noopener"><code>{esc(os.path.basename(info["file"]))}</code></a>.</p>'+ lead += grouped feats = [l for l in S["bom"] if l["feature"]] tail = "" if feats: tail = "<p class=\"muted\">Board features, not bought parts: " + "; ".join(f"{esc(' '.join(l['refs']))} ({esc(l['value'])})" for l in feats) + ".</p>"- tail += "<p class=\"muted\">Buy links search Mouser by the exact MPN. Pictures are each part's own wiki page hero.</p>"+ tail += "<p class=\"muted\">Buy links search Mouser by the exact MPN. Pictures are each part's own component-page chip thumbnail, else its wiki page hero.</p>" return section("components", "Components", lead + tbl + tail) @@ -2270,6 +2366,9 @@ def build(cfg): # components bom_path = cfg.get("bom") or ((run.get("outcomes") or {}).get("sourcing") or {}).get("bom") or ((run.get("outcomes") or {}).get("parts") or {}).get("bom") bom, binfo = bom_lines(bom_path, design, run)+ binfo["placements"] = sum(len(l["refs"]) for l in bom if not l["feature"])+ binfo["rowsBefore"] = len([l for l in bom if not l["feature"]])+ bom = group_lines(bom) pdir = os.path.join(docs, "parts") os.makedirs(pdir, exist_ok=True) cache = os.path.join(cfg["run"], "project-page", "part-images")