← Commit history
AI Flow 0.2.97: fixes for #224 #225 #226 #227 #231 #232 #233 #234
Co-Authored-By: Claude Opus 5.5 <[email protected]>
26 files changed
+529−44
Cargo.lock+10−10Cargo.toml+1−1SKILL.md+1bin/adom-aiflowcrates/adom-aiflow/src/bare_lands.rs+46crates/adom-aiflow/src/main.rs+29−8crates/adom-aiflow/src/testplan.rs+35−7crates/aiflow-board/src/lib.rs+11−1crates/aiflow-bridge/src/lib.rs+7crates/aiflow-pours/src/lib.rs+11−5crates/aiflow-pours/src/stitch_grid.rs+116docs/release-0.2.97.md+28package.json+1−1page.json+1−1skills/adom-aiflow/SKILL.md+1skills/aiflow-test-plan/SKILL.md+1−1tests/altium-lane.py+24tests/page-build-export.py+50tests/project-page-library.py+16tests/project-steps-flow.py+26tools/altium-project.py+37−3tools/kicad-cli-remote+5−3tools/page-build.py+39−1tools/project-page.py+13tools/project-steps.py+14−1tools/test-kicad-cli-remote.py+6−1Cargo.lock+10−10@@ -4,7 +4,7 @@ version = 4 [[package]] name = "adom-aiflow"-version = "0.2.96"+version = "0.2.97" dependencies = [ "aiflow-analyze", "aiflow-board",@@ -25,7 +25,7 @@ dependencies = [ [[package]] name = "aiflow-analyze"-version = "0.2.96"+version = "0.2.97" dependencies = [ "aiflow-board", "serde",@@ -35,7 +35,7 @@ dependencies = [ [[package]] name = "aiflow-board"-version = "0.2.96"+version = "0.2.97" dependencies = [ "roxmltree", "serde",@@ -44,7 +44,7 @@ dependencies = [ [[package]] name = "aiflow-bridge"-version = "0.2.96"+version = "0.2.97" dependencies = [ "aiflow-board", "serde",@@ -53,7 +53,7 @@ dependencies = [ [[package]] name = "aiflow-copper"-version = "0.2.96"+version = "0.2.97" dependencies = [ "aiflow-board", "aiflow-grid",@@ -63,7 +63,7 @@ dependencies = [ [[package]] name = "aiflow-grid"-version = "0.2.96"+version = "0.2.97" dependencies = [ "aiflow-board", "serde",@@ -72,7 +72,7 @@ dependencies = [ [[package]] name = "aiflow-place"-version = "0.2.96"+version = "0.2.97" dependencies = [ "aiflow-board", "serde",@@ -81,7 +81,7 @@ dependencies = [ [[package]] name = "aiflow-pours"-version = "0.2.96"+version = "0.2.97" dependencies = [ "aiflow-board", "aiflow-copper",@@ -91,7 +91,7 @@ dependencies = [ [[package]] name = "aiflow-router"-version = "0.2.96"+version = "0.2.97" dependencies = [ "aiflow-board", "aiflow-grid",@@ -101,7 +101,7 @@ dependencies = [ [[package]] name = "aiflow-run"-version = "0.2.96"+version = "0.2.97" dependencies = [ "serde", "serde_json",
Cargo.toml+1−1@@ -14,7 +14,7 @@ members = [ ] [workspace.package]-version = "0.2.96"+version = "0.2.97" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
SKILL.md+1@@ -598,6 +598,7 @@ A drilled pad with no copper layer (an NPTH that lists only `*.Mask`, such as a - `thermal-vias land --ack U3 --why "..."` (or on `plan`; `--ack Q1,Q2` or `--ack Q1 --ack Q2`; acks are saved at once and kept across calls, and finish honours them) leaves U3's planned vias out of the landing (the plan entries carry `ref`; the outcome records `leftOutAcked`). Acknowledged parts are never landed, whenever the ack was given. - The heatsink via planner (`thermal-vias plan`) and the small-pin ring of `thermalVias` keep every via clear of visible silkscreen on both sides: board and footprint text (the printed text's extent) and silk graphics, by `silkClearance` (default 0.1 mm). A part short of its target says how many spots the silk took; move the label to free them. - A `stitchVias` entry takes `size` and `drill` in mm. Without them it gets the spec's `viaSignal` (and `drillSignal`), else the board's most common via, else 0.6 / 0.3 mm (it was 0.8 / 0.4).+- `stitchVias` can also be a grid: `{"net": "GND", "pitch": 8.0, "size"?, "drill"?, "edge"?}` fills the board outline every `pitch` mm and keeps the spots clear of the edge (`edge`, 0.5 mm), every pad, other nets' tracks, the vias already there and the silkscreen (issue #231). `pour` prints how many grid spots it kept. - Via-to-via copper clearance and the hole-to-hole minimum come from the spec (`viaClearance`, else `clearance`; `holeToHole`); when the spec names neither, from the project's `.kicad_dru` beside the board (its unconditioned or via-only clearance and hole_to_hole rules, the last one winning as in KiCad); else 0.2 mm. This applies to `land vias`, `pour` and `thermal-vias plan`; zones keep `clearance`. - A pad number used twice on one footprint (a connector's two `MP` pads, a ring drawn as two custom pads) is ambiguous as a key. The router writes such a pad as its coordinates, and the gate and `land route` both replace an ambiguous key in any plan by the coordinates of the pad nearest the path's neighbouring point (a note says so), so they land on the same pad. `route` also keeps the two pads apart as clusters, joins existing copper that crosses a custom pad's polygon anywhere along a track, and treats overlapping pads of one net as one piece of copper. - `route` reads the board's own copper the way KiCad's connectivity does (issue #103): two items of one net join when their copper overlaps on a layer they share, so a track ending inside another track's width, a track end on a via's annulus off its centre, collinear overlapping pieces, overlapping zone fills of one net and a pad's real outline all count. It reads every copper layer for this (inner-layer tracks and plane fills joined through through-hole pads and vias; blind and buried vias only on the layers they span), stamps only F.Cu and B.Cu, and keeps the router's vias clear of inner-layer tracks of other nets (a long track counts along its whole length). A pad's angle in the board file is absolute and 0 when left out, also in a rotated footprint. On a fully routed board `route` writes an empty plan; the nets it still plans are the ones KiCad's DRC lists as unconnected.
bin/adom-aiflow⋯ 1 unchanged line ⋯
crates/adom-aiflow/src/bare_lands.rsadded+46@@ -0,0 +1,46 @@+//! Issue #226: footprints that are bare copper (wire solder pads, an unpopulated header land) carry+//! `exclude_from_bom` and no `(model ...)`: no purchased body, so no 3D model is right. `models` counts them as+//! expecting none, like net ties and test points, and names every footprint it still counts as missing.+use aiflow_board::{reference_of, sx, Board};+use std::collections::BTreeSet;++fn flag(fp: &sx::Node, name: &str) -> bool {+ fp.find("attr").is_some_and(|a| a.items.iter().any(|it| matches!(it, sx::Item::Atom { text, .. } if text == name)))+ || fp.find(name).is_some_and(|n| n.value() != Some("no"))+}++/// The references of the board's bare solder lands: out of the BOM, with no model.+pub fn of(board: &Board) -> BTreeSet<String> {+ board.root.find_all("footprint").filter(|fp| flag(fp, "exclude_from_bom") && fp.find("model").is_none())+ .filter_map(|fp| reference_of(fp)).collect()+}++/// The references with no `(model ...)` at all in the board file, bare lands left out: the names the+/// findings line gives when the bridge's reply does not list them (an older bridge).+pub fn without_model(board: &Board) -> Vec<String> {+ let bare = of(board);+ board.root.find_all("footprint").filter(|fp| fp.find("model").is_none()).filter_map(|fp| reference_of(fp))+ .filter(|r| !bare.contains(r)).collect()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_bare_land_expects_no_model_and_a_bought_part_does() {+ let t = r#"(kicad_pcb (layers (0 "F.Cu" signal) (31 "B.Cu" signal))+ (footprint "Wire:SolderPad" (layer "F.Cu") (at 1 1) (property "Reference" "W1") (attr through_hole exclude_from_bom)+ (pad "1" thru_hole circle (at 0 0) (size 2 2) (drill 1) (layers "*.Cu")))+ (footprint "R:R0603" (layer "F.Cu") (at 5 1) (property "Reference" "R1") (attr smd)+ (pad "1" smd rect (at 0 0) (size 1 1) (layers "F.Cu")))+ (footprint "C:C0603" (layer "F.Cu") (at 9 1) (property "Reference" "C1") (attr smd)+ (pad "1" smd rect (at 0 0) (size 1 1) (layers "F.Cu")) (model "c.step"))+ (footprint "J:Hdr" (layer "F.Cu") (at 13 1) (property "Reference" "J1") (attr through_hole exclude_from_bom)+ (pad "1" thru_hole circle (at 0 0) (size 2 2) (drill 1) (layers "*.Cu")) (model "hdr.step"))+ (gr_rect (start 0 0) (end 20 20) (layer "Edge.Cuts")))"#;+ let b = Board::from_text("t.kicad_pcb", t.to_string()).unwrap();+ assert_eq!(of(&b).into_iter().collect::<Vec<_>>(), vec!["W1"]);+ assert_eq!(without_model(&b), vec!["R1"]);+ }+}
crates/adom-aiflow/src/main.rs+29−8@@ -1,5 +1,6 @@ //! adom-aiflow: the board loop as one command, with the clock, the negotiation and the finish line. //! Every reply starts with OK: or ERROR: and carries Hint: lines that depend on this board and run.+mod bare_lands; mod continuation; mod fields_versions; mod winpath;@@ -746,6 +747,13 @@ fn run_kicad_socket(dir: &Path) -> Option<String> { v["kicadIsolated"]["socketPath"].as_str().filter(|s| !s.trim().is_empty()).map(str::to_string) } +/// Issue #234: the flow (step titles, summaries, what each step does) as a file in the run, for project-steps.py.+fn flow_file(dir: &Path) -> PathBuf {+ let f = dir.join(".aiflow-flow.json");+ let _ = std::fs::write(&f, include_str!("../../../flows/board.json"));+ f+}+ fn run_dir(cli: &Cli) -> PathBuf { cli.run.clone().unwrap_or_else(|| std::env::var("AIFLOW_RUN").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from("./aiflow-run"))) }@@ -5055,7 +5063,7 @@ fn main() { if *sync { if let Err(e) = pagedir::set(&mut r.data, "projectPage", "projectPageDir", Some(page.as_str()), page_dir_arg.as_deref()) { err(&e, &[]); } r.save().unwrap();- let o = std::process::Command::new("python3").arg("-c").arg(include_str!("../../../tools/project-steps.py")).arg(&dir).arg(page).stdin(std::process::Stdio::null()).output().unwrap_or_else(|e| err(&format!("python3: {e}"), &[]));+ let o = std::process::Command::new("python3").arg("-c").arg(include_str!("../../../tools/project-steps.py")).arg(&dir).arg(page).env("AIFLOW_FLOW_FILE", flow_file(&dir)).stdin(std::process::Stdio::null()).output().unwrap_or_else(|e| err(&format!("python3: {e}"), &[])); let v: Value = serde_json::from_slice(&o.stdout).unwrap_or(json!({"ok": false, "error": String::from_utf8_lossy(&o.stderr).to_string()})); if v["ok"] != true { err(&format!("step pages: {}", v["error"].as_str().unwrap_or("failed")), &[]); } // an explicit push of the step pages binds the page for the background pushes too@@ -7364,7 +7372,7 @@ fn main() { let np = netlist.clone().unwrap_or_else(|| err("before the board, testplan check needs --netlist <netlist.json>", &[])); let mut nl = read_json(&np); let (mut rows, mut gaps, unknown) = testplan::check_netlist_with_fixture(&list, &nl, &fixture_cfg);- if !unknown.is_empty() { err(&format!("tests name nets the netlist does not have: {}", unknown.join(", ")), &["Use the netlist's own net names (or rename the net in the design so the measurement has a name).".into()]); }+ if !unknown.is_empty() { err(&format!("tests whose net the netlist does not have: {}", unknown.join(", ")), &["Use the netlist's own net names (or rename the net in the design so the measurement has a name).".into(), "A measurement that needs no probe spot (a case temperature, a mechanical check) leaves out \"net\", or says \"kind\": \"thermal\" or \"mechanical\".".into()]); } let fixable = testplan::addable_for_fixture(&rows, &fixture_cfg); let added = if *add && !fixable.is_empty() { let a = testplan::add_test_points_for_fixture(&mut nl, &fixable, &fixture_cfg); write_json(Path::new(&np), &nl);@@ -7699,20 +7707,33 @@ fn main() { let v = br.call("kicad_model_check", &json!({"filePath": rb})); let d = v.get("data").cloned().unwrap_or(v.clone()); let counts = d["counts"].clone();- let unresolved = counts["unresolvedModel"].as_u64().unwrap_or(0) + counts["missingModel"].as_u64().unwrap_or(0);+ let mut unresolved = counts["unresolvedModel"].as_u64().unwrap_or(0) + counts["missingModel"].as_u64().unwrap_or(0); // complete modelBindings + viewer classes (KiCad Bridge 1.0.22+); file resolution is not render proof let mc = aiflow_bridge::model_check_summary(&d);- let missing = mc.missing.clone();+ let mut missing = mc.missing.clone();+ // issue #226: a bare solder land (out of the BOM, no model) expects none; every other footprint with no+ // model is named, never an empty list+ let local = board_of(&r);+ let bare = bare_lands::of(&local);+ let bare_hit: Vec<String> = mc.no_model.iter().filter(|(rf, _)| bare.contains(rf)).map(|(rf, _)| rf.clone()).collect();+ unresolved = unresolved.saturating_sub(bare_hit.len() as u64);+ missing.extend(mc.no_model.iter().filter(|(rf, _)| !bare.contains(rf)).map(|(rf, fp)| format!("{fp} ({rf}): no 3D model")));+ if mc.no_model.is_empty() && (missing.len() as u64) < unresolved {+ // an older bridge names only the models it could not find: the board file names the rest+ let named: Vec<String> = bare_lands::without_model(&local).into_iter().filter(|rf| !missing.iter().any(|m| m.contains(&format!("({rf})")) || m.contains(&format!("{rf},")) || m.contains(&format!(",{rf}")))).collect();+ missing.extend(named.into_iter().map(|rf| format!("{rf}: no 3D model in the board file")));+ }+ let bare_note = if bare_hit.is_empty() { String::new() } else { format!("; {} bare solder land(s) out of the BOM expect none ({})", bare_hit.len(), bare_hit.join(", ")) }; let vis = if mc.hidden.is_empty() { String::new() } else { format!("; NOT visible proof, {}: read/set with kicad_3d_viewer_settings (KiCad closed) and confirm in the 3D frame, never by changing BOM/POS/DNP flags", mc.hidden.join("; ")) }; r.stage_end("models", Some(json!({"counts": counts, "unresolved": unresolved})), None);- r.outcome("models", json!({"counts": counts, "unresolved": unresolved, "missing": missing, "viewerHidden": mc.hidden, "bindingsComplete": mc.bindings_complete, "evidenceSource": mc.evidence}));+ r.outcome("models", json!({"counts": counts, "unresolved": unresolved, "missing": missing, "bareLands": bare_hit, "viewerHidden": mc.hidden, "bindingsComplete": mc.bindings_complete, "evidenceSource": mc.evidence})); r.log("artifact", json!({"step": "models", "kind": "model-check", "counts": counts})); r.save().unwrap(); if !Bridge::ok(&v) && d["counts"].is_null() { err(&format!("model check did not answer: {}", v["errorCode"].as_str().unwrap_or("?")), &["The run needs a live board on the test box (capture open) for kicad_model_check.".into()]); } if unresolved > 0 {- findings(&format!("{unresolved} footprint model(s) unresolved on the board ({} with a model, {} expect none):\n{}", counts["withModel"], counts["noModelExpected"], missing.iter().take(40).map(|m| format!(" {m}")).collect::<Vec<_>>().join("\n")), &["Every part the viewer shows as a bare footprint is a missing 3D model. Fetch the vendor STEP (adom-parts-search, chip-fetcher), build one (chip-thumbnailer, adom-footprint), or fix the path in the footprint; then `models` again. A board is not delivered with bare footprints.".into()]);+ findings(&format!("{unresolved} footprint model(s) unresolved on the board ({} with a model, {} expect none{bare_note}):\n{}", counts["withModel"], counts["noModelExpected"], missing.iter().take(40).map(|m| format!(" {m}")).collect::<Vec<_>>().join("\n")), &["Every part the viewer shows as a bare footprint is a missing 3D model. Fetch the vendor STEP (adom-parts-search, chip-fetcher), build one (chip-thumbnailer, adom-footprint), or fix the path in the footprint; then `models` again. A board is not delivered with bare footprints.".into()]); } let proxies = provenance::proxy_models(&board_of(&r), &project_dir_of(&r)); if !proxies.is_empty() {@@ -7721,7 +7742,7 @@ fn main() { if !unacked.is_empty() { findings(&format!("every footprint has its 3D model, but {} model(s) may not be right way up:\n{}", unacked.len(), orient_lines.join("\n")), &[orient_hint]); }- ok(&format!("every footprint has its 3D model ({} with a model, {} expect none{vis}); 3D orientation: {} warning(s), all acknowledged; {} not checked here{}", counts["withModel"], counts["noModelExpected"], orient.len(), orient_notes.len(), if orient_lines.is_empty() { String::new() } else { format!("\n{}", orient_lines.join("\n")) }), &["Next: step placement.".into()]);+ ok(&format!("every footprint has its 3D model ({} with a model, {} expect none{bare_note}{vis}); 3D orientation: {} warning(s), all acknowledged; {} not checked here{}", counts["withModel"], counts["noModelExpected"], orient.len(), orient_notes.len(), if orient_lines.is_empty() { String::new() } else { format!("\n{}", orient_lines.join("\n")) }), &["Next: step placement.".into()]); } Cmd::Tour { what, nets, port, on } => { let t = thread(&cli);@@ -8291,7 +8312,7 @@ fn main() { let _ = std::fs::write(&helper, include_str!("../../../tools/project-steps.py")); let log = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("project-steps.log")).ok(); let mut c = std::process::Command::new("python3");- c.arg(&helper).arg(&dir).arg(pg).arg(pv).stdin(std::process::Stdio::null());+ c.arg(&helper).arg(&dir).arg(pg).arg(pv).env("AIFLOW_FLOW_FILE", flow_file(&dir)).stdin(std::process::Stdio::null()); if let Some(l) = log { if let Ok(l2) = l.try_clone() { c.stdout(l).stderr(l2); } } let _ = c.spawn(); }
crates/adom-aiflow/src/testplan.rs+35−7@@ -173,7 +173,22 @@ pub fn intake_fixture_hint(req: &Value) -> String { } } -pub fn needs_spot(kind: &str) -> bool { !matches!(kind, "camera" | "fixture") }+pub fn needs_spot(kind: &str) -> bool { !matches!(kind, "camera" | "fixture" | "none" | "thermal" | "mechanical") }++/// Issue #224: a measurement with no `net` and no `kind` (a case temperature, a mechanical check) needs no+/// probe spot: its kind is "none". A row with a net and no kind is a DC probe, as before.+pub fn kind_of(t: &Value) -> &str {+ t["kind"].as_str().unwrap_or(if t["net"].as_str().unwrap_or("").trim().is_empty() { "none" } else { "dc" })+}++/// The status of a row that needs no probe spot: the camera's own kinds keep "camera".+fn no_spot_status(kind: &str) -> &'static str { if matches!(kind, "camera" | "fixture") { "camera" } else { "no probe" } }++/// How an unknown-net row is named in the error: its id and net, or that it has no net (issue #224).+fn unknown_label(t: &Value, net: &str) -> String {+ let id = t["id"].as_str().map(str::to_string).unwrap_or_else(|| t["id"].to_string());+ if net.trim().is_empty() { format!("{id} (no \"net\"; a {} test needs one)", kind_of(t)) } else { format!("{id} ({net})") }+} /// A machine contact by its name: Some(true) large, Some(false) medium (or a contact of no stated size). fn contact_class(name: &str) -> Option<bool> {@@ -263,9 +278,10 @@ pub fn check_netlist_with_fixture(tests: &[Value], netlist: &Value, cfg: &TestFi let (mut rows, mut gaps, mut unknown) = (Vec::new(), Vec::new(), Vec::new()); for t in tests { let net = t["net"].as_str().unwrap_or("");- let kind = t["kind"].as_str().unwrap_or("dc");+ let kind = kind_of(t);+ if !needs_spot(kind) { rows.push(json!({"id": t["id"], "net": net, "kind": kind, "spot": null, "status": no_spot_status(kind)})); continue; } let Some((_, pins)) = nets.iter().find(|(n, _)| n == net) else {- if needs_spot(kind) { unknown.push(net.to_string()); }+ unknown.push(unknown_label(t, net)); rows.push(json!({"id": t["id"], "net": net, "kind": kind, "spot": null, "status": "unknown net"})); continue; }; let on = |refs: &[String]| pins.iter().find(|p| refs.iter().any(|r| p.split('.').next() == Some(r.as_str())));@@ -491,8 +507,8 @@ pub fn check_board_with_fixture(tests: &[Value], b: &Board, cfg: &TestFixtureCon let mut selected_spots: Vec<(String, String, f64, f64)> = Vec::new(); for t in tests { let net = t["net"].as_str().unwrap_or("");- let kind = t["kind"].as_str().unwrap_or("dc");- if !needs_spot(kind) { rows.push(json!({"id": t["id"], "net": net, "kind": kind, "status": "camera"})); continue; }+ let kind = kind_of(t);+ if !needs_spot(kind) { rows.push(json!({"id": t["id"], "net": net, "kind": kind, "status": no_spot_status(kind)})); continue; } if kind == "ground" && !bon { let contact = b.pads.iter().find(|p| p.net == net && medium_refs.contains(&p.reference)); match contact {@@ -642,7 +658,7 @@ mod tests { let tests = vec![json!({"id": "vin", "net": "VIN", "kind": "dc"}), json!({"id": "sw", "net": "SW", "kind": "waveform"}), json!({"id": "led", "net": "LED", "kind": "camera"}), json!({"id": "x", "net": "NOPE", "kind": "dc"})]; let (rows, gaps, unknown) = check_netlist(&tests, &nl); assert_eq!(gaps, vec!["SW".to_string()]);- assert_eq!(unknown, vec!["NOPE".to_string()]);+ assert_eq!(unknown, vec!["x (NOPE)".to_string()]); assert_eq!(rows[0]["status"], "test point"); let added = add_test_points(&mut nl, &gaps); assert_eq!(added, vec!["TP2 on SW".to_string()]);@@ -650,6 +666,18 @@ mod tests { let (_, gaps2, _) = check_netlist(&tests, &nl); assert!(gaps2.is_empty()); }+ /// Issue #224: a row with no net and no kind (a case temperature) needs no probe spot; a DC row with no+ /// net is named by its id, never an empty name.+ #[test]+ fn a_test_without_a_net_needs_no_probe_and_is_named_when_it_needs_one() {+ let nl = json!({"components": [{"ref": "U1"}], "nets": [["VIN", ["U1.3"]]]});+ let tests = vec![json!({"id": "T04", "name": "case temperature", "expect_C": 60}), json!({"id": "T05", "kind": "dc"}), json!({"id": "T06", "kind": "thermal"})];+ let (rows, gaps, unknown) = check_netlist(&tests, &nl);+ assert_eq!(rows[0]["status"], "no probe");+ assert_eq!(rows[2]["status"], "no probe");+ assert!(gaps.is_empty());+ assert_eq!(unknown, vec!["T05 (no \"net\"; a dc test needs one)".to_string()]);+ } /// The real contact footprints' shape, and three test kinds on them. fn contacts_board(medium_fab: &str) -> Board { let text = format!(r#"(kicad_pcb@@ -775,7 +803,7 @@ mod tests { let tests = vec![json!({"id": "vin", "net": "VIN", "kind": "dc"}), json!({"id": "sw", "net": "SW", "kind": "waveform"}), json!({"id": "x", "net": "NOPE", "kind": "dc"})]; let (rows, gaps, unknown) = check_netlist(&tests, &nl); assert_eq!(gaps, vec!["SW".to_string()]);- assert_eq!(unknown, vec!["NOPE".to_string()]);+ assert_eq!(unknown, vec!["x (NOPE)".to_string()]); assert_eq!(rows[0]["status"], "test point"); assert_eq!(rows[0]["spot"], "TP1.1"); assert_eq!(add_test_points(&mut nl, &gaps), vec!["TP2 on SW".to_string()]);
crates/aiflow-board/src/lib.rs+11−1@@ -320,7 +320,8 @@ impl Board { if let Some(layers) = b.root.find("layers") { for l in layers.nodes() { let kind = l.atom(2).unwrap_or("");- if matches!(kind, "signal" | "power" | "mixed") {+ // issue #226: every copper layer counts whatever its type (KiCad's jumper type is copper too)+ if matches!(kind, "signal" | "power" | "mixed" | "jumper") || l.atom(1).is_some_and(|n| n.ends_with(".Cu")) { if let Some(name) = l.atom(1) { b.copper_layers.push(name.to_string()); }@@ -673,4 +674,13 @@ mod tests { assert!(v[0].on_copper(3) && v[0].on_copper(B_CU)); assert!(v[1].on_copper(F_CU) && v[1].on_copper(2) && !v[1].on_copper(3) && !v[1].on_copper(B_CU)); }++ /// Issue #226: an inner layer typed `jumper` is copper; a 4-layer board counts 4.+ #[test]+ fn a_jumper_typed_inner_layer_is_copper() {+ let t = r#"(kicad_pcb (layers (0 "F.Cu" signal) (4 "In1.Cu" jumper) (6 "In2.Cu" power) (2 "B.Cu" signal) (25 "Edge.Cuts" user) (5 "F.SilkS" user))+ (gr_rect (start 0 0) (end 20 20) (layer "Edge.Cuts")))"#;+ let b = Board::from_text("t.kicad_pcb", t.to_string()).unwrap();+ assert_eq!(b.copper_layers, vec!["F.Cu", "In1.Cu", "In2.Cu", "B.Cu"]);+ } }
crates/aiflow-bridge/src/lib.rs+7@@ -138,6 +138,8 @@ pub fn legacy_pull_needs_split(ab_version: Option<&str>) -> bool { #[derive(Debug, Default, PartialEq)] pub struct ModelCheck { pub missing: Vec<String>,+ /// Issue #226: footprints that carry no model at all and are not marked as expecting none: (reference, footprint)+ pub no_model: Vec<(String, String)>, pub hidden: Vec<String>, pub bindings_complete: bool, pub evidence: String,@@ -153,6 +155,7 @@ pub fn model_check_summary(d: &Value) -> ModelCheck { let models = b["models"].as_array().cloned().unwrap_or_default(); let gone: Vec<String> = models.iter().filter(|m| m["exists"].as_bool() != Some(true)).filter_map(|m| m["reference"].as_str().map(str::to_string)).collect(); if !gone.is_empty() { out.missing.push(format!("{fp} ({r}): {}", gone.join(", "))); }+ if models.is_empty() && b["noModelExpected"].as_bool() != Some(true) { out.no_model.push((r.to_string(), fp.to_string())); } if models.iter().any(|m| m["hidden"].as_bool() == Some(true)) { out.hidden.push(format!("{r}: model marked hidden in the footprint")); } } } else {@@ -1100,6 +1103,10 @@ mod native_preflight_tests { "footprintsWithModelByViewerClass":{"smd":3,"notInPosFile":1,"dnp":0}}); let s = super::model_check_summary(&d); assert_eq!(s.missing, vec!["Lib:Fp (U1): ${X}/U1.step".to_string()]);+ assert!(s.no_model.is_empty(), "TP1 expects none");+ let mut d2 = d.clone();+ d2["modelBindings"].as_array_mut().unwrap().push(json!({"reference": "J9", "footprint": "Wire:Pad", "models": []}));+ assert_eq!(super::model_check_summary(&d2).no_model, vec![("J9".to_string(), "Wire:Pad".to_string())]); assert!(s.hidden.iter().any(|h| h.contains("notInPosFile (1"))); assert!(!s.hidden.iter().any(|h| h.contains("dnp")), "a hidden class with no modelled footprints is not reported"); assert!(s.hidden.iter().any(|h| h.starts_with("R1:")));
crates/aiflow-pours/src/lib.rs+11−5@@ -4,6 +4,8 @@ use aiflow_board::{geom, num, quote, Board, NetFormat, Pt}; use serde_json::{json, Value}; +pub mod stitch_grid;+ pub type Box4 = (f64, f64, f64, f64); fn pad_box(board: &Board, keys: &[String]) -> Option<Box4> {@@ -378,7 +380,11 @@ pub fn build_with(board: &Board, spec: &Value, plan: Option<&Value>, planned: &[ // issue #183: a board with no vias (spec "vias": false, one routed face, or the project's .kicad_dru) // gets no thermal or stitching vias let no_vias = spec.get("vias").and_then(|v| v.as_bool()) == Some(false);- let via_asks = spec.get("thermalVias").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0) + spec.get("stitchVias").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0);+ // issue #231: stitchVias as a list of spots or a grid {net, pitch}; any other shape is said+ let (dsize, ddrill, dfrom) = stitch_via_default(spec, board);+ let (stitch, stitch_note) = stitch_grid::entries(spec, board, dsize, ddrill, vclr, &silk, silk_gap);+ if let Some(n) = &stitch_note { eprintln!("pours: {n}"); }+ let via_asks = spec.get("thermalVias").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0) + stitch.len(); if no_vias && via_asks > 0 { eprintln!("pours: this board has no vias (single-face or vias off): the spec's {via_asks} thermalVias/stitchVias entr{} left out", if via_asks == 1 { "y is" } else { "ies are" }); } let empty: Vec<Value> = Vec::new(); for tv in if no_vias { empty.clone() } else { spec.get("thermalVias").and_then(|v| v.as_array()).cloned().unwrap_or_default() } {@@ -434,7 +440,7 @@ pub fn build_with(board: &Board, spec: &Value, plan: Option<&Value>, planned: &[ let (bx0, by0, bx1, by1) = board.bbox; let mut under_silk = 0; // keep clear of the spec's stitch vias and any via already on the board, not only our own- let mut mine: Vec<Pt> = spec.get("stitchVias").and_then(|v| v.as_array()).cloned().unwrap_or_default().iter()+ let mut mine: Vec<Pt> = stitch.iter() .filter_map(|v| v.get("x").and_then(|x| x.as_f64()).zip(v.get("y").and_then(|y| y.as_f64()))).collect(); mine.extend(board.root.find_all("via").filter_map(|v| { let at = v.find("at")?; Some((at.number(1)?, at.number(2)?)) })); for (cx, cy) in cands {@@ -470,13 +476,13 @@ pub fn build_with(board: &Board, spec: &Value, plan: Option<&Value>, planned: &[ } } // a stitch via with no size and drill takes the spec's signal via, else the board's own (issue #90)- let (dsize, ddrill, dfrom) = stitch_via_default(spec, board);- for sv in if no_vias { empty.clone() } else { spec.get("stitchVias").and_then(|v| v.as_array()).cloned().unwrap_or_default() } {+ for sv in if no_vias { empty.clone() } else { stitch.clone() } { let (Some(net), Some(x), Some(y)) = (sv.get("net").and_then(|n| n.as_str()), sv.get("x").and_then(|v| v.as_f64()), sv.get("y").and_then(|v| v.as_f64())) else { continue }; let (size, drill) = (sv.get("size").and_then(|v| v.as_f64()).unwrap_or(dsize), sv.get("drill").and_then(|v| v.as_f64()).unwrap_or(ddrill)); let sized = if sv.get("size").is_some() { String::new() } else { format!(" ({size}/{drill} mm from {dfrom}; give the entry \"size\" and \"drill\" in mm for another via)") }; // a stitch via on top of a heatsink via (or any hole) is a drill hit: left out, said why- if !via_clear(x, y, size, drill, net, &holes, h2h, vclr) { eprintln!("stitch via {net} at ({x:.2}, {y:.2}) left out: within the hole-to-hole minimum ({h2h} mm) or the {vclr} mm clearance of a via or hole already there or planned{sized}"); continue; }+ let grid_spot = sv.get("grid").and_then(|g| g.as_bool()) == Some(true);+ if !via_clear(x, y, size, drill, net, &holes, h2h, vclr) { if grid_spot { continue; } eprintln!("stitch via {net} at ({x:.2}, {y:.2}) left out: within the hole-to-hole minimum ({h2h} mm) or the {vclr} mm clearance of a via or hole already there or planned{sized}"); continue; } if clear(x, y, net, &blockers) { vias.push(via_entry(net, x, y, size, drill)); holes.push((x, y, size, drill, net.to_string()));
crates/aiflow-pours/src/stitch_grid.rsadded+116@@ -0,0 +1,116 @@+//! Issue #231: `stitchVias` as a grid, `{"net": "GND", "pitch": 8.0, "size"?, "drill"?, "edge"?}`, besides the+//! list of spots `[{net, x, y, size?, drill?}]`. The grid fills the board outline at `pitch` and keeps only+//! the spots clear of the outline and its cutouts, of every pad, of other nets' tracks, of the vias already+//! on the board and of the silkscreen; the planner's own checks (other vias and holes, the route plan) then+//! run on each spot as on a hand-placed one. Any other shape is said, never silently dropped.+use aiflow_board::{geom, silk::Shape, Board, Pt};+use serde_json::{json, Value};++/// What the spec's `stitchVias` asks for, as spots, with a line for the log when it was a grid or a shape+/// the planner does not read.+pub fn entries(spec: &Value, board: &Board, size: f64, drill: f64, clearance: f64, silk: &[Shape], silk_gap: f64) -> (Vec<Value>, Option<String>) {+ match spec.get("stitchVias") {+ None | Some(Value::Null) => (Vec::new(), None),+ Some(Value::Array(a)) => (a.clone(), None),+ Some(Value::Object(o)) => {+ let net = o.get("net").and_then(|n| n.as_str()).unwrap_or("");+ let Some(pitch) = o.get("pitch").and_then(|p| p.as_f64()).filter(|p| *p > 0.0) else {+ return (Vec::new(), Some(format!("stitchVias is an object without a positive \"pitch\": nothing planned. Give a grid {{\"net\": \"GND\", \"pitch\": 8.0}} or a list [{{\"net\", \"x\", \"y\"}}].")));+ };+ if net.is_empty() { return (Vec::new(), Some("stitchVias grid names no \"net\": nothing planned.".into())); }+ let size = o.get("size").and_then(|v| v.as_f64()).unwrap_or(size);+ let drill = o.get("drill").and_then(|v| v.as_f64()).unwrap_or(drill);+ let edge = o.get("edge").and_then(|v| v.as_f64()).unwrap_or(0.5);+ let (spots, tried) = grid(board, net, pitch, size, edge, clearance, silk, silk_gap);+ let list: Vec<Value> = spots.iter().map(|(x, y)| json!({"net": net, "x": x, "y": y, "size": size, "drill": drill, "grid": true})).collect();+ let note = format!("stitchVias grid {net} every {pitch} mm ({size}/{drill} mm): {} of {tried} grid spots inside the outline are clear of pads, other nets' tracks, vias and silkscreen", list.len());+ (list, Some(note))+ }+ Some(other) => (Vec::new(), Some(format!("stitchVias is {} and the planner reads a list [{{\"net\", \"x\", \"y\", \"size\"?, \"drill\"?}}] or a grid {{\"net\", \"pitch\", \"size\"?, \"drill\"?}}: nothing planned", kind(other)))),+ }+}++fn kind(v: &Value) -> &'static str {+ match v { Value::String(_) => "a string", Value::Number(_) => "a number", Value::Bool(_) => "a boolean", _ => "not a list" }+}++fn edge_distance(x: f64, y: f64, poly: &[Pt]) -> f64 {+ let n = poly.len();+ (0..n).map(|i| { let (a, b) = (poly[i], poly[(i + 1) % n]); geom::seg_distance(x, y, a.0, a.1, b.0, b.1) }).fold(f64::INFINITY, f64::min)+}++/// The grid spots kept, and how many grid spots fell inside the outline.+#[allow(clippy::too_many_arguments)]+fn grid(board: &Board, net: &str, pitch: f64, size: f64, edge: f64, clearance: f64, silk: &[Shape], silk_gap: f64) -> (Vec<Pt>, usize) {+ let vr = size / 2.0;+ let (bx0, by0, bx1, by1) = board.bbox;+ let outline: Vec<Pt> = if board.outline.len() >= 3 { board.outline.clone() } else { vec![(bx0, by0), (bx1, by0), (bx1, by1), (bx0, by1)] };+ let tracks = board.copper_tracks();+ let vias: Vec<Pt> = board.root.find_all("via").filter_map(|v| { let at = v.find("at")?; Some((at.number(1)?, at.number(2)?)) }).collect();+ let pad_boxes: Vec<(bool, (f64, f64, f64, f64))> = board.pads.iter().filter(|p| p.polys.iter().flatten().count() > 0)+ .map(|p| (p.net == net, geom::bbox(&p.polys.iter().flatten().copied().collect::<Vec<_>>()))).collect();+ // the grid is centred on the board, so its margins match on both sides+ let (nx, ny) = (((bx1 - bx0) / pitch).floor() as i64, ((by1 - by0) / pitch).floor() as i64);+ let (ox, oy) = (bx0 + ((bx1 - bx0) - nx as f64 * pitch) / 2.0, by0 + ((by1 - by0) - ny as f64 * pitch) / 2.0);+ let (mut keep, mut tried) = (Vec::new(), 0);+ for i in 0..=nx {+ for j in 0..=ny {+ let (x, y) = (((ox + i as f64 * pitch) * 100.0).round() / 100.0, ((oy + j as f64 * pitch) * 100.0).round() / 100.0);+ if !geom::point_in_poly(x, y, &outline) || board.outline_cutouts.iter().any(|c| geom::point_in_poly(x, y, c)) { continue; }+ tried += 1;+ if edge_distance(x, y, &outline) < vr + edge || board.outline_cutouts.iter().any(|c| edge_distance(x, y, c) < vr + edge) { continue; }+ let near_pad = pad_boxes.iter().any(|(own, (qx0, qy0, qx1, qy1))| {+ let (cx, cy) = (x.clamp(*qx0, *qx1), y.clamp(*qy0, *qy1));+ (x - cx).hypot(y - cy) < vr + if *own { 0.1 } else { clearance + 0.1 }+ });+ if near_pad { continue; }+ if tracks.iter().any(|t| t.net != net && geom::seg_distance(x, y, t.a.0, t.a.1, t.b.0, t.b.1) < vr + clearance + t.width / 2.0) { continue; }+ if vias.iter().any(|v| (v.0 - x).hypot(v.1 - y) < size + 0.3) { continue; }+ if aiflow_board::silk::near(silk, (x, y), vr + silk_gap).is_some() { continue; }+ keep.push((x, y));+ }+ }+ (keep, tried)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn board() -> Board {+ Board::from_text("t.kicad_pcb", r#"(kicad_pcb+ (layers (0 "F.Cu" signal) (31 "B.Cu" signal))+ (net 1 "GND") (net 2 "SIG")+ (gr_rect (start 0 0) (end 20 20) (layer "Edge.Cuts"))+ (footprint "R" (layer "F.Cu") (at 10 10) (property "Reference" "R1")+ (pad "1" smd rect (at 0 0) (size 1 1) (layers "F.Cu") (net 2 "SIG")))+ (segment (start 2 18) (end 18 18) (width 0.25) (layer "B.Cu") (net 2 "SIG"))+)"#.to_string()).unwrap()+ }++ #[test]+ fn a_grid_fills_the_board_clear_of_pads_tracks_and_the_edge() {+ let b = board();+ let (list, note) = entries(&json!({"stitchVias": {"net": "GND", "pitch": 5.0}}), &b, 0.6, 0.3, 0.2, &[], 0.1);+ let pts: Vec<(f64, f64)> = list.iter().map(|v| (v["x"].as_f64().unwrap(), v["y"].as_f64().unwrap())).collect();+ assert!(note.unwrap().contains("stitchVias grid GND every 5 mm"));+ // 0, 5, 10, 15, 20 on each axis: the edge rows go (0.5 mm edge), the pad at (10, 10) and the track at y 18 are kept clear+ assert!(pts.contains(&(5.0, 5.0)) && pts.contains(&(15.0, 15.0)), "{pts:?}");+ assert!(!pts.contains(&(10.0, 10.0)), "on R1's pad: {pts:?}");+ assert!(pts.iter().all(|p| p.0 > 0.5 && p.1 > 0.5 && p.0 < 19.5 && p.1 < 19.5), "{pts:?}");+ assert!(pts.iter().all(|p| (p.1 - 18.0).abs() > 0.3), "{pts:?}");+ assert_eq!(list[0]["size"], 0.6);+ }++ #[test]+ fn a_list_passes_through_and_other_shapes_are_said() {+ let b = board();+ let (list, note) = entries(&json!({"stitchVias": [{"net": "GND", "x": 1.0, "y": 1.0}]}), &b, 0.6, 0.3, 0.2, &[], 0.1);+ assert_eq!((list.len(), note), (1, None));+ let (list, note) = entries(&json!({"stitchVias": {"net": "GND"}}), &b, 0.6, 0.3, 0.2, &[], 0.1);+ assert!(list.is_empty() && note.unwrap().contains("pitch"));+ let (list, note) = entries(&json!({"stitchVias": "GND"}), &b, 0.6, 0.3, 0.2, &[], 0.1);+ assert!(list.is_empty() && note.unwrap().contains("a string"));+ assert_eq!(entries(&json!({}), &b, 0.6, 0.3, 0.2, &[], 0.1), (vec![], None));+ }+}
docs/release-0.2.97.mdadded+28@@ -0,0 +1,28 @@+# AI Flow 0.2.97++Fixes from RobInMaine's and rolwang's runs.++- **Test plans: a measurement with no probe** (#224). A test row with no `net` and no `kind` (a case temperature, a+ mechanical check) needs no probe spot (status "no probe"); `kind` `thermal` and `mechanical` say the same. A DC+ row with no net is named by its id in the error, never an empty list.+- **project-page after a library edit** (#225). A project-library file named by the last `parts --project-lib`+ run and gone since is named, with "run `parts --project-lib` again", instead of a Python traceback.+- **models** (#226). A bare solder land (a footprint out of the BOM with no model: wire pads, an unpopulated+ header land) expects no model. Every footprint still counted as missing is named in the findings and in+ run.json, also when it has no model at all. An inner layer typed `jumper` counts as copper, so a 4-layer board+ with one is 4-layer (and gets the 4-layer rules pack).+- **stitchVias as a grid** (#231). `{"net": "GND", "pitch": 8.0, "size"?, "drill"?, "edge"?}` fills the board+ outline every `pitch` mm, keeping spots clear of the edge, every pad, other nets' tracks, the vias already there+ and the silkscreen; the planner's own via checks then run on each spot. Any other shape is said, never ignored.+- **Board pictures from a container** (#232). The remote kicad-cli (`adom-aiflow-kicad-cli-remote`) runs+ `pcb export svg` on the desktop's own KiCad, so `project-page` draws the board from a container too.+- **Manufacturing on a board page** (#233). With no export.json in the page folder, the page build makes the fab+ zip (Gerbers and drill), copies the BOM and CPL and writes export.json from the run's own `export`. A+ molecule's fab_bundle.py export.json is left as it is.+- **Step pages have their titles** (#234). The step pages and the README's build section read the step titles,+ summaries and what each step does from the package flow when run.json carries none.+- **Altium export: every copper layer in the zip** (#227, Jelle). The Gerber zip took the outer copper and mid+ signal layers but not Altium's internal planes (.GP1, .GP2), and the export still said the set was checked. The+ zip now takes the planes, the export counts the copper Gerbers against the board's copper layers (the bridge's+ own count, else `altium_layer_stack`) and says so when any is missing, and the zip is read back for every copper+ file before the export answers OK.
package.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.96",+ "version": "0.2.97", "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.96",+ "version": "0.2.97", "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@@ -718,6 +718,7 @@ A drilled pad with no copper layer (an NPTH that lists only `*.Mask`, such as a - `thermal-vias land --ack U3 --why "..."` (or on `plan`; `--ack Q1,Q2` or `--ack Q1 --ack Q2`; acks are saved at once and kept across calls, and finish honours them) leaves U3's planned vias out of the landing (the plan entries carry `ref`; the outcome records `leftOutAcked`). Acknowledged parts are never landed, whenever the ack was given. - The heatsink via planner (`thermal-vias plan`) and the small-pin ring of `thermalVias` keep every via clear of visible silkscreen on both sides: board and footprint text (the printed text's extent) and silk graphics, by `silkClearance` (default 0.1 mm). A part short of its target says how many spots the silk took; move the label to free them. - A `stitchVias` entry takes `size` and `drill` in mm. Without them it gets the spec's `viaSignal` (and `drillSignal`), else the board's most common via, else 0.6 / 0.3 mm (it was 0.8 / 0.4).+- `stitchVias` can also be a grid: `{"net": "GND", "pitch": 8.0, "size"?, "drill"?, "edge"?}` fills the board outline every `pitch` mm and keeps the spots clear of the edge (`edge`, 0.5 mm), every pad, other nets' tracks, the vias already there and the silkscreen (issue #231). `pour` prints how many grid spots it kept. - Via-to-via copper clearance and the hole-to-hole minimum come from the spec (`viaClearance`, else `clearance`; `holeToHole`); when the spec names neither, from the project's `.kicad_dru` beside the board (its unconditioned or via-only clearance and hole_to_hole rules, the last one winning as in KiCad); else 0.2 mm. This applies to `land vias`, `pour` and `thermal-vias plan`; zones keep `clearance`. - A pad number used twice on one footprint (a connector's two `MP` pads, a ring drawn as two custom pads) is ambiguous as a key. The router writes such a pad as its coordinates, and the gate and `land route` both replace an ambiguous key in any plan by the coordinates of the pad nearest the path's neighbouring point (a note says so), so they land on the same pad. `route` also keeps the two pads apart as clusters, joins existing copper that crosses a custom pad's polygon anywhere along a track, and treats overlapping pads of one net as one piece of copper. - `route` reads the board's own copper the way KiCad's connectivity does (issue #103): two items of one net join when their copper overlaps on a layer they share, so a track ending inside another track's width, a track end on a via's annulus off its centre, collinear overlapping pieces, overlapping zone fills of one net and a pad's real outline all count. It reads every copper layer for this (inner-layer tracks and plane fills joined through through-hole pads and vias; blind and buried vias only on the layers they span), stamps only F.Cu and B.Cu, and keeps the router's vias clear of inner-layer tracks of other nets (a long track counts along its whole length). A pad's angle in the board file is absolute and 0 when left out, also in a rotated footprint. On a fully routed board `route` writes an empty plan; the nets it still plans are the ones KiCad's DRC lists as unconnected.
skills/aiflow-test-plan/SKILL.md+1−1@@ -28,7 +28,7 @@ Write `tests.json`, one entry per measurement, from THIS circuit and its simulat ] ``` -Kinds: `dc`, `ripple`, `waveform` need a probe landing; `camera` (an LED, a display) needs none;+Kinds: `dc`, `ripple`, `waveform` need a probe landing; `camera` (an LED, a display) needs none; `thermal` and `mechanical` (a case temperature, an enclosure check) need none either, and a row with no `net` and no `kind` is read as one of those (issue #224); `ground` is the tether's machine contact, which must be a free `MachineContactMedium` on that net (the tether ends in a medium pin; a test point or a large contact cannot take it). Typical for a regulator: the input at the board, the output, the switch node, both inductor ends, feedback, enable, power-good, the bulk caps' ripple, every LED.
tests/altium-lane.py+24@@ -398,5 +398,29 @@ class SymbolsCommand(unittest.TestCase): self.assertEqual(len(proof['symbols']['errors']), 3) +class ExportZip(unittest.TestCase):+ """Issue #227: the internal planes (.GP1 ...) are copper Gerbers: counted against the stack and zipped."""+ @classmethod+ def setUpClass(cls):+ import ast, re+ src = (ROOT / 'tools' / 'altium-project.py').read_text()+ keep = [n for n in ast.parse(src).body if isinstance(n, ast.FunctionDef) and n.name in ('is_copper_gerber', 'in_fab_zip', 'copper_layer_count')]+ cls.ns = {'re': re}+ exec(compile(ast.Module(body=keep, type_ignores=[]), 'altium-project.py', 'exec'), cls.ns)++ def test_planes_are_copper_and_go_in_the_zip(self):+ cu, z = self.ns['is_copper_gerber'], self.ns['in_fab_zip']+ names = ['b.GTL', 'b.GP1', 'b.GP2', 'b.G1', 'b.GBL', 'b.GTO', 'b.GKO', 'b.GM1', 'b-RoundHoles.TXT', 'b.REP', 'Status Report.Txt.rep']+ self.assertEqual([n for n in names if cu(n)], ['b.GTL', 'b.GP1', 'b.GP2', 'b.G1', 'b.GBL'])+ self.assertEqual([n for n in names if z(n)], ['b.GTL', 'b.GP1', 'b.GP2', 'b.G1', 'b.GBL', 'b.GTO', 'b.GKO', 'b.GM1', 'b-RoundHoles.TXT'])++ def test_the_stack_count_reads_each_reply_shape(self):+ n = self.ns['copper_layer_count']+ self.assertEqual(n({'success': True, 'layers': ['F.Cu', 'L39', 'L40', 'B.Cu']}), 4)+ self.assertEqual(n({'success': True, 'stack': {'layers': [{}, {}]}}), 2)+ self.assertIsNone(n({'success': False, 'error': 'no board'}))+ self.assertIsNone(n({}))++ if __name__ == '__main__': unittest.main(verbosity=1)
tests/page-build-export.pyadded+50@@ -0,0 +1,50 @@+"""page-build's Manufacturing files for a board page (issue #233): with no export.json in the folder, the run's+own `export` (its folder from run.json, else <run>/manufacturing) gives the fab zip, the BOM, the CPL and+export.json; a folder that has export.json (a molecule's fab_bundle.py) is left alone.++ python3 tests/page-build-export.py+"""+import importlib.util, json, os, tempfile, unittest, zipfile+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)+++class BoardExportBundle(unittest.TestCase):+ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory(); t = Path(self.tmp.name)+ self.run, self.bundle = t / "run", t / "page"+ g = self.run / "manufacturing" / "gerbers"; g.mkdir(parents=True); self.bundle.mkdir()+ for f in ("b-F_Cu.gbr", "b-B_Cu.gbr", "b-PTH.drl", "b-job.gbrjob"):+ (g / f).write_text("G04*")+ m = self.run / "manufacturing"+ (m / "b-bom.csv").write_text("Reference\n"); (m / "b-cpl.csv").write_text("Ref\n")+ (m / "export-check.json").write_text(json.dumps({"pass": True, "board": "/x/b.kicad_pcb", "boardSha256": "abc"}))++ def tearDown(self):+ self.tmp.cleanup()++ def test_a_board_page_gets_the_fab_zip_bom_cpl_and_export_json(self):+ note = pb.board_export_bundle(str(self.run), str(self.bundle))+ self.assertIn("b-fab.zip", note)+ ex = json.loads((self.bundle / "export.json").read_text())+ roles = {f["role"]: f for f in ex["files"]}+ self.assertEqual(set(roles), {"fab_zip", "bom", "cpl"})+ self.assertEqual(ex["boardSha256"], "abc")+ self.assertEqual(sorted(zipfile.ZipFile(self.bundle / "b-fab.zip").namelist()), sorted(roles["fab_zip"]["entries"]))+ self.assertTrue((self.bundle / "b-bom.csv").is_file() and (self.bundle / "b-cpl.csv").is_file())++ def test_a_folder_with_export_json_and_a_run_without_export_are_left_alone(self):+ (self.bundle / "export.json").write_text("{}")+ self.assertIsNone(pb.board_export_bundle(str(self.run), str(self.bundle)))+ self.assertEqual((self.bundle / "export.json").read_text(), "{}")+ os.remove(self.bundle / "export.json")+ os.remove(self.run / "manufacturing" / "export-check.json")+ self.assertIsNone(pb.board_export_bundle(str(self.run), str(self.bundle)))+ self.assertFalse((self.bundle / "export.json").exists())+++if __name__ == "__main__":+ unittest.main()
tests/project-page-library.py+16@@ -614,5 +614,21 @@ class PageStepName(unittest.TestCase): self.assertTrue(out.endswith(' (model "m.step")\n)\n'), out) self.assertEqual(self.pp.sx_parse(out)[-1], ["model", "m.step"]) +class StaleProjectLib(unittest.TestCase):+ """Issue #225: a project library edited after `parts --project-lib` is named, never a traceback."""+ def test_a_file_gone_since_parts_says_to_run_parts_again(self):+ import importlib.util+ spec = importlib.util.spec_from_file_location("project_page", SCRIPT)+ mod = importlib.util.module_from_spec(spec); spec.loader.exec_module(mod)+ with tempfile.TemporaryDirectory() as d:+ here = os.path.join(d, "Here.kicad_sym"); open(here, "w").write("(kicad_symbol_lib)")+ mod.stale_project_lib([{"mpn": "OK1", "projectLib": {"symbolFile": here}}])+ with self.assertRaises(SystemExit) as e:+ mod.stale_project_lib([{"mpn": "CONN2", "projectLib": {"symbolFile": os.path.join(d, "Conn_01x02.kicad_sym")}}])+ msg = json.loads(str(e.exception.code))+ self.assertIn("Conn_01x02.kicad_sym", msg["error"])+ self.assertIn("parts --project-lib", msg["error"])++ if __name__ == "__main__": unittest.main()
tests/project-steps-flow.pyadded+26@@ -0,0 +1,26 @@+"""project-steps.py reads the step titles, summaries and "does" text from the package flow when run.json has no+`flow` (issue #234): from AIFLOW_FLOW_FILE, else flows/board.json beside the script's package.++ python3 tests/project-steps-flow.py+"""+import importlib.util, json, os, unittest+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+spec = importlib.util.spec_from_file_location("project_steps", ROOT / "tools" / "project-steps.py")+ps = importlib.util.module_from_spec(spec); spec.loader.exec_module(ps)+++class FlowOf(unittest.TestCase):+ def test_the_package_flow_fills_titles_and_summaries(self):+ os.environ.pop("AIFLOW_FLOW_FILE", None)+ f = ps.flow_of({})+ self.assertEqual(f["titles"]["intake"], "Intake")+ self.assertTrue(f["short"]["design"])+ os.environ["AIFLOW_FLOW_FILE"] = str(ROOT / "flows" / "board.json")+ self.assertEqual(ps.flow_of({})["titles"]["sourcing"], "Sourcing")+ self.assertEqual(ps.flow_of({"flow": {"titles": {"intake": "Mine"}}})["titles"]["intake"], "Mine")+++if __name__ == "__main__":+ unittest.main()
tools/altium-project.py+37−3@@ -589,6 +589,30 @@ def jlc_files(out, name, bom, cpl): w.writerow([g(di), g(xi) + 'mm', g(yi) + 'mm', 'Top' if 'top' in g(li).lower() else 'Bottom', g(ri)]) +def is_copper_gerber(name):+ """A copper Gerber in Altium's names: top and bottom (.GTL, .GBL), mid signal layers (.G1 ...) and the+ internal planes (.GP1 ...), issue #227."""+ return bool(re.search(r'\.(gtl|gbl|g\d+|gp\d+)$', name.lower()))+++def in_fab_zip(name):+ """Every file a fab builds the board from: copper (planes included), mask, paste, silkscreen, the outline+ and mechanical layers, and the NC drill."""+ n = name.lower()+ return is_copper_gerber(n) or bool(re.search(r'\.(gts|gbs|gto|gbo|gtp|gbp|gko|gm\d+|txt|drl)$', n))+++def copper_layer_count(r):+ """The copper layers of an `altium_layer_stack` reply (top, mid signal layers, planes, bottom), or None+ when it gave none."""+ if not isinstance(r, dict) or r.get('success') is False:+ return None+ for v in (r.get('layers'), (r.get('stack') or {}).get('layers'), (r.get('stackup') or {}).get('layers'), r.get('copperLayers')):+ if isinstance(v, list) and v:+ return len(v)+ return None++ def cmd_export(a): st = load_state() prj, pcb = st.get('project'), a.design or st.get('board')@@ -649,19 +673,29 @@ def cmd_export(a): fills_gerbers = {'pass': bool(poured) and all(n > 0 for n in regions.values()), 'regions': regions} if ps.get('success') else {'pass': None, 'why': 'altium_pour_state failed'} for l, n in regions.items(): if n == 0: problems.append('the %s Gerber has no filled regions (G36) though Altium poured that layer' % l)+ # issue #227: every copper layer of the board's stack (planes included) has its Gerber, and the zip takes them all+ copper_files = sorted(x.name for x in out.iterdir() if is_copper_gerber(x.name))+ # the bridge's own count of the board's copper layers (fabChecks.copperLayers.board), else the stack read+ stack_n = ((r.get('fabChecks') or {}).get('copperLayers') or {}).get('board') or copper_layer_count(ab('altium_layer_stack', {'filePath': pcb}, timeout=120))+ if stack_n and len(copper_files) < stack_n:+ problems.append('the board has %d copper layers (planes included) but %d copper Gerber(s) were written (%s)' % (stack_n, len(copper_files), ', '.join(copper_files) or 'none')) if problems: err('manufacturing files written to %s, but they do not check out: %s' % (out, '; '.join(problems)), ['Fix the board or the parts\' parameters and run `altium export` again; never hand the human files that do not match the board.']) import zipfile zp = out / (Path(pcb.replace('\\', '/')).stem + '-gerbers.zip') with zipfile.ZipFile(zp, 'w', zipfile.ZIP_DEFLATED) as z: for x in sorted(out.iterdir()):- if x.suffix.lower() in ('.gtl', '.gbl', '.gts', '.gbs', '.gto', '.gbo', '.gtp', '.gbp', '.gko', '.gm1', '.txt') or re.fullmatch(r'\.g\d+|\.gm\d+', x.suffix.lower()):+ if in_fab_zip(x.name): z.write(x, x.name)+ with zipfile.ZipFile(zp) as z:+ zipped_copper = sorted(n for n in z.namelist() if is_copper_gerber(n))+ if zipped_copper != copper_files:+ err('the Gerber zip %s lacks copper layer(s): %s' % (zp, ', '.join(sorted(set(copper_files) - set(zipped_copper)))), ['This is AI Flow\'s zip, not the board: report it on adom/adom-aiflow and send the folder\'s Gerbers meanwhile.']) missing_numbers = sorted({r_[0] for r_ in [(row[0],) for row in table(out / 'bom-jlcpcb.csv')[1] if len(row) > 3 and not row[3].strip()]}) if (out / 'bom-jlcpcb.csv').is_file() else [] prove('export', {'dir': str(out.resolve()), 'gerberZip': zp.name, 'drillHits': hits, 'cplRefs': len(refs_in(cpl)), 'bomLines': len(table(bom)[1]), 'tool': 'altium', 'fillsGerbers': fills_gerbers}) if os.environ.get('AIFLOW_EXE'): run([os.environ['AIFLOW_EXE'], '--run', str(RUN), 'timeline', 'write'], timeout=60) tps = sorted(r_ for r_, k in roles.items() if k == 'tp'); dnp = sorted(r_ for r_, k in roles.items() if k == 'machine')- ok('manufacturing files in %s, checked against the board: Gerbers (%s), NC drill (%d hits = vias + drilled pads), pick and place (%d parts), BOM (%d lines), the JLCPCB BOM and CPL' % (- out, zp.name, hits, len(refs_in(cpl)), len(table(bom)[1])),+ ok('manufacturing files in %s, checked against the board: Gerbers (%s, %d copper layer(s)%s), NC drill (%d hits = vias + drilled pads), pick and place (%d parts), BOM (%d lines), the JLCPCB BOM and CPL' % (+ out, zp.name, len(copper_files), ' as the stack has' if stack_n else ', stack not read', hits, len(refs_in(cpl)), len(table(bom)[1])), ['No LCSC number on: ' + ', '.join(missing_numbers) + '. That is fine: for a JLCPCB build, buy these anywhere (DigiKey, Mouser, ...) and send them as consigned parts, or add an LCSC number to the part to have JLCPCB source it (usually cheaper and faster).' if missing_numbers else '', 'Test points and board-only pads are bare copper, out of the BOM and the pick and place: ' + ', '.join(tps) if tps else '', 'Machine contacts and pins are fitted after assembly: DNP in the BOM, out of the pick and place: ' + ', '.join(dnp) if dnp else ''])
tools/kicad-cli-remote+5−3@@ -8,6 +8,7 @@ # kicad-cli-remote sch export netlist --format kicadsexpr --output <out.net> <design.kicad_sch> # kicad-cli-remote pcb export gerbers|drill --output <dir>/ [flags] <board.kicad_pcb> # kicad-cli-remote pcb export pos --output <file.csv> [flags] <board.kicad_pcb>+# kicad-cli-remote pcb export svg --mode-multi --output <dir> [flags] <board.kicad_pcb> (one SVG per layer) # kicad-cli-remote pcb export step --output <file.step> [flags] <board.kicad_pcb> (native output passed through) # The board travels with its sibling .kicad_pro / .kicad_dru so project rules are kept. The board and # the schematic both travel with the project's sym-lib-table and fp-lib-table and every ${KIPRJMOD}@@ -438,7 +439,8 @@ c=d.get("exitCode", d.get("code")); print(1 if c is None else int(c))' 2>/dev/nu exit $(( rc == 0 ? 1 : rc )) fi -if [[ "${1:-}" == "pcb" && "${2:-}" == "export" && "${3:-}" =~ ^(gerbers|drill|pos)$ ]]; then+# issue #232: `pcb export svg --mode-multi` too (project-page's board pictures), one file per layer in the folder+if [[ "${1:-}" == "pcb" && "${2:-}" == "export" && "${3:-}" =~ ^(gerbers|drill|pos|svg)$ ]]; then kind="$3"; shift 3 if [[ " $* " == *" --help "* || " $* " == *" -h "* ]]; then echo "Usage: kicad-cli-remote pcb export $kind [flags] --output OUT INPUT_FILE (flags are passed to the desktop's native KiCad)"@@ -448,7 +450,7 @@ if [[ "${1:-}" == "pcb" && "${2:-}" == "export" && "${3:-}" =~ ^(gerbers|drill|p while [[ $# -gt 0 ]]; do case "$1" in --output|-o) out="$2"; shift 2;;- --layers|-l|--format|--units|--side|--excellon-units|-u|--excellon-oval-format|--excellon-zeros-format|--drill-origin|--map-format|--gerber-precision|--precision|--common-layers|--cl) pass+=("$1" "$2"); shift 2;;+ --layers|-l|--format|--units|--side|--excellon-units|-u|--excellon-oval-format|--excellon-zeros-format|--drill-origin|--map-format|--gerber-precision|--precision|--common-layers|--cl|--page-size-mode|--drill-shape-opt|--theme|-t|--scale|--variant) pass+=("$1" "$2"); shift 2;; --*) pass+=("$1"); shift;; *) board="$1"; shift;; esac@@ -482,7 +484,7 @@ if [[ "${1:-}" == "pcb" && "${2:-}" == "export" && "${3:-}" =~ ^(gerbers|drill|p exit $code fi -[[ "${1:-}" == "pcb" && "${2:-}" == "drc" ]] || { echo "kicad-cli-remote: only 'pcb drc', 'sch erc', 'pcb export gerbers|drill|pos|step', 'sch export netlist', 'version' and '--version' are supported" >&2; exit 2; }+[[ "${1:-}" == "pcb" && "${2:-}" == "drc" ]] || { echo "kicad-cli-remote: only 'pcb drc', 'sch erc', 'pcb export gerbers|drill|pos|svg|step', 'sch export netlist', 'version' and '--version' are supported" >&2; exit 2; } shift 2 if [[ " $* " == *" --help "* || " $* " == *" -h "* ]]; then echo "Usage: kicad-cli-remote pcb drc [--format json] [--output FILE] [--refill-zones] [--schematic-parity] [--severity-all] INPUT_FILE"
tools/page-build.py+39−1@@ -23,7 +23,7 @@ block's drawing is a small JSON in the explorer folder (<id>.json, "block": <net textbook way; a block with no drawing gets an auto-drawn one (every pin labelled with its net) in explorer/auto/. Every drawing is checked against the netlist: each wired group of pins and labels must be one net, every connected pin of a drawn part drawn, every part in some drawing. Prints one JSON object. Findings only: nothing here refuses."""-import csv, hashlib, html, io, json, math, os, re, shutil, subprocess, sys, tempfile, time, urllib.parse+import csv, hashlib, html, io, json, math, os, re, shutil, subprocess, sys, tempfile, time, urllib.parse, zipfile from concurrent.futures import ThreadPoolExecutor PROOF_SCHEMA = "aiflow.explorer-proof/1"@@ -2071,6 +2071,41 @@ ROLE_TEXT = {"step": "The assembled board in 3D (STEP)", "board_kicad_pcb": "The "bom": "Bill of materials", "cpl": "Pick and place"} +def board_export_bundle(run_dir, bundle):+ """Issue #233: a board page (not a molecule) has no export.json: molecule-publish's fab_bundle.py writes it for+ a molecule only. When the run has a passing or recorded `export` (<run>/manufacturing/export-check.json),+ zip its Gerbers and drill into the folder, copy the BOM and CPL, and write export.json from that record.+ Returns a note, or None when nothing was done (export.json already there, or no export yet)."""+ if os.path.isfile(os.path.join(bundle, "export.json")):+ return None+ # the folder `export` wrote (its --out), else the default <run>/manufacturing+ rec = ((rjson(os.path.join(run_dir, "run.json"), {}) or {}).get("outcomes") or {}).get("export") or {}+ mdir = rec.get("dir") if rec.get("dir") and os.path.isdir(rec.get("dir")) else os.path.join(run_dir, "manufacturing")+ check = rjson(os.path.join(mdir, "export-check.json"), None)+ gdir = os.path.join(mdir, "gerbers")+ if not check or not os.path.isdir(gdir):+ return None+ fab = sorted(f for f in os.listdir(gdir) if f.lower().endswith((".gbr", ".gbrjob", ".drl")))+ if not fab:+ return None+ board = check.get("board") or ""+ stem = os.path.splitext(os.path.basename(board))[0] if board else "board"+ files = []+ zname = f"{stem}-fab.zip"+ with zipfile.ZipFile(os.path.join(bundle, zname), "w", zipfile.ZIP_DEFLATED) as z:+ for f in fab:+ z.write(os.path.join(gdir, f), f)+ files.append({"path": zname, "role": "fab_zip", "bytes": os.path.getsize(os.path.join(bundle, zname)), "entries": fab})+ for f in sorted(os.listdir(mdir)):+ role = "bom" if re.search(r"-bom\.csv$", f) else "cpl" if re.search(r"-cpl\.csv$", f) else None+ if role:+ shutil.copy(os.path.join(mdir, f), os.path.join(bundle, f))+ files.append({"path": f, "role": role, "bytes": os.path.getsize(os.path.join(bundle, f))})+ wjson(os.path.join(bundle, "export.json"), {"source": "adom-aiflow export", "board": os.path.basename(board) if board else None,+ "boardSha256": check.get("boardSha256"), "files": files})+ return f"Manufacturing: {zname} ({len(fab)} Gerber and drill files), the BOM and CPL and export.json written from the run's export"++ def mfg_section(S, url_of): ex = S.get("exportJson") or {} rows = []@@ -2176,6 +2211,9 @@ def build(cfg): for sub in ("board", "review", "parts", "explorer"): shutil.rmtree(os.path.join(docs, sub), ignore_errors=True) os.makedirs(docs, exist_ok=True)+ mfg_note = board_export_bundle(cfg["run"], bundle)+ if mfg_note:+ print(mfg_note, file=sys.stderr) fp = board_fingerprint(board_path) if board_path else None notes = [] renders, rnote = (board_renders(board_path, os.path.join(docs, "board"), work) if board_path else ({}, "no board file"))
tools/project-page.py+13@@ -862,6 +862,18 @@ def pcm_previous(cfg, folder, work, pkgid): return out +def stale_project_lib(proj):+ """Issue #225: the parts record names the project library's files as `parts --project-lib` last read them; a+ library edited since (a symbol split in two after a name clash) leaves a path that is gone. Say so, never a+ traceback."""+ gone = [(p.get("mpn") or "?", p["projectLib"].get(k)) for p in proj for k in ("symbolFile", "footprintFile", "model")+ if p["projectLib"].get(k) and not os.path.isfile(p["projectLib"][k])]+ if gone:+ listed = "; ".join(f"{m}: {f}" for m, f in gone[:6]) + (f"; and {len(gone) - 6} more" if len(gone) > 6 else "")+ fail(f"the project library has changed since `parts --project-lib` last read it ({listed} no longer exists). "+ "Run `parts --project-lib <dir>` again, then `project-page`.", missing=[f for _, f in gone])++ def pcm_package(bundle, lib, pkgid, version, title, brief, page_url, work, parts=(), report=None): """Repackage the Cloud Library bundle (and the project-library parts) in the PCM layout, bind a wiki part's own page STEP where its footprint names no model (bind_page_models), normalise and parse-check the symbol@@ -889,6 +901,7 @@ def pcm_package(bundle, lib, pkgid, version, title, brief, page_url, work, parts # one entry per MPN: the parts record lists a part once per reference group, so a value on several # references (four 1 uF caps) arrives more than once and must be merged only once proj = list({p["mpn"]: p for p in reversed([p for p in parts if p.get("projectLib") and not p.get("wiki")])}.values())[::-1]+ stale_project_lib(proj) versions = [sym_header_version(t) or 0] + [sym_header_version(open(p["projectLib"]["symbolFile"]).read()) or 0 for p in proj] t = merge_project_parts(proj, t, fp_dir, m_dir, lib, pkgid) if t:
tools/project-steps.py+14−1@@ -35,7 +35,20 @@ def load(run): def flow_of(data):- return data.get("flow") or {}+ """The flow's step titles, one-line summaries and "does" text: run.json's own `flow` when a run carries one,+ else the package's flows/board.json (issue #234: the binary never writes `flow` into run.json). adom-aiflow+ hands the file's path in AIFLOW_FLOW_FILE (it runs this script from its own copy); beside the script is the+ fallback for a hand run from the package."""+ if data.get("flow"):+ return data["flow"]+ here = os.path.dirname(os.path.abspath(__file__)) if "__file__" in globals() else ""+ for p in (os.environ.get("AIFLOW_FLOW_FILE"), here and os.path.join(here, "..", "flows", "board.json")):+ if p and os.path.isfile(p):+ try:+ return json.load(open(p))+ except Exception:+ pass+ return {} def steps_done(data):
tools/test-kicad-cli-remote.py+6−1@@ -102,6 +102,8 @@ case "$1 $2 $3" in "pcb export gerbers") libs "$last"; for l in F_Cu B_Cu Edge_Cuts; do echo "G04 $l*" > "${out%/}/demo-$l.gbr"; done; echo '{}' > "${out%/}/demo-job.gbrjob";; "pcb export drill") echo "M48" > "${out%/}/demo-PTH.drl";; "pcb export pos") echo "Ref,Val" > "$out";;+"pcb export svg") case " $* " in *" --mode-multi "*" --page-size-mode 2 "*) ;; *) echo "svg flags lost: $*" >&2; exit 9;; esac+ for l in F_Cu B_Cu Edge_Cuts; do echo "<svg/>" > "${out%/}/demo-$l.svg"; done;; "pcb export step") [ -f "$(dirname "$last")/models/part.step" ] || exit 4 # a ${KICAD10_3RD_PARTY} model travelled into the job folder and the variable points there (#177) case "$KICAD10_3RD_PARTY" in "$(dirname "$last")"/*) ;; *) echo "3rd-party folder not in the job: $KICAD10_3RD_PARTY" >&2; exit 7;; esac@@ -160,6 +162,9 @@ def run(osname): kc("pcb", "export", "gerbers", "--output", "run/mfg/gerbers/", "--layers", "F.Cu,B.Cu,Edge.Cuts", "demo.kicad_pcb") kc("pcb", "export", "drill", "--output", "run/mfg/gerbers/", "--format", "excellon", "demo.kicad_pcb") kc("pcb", "export", "pos", "--output", "run/mfg/demo-cpl.csv", "--format", "csv", "demo.kicad_pcb")+ # issue #232: project-page's per-layer SVGs come back into the folder+ kc("pcb", "export", "svg", "--mode-multi", "-o", "pics", "-l", "F.Cu,B.Cu,Edge.Cuts", "--black-and-white", "--page-size-mode", "2", "--exclude-drawing-sheet", "--drill-shape-opt", "2", "demo.kicad_pcb")+ assert sorted(os.listdir(os.path.join(work, "pics"))) == ["demo-B_Cu.svg", "demo-Edge_Cuts.svg", "demo-F_Cu.svg"], os.listdir(os.path.join(work, "pics")) # the board twin's STEP: the ${KIPRJMOD} model travels, the native output passes through env["KICAD10_3RD_PARTY"] = os.path.join(work, "kicad", "3rdparty") # what step-export sets (#177) st = kc("pcb", "export", "step", "--subst-models", "--include-tracks", "--include-silkscreen", "--output", "twin/demo.step", "demo.kicad_pcb", full=True)@@ -172,7 +177,7 @@ def run(osname): calls = [json.loads(l) for l in open(log)] sent = [os.path.relpath(f, work) for c in calls if c[0] == "send_files" for f in c[1]["filePaths"]] for f in ("fp-lib-table", "sym-lib-table", "lib/Demo.pretty/A.kicad_mod", "lib/Demo.pretty/B.kicad_mod"):- assert sent.count(f) == 8, (f, sent.count(f)) # 3 drc, erc, netlist, gerbers, drill, pos+ assert sent.count(f) == 9, (f, sent.count(f)) # 3 drc, erc, netlist, gerbers, drill, pos, svg dests = [c[1]["dest"].replace("\\", "/") for c in calls if c[0] == "send_files"] if osname == "linux": assert all(d.startswith(home + "/.adom-aiflow-kicad/aiflow-") for d in dests), dests