← Commit history
Cargo.lock+11−11
@@ -4,7 +4,7 @@ version = 4  [[package]] name = "adom-aiflow"-version = "0.2.140"+version = "0.2.141" dependencies = [  "aiflow-analyze",  "aiflow-board",@@ -28,7 +28,7 @@ dependencies = [  [[package]] name = "aiflow-analyze"-version = "0.2.140"+version = "0.2.141" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -39,7 +39,7 @@ dependencies = [  [[package]] name = "aiflow-board"-version = "0.2.140"+version = "0.2.141" dependencies = [  "aiflow-sys",  "roxmltree",@@ -49,7 +49,7 @@ dependencies = [  [[package]] name = "aiflow-bridge"-version = "0.2.140"+version = "0.2.141" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -59,7 +59,7 @@ dependencies = [  [[package]] name = "aiflow-copper"-version = "0.2.140"+version = "0.2.141" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -70,7 +70,7 @@ dependencies = [  [[package]] name = "aiflow-grid"-version = "0.2.140"+version = "0.2.141" dependencies = [  "aiflow-board",  "serde",@@ -79,7 +79,7 @@ dependencies = [  [[package]] name = "aiflow-place"-version = "0.2.140"+version = "0.2.141" dependencies = [  "aiflow-board",  "aiflow-sys",@@ -89,7 +89,7 @@ dependencies = [  [[package]] name = "aiflow-pours"-version = "0.2.140"+version = "0.2.141" dependencies = [  "aiflow-board",  "aiflow-copper",@@ -100,7 +100,7 @@ dependencies = [  [[package]] name = "aiflow-router"-version = "0.2.140"+version = "0.2.141" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -111,7 +111,7 @@ dependencies = [  [[package]] name = "aiflow-run"-version = "0.2.140"+version = "0.2.141" dependencies = [  "aiflow-sys",  "serde",@@ -120,7 +120,7 @@ dependencies = [  [[package]] name = "aiflow-sys"-version = "0.2.140"+version = "0.2.141" dependencies = [  "serde_json", ]
Cargo.toml+1−1
@@ -15,7 +15,7 @@ members = [ ]  [workspace.package]-version = "0.2.140"+version = "0.2.141" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
crates/adom-aiflow/src/export.rs+2−2
@@ -379,7 +379,7 @@ fn read_dir(dir: &Path, exts: &[&str]) -> Vec<(String, String)> { }  fn kicad(cli: &str, args: &[String]) -> Result<(), String> {-    let o = aiflow_sys::process::Command::new(cli).args(args).output().map_err(|e| format!("{cli} is not runnable: {e}"))?;+    let o = aiflow_sys::process::Command::new(cli).args(aiflow_copper::cli_args(cli, args)).output().map_err(|e| format!("{cli} is not runnable: {e}"))?;     if o.status.success() { return Ok(()); }     let tail = |b: &[u8]| aiflow_run::clip_text(&String::from_utf8_lossy(b), 400);     Err(format!("{cli} {} failed: {} {}", args[..3.min(args.len())].join(" "), tail(&o.stdout), tail(&o.stderr)))@@ -457,7 +457,7 @@ pub fn order_files(board_path: &str, stem: &str, profile: Option<&str>, sourcing fn saved_drc(cli: &str, board_path: &str, out: &Path) -> Result<Value, String> {     let report = out.join("drc-saved-fills.json");     let _ = std::fs::remove_file(&report);-    let o = aiflow_sys::process::Command::new(cli).args(["pcb", "drc", "--format", "json", "--output"]).arg(&report).arg(board_path)+    let o = aiflow_sys::process::Command::new(cli).args(["pcb", "drc", "--format", "json", "--output"]).arg(aiflow_copper::cli_path(cli, &report.display().to_string())).arg(aiflow_copper::cli_path(cli, &board_path.to_string()))         .stdin(aiflow_sys::process::Stdio::null()).output().map_err(|e| format!("{cli} is not runnable: {e}"))?;     let text = std::fs::read_to_string(&report).map_err(|_| {         let tail = |b: &[u8]| aiflow_run::clip_text(&String::from_utf8_lossy(b), 300);
crates/adom-aiflow/src/main.rs+9−3
@@ -3701,7 +3701,7 @@ fn sha256_file(p: &str) -> String { /// `kicad-cli`. In a container with no native KiCad, adom-aiflow-kicad-cli-remote runs a desktop's. fn export_sch_netlist(sch: &str, out: &Path) -> Result<String, String> {     let cli = std::env::var("ADOM_AIFLOW_KICAD_CLI").unwrap_or_else(|_| "kicad-cli".into());-    let o = aiflow_sys::process::Command::new(&cli).args(["sch", "export", "netlist", "--format", "kicadsexpr", "--output"]).arg(out).arg(sch).output()+    let o = aiflow_sys::process::Command::new(&cli).args(["sch", "export", "netlist", "--format", "kicadsexpr", "--output"]).arg(aiflow_copper::cli_path(&cli, &Path::new(out).display().to_string())).arg(aiflow_copper::cli_path(&cli, &Path::new(sch).display().to_string())).output()         .map_err(|e| format!("{cli} is not runnable: {e}"))?;     if !o.status.success() || !out.is_file() {         let tail = |b: &[u8]| aiflow_run::clip_text(&String::from_utf8_lossy(b), 500);@@ -5420,7 +5420,13 @@ fn main() {             export_sch_netlist(sch, &net).unwrap_or_else(|e| err(&e, &[]));             let on_sheet = schematic_check::sheet_symbols(&std::fs::read_to_string(&net).unwrap_or_default()).unwrap_or_else(|e| err(&format!("netlist: {e}"), &[]));             let lib = r.data["outcomes"]["project-page"]["libName"].as_str().map(|l| format!("PCM_{l}"));-            let bom_refs: Vec<String> = r.data["outcomes"]["parts"]["parts"].as_array().cloned().unwrap_or_default().iter().flat_map(|p| p["refs"].as_array().cloned().unwrap_or_default()).filter_map(|v| v.as_str().map(str::to_string)).collect();+            let mut bom_refs: Vec<String> = r.data["outcomes"]["parts"]["parts"].as_array().cloned().unwrap_or_default().iter().flat_map(|p| p["refs"].as_array().cloned().unwrap_or_default()).filter_map(|v| v.as_str().map(str::to_string)).collect();+            // issue #283 (RobInMaine): the BOM file itself, read the way `sourcing check` reads it, so a reference the parts+            // record did not carry is not reported "not in the BOM"+            let bom_file = r.data["outcomes"]["parts"]["bom"].as_str().or(r.data["outcomes"]["sourcing"]["bom"].as_str()).map(str::to_string);+            if let Some(t) = bom_file.as_deref().and_then(|f| std::fs::read_to_string(f).ok()) {+                for rf in preboard::bom_ref_list(&t) { if !bom_refs.contains(&rf) { bom_refs.push(rf); } }+            }             // issue #248: a part the BOM marks off-board (a battery, a coil, a motor wired to the board) is drawn but             // marked "exclude from board", which leaves it out of the netlist: it counts when the sheet draws it             let off_board: Vec<String> = r.data["outcomes"]["sourcing"]["offBoard"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_string)).collect();@@ -5458,7 +5464,7 @@ fn main() {                 hints.extend(pin_hints.iter().cloned());                 findings(&format!("schematic check failed:\n  {}", why.join("\n  ")), &hints);             }-            ok(&format!("schematic {canon}: {} symbols, ERC clean, every BOM reference placed from {}{}", on_sheet.len(), lib.unwrap_or_else(|| "the project library".into()), if extra.is_empty() { String::new() } else { format!(" ({} not in the BOM: {})", extra.len(), extra.join(", ")) }),+            ok(&format!("schematic {canon}: {} symbols, ERC clean, every BOM reference placed from {}{}", on_sheet.len(), lib.unwrap_or_else(|| "the project library".into()), if extra.is_empty() { String::new() } else if bom_refs.is_empty() { format!(" (no BOM references to compare with: the parts record names none{})", bom_file.as_deref().map(|f| format!(" and {f} has no reference column")).unwrap_or_default()) } else { format!(" ({} not in the BOM{}: {})", extra.len(), bom_file.as_deref().map(|f| format!(" {f}")).unwrap_or_default(), extra.join(", ")) }),                &[pin_hints, vec![schematic_symbols::warning_hint(&symbols), "Next: make the board from it (KiCad: Update PCB from Schematic), draw the outline, save, bind it (`bind-remote-board` / `start --board`), then `step components`.".into()]].concat());         }         Cmd::Components { etch } => {
crates/adom-aiflow/src/part_check.rs+72−15
@@ -115,19 +115,41 @@ pub fn dims(facts: &Value, what: &str, pads: &[Pad], fab: Option<(f64, f64, f64,     (rows, stop, acked) } -/// The height of a STEP model: the spread of its points' z (mm), when it has any.+/// The height of a STEP model: the spread of z over the solid's vertices (`VERTEX_POINT`), else over every point.+/// Issue #279 (RobInMaine): every `CARTESIAN_POINT` includes the origins of `LINE`s and placements, which can lie far+/// outside the solid (a 0.635 mm resistor read 2.17 mm); a vertex is a corner of the solid itself. pub fn step_height(text: &str) -> Option<f64> {-    let mut lo = f64::MAX;-    let mut hi = f64::MIN;-    for line in text.split("CARTESIAN_POINT").skip(1) {-        // CARTESIAN_POINT('name',(x,y,z)): the coordinates are the last parenthesised group before ';'-        let stmt = &line[..line.find(';').unwrap_or(line.len())];-        let Some(close) = stmt.rfind(')').and_then(|c| stmt[..c].rfind(')')) else { continue };-        let Some(open) = stmt[..close].rfind('(') else { continue };-        let nums: Vec<f64> = stmt[open + 1..close].split(',').filter_map(|v| v.trim().parse::<f64>().ok()).collect();-        if nums.len() == 3 { lo = lo.min(nums[2]); hi = hi.max(nums[2]); }+    // #12 = CARTESIAN_POINT('name',(x,y,z)) by its id+    let mut points: std::collections::HashMap<&str, f64> = std::collections::HashMap::new();+    let mut all_lo = f64::MAX;+    let mut all_hi = f64::MIN;+    let mut vertex_refs: Vec<&str> = Vec::new();+    for stmt in text.split(';') {+        let s = stmt.trim();+        let Some(eq) = s.find('=') else { continue };+        let id = s[..eq].trim();+        let body = s[eq + 1..].trim_start();+        if body.starts_with("CARTESIAN_POINT") {+            let Some(close) = body.rfind(')').and_then(|c| body[..c].rfind(')')) else { continue };+            let Some(open) = body[..close].rfind('(') else { continue };+            let nums: Vec<f64> = body[open + 1..close].split(',').filter_map(|v| v.trim().parse::<f64>().ok()).collect();+            if nums.len() == 3 {+                points.insert(id, nums[2]);+                all_lo = all_lo.min(nums[2]);+                all_hi = all_hi.max(nums[2]);+            }+        } else if body.starts_with("VERTEX_POINT") {+            // VERTEX_POINT('',#123): the point it names+            if let Some(h) = body.rfind('#') { vertex_refs.push(body[h..].trim_end_matches(|c: char| c == ')' || c.is_whitespace())); }+        }+    }+    let zs: Vec<f64> = vertex_refs.iter().filter_map(|r| points.get(r).copied()).collect();+    if !zs.is_empty() {+        let lo = zs.iter().cloned().fold(f64::MAX, f64::min);+        let hi = zs.iter().cloned().fold(f64::MIN, f64::max);+        return Some(hi - lo);     }-    (hi >= lo).then_some(hi - lo)+    (all_hi >= all_lo).then_some(all_hi - all_lo) }  fn norm(s: &str) -> String {@@ -175,11 +197,24 @@ pub fn compare(facts: &Value, what: &str, pads: &[Pad], height: Option<f64>, pag     }     // the body height     let (nom, max) = (facts["bodyHeightMm"]["nom"].as_f64().or(facts["bodyHeightMm"].as_f64()), facts["bodyHeightMm"]["max"].as_f64());-    match (height, nom.or(max)) {+    // issue #277 (RobInMaine): the datasheet's tolerance band, when it gives one: a model inside [min, max] agrees+    let min = facts["bodyHeightMm"]["min"].as_f64();+    match (height, nom.or(max).or(min)) {         (Some(hm), Some(want)) => {-            let low = nom.unwrap_or(want) - HEIGHT_TOL;-            let high = max.unwrap_or(want) + HEIGHT_TOL;-            if hm < low || hm > high { f.push(format!("{mpn}: the 3D model of {what} is {hm:.2} mm tall, the datasheet {} ", match (nom, max) { (Some(n), Some(m)) => format!("{n:.2} mm (max {m:.2})"), (Some(n), None) => format!("{n:.2} mm"), (None, Some(m)) => format!("at most {m:.2} mm"), _ => String::new() }).trim_end().to_string()); }+            let low = min.unwrap_or(nom.unwrap_or(want)) - HEIGHT_TOL;+            let high = max.unwrap_or(nom.unwrap_or(want)) + HEIGHT_TOL;+            if hm < low || hm > high {+                let said = match (min, nom, max) {+                    (Some(lo), n, Some(hi)) => format!("{lo:.2} to {hi:.2} mm{}", n.map(|n| format!(" (nominal {n:.2})")).unwrap_or_default()),+                    (Some(lo), Some(n), None) => format!("{n:.2} mm (min {lo:.2})"),+                    (Some(lo), None, None) => format!("at least {lo:.2} mm"),+                    (None, Some(n), Some(m)) => format!("{n:.2} mm (max {m:.2})"),+                    (None, Some(n), None) => format!("{n:.2} mm"),+                    (None, None, Some(m)) => format!("at most {m:.2} mm"),+                    _ => String::new(),+                };+                f.push(format!("{mpn}: the 3D model of {what} is {hm:.2} mm tall, the datasheet {said}"));+            }         }         (None, Some(_)) => f.push(format!("{mpn}: no 3D model of {what} to measure against the datasheet's body height")),         _ => {}@@ -225,6 +260,28 @@ mod tests {         assert!(stop[0].contains("no assembly outline"), "{stop:?}");     } +    #[test]+    fn the_model_height_is_the_solids_not_a_line_origin() {+        // issue #279 (RobInMaine): a WSK2512 solid 0.635 mm tall, with a LINE whose origin sits at z 2.1725+        let step = "DATA;\n#10=CARTESIAN_POINT('',(0.,0.,0.));\n#11=CARTESIAN_POINT('',(6.3,3.2,0.635));\n#12=CARTESIAN_POINT('',(1.,1.,2.1725));\n\+            #20=VERTEX_POINT('',#10);\n#21=VERTEX_POINT('',#11);\n#30=LINE('',#12,#40);\nENDSEC;";+        assert!((step_height(step).unwrap() - 0.635).abs() < 1e-9, "{:?}", step_height(step));+        // a file with no vertices keeps the old reading+        assert!((step_height("#1=CARTESIAN_POINT('',(0.,0.,0.));#2=CARTESIAN_POINT('',(0.,0.,0.5));").unwrap() - 0.5).abs() < 1e-9);+    }+    #[test]+    fn a_model_inside_the_datasheets_tolerance_agrees() {+        // issue #277 (RobInMaine): 0.55 +/- 0.10 mm, a 0.45 mm model+        let pads = vec![];+        let band = json!({"mpn": "R", "source": "ds", "bodyHeightMm": {"min": 0.45, "nom": 0.55, "max": 0.65}});+        assert!(compare(&band, "p", &pads, Some(0.45), None, None).1.is_empty());+        let (_, f) = compare(&band, "p", &pads, Some(0.30), None, None);+        assert!(f[0].contains("is 0.30 mm tall, the datasheet 0.45 to 0.65 mm (nominal 0.55)"), "{f:?}");+        // without min, the nominal still sets the low end+        let nominal = json!({"mpn": "R", "source": "ds", "bodyHeightMm": {"nom": 0.55, "max": 0.65}});+        assert!(!compare(&nominal, "p", &pads, Some(0.45), None, None).1.is_empty());+    }+     #[test]     fn reads_pads_and_a_step_height() {         let p = footprint_pads(FP);
crates/adom-aiflow/src/preboard.rs+26
@@ -602,6 +602,17 @@ fn make_poster(clip: &Path, out: &Path) {         .args(["-frames:v", "1", "-vf", "scale=1280:-2", "-q:v", "3"]).arg(out).status(); } +#[cfg(test)]+mod bom_ref_list_tests {+    #[test]+    fn every_reference_of_every_row_is_read() {+        // issue #283: refs space-separated in one cell, a row with no MPN, a header named refs+        let bom = "refs,qty,value,mpn\nC2 C215 C216,3,100n,CL05B104\nR1;R2,2,10k,RC0402\nTP1,1,,\n";+        assert_eq!(super::bom_ref_list(bom), ["C2", "C215", "C216", "R1", "R2", "TP1"]);+        assert!(super::bom_ref_list("mpn,qty\nX,1\n").is_empty());+    }+}+ #[cfg(test)] mod tests {     use super::*;@@ -901,6 +912,21 @@ pub fn brief_text(arg: &str) -> String {     arg.to_string() } +/// Issue #283 (RobInMaine): every reference a BOM names, read the way `sourcing check` reads it (the reference+/// column, references split on spaces, commas and semicolons), every row, with or without an MPN.+pub fn bom_ref_list(text: &str) -> Vec<String> {+    let rows = parse_csv(text);+    let Some(header) = rows.first() else { return Vec::new() };+    let Some(c) = col(header, &["ref", "refs", "reference", "references", "designator", "designators", "refdes"]) else { return Vec::new() };+    let mut out: Vec<String> = Vec::new();+    for row in rows.iter().skip(1) {+        for r in row.get(c).map(|s| s.as_str()).unwrap_or("").split(|ch: char| ch == ' ' || ch == ',' || ch == ';').map(str::trim).filter(|s| !s.is_empty()) {+            if !out.iter().any(|x| x == r) { out.push(r.to_string()); }+        }+    }+    out+}+ pub fn bom_parts(text: &str) -> Vec<Value> {     let rows = parse_csv(text);     let Some(header) = rows.first() else { return Vec::new() };
crates/adom-aiflow/src/project_lib.rs+30−2
@@ -32,7 +32,9 @@ fn walk(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {     let Ok(rd) = std::fs::read_dir(dir) else { return };     for e in rd.flatten() {         let p = e.path();-        if p.is_dir() { if depth < 4 { walk(&p, depth + 1, out); } } else { out.push(p); }+        // issue #280 (RobInMaine): a KiCad package installed inside the library folder (its metadata.json beside it) is a+        // built copy of an earlier library, not the library: its symbols would shadow the entries' own+        if p.is_dir() { if depth < 4 && !p.join("metadata.json").is_file() { walk(&p, depth + 1, out); } } else { out.push(p); }     } } @@ -73,7 +75,10 @@ impl ProjectLib {                     for s in root.nodes().filter(|n| n.tag == "symbol") {                         let Some(name) = s.atom(1) else { continue };                         let fp = s.nodes().find(|p| p.tag == "property" && p.atom(1) == Some("Footprint")).and_then(|p| p.atom(2)).unwrap_or("").to_string();-                        symbols.insert(key(name), Symbol { file: f.clone(), footprint: fp });+                        // issue #280: two files with the symbol: the one named for it (<MPN>.kicad_sym, the entry's own) wins+                        let named = f.file_stem().and_then(|s| s.to_str()).is_some_and(|s| key(s) == key(name));+                        let keep_old = symbols.get(&key(name)).is_some_and(|o: &Symbol| o.file.file_stem().and_then(|s| s.to_str()).is_some_and(|s| key(s) == key(name)));+                        if named || !keep_old { symbols.insert(key(name), Symbol { file: f.clone(), footprint: fp }); }                     }                 }                 "kicad_mod" if f.parent().map(|p| ext(p) == "pretty").unwrap_or(false) => {@@ -232,6 +237,29 @@ pub fn stale(parts: &Value, bom_path: &str, bom: Option<&str>) -> Vec<String> {     out } +#[cfg(test)]+mod shadow_tests {+    use super::*;+    #[test]+    fn an_installed_package_and_another_file_do_not_shadow_the_entrys_own_symbol() {+        let d = aiflow_sys::temp_dir().join(format!("aiflow-projlib-280-{}", aiflow_sys::process::id()));+        let _ = std::fs::remove_dir_all(&d);+        std::fs::create_dir_all(d.join("pcm/symbols")).unwrap();+        std::fs::write(d.join("provenance.json"), r#"{"parts": [{"mpn": "ABC-1", "source": "ds", "prefer": true}]}"#).unwrap();+        let sym = |fp: &str| format!("(kicad_symbol_lib (version 20241209) (generator \"x\") (symbol \"ABC-1\" (property \"Footprint\" \"{fp}\")))");+        std::fs::write(d.join("ABC-1.kicad_sym"), sym("Lib:OWN")).unwrap();+        std::fs::write(d.join("all.kicad_sym"), sym("Lib:OTHER")).unwrap();+        // the project's own package, installed under the folder+        std::fs::write(d.join("pcm/metadata.json"), "{}").unwrap();+        std::fs::write(d.join("pcm/symbols/lib.kicad_sym"), sym("Lib:PAGE")).unwrap();+        let lib = ProjectLib::load(&d).unwrap();+        let s = lib.symbols.get("ABC-1").unwrap();+        assert_eq!(s.footprint, "Lib:OWN");+        assert!(s.file.ends_with("ABC-1.kicad_sym"), "{:?}", s.file);+        let _ = std::fs::remove_dir_all(&d);+    }+}+ #[cfg(test)] mod tests {     use super::*;
crates/adom-aiflow/src/schematic_check.rs+3−1
@@ -45,7 +45,9 @@ pub fn erc_errors(report: &Path) -> Result<(Value, Vec<String>), String> { pub fn run_erc(cli: &str, sch: &str, report: &Path) -> Result<(Value, Vec<String>), String> {     let _ = std::fs::remove_file(report);     let o = aiflow_sys::process::Command::new(cli)-        .args(["sch", "erc", "--format", "json", "--severity-all", "--output"]).arg(report).arg(sch)+        .args(["sch", "erc", "--format", "json", "--severity-all", "--output"])+        // issue #282: a Windows kicad-cli.exe from WSL gets Windows paths+        .arg(aiflow_copper::cli_path(cli, &report.display().to_string())).arg(aiflow_copper::cli_path(cli, sch))         .stdin(aiflow_sys::process::Stdio::null()).output()         .map_err(|e| format!("{cli} is not runnable: {e}"))?;     erc_errors(report).map_err(|e| {
crates/adom-aiflow/src/step_export.rs+1−1
@@ -156,7 +156,7 @@ pub fn run(board_path: &str, out: &Path, cli: &str, project_dir: &Path) -> Value     args.extend(LAYER_FLAGS.iter().map(|s| s.to_string()));     args.extend(["--output".to_string(), out.display().to_string(), ctx.board.display().to_string()]);     let command = format!("{}{cli} {}", ctx.env.iter().map(|(k, v)| format!("{k}={v} ")).collect::<String>(), args.join(" "));-    let result = aiflow_sys::process::Command::new(cli).args(&args).envs(ctx.env.iter().map(|(k, v)| (k, v))).output();+    let result = aiflow_sys::process::Command::new(cli).args(aiflow_copper::cli_args(cli, &args)).envs(ctx.env.iter().map(|(k, v)| (k, v))).output();     if let Some(t) = &ctx.temp { let _ = std::fs::remove_file(t); }     let mut rec = match result {         Ok(o) => {
crates/aiflow-copper/src/lib.rs+29−1
@@ -616,6 +616,18 @@ pub fn copy_project_rules(source: &str, destination: &str) -> Result<(), String>     Ok(()) } +/// Issue #282 (RobInMaine): a Windows `kicad-cli.exe` called from WSL reads and writes Windows paths, so an absolute+/// workspace path is handed to it in its Windows form (`wslpath -w`: \\wsl.localhost\...); a relative path resolves+/// through the working folder already, and a Linux or macOS kicad-cli gets every path unchanged.+pub fn cli_path(cli: &str, p: &str) -> String {+    if cfg!(windows) || !cli.to_ascii_lowercase().ends_with(".exe") || !p.starts_with('/') { return p.to_string(); }+    Command::new("wslpath").args(["-w", p]).output().ok().filter(|o| o.status.success())+        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).filter(|s| !s.is_empty()).unwrap_or_else(|| p.to_string())+}++/// `cli_path` on every argument that is an absolute path.+pub fn cli_args(cli: &str, args: &[String]) -> Vec<String> { args.iter().map(|a| cli_path(cli, a)).collect() }+ /// The native kicad-cli to use for DRC, when one is usable: `ADOM_AIFLOW_KICAD_CLI` or `kicad-cli`, /// and only if its `pcb drc` supports `--refill-zones` (KiCad 9+). A stock KiCad 7 `kicad-cli` answers /// `--version` but has no `pcb drc` and cannot read a KiCad 10 board, so it is not native here.@@ -673,7 +685,7 @@ pub fn run_drc_with(path: &str, schematic: Option<&str>) -> Result<Value, String             c.arg("--schematic-parity");             if let Some(s) = env { c.env("KICAD_REMOTE_SCHEMATIC", s); }         }-        c.args(["--format","json","--output",report.to_str().unwrap(),path]).output()+        c.args(["--format".to_string(),"json".to_string(),"--output".to_string(),cli_path(cli, report.to_str().unwrap()),cli_path(cli, path)]).output()     } else {         Command::new("service-kicad").args(["pcb", "drc", "--format", "json", "--out", report.to_str().unwrap(), path]).output()     }.map_err(|e|format!("DRC backend not runnable: {e}"))?;@@ -983,3 +995,19 @@ mod duplicate_pad_tests {         assert!(normalise_plan(&b, &mut plan).is_empty());     } }++#[cfg(test)]+mod cli_path_tests {+    #[test]+    fn only_a_windows_cli_gets_windows_paths() {+        // issue #282: a Linux or macOS kicad-cli, and a relative path, are left as they are+        assert_eq!(super::cli_path("/usr/bin/kicad-cli", "/home/me/run/erc.json"), "/home/me/run/erc.json");+        assert_eq!(super::cli_path("/mnt/c/Program Files/KiCad/10.0/bin/kicad-cli.exe", "run/erc.json"), "run/erc.json");+        assert_eq!(super::cli_args("kicad-cli", &["sch".into(), "/a/b".into()]), vec!["sch".to_string(), "/a/b".to_string()]);+        // under WSL, a Windows kicad-cli.exe gets the \\wsl.localhost form (only checked where wslpath exists)+        if std::path::Path::new("/usr/bin/wslpath").exists() || std::path::Path::new("/bin/wslpath").exists() {+            let w = super::cli_path("/mnt/c/KiCad/bin/kicad-cli.exe", "/home/me/run/erc.json");+            assert!(w.starts_with("\\\\") && w.ends_with("\\run\\erc.json"), "{w}");+        }+    }+}
docs/release-0.2.141.mdadded+10
@@ -0,0 +1,10 @@+# adom-aiflow 0.2.141++Six reported bugs, fixed together.++- **#283 (RobInMaine): `schematic check` listed every reference as "not in the BOM".** It compared the sheet with the references the `parts` record carried; it now also reads the BOM file itself, the way `sourcing check` does (references in one cell split on spaces, commas and semicolons, every row), names the BOM file it compared with, and says so when there are no references to compare at all instead of listing every symbol.+- **#279 (RobInMaine): `part-check` read a 3D model's height from construction points.** It took the spread of every point in the STEP file, including the origins of lines, which can lie far outside the part (a 0.635 mm resistor read 2.17 mm). It now measures the solid's vertices, and falls back to every point only in a file with none.+- **#277 (RobInMaine): `part-check` ignored the datasheet's height tolerance.** With `"bodyHeightMm": {"min": ..., "nom": ..., "max": ...}`, a model anywhere in [min, max] agrees; a finding states the whole band. Without `min`, the nominal sets the low end as before.+- **#280 (RobInMaine): `parts --project-lib` took a symbol from an installed package.** A KiCad package installed inside the library folder (a folder with its `metadata.json`) is no longer read as part of the library, and when two files define a symbol, the one named for it (`<MPN>.kicad_sym`) wins.+- **#281 (Jinwon Kim): three in one.** The project page's manufacturing bundle copies only the BOM and CPL of the board the export checked, not an earlier board's too; it no longer fails (SameFileError) when `export --out` wrote straight into the page folder; and the remote kicad-cli (`adom-aiflow-kicad-cli-remote`) passes `pcb drc --save-board` to the desktop and brings the refilled board back over the local file (tested on a Windows desktop with KiCad 10).+- **#282 (RobInMaine): a Windows kicad-cli from WSL could not write its reports.** With `ADOM_AIFLOW_KICAD_CLI` set to a Windows `kicad-cli.exe`, absolute workspace paths are handed to it in their Windows form (`wslpath -w`) for the ERC, the netlist, the DRC, the manufacturing export and the STEP export; a Linux or macOS kicad-cli gets every path unchanged.
package.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow",   "type": "app",-  "version": "0.2.140",+  "version": "0.2.141",   "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.140",+  "version": "0.2.141",   "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.",
tools/kicad-cli-remote+12−2
@@ -513,14 +513,17 @@ 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"   echo "  --refill-zones      Refill zones before running DRC (passed to the desktop's native KiCad)"+  echo "  --save-board        Save the refilled board on the desktop and bring it back over INPUT_FILE"   echo "  --schematic-parity  Test the board against its schematic (<board>.kicad_sch, else KICAD_REMOTE_SCHEMATIC; sent with its sub-sheets)"   exit 0 fi-fmt=json; out=""; board=""; extra=()+fmt=json; out=""; board=""; extra=(); save_board=0 while [[ $# -gt 0 ]]; do   case "$1" in     --format) fmt="$2"; shift 2;;     --output|-o) out="$2"; shift 2;;+    # issue #281 (Jinwon Kim): KiCad saves the refilled board on the desktop; it is brought back over the local file+    --save-board) extra+=("$1"); save_board=1; shift;;     --refill-zones|--severity-all|--severity-error|--severity-warning|--severity-exclusions|--all-track-errors|--schematic-parity|--exit-code-violations) extra+=("$1"); shift;;     --units) extra+=("$1" "$2"); shift 2;;     --*) shift;;@@ -541,7 +544,14 @@ new_job drc send_board "$board" "$JOB" "$psch" rrep="$JOB/$base.drc.$fmt" res=$(run_cli 240 "offline KiCad DRC for adom-aiflow" "" pcb drc "${extra[@]}" --format "$fmt" --output "$rrep" "$JOB/$base.kicad_pcb") || true-if fetch_one "$rrep" "$out"; then cleanup_remote "$JOB"; exit 0; fi+if fetch_one "$rrep" "$out"; then+  if (( save_board )); then+    tmpb="$(dirname "$(absp "$board")")/.$base.saved.$$.kicad_pcb"+    if fetch_one "$JOB/$base.kicad_pcb" "$tmpb" && [[ -s "$tmpb" ]]; then mv -f "$tmpb" "$board"+    else rm -f "$tmpb"; echo "kicad-cli-remote: --save-board: the refilled board did not come back; $board is unchanged" >&2; fi+  fi+  cleanup_remote "$JOB"; exit 0+fi cleanup_remote "$JOB" echo "kicad-cli-remote: no report came back" >&2 echo "$res" | tail_of
tools/page-build.py+10−2
@@ -2192,11 +2192,19 @@ def board_export_bundle(run_dir, bundle):         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})+    # issue #281 (Jinwon Kim): only the BOM and CPL of the board this export checked (an earlier board's files stay+    # in the folder), and nothing copied onto itself when `export --out` wrote straight into the page bundle+    sheets = []     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))})+            sheets.append((f, role))+    ours = [x for x in sheets if x[0].startswith(stem + "-")] if board else []+    for f, role in (ours or sheets):+        src, dst = os.path.join(mdir, f), os.path.join(bundle, f)+        if not (os.path.exists(dst) and os.path.samefile(src, dst)):+            shutil.copy(src, dst)+        files.append({"path": f, "role": role, "bytes": os.path.getsize(dst)})     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"