← Commit history
Merge PR #689: 0.2.152: check and planner fixes from #292, #293, #294 (aiflow-0.2.152 -> main) merge
Showing changes introduced by the merge (against its first parent).
31 files changed
+881−161
Cargo.lock+11−11Cargo.toml+1−1crates/adom-aiflow/src/checks.rs+35−3crates/adom-aiflow/src/fields_suggest.rs+80−5crates/adom-aiflow/src/fills.rs+8−2crates/adom-aiflow/src/main.rs+184−22crates/adom-aiflow/src/mechanical.rs+1−14crates/adom-aiflow/src/part_check.rs+40−13crates/adom-aiflow/src/pourverify.rs+4−19crates/adom-aiflow/src/schematic_check.rs+7crates/adom-aiflow/src/silk_polarity.rs+63−7crates/adom-aiflow/src/verified.rs+3crates/adom-aiflow/src/zone_ownership.rs+12crates/aiflow-analyze/src/current_acks.rs+1−1crates/aiflow-analyze/src/lib.rs+12−1crates/aiflow-analyze/src/pour_cover.rs+36−5crates/aiflow-board/src/geom.rs+39crates/aiflow-board/src/lib.rs+22−1crates/aiflow-copper/src/lib.rs+3−1crates/aiflow-pours/src/lib.rs+127−29crates/aiflow-pours/src/stitch_grid.rs+39−14crates/aiflow-router/src/drive.rs+21−3crates/aiflow-router/src/lib.rs+23−2crates/aiflow-router/src/plane_under.rs+10crates/aiflow-router/src/rules.rs+7−1crates/aiflow-router/tests/qfn_escape.rs+41docs/release-0.2.152.md+45package.json+1−1page.json+1−1skills/adom-aiflow/SKILL.md+1−1skills/aiflow-power-layout/SKILL.md+3−3Cargo.lock+11−11@@ -4,7 +4,7 @@ version = 4 [[package]] name = "adom-aiflow"-version = "0.2.151"+version = "0.2.152" dependencies = [ "aiflow-analyze", "aiflow-board",@@ -28,7 +28,7 @@ dependencies = [ [[package]] name = "aiflow-analyze"-version = "0.2.151"+version = "0.2.152" dependencies = [ "aiflow-board", "aiflow-sys",@@ -39,7 +39,7 @@ dependencies = [ [[package]] name = "aiflow-board"-version = "0.2.151"+version = "0.2.152" dependencies = [ "aiflow-sys", "roxmltree",@@ -49,7 +49,7 @@ dependencies = [ [[package]] name = "aiflow-bridge"-version = "0.2.151"+version = "0.2.152" dependencies = [ "aiflow-board", "aiflow-sys",@@ -59,7 +59,7 @@ dependencies = [ [[package]] name = "aiflow-copper"-version = "0.2.151"+version = "0.2.152" dependencies = [ "aiflow-board", "aiflow-grid",@@ -70,7 +70,7 @@ dependencies = [ [[package]] name = "aiflow-grid"-version = "0.2.151"+version = "0.2.152" dependencies = [ "aiflow-board", "serde",@@ -79,7 +79,7 @@ dependencies = [ [[package]] name = "aiflow-place"-version = "0.2.151"+version = "0.2.152" dependencies = [ "aiflow-board", "aiflow-sys",@@ -89,7 +89,7 @@ dependencies = [ [[package]] name = "aiflow-pours"-version = "0.2.151"+version = "0.2.152" dependencies = [ "aiflow-board", "aiflow-copper",@@ -100,7 +100,7 @@ dependencies = [ [[package]] name = "aiflow-router"-version = "0.2.151"+version = "0.2.152" dependencies = [ "aiflow-board", "aiflow-grid",@@ -111,7 +111,7 @@ dependencies = [ [[package]] name = "aiflow-run"-version = "0.2.151"+version = "0.2.152" dependencies = [ "aiflow-sys", "serde",@@ -120,7 +120,7 @@ dependencies = [ [[package]] name = "aiflow-sys"-version = "0.2.151"+version = "0.2.152" dependencies = [ "serde_json", ]
Cargo.toml+1−1@@ -15,7 +15,7 @@ members = [ ] [workspace.package]-version = "0.2.151"+version = "0.2.152" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
crates/adom-aiflow/src/checks.rs+35−3@@ -89,7 +89,13 @@ pub fn board_netlist(b: &Board) -> (BTreeMap<String, String>, BTreeMap<(String, pub fn compare_netlists(sch: &SchNetlist, b: &Board) -> Value { let (brefs, bpins) = board_netlist(b); let missing_refs: Vec<String> = sch.refs.keys().filter(|r| !brefs.contains_key(*r)).cloned().collect();- let extra_refs: Vec<String> = brefs.keys().filter(|r| !sch.refs.contains_key(*r)).cloned().collect();+ // issue #294 (Mohit Singh): a footprint with no pad on any net (a fiducial, a logo, an unplated hole) carries no+ // connectivity, so it cannot make the board differ from the schematic: listed apart, never a parity failure. A+ // netted extra part (a plated hole on GND, a part added only on the board) still fails, exclude_from_bom or not.+ // issue #294: KiCad's own `board_only` attribute says the same (Update PCB from Schematic leaves the footprint alone)+ let board_only: Vec<String> = b.root.find_all("footprint").filter(|f| f.find("attr").is_some_and(|a| a.items.iter().any(|it| matches!(it, aiflow_board::sx::Item::Atom { text, .. } if text == "board_only")))).filter_map(aiflow_board::reference_of).collect();+ let netless = |r: &String| board_only.contains(r) || !bpins.iter().any(|((pr, _), ns)| pr == r && !ns.is_empty());+ let (extra_refs, board_furniture): (Vec<String>, Vec<String>) = brefs.keys().filter(|r| !sch.refs.contains_key(*r)).cloned().partition(|r| !netless(r)); let mut footprint_diffs = Vec::new(); for (r, f) in &sch.refs { if let Some(bf) = brefs.get(r) {@@ -125,7 +131,7 @@ pub fn compare_netlists(sch: &SchNetlist, b: &Board) -> Value { } let ok = missing_refs.is_empty() && extra_refs.is_empty() && mismatches.is_empty(); json!({"ok": ok, "schematicRefs": sch.refs.len(), "boardRefs": brefs.len(), "connectedPins": connected, "matchedPins": matched,- "missingRefs": missing_refs, "extraRefs": extra_refs, "mismatches": mismatches, "footprintDifferences": footprint_diffs})+ "missingRefs": missing_refs, "extraRefs": extra_refs, "boardFurniture": board_furniture, "mismatches": mismatches, "footprintDifferences": footprint_diffs}) } // ----------------------------------------------------------------------------- molecule (#9)@@ -415,7 +421,15 @@ pub fn molecule_check_bom(b: &Board, spec: &Value, before: Option<&Board>, bom: }); if moved.is_empty() { f.ok(format!("{} fixed references match explicit positions or starting-board locks; anchor and rotations retained", refs.len())); } else if rename_only { f.ok(format!("{} fixed references renamed in place, nothing moved (same footprints, positions and rotations as the start board): {}", renamed.len(), renamed.join("; "))); }- else { f.error(format!("fixed references moved since the run started: {}", moved.join("; ")), "Put them back where the start board had them (spec.fixedRefs); placement must not move the molecule interface. If the human changed the interface, record it: `prompt --text \"<their words>\" --rebaseline <new board>`."); }+ else {+ // issue #293: the refs spec.molecule.fixed places relative to MP1 are not counted as moved, but they moved+ // with it: name them, so the report does not read as MP1 alone+ let with_mp1: Vec<&String> = if moved_refs.iter().any(|r| *r == "MP1") {+ refs.iter().filter(|r| *r != "MP1" && m["fixed"].get(r.as_str()).is_some() && !moved_refs.contains(r)).filter(|r| matches!((b0.footprints.get(*r), b.footprints.get(*r)), (Some(a), Some(c)) if (a.x - c.x).abs() > 0.005 || (a.y - c.y).abs() > 0.005)).collect()+ } else { Vec::new() };+ let also = if with_mp1.is_empty() { String::new() } else { format!(" ({} more moved with MP1 and sit where spec.molecule.fixed puts them: {})", with_mp1.len(), with_mp1.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", ")) };+ f.error(format!("fixed references moved since the run started: {}{also}", moved.join("; ")), "Put them back where the baseline board had them (spec.fixedRefs); placement must not move the molecule interface. The baseline is the first board of the run with the interface inside the outline (a start board that staged parts beside the outline is skipped). If the human changed the interface, record it: `prompt --text \"<their words>\" --rebaseline <new board>`.");+ } } pin_class_check(b, spec, &m, bom, &mut f); f@@ -1415,6 +1429,24 @@ mod tests { assert!(pins.contains(&"R2.3") && pins.contains(&"R2.2"), "{rep}"); } + /// Issue #294 (Mohit Singh): fiducials (no pad on any net) are board furniture, not a parity failure; a netted+ /// extra part still is.+ #[test]+ fn netless_footprints_do_not_break_schematic_parity() {+ let fid = |r: &str, x: u32| format!(r#" (footprint "Fiducial:Fiducial_1mm_Mask2mm" (layer "F.Cu") (at {x} 95) (property "Reference" "{r}") (attr smd exclude_from_bom) (pad "1" smd circle (at 0 0) (size 1 1) (layers "F.Cu" "F.Mask")))"#);+ let with_fids = BOARD.replacen(" (footprint \"Resistor_SMD:R_0402_1005Metric\" (layer \"F.Cu\") (at 110 90)", &format!("{}{} (footprint \"Resistor_SMD:R_0402_1005Metric\" (layer \"F.Cu\") (at 110 90)", fid("FID1", 104), fid("FID2", 120)), 1);+ assert!(with_fids.contains("FID2"));+ let sch = parse_sch_netlist(&netlist("2", "")).unwrap();+ let rep = compare_netlists(&sch, &board(&with_fids));+ assert_eq!(rep["ok"], true, "{rep}");+ assert_eq!(rep["boardFurniture"], json!(["FID1", "FID2"]));+ assert_eq!(rep["extraRefs"], json!([]));+ // a part on a net that the schematic does not have still fails+ let netted = with_fids.replacen("(layers \"F.Cu\" \"F.Mask\")))", "(layers \"F.Cu\" \"F.Mask\") (net \"GND\")))", 1);+ let rep = compare_netlists(&sch, &board(&netted));+ assert_eq!((rep["ok"].clone(), rep["extraRefs"].clone()), (json!(false), json!(["FID1"])), "{rep}");+ }+ #[test] fn molecule_conforms_and_catches_off_grid_contact() { let spec = json!({"molecule": {"gridMm": 2, "edgeMarginMm": 2, "fixed": {"MC1": [0, 12]}}});
crates/adom-aiflow/src/fields_suggest.rs+80−5@@ -120,16 +120,69 @@ pub fn spec_net_lines(fields: &Value) -> Vec<String> { by.into_iter().map(|(s, b, ats)| format!("spec net {s} read as the board's {b}{}", if ats.is_empty() { String::new() } else { format!(" (at {})", ats.join(", ")) })).collect() } +/// The spec's value at a Fields spec key (`switching./SW.freqHz`, `epsilonR`), a net key matched in either spelling+/// (`SW` and `/SW`), with the section entry it sits in.+pub fn spec_at<'a>(spec: &'a Value, key: &str) -> Option<(&'a Value, &'a Value)> {+ let parts: Vec<&str> = key.split('.').collect();+ match parts.len() {+ 0 => None,+ 1 => spec.get(parts[0]).map(|v| (v, spec)),+ 2 => { let e = &spec[parts[0]]; e.get(parts[1]).map(|v| (v, e)) }+ n => {+ let (sec, leaf, net) = (parts[0], parts[n - 1], parts[1..n - 1].join("."));+ let entry = spec[sec].as_object()?.iter().find(|(k, _)| aiflow_board::netname::norm_net(k) == aiflow_board::netname::norm_net(&net)).map(|(_, v)| v)?;+ entry.get(leaf).map(|v| (v, entry))+ }+ }+}++/// Issue #294 (Mohit Singh): a fragment's net keys in the spelling the spec already uses (`switching./SW` fills the+/// spec's `switching.SW`, never a sibling entry the next solve refuses). Returns (fragment key, spec key) renamed.+pub fn rekey_to_spec(spec: &Value, patch: &mut Value) -> Vec<(String, String)> {+ let mut renamed = Vec::new();+ let Some(p) = patch.as_object_mut() else { return renamed };+ for (sec, v) in p.iter_mut() {+ let (Some(have), Some(frag)) = (spec.get(sec).and_then(Value::as_object), v.as_object_mut()) else { continue };+ let keys: Vec<String> = frag.keys().cloned().collect();+ for k in keys {+ if have.contains_key(&k) { continue; }+ let Some(sk) = have.keys().find(|h| aiflow_board::netname::norm_net(h) == aiflow_board::netname::norm_net(&k)).cloned() else { continue };+ if frag.contains_key(&sk) { continue; }+ let val = frag.remove(&k).unwrap();+ frag.insert(sk.clone(), val);+ renamed.push((format!("{sec}.{k}"), format!("{sec}.{sk}")));+ }+ }+ renamed+}+ /// Fields' assumed inputs (2, `review.inputs.items`), most important first: each with its part, the datasheet field to /// read, the spec key it goes to, what was used meanwhile, and the part's component page when `parts` found one.-pub fn assumed_inputs(fields: &Value, parts: &[Value]) -> Vec<Value> {+/// Issue #294: a value the spec gives is said as the spec's (Fields labels it a default when no source is recorded),+/// and the switching frequency names the controller that sets it (`controller`), not a FET on the switch node.+pub fn assumed_inputs(fields: &Value, parts: &[Value], spec: Option<&Value>, controller: Option<&str>) -> Vec<Value> { let rank = |m: &str| match m { "high" => 0, "medium" => 1, _ => 2 }; let mut items: Vec<Value> = fields["review"]["inputs"]["items"].as_array().cloned().unwrap_or_default(); items.sort_by_key(|i| rank(i["matters"].as_str().unwrap_or(""))); items.into_iter().map(|i| {- let r = i["part"]["ref"].as_str().unwrap_or("");- let page = parts.iter().find(|p| p["refs"].as_array().is_some_and(|a| a.iter().any(|x| x.as_str() == Some(r)))).and_then(|p| p["wiki"].as_str().map(str::to_string));- json!({"matters": i["matters"], "ref": i["part"]["ref"], "mpn": i["part"]["mpn"], "what": i["what"], "datasheetField": i["datasheetField"], "specKey": i["specKey"], "used": i["used"], "affects": i["affects"], "page": page})+ let key = i["specKey"].as_str().unwrap_or("");+ let leaf = key.rsplit('.').next().unwrap_or("");+ let (mut r, mut mpn) = (i["part"]["ref"].clone(), i["part"]["mpn"].clone());+ if leaf == "freqHz" {+ if let Some(c) = controller.filter(|c| r.as_str() != Some(*c)) { r = json!(c); mpn = Value::Null; }+ }+ let rs = r.as_str().unwrap_or("").to_string();+ let page = parts.iter().find(|p| p["refs"].as_array().is_some_and(|a| a.iter().any(|x| x.as_str() == Some(rs.as_str())))).and_then(|p| p["wiki"].as_str().map(str::to_string));+ let mpn = if mpn.is_null() { parts.iter().find(|p| p["refs"].as_array().is_some_and(|a| a.iter().any(|x| x.as_str() == Some(rs.as_str())))).map(|p| p["mpn"].clone()).unwrap_or(Value::Null) } else { mpn };+ let mut used = i["used"].clone();+ if let Some((v, entry)) = spec.and_then(|s| spec_at(s, key)) {+ let stem = leaf.trim_end_matches("Hz").trim_end_matches("Ns").trim_end_matches("V");+ let src = entry.get(format!("{leaf}Source")).or(entry.get(format!("{stem}Source"))).and_then(Value::as_str);+ let shown = v.as_f64().map(|x| format!("{}", (x * 1e6).round() / 1e6)).unwrap_or_else(|| v.to_string());+ used = json!(match src { Some(s) => format!("{shown} from the spec ({s}); Fields still lists it as assumed: name the datasheet in {leaf}Source"), None => format!("{shown} from the spec, no source recorded (add {leaf}Source naming the datasheet and page)") });+ }+ json!({"matters": i["matters"], "ref": r, "mpn": mpn, "what": i["what"], "datasheetField": i["datasheetField"], "specKey": i["specKey"], "used": used, "affects": i["affects"], "page": page,+ "setBy": if leaf == "freqHz" && controller.is_some() { json!("the controller that sets the switching frequency") } else { Value::Null }}) }).collect() } @@ -246,7 +299,7 @@ mod tests { {"matters": "low", "part": null, "specKey": "ambientC", "datasheetField": "product: worst-case ambient", "used": "25 C", "what": "ambient"}, {"matters": "high", "part": {"ref": "U7", "mpn": "W25Q32JVSSIQ"}, "specKey": "hot.U7.thetaJcKPerW", "datasheetField": "thermal information: RthJC", "used": "not included", "what": "U7's junction-to-case"}]}}}); let parts = vec![json!({"refs": ["U7"], "wiki": "adom/w25q32jvssiq"})];- let items = assumed_inputs(&fields, &parts);+ let items = assumed_inputs(&fields, &parts, None, None); assert_eq!(items[0]["specKey"], "hot.U7.thetaJcKPerW", "high first"); let lines = input_lines(&items); assert!(lines[0].contains("1 high, 0 medium, 1 low"), "{lines:?}");@@ -263,4 +316,26 @@ mod tests { assert_eq!(set, vec!["ambientC", "hot.U7.thetaJcKPerW", "hot.U7.tjMaxC"]); } ++ /// Issue #294: a fragment keyed `switching./SW` fills the spec's `switching.SW`; a spec value is not "(default)".+ #[test]+ fn a_fragment_fills_the_spec_net_key_and_spec_values_are_named() {+ let spec = json!({"switching": {"SW": {"freqHz": 350000, "highV": 24.0, "lowV": 0.0, "riseNs": 13.3, "riseSource": "calc"}}});+ let mut frag = json!({"switching": {"/SW": {"freqHz": 400000}}});+ let renamed = rekey_to_spec(&spec, &mut frag);+ assert_eq!(renamed, vec![("switching./SW".to_string(), "switching.SW".to_string())]);+ let mut s2 = spec.clone();+ let mut set = Vec::new();+ merge(&mut s2, &frag, "", &mut set);+ assert_eq!(s2["switching"]["SW"]["freqHz"], 400000);+ assert_eq!(s2["switching"]["SW"]["highV"], 24.0);+ assert!(s2["switching"].get("/SW").is_none());+ let fields = json!({"review": {"inputs": {"items": [+ {"matters": "high", "part": {"ref": "Q1", "mpn": "FET"}, "specKey": "switching./SW.freqHz", "used": "350 kHz (default)"},+ {"matters": "medium", "part": {"ref": "Q1"}, "specKey": "switching./SW.riseNs", "used": "13.3 ns (default)"}]}}});+ let items = assumed_inputs(&fields, &[], Some(&spec), Some("U1"));+ assert_eq!(items[0]["ref"], "U1");+ assert!(items[0]["used"].as_str().unwrap().contains("from the spec, no source recorded"), "{}", items[0]["used"]);+ assert!(items[1]["used"].as_str().unwrap().contains("from the spec (calc)"), "{}", items[1]["used"]);+ } }
crates/adom-aiflow/src/fills.rs+8−2@@ -61,13 +61,19 @@ pub fn saved(b: &Board) -> (Value, Vec<String>, Vec<String>) { should += 1; let mut per_layer = serde_json::Map::new(); let mut missing = Vec::new();+ let mut absorbed = serde_json::Map::new(); for l in &layers { let n = z.find_all("filled_polygon").filter(|f| f.find("layer").and_then(|x| x.value()) == Some(l.as_str())).count(); per_layer.insert(l.clone(), json!(n));- if n == 0 { missing.push(l.clone()); } else if !filled_layers.contains(l) { filled_layers.push(l.clone()); }+ if n == 0 {+ match b.zone_absorbed(z, l) { Some(by) => { absorbed.insert(l.clone(), json!(by)); } None => missing.push(l.clone()) }+ } else if !filled_layers.contains(l) { filled_layers.push(l.clone()); } } if missing.is_empty() { ok += 1; } else { problems.push(format!("{label} has no filled polygon on {} in the saved board", missing.join(", "))); }- zones.push(json!({"zone": label, "layers": layers, "filledPolygons": per_layer, "outlineMm2": (area * 100.0).round() / 100.0}));+ let mut entry = json!({"zone": label, "layers": layers, "filledPolygons": per_layer, "outlineMm2": (area * 100.0).round() / 100.0});+ // issue #293: a layer a higher-priority same-net zone covers is that zone's copper, not a missing fill+ if !absorbed.is_empty() { entry["absorbedBy"] = Value::Object(absorbed); }+ zones.push(entry); } (json!({"zones": zones, "shouldFill": should, "filled": ok, "pass": problems.is_empty(), "filledLayers": filled_layers}), problems, filled_layers) }
crates/adom-aiflow/src/main.rs+184−22@@ -348,7 +348,8 @@ enum Cmd { /// Filled copper per layer from the live board Measure, /// current, thermal, impedance, si, or dfa (assembly solderability, tombstoning, fiducials, bottom-side reflow). `analyze current --ack [email protected]|NET@x,y --why "..."` records a reviewed part-limited peak over the Fields density screen (repeat --ack for more); it covers only that place (the pad or 0.5 mm), keeps the number reported and expires when the copper fingerprint or the spec changes. spec.boardSink declares a board-face heat sink for named parts (thermal).- Analyze { what: String, #[arg(long)] plan: Option<String>, #[arg(long)] fields: Option<PathBuf>, #[arg(long)] ack: Vec<String>, #[arg(long)] why: Option<String> },+ Analyze { what: String, #[arg(long)] plan: Option<String>, #[arg(long)] fields: Option<PathBuf>, #[arg(long)] ack: Vec<String>, /// one --why for every --ack, or one per --ack in the same order (issue #293)+ #[arg(long)] why: Vec<String> }, /// The finish line, as a report card: what passed, what is still open and what to do next (it never refuses) Finish, /// Impedance targets (spec impedanceTargets, or adom-fields' impedance map): `table` prints the trace width (and pair gap) for each target on every copper layer from the stackup, refusing a layer the target cannot reach within the fab's minimums; `check` judges the board's copper (or --plan) against them. On the run's board and spec, or on --board and --spec.@@ -3706,6 +3707,31 @@ fn record_fields_solve(r: &mut Run, file: &Path, how: &str, args: &[String]) { } } +/// Issue #293 (Mohit Singh): the desktop project the run's bound board belongs to, for `rules check` and `rules sync`.+/// None when the run has no bound desktop board on the KiCad lane. Ok((local board path, writable)): the board+/// itself on a mounted drive (writable), or a fresh pull of the board, its .kicad_pro and .kicad_dru (read only).+fn live_project(r: &Run, cli: &Cli) -> Option<Result<(PathBuf, bool), String>> {+ let rb = r.data["remoteBoard"].as_str()?.to_string();+ if !r.data["target"].is_string() || aiflow_bridge::eda::active().id() != "kicad" { return None; }+ if let Ok(p) = winpath::local(Path::new(&rb), Path::new("/mnt")) { if p.is_file() && !p.starts_with(&r.dir) { return Some(Ok((p, true))); } }+ let br = bridge_of(r, cli);+ Some(zone_ownership::pull_saved(&br, &rb, &r.dir, "live-rules").map(|local| {+ for ext in ["kicad_pro", "kicad_dru"] {+ let side = Path::new(&rb.replace('\\', "/")).with_extension(ext).display().to_string();+ let side = if rb.contains('\\') { side.replace('/', "\\") } else { side };+ let _ = br.call("pull_file", &json!({"filePaths": [side], "saveTo": aiflow_sys::canonicalize(local.parent().unwrap()).map(|p| p.display().to_string()).unwrap_or_default()}));+ }+ (local, false)+ }))+}++/// The spec and the switching controller (the U part on the switch node), for the assumed-input list (issue #294).+fn fields_input_ctx(r: &Run) -> (Value, Option<String>) {+ let sv = spec_soft(r);+ let ctl = Board::load(&r.current_board()).ok().and_then(|b| converter::board_refs(&sv, &b)).and_then(|t| t.1);+ (sv, ctl)+}+ fn checked_remote_binding(r:&Run,br:&Bridge,remote:&str,dir:&Path)->Result<Value,String>{ let local=PathBuf::from(r.current_board()); let files=remote_binding::files(&local,remote)?;@@ -3736,9 +3762,22 @@ fn export_sch_netlist(sch: &str, out: &Path) -> Result<String, String> { /// The reference for fixed parts: the run's first board (what `start` copied), or the board a human-approved /// interface change re-baselined to (`prompt --rebaseline`, issue #187).+/// Issue #293 (Mohit Singh): a from-scratch board stages every part beside the outline, so the first board whose+/// interface (spec.fixedRefs, spec.molecule.fixed, the MPn pins) sits inside the outline is the baseline; a start+/// board that only staged the interface off the board fixes nothing. fn first_board(r: &Run) -> Option<Board> { if let Some(b) = r.data["interfaceBaseline"]["board"].as_str().and_then(|p| Board::load(p).ok()) { return Some(b); }- r.data["boards"].as_array().and_then(|b| b.first()).and_then(|b| b.as_str()).and_then(|p| Board::load(p).ok())+ let spec = spec_soft(r);+ let mut named: Vec<String> = spec["fixedRefs"].as_array().map(|a| a.iter().filter_map(|x| x.as_str().map(str::to_string)).collect()).unwrap_or_default();+ if let Some(f) = spec["molecule"]["fixed"].as_object() { named.extend(f.keys().cloned()); }+ let is_mp = |r: &str| r.strip_prefix("MP").is_some_and(|n| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()));+ let on_board = |b: &Board| {+ let refs: Vec<&aiflow_board::Footprint> = b.footprints.iter().filter(|(r, _)| is_mp(r) || named.contains(r)).map(|(_, f)| f).collect();+ b.outline.len() < 3 || refs.iter().all(|f| aiflow_board::geom::point_in_poly(f.x, f.y, &b.outline))+ };+ let boards: Vec<Board> = r.data["boards"].as_array().map(|a| a.iter().filter_map(|b| b.as_str()).filter_map(|p| Board::load(p).ok()).collect()).unwrap_or_default();+ let first_inside = boards.iter().position(|b| on_board(b));+ match first_inside { Some(i) => boards.into_iter().nth(i), None => if spec.get("molecule").is_some() || !named.is_empty() { None } else { boards.into_iter().next() } } } /// Molecule conformance of a board when the spec declares a molecule; None otherwise.@@ -3981,6 +4020,17 @@ fn supply_assessed(r: &Run, mpn: &str) -> Option<Value> { supply::find(&parts, mpn).cloned() } +/// A page's 3D model size (x, y, z in mm, Z up) as the wiki measures its GLB (`adom-wiki page bounds`), issue #293.+fn page_bounds(page: &str) -> Option<[f64; 3]> {+ let o = aiflow_sys::process::Command::new("adom-wiki").args(["page", "bounds", page, "--json"]).stdin(aiflow_sys::process::Stdio::null()).output().ok().filter(|o| o.status.success())?;+ let t = String::from_utf8_lossy(&o.stdout);+ let v: Value = serde_json::from_str(t.get(t.find('{')?..=t.rfind('}')?)?).ok()?;+ let d = &v["data"];+ let s: Vec<f64> = d["size"].as_array()?.iter().filter_map(Value::as_f64).collect();+ if s.len() != 3 { return None; }+ Some(if d["upAxis"].as_str().is_some_and(|a| a.eq_ignore_ascii_case("y")) { [s[0], s[2], s[1]] } else { [s[0], s[1], s[2]] })+}+ fn wiki_page_json(page: &str) -> Option<Value> { let o = aiflow_sys::process::Command::new("adom-wiki").args(["repo", "show", page, "page.json"]).stdin(aiflow_sys::process::Stdio::null()).output().ok().filter(|o| o.status.success())?; let t = String::from_utf8_lossy(&o.stdout);@@ -4537,18 +4587,39 @@ fn main() { Cmd::Silkscreen { action, board, out, size, .. } => { // issue #163: findings and an offline tidy the AI may run; never a gate let (r, bp) = match board.clone() { Some(b) => (Run::open(&run_dir(&cli)), b), None => { let r = load_run(&cli); let b = r.current_board(); (Some(r), b) } };+ // issue #293 (Mohit Singh): fab-check judges the board the human has. With no --board and a bound desktop+ // board, it reads the saved desktop file fresh (the run's snapshot only changes at adopt-board), and it+ // always says which board it read.+ let mut read_note = format!("read {bp}");+ let mut bp = bp;+ if action == "fab-check" && board.is_none() {+ if let (Some(rr), Some(rb)) = (r.as_ref(), r.as_ref().and_then(|x| x.data["remoteBoard"].as_str().map(str::to_string))) {+ if rr.data["target"].is_string() && aiflow_bridge::eda::active().id() == "kicad" {+ match zone_ownership::pull_saved(&bridge_of(rr, &cli), &rb, &rr.dir, "fab-check") {+ Ok(p) => {+ let newer = sha256_file(&p.display().to_string()) != sha256_file(&bp);+ read_note = format!("read the saved desktop board {rb}{}", if newer { " (newer than the run's snapshot: `adopt-board` makes it the run's board)" } else { " (the same as the run's snapshot)" });+ bp = p.display().to_string();+ }+ Err(e) => read_note = format!("read the run's snapshot {bp} ({e})"),+ }+ }+ }+ } let b = Board::load(&bp).unwrap_or_else(|e| err(&e, &["Pass --board <a saved .kicad_pcb>.".into()])); if action == "fab-check" { let c = fab_layer::check(&b); let lines: Vec<String> = c["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();- if lines.is_empty() { ok(&format!("Fab layer meets the standard: {} parts, {} Fab texts, reference size {} mm", c["parts"], c["fabTexts"], c["boardSizeMm"]), &[]); return; }- findings(&lines.join("; "), &[fab_layer::TIDY_HINT.into()]);+ if lines.is_empty() { ok(&format!("Fab layer meets the standard: {} parts, {} Fab texts, reference size {} mm ({read_note})", c["parts"], c["fabTexts"], c["boardSizeMm"]), &[]); return; }+ findings(&format!("{} ({read_note})", lines.join("; ")), &[fab_layer::TIDY_HINT.into()]); } if size.is_some_and(|s| !(s.is_finite() && s >= fab_layer::FLOOR)) { err(&format!("--size is the Fab reference height in mm, at least {}", fab_layer::FLOOR), &[]); } let (text, changes) = fab_layer::tidy(&b, *size); let outp = out.clone().unwrap_or_else(|| { let p = Path::new(&bp); p.with_file_name(format!("{}-fab.kicad_pcb", p.file_stem().and_then(|s| s.to_str()).unwrap_or("board"))).display().to_string() }); let tidied = Board::from_text(&outp, text.clone()).unwrap_or_else(|e| err(&format!("the tidied board does not parse ({e}); nothing written"), &[])); std::fs::write(&outp, &text).unwrap_or_else(|e| err(&format!("{outp}: {e}"), &[]));+ // issue #292: the tidied copy keeps the project's rules beside it, so adopting it checks against them+ let _ = aiflow_copper::copy_project_rules(&bp, &outp); let after = fab_layer::check(&tidied); if let Some(mut r) = r { r.log("fab-tidy", json!({"board": bp, "out": outp, "parts": changes.len(), "changes": changes, "sizeMm": size, "clean": after["clean"]})); let _ = r.save(); } let left: Vec<String> = after["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();@@ -5020,20 +5091,40 @@ fn main() { if evidence.trim().is_empty(){err("adopt-board needs --evidence describing native save/refill/read-back", &["Save and refill the board in its EDA, then pass --board <file> --evidence <review notes or report path>.".into()]);} if aiflow_bridge::eda::active().id()=="altium" { adopt_altium(&mut r,&cli,&dir,board,evidence); } Board::load(board).unwrap_or_else(|e|err(&e,&[]));- let base=run_drc_for(&r, &r.current_board()).unwrap_or_else(|e|err(&e,&[]));- let candidate=run_drc_for(&r, board).unwrap_or_else(|e|err(&e,&[]));- let summary=aiflow_copper::summarize_with(&candidate,Some(&base),silk_policy::blocking(&spec_soft(&r),&r.current_board()));- if summary["newErrors"].as_u64()!=Some(0){err(&format!("adopt-board adds native DRC violations: {}",summary["newErrorList"]), &["Correct the new violations and rerun adopt-board. Existing connectivity may remain for later routing.".into()]);}+ let cur = r.current_board();+ let base=run_drc_for(&r, &cur).unwrap_or_else(|e|err(&e,&[])); let n=r.data["boards"].as_array().map(|a|a.len()).unwrap_or(1); let dest=dir.join(format!("board-{n}.kicad_pcb"));- std::fs::copy(board,&dest).unwrap_or_else(|e|err(&e.to_string(),&[]));- aiflow_copper::copy_project_rules(board,&dest.display().to_string()).unwrap_or_else(|e|err(&e,&[]));+ // issue #292 (Mohit Singh): the candidate is checked as a staged copy with its project rules beside it, and+ // only renamed into the run once it passes. `--board` is never written (it once was the destination itself,+ // board-N, and the copy onto itself left it at 0 bytes), and a refused board leaves nothing behind.+ let stage = dir.join(format!("adopt-candidate-{n}-{}.kicad_pcb", aiflow_sys::process::id()));+ let stage_s = stage.display().to_string();+ let unstage = || for ext in ["kicad_pcb", "kicad_pro", "kicad_dru"] { let _ = std::fs::remove_file(stage.with_extension(ext)); };+ std::fs::copy(board,&stage).unwrap_or_else(|e|err(&format!("stage {board}: {e}"),&[]));+ // the DRC reads the .kicad_pro/.kicad_dru beside the file: a bare board inside the run takes the run's own+ // rules (the current snapshot's) rather than KiCad's defaults+ let has_rules = |p: &str| ["kicad_pro", "kicad_dru"].iter().any(|e| Path::new(p).with_extension(e).is_file());+ let rules_note = if has_rules(board) {+ aiflow_copper::copy_project_rules(board, &stage_s).unwrap_or_else(|e| { unstage(); err(&e,&[]) }); None+ } else if has_rules(&cur) {+ aiflow_copper::copy_project_rules(&cur, &stage_s).unwrap_or_else(|e| { unstage(); err(&e,&[]) });+ Some(format!("no .kicad_pro or .kicad_dru beside {board}: its DRC used the run's current project rules (beside {cur}), not KiCad's defaults"))+ } else { Some(format!("no .kicad_pro or .kicad_dru beside {board} or the run's current board: both DRCs ran with KiCad's default rules")) };+ if let Some(nt) = &rules_note { note(nt, &[]); }+ let candidate=run_drc_for(&r, &stage_s).unwrap_or_else(|e| { unstage(); err(&e,&[]) });+ let summary=aiflow_copper::summarize_with(&candidate,Some(&base),silk_policy::blocking(&spec_soft(&r),&cur));+ if summary["newErrors"].as_u64()!=Some(0){ unstage(); err(&format!("adopt-board adds native DRC violations: {} ({board} is unchanged{})",summary["newErrorList"], rules_note.as_deref().map(|x| format!("; {x}")).unwrap_or_default()), &["Correct the new violations and rerun adopt-board. Existing connectivity may remain for later routing.".into(), "Violations a project rule allows (a .kicad_dru constraint) mean the DRC did not have that project's rules: put the board's .kicad_pro and .kicad_dru beside it, or adopt the saved desktop board.".into()]);}+ for ext in ["kicad_pcb", "kicad_pro", "kicad_dru"] {+ let s = stage.with_extension(ext);+ if s.is_file() { std::fs::rename(&s, dest.with_extension(ext)).unwrap_or_else(|e| { unstage(); err(&format!("move the adopted board into the run: {e}"),&[]) }); }+ } let (carried, carry_note) = copper_carry::adopt(&mut r, &dest.display().to_string()); r.data["remoteBinding"]=Value::Null; // N4: dangling tracks and vias (KiCad's own DRC warnings) are named, not left for the human to find; // AF112: pads and vias that ask KiCad for teardrops are named (a refill adds teardrop zones there) let dangling = dangling_copper(&candidate);- let teardrops = teardrop_items(&Board::load(board).unwrap_or_else(|e| err(&e, &[])));+ let teardrops = teardrop_items(&Board::load(&dest.display().to_string()).unwrap_or_else(|e| err(&e, &[]))); r.log("adopt-board",json!({"source":board,"board":dest,"evidence":evidence,"drc":summary,"copperCarried":carried,"dangling":dangling,"teardropItems":teardrops})); r.save().unwrap(); let mut extra: Vec<String> = Vec::new();@@ -5189,6 +5280,7 @@ fn main() { let (mut results, mut lines) = (Vec::new(), Vec::new()); let mut dim_stops: Vec<String> = Vec::new(); for f in &facts {+ let mut named_model: Option<String> = None; let mpn = f["mpn"].as_str().unwrap_or(""); let row = rows.iter().find(|x| x["mpn"].as_str().is_some_and(|m| m.eq_ignore_ascii_case(mpn))).cloned().unwrap_or(Value::Null); let bom_maker = row["manufacturer"].as_str().map(str::to_string);@@ -5201,13 +5293,25 @@ fn main() { let pj = wiki_page_json(page).unwrap_or(Value::Null); let parts = &pj["component"]["parts"]; let pads = parts["footprint"].as_str().and_then(|fp| wiki_file(page, fp));- let h = parts["step"].as_str().and_then(|st| wiki_file(page, st)).and_then(|t| part_check::step_height(&t));+ // issue #293 (Mohit Singh): the page's model is where the page says (component.parts, or the top-level+ // step_path / model_3d_path); the STEP is measured, the GLB by the wiki (`page bounds`), and the two compared+ let step = parts["step"].as_str().or(pj["step_path"].as_str()).map(str::to_string);+ let glb = parts["glb"].as_str().or(pj["model_3d_path"].as_str()).filter(|p| p.to_ascii_lowercase().ends_with(".glb")).map(str::to_string);+ let step_ext = step.as_deref().and_then(|st| wiki_file(page, st)).and_then(|t| part_check::step_extents(&t));+ let glb_ext = glb.as_ref().and_then(|_| page_bounds(page));+ if let (Some(a), Some(b)) = (step_ext, glb_ext) {+ let m = part_check::model_mismatch(a, b);+ if !m.is_empty() { lines.push(format!("{mpn}: the STEP and the GLB of {page} disagree in size: {} (advisory: one of the page's models is wrong; tell the page owner)", m.join(", "))); }+ }+ let h = step_ext.map(|e| e[2]).or(glb_ext.map(|e| e[2]));+ if h.is_none() { if let Some(m) = step.clone().or(glb.clone()) { named_model = Some(m); } } (page.to_string(), pads, h, pj["component"]["manufacturer"].as_str().map(str::to_string)) } else { lines.push(format!("{mpn}: not in the parts record and no \"page\" given: nothing to compare (run `parts` first)")); continue; }; let pads = fp_text.as_deref().map(part_check::footprint_pads).unwrap_or_default();+ let f = &{ let mut g = f.clone(); if let Some(m) = named_model.take() { g["_modelNamed"] = json!(m); } g }; let (mut v, fl) = part_check::compare(f, &what, &pads, height, maker.as_deref(), bom_maker.as_deref()); // the datasheet's key distances on the footprint (pitch, span, body): a mismatch stops unless acknowledged let (drows, dstop, dacked) = part_check::dims(f, &what, &pads, fp_text.as_deref().and_then(part_check::fab_box));@@ -5522,7 +5626,18 @@ fn main() { // the existing schematic uses (provenance.json nativeSourceBindings) is not asked to move to the PCM library let part_rows = r.data["outcomes"]["parts"]["parts"].as_array().cloned().unwrap_or_default(); let bound: Vec<String> = on_sheet.iter().filter(|(rf, (sl, fp))| bom_refs.contains(rf) && project_lib::native_binding_matches(&part_rows, rf, sl, fp)).map(|(rf, _)| rf.clone()).collect();- let foreign: Vec<String> = match &lib { Some(l) => on_sheet.iter().filter(|(rf, (sl, fp))| bom_refs.contains(rf) && (sl != l || !fp.starts_with(&format!("{l}:"))) && !bound.contains(rf)).map(|(rf, (sl, fp))| format!("{rf} ({sl} / {fp})")).collect(), None => Vec::new() };+ // issue #294 (Mohit Singh): the flow's own test points (`testplan check --add`, a bare copper pad, not a+ // purchased part) and any part with nothing to buy, drawn from a library the project's own sym-lib-table+ // registers, are the project's library too: the Adom Cloud Library is built from purchased parts' pages+ let local_libs = schematic_check::project_sym_libs(Path::new(sch));+ let row_of = |rf: &str| part_rows.iter().find(|p| p["refs"].as_array().is_some_and(|a| a.iter().any(|x| x.as_str() == Some(rf))));+ let nothing_to_buy = |rf: &str| row_of(rf).map(|p| { let m = p["mpn"].as_str().unwrap_or("").trim().to_ascii_lowercase(); m.is_empty() || m.starts_with("none") || m == testplan::TP_MPN.to_ascii_lowercase() || p["page"].as_str() == Some(testplan::TP_PAGE) }).unwrap_or(false);+ let flow_tp = |rf: &str, fp: &str| fp.rsplit(':').next() == Some(testplan::TP_MPN) || row_of(rf).is_some_and(|p| p["mpn"].as_str() == Some(testplan::TP_MPN));+ let mut project_local: Vec<String> = Vec::new();+ let foreign: Vec<String> = match &lib { Some(l) => on_sheet.iter().filter(|(rf, (sl, fp))| bom_refs.contains(rf) && (sl != l || !fp.starts_with(&format!("{l}:"))) && !bound.contains(rf))+ .filter(|(rf, (sl, fp))| { let local = flow_tp(rf, fp) || (local_libs.contains(sl) && nothing_to_buy(rf)); if local { project_local.push((*rf).clone()); } !local })+ .map(|(rf, (sl, fp))| format!("{rf} ({sl} / {fp})")).collect(), None => Vec::new() };+ if !project_local.is_empty() { eprintln!("schematic check: {} from the project's own library (the flow's test points, or parts with nothing to buy): {}", project_local.len(), project_local.join(", ")); } let extra: Vec<String> = on_sheet.keys().filter(|rf| !bom_refs.contains(rf)).cloned().collect(); // issue #39: symbol polarity drawings, active-device pin types and readability (schematic_symbols.rs) let symbols = schematic_symbols::check(Path::new(sch), &spec_soft(&r)).unwrap_or_else(|e| json!({"ok": false, "errors": [format!("could not read the hierarchy: {e}")], "warnings": []}));@@ -5534,7 +5649,7 @@ fn main() { let pin_hints: Vec<String> = pin_names.iter().map(|(finding, suggestion)| format!("Molecule names: {finding}. {suggestion}")).collect(); let canon = aiflow_sys::canonicalize(sch).map(|p| p.display().to_string()).unwrap_or(sch.clone()); r.outcome("erc", json!({"pass": erc_errors.is_empty(), "errors": erc_errors, "schematic": canon, "sha256": sha256_file(sch), "report": erc.display().to_string(), "source": "schematic check (kicad-cli sch erc)"}));- r.outcome("schematic", json!({"pass": pass, "schematic": canon, "sha256": sha256_file(sch), "ercErrors": erc_errors, "symbols": on_sheet.len(), "missingRefs": missing, "notFromProjectLibrary": foreign, "nativeBound": bound, "notInBom": extra, "library": lib, "moleculeNames": pin_names.iter().map(|(a, b)| json!({"finding": a, "suggestion": b})).collect::<Vec<_>>()}));+ r.outcome("schematic", json!({"pass": pass, "schematic": canon, "sha256": sha256_file(sch), "ercErrors": erc_errors, "symbols": on_sheet.len(), "missingRefs": missing, "notFromProjectLibrary": foreign, "projectLocal": project_local, "nativeBound": bound, "notInBom": extra, "library": lib, "moleculeNames": pin_names.iter().map(|(a, b)| json!({"finding": a, "suggestion": b})).collect::<Vec<_>>()})); if pass { r.data["schematic"] = json!(canon); } r.save().unwrap(); if !pass {@@ -5926,6 +6041,8 @@ fn main() { let pro = std::fs::read_to_string(Path::new(&cb).with_extension("kicad_pro")).ok(); let dru = std::fs::read_to_string(Path::new(&cb).with_extension("kicad_dru")).ok(); let pc = aiflow_router::project_rules::read(&b, pro.as_deref(), dru.as_deref(), rules.clearance);+ // issue #293: the fab's minimum track, so fine-pitch escapes can neck down to their pads+ if rules.min_track.is_none() { rules.min_track = dru.as_deref().map(aiflow_bridge::eda::fab_numbers).and_then(|d| d["trackWidth"]["min"].as_f64()).filter(|v| *v > 0.0); } for (n, v) in &pc.nets { let e = rules.net_clearance.entry(n.clone()).or_insert(*v); if *v > *e { *e = *v; } } rules.clear_regions = pc.regions.clone(); // issue #255: the board-wide hole clearance of the .kicad_dru, when wider than the spec's@@ -6568,7 +6685,7 @@ fn main() { } Cmd::Analyze { what, plan, fields, ack, why } => { let t = thread(&cli);- if !ack.is_empty() && what != "current" { err("--ack acknowledges a current-density peak: `analyze current --ack [email protected] --why ...`", &[]); }+ if !ack.is_empty() && what != "current" { err("--ack acknowledges a current-density peak: `analyze current --ack [email protected]|NET@x,y --why ...`", &[]); } let mut r = load_run(&cli); if what == "balance" || what == "copper-balance" { let live = live_board(&r, &cli, &dir);@@ -6837,9 +6954,12 @@ fn main() { let spec_sha = { use sha2::{Digest, Sha256}; format!("{:x}", Sha256::digest(&spec_bytes)) }; if f["inputIdentity"]["spec"].as_str() != Some(spec_sha.as_str()) || copper_carry::carried_from(&r.data, f["inputIdentity"]["board"].as_str().unwrap_or(""), Path::new(&solved_board)).is_err() { err("--ack: the Fields report is not of this saved board (or its carried-over copper) and spec; solve again, then acknowledge", &[]); } let copper = copper.clone().unwrap_or_else(|e| err(&format!("--ack: this board has no copper fingerprint to bind the acknowledgement to ({e})"), &[]));- let w = why.clone().unwrap_or_else(|| err("--ack needs --why \"<what limits the peak and why the board cannot change it>\"", &[]));+ if why.is_empty() { err("--ack needs --why \"<what limits the peak and why the board cannot change it>\"", &[]); }+ // issue #293 (Mohit Singh): each place keeps its own review: one --why per --ack, in order, or one for all+ if why.len() != 1 && why.len() != ack.len() { err(&format!("{} --ack and {} --why: give one --why for all of them, or one per --ack in the same order", ack.len(), why.len()), &[]); } let limit = spec["maxCurrentDensityAperMm2"].as_f64().unwrap_or(60.0);- for a in ack.iter() {+ for (k, a) in ack.iter().enumerate() {+ let w = if why.len() == 1 { why[0].clone() } else { why[k].clone() }; let rec = aiflow_analyze::current_acks::record(a, &w, &t, &f, &board_now, &copper, limit, &now()).unwrap_or_else(|e| err(&e, &["The place is a pad of the part that limits the peak (REF.PAD on that net) or the Fields peak location x,y within 0.5 mm.".into()])); let mut list: Vec<Value> = r.data["currentAcks"].as_array().cloned().unwrap_or_default(); list.retain(|x| x["target"] != rec["target"]);@@ -6883,7 +7003,7 @@ fn main() { det.extend(fields_suggest::spec_net_lines(fd)); det.extend(fields_suggest::board_line(fd)); det.extend(fields_suggest::module_lines(fd, &fields_mod_plan.modules));- det.extend(fields_suggest::input_lines(&fields_suggest::assumed_inputs(fd, r.data["outcomes"]["parts"]["parts"].as_array().map(|a| a.as_slice()).unwrap_or(&[]))));+ { let (sv, ctl) = fields_input_ctx(&r); det.extend(fields_suggest::input_lines(&fields_suggest::assumed_inputs(fd, r.data["outcomes"]["parts"]["parts"].as_array().map(|a| a.as_slice()).unwrap_or(&[]), Some(&sv), ctl.as_deref()))); } (sug, det) } None => (Vec::new(), Vec::new()),@@ -7958,7 +8078,7 @@ fn main() { let rep = checks::compare_netlists(&sn, &b); let passed = rep["ok"] == true; let mut lines = vec![format!("schematic {} ({} refs) vs board {} ({} refs): {}/{} connected pins on the same net ({via})", sch, rep["schematicRefs"], board_path, rep["boardRefs"], rep["matchedPins"], rep["connectedPins"])];- for (k, label) in [("missingRefs", "missing on the board"), ("extraRefs", "on the board, not in the schematic")] {+ for (k, label) in [("missingRefs", "missing on the board"), ("extraRefs", "on the board, not in the schematic"), ("boardFurniture", "on the board only, on no net (fiducials, logos, unplated holes; not compared)")] { if let Some(a) = rep[k].as_array().filter(|a| !a.is_empty()) { lines.push(format!(" {label}: {}", a.iter().filter_map(|x| x.as_str()).collect::<Vec<_>>().join(", "))); } } for m in rep["mismatches"].as_array().cloned().unwrap_or_default() {@@ -7985,7 +8105,7 @@ fn main() { let report = dir.join("netlist.json"); write_json(&report, &rep); if r.data["schematic"].is_null() { r.data["schematic"] = json!(aiflow_sys::canonicalize(&sch).map(|p| p.display().to_string()).unwrap_or(sch.clone())); }- r.outcome("netlist", json!({"ok": passed, "schematic": sch, "sha256": sha256_file(&sch), "schematicFiles": schematic_files, "netlistSha256": netlist_hash, "netlist": aiflow_sys::canonicalize(&netfile).map(|p| p.display().to_string()).unwrap_or_default(), "board": board_path, "report": report.display().to_string(), "matchedPins": rep["matchedPins"], "connectedPins": rep["connectedPins"], "mismatches": rep["mismatches"].as_array().map(|a| a.len()).unwrap_or(0), "missingRefs": rep["missingRefs"], "extraRefs": rep["extraRefs"]}));+ r.outcome("netlist", json!({"ok": passed, "schematic": sch, "sha256": sha256_file(&sch), "schematicFiles": schematic_files, "netlistSha256": netlist_hash, "netlist": aiflow_sys::canonicalize(&netfile).map(|p| p.display().to_string()).unwrap_or_default(), "board": board_path, "report": report.display().to_string(), "matchedPins": rep["matchedPins"], "connectedPins": rep["connectedPins"], "mismatches": rep["mismatches"].as_array().map(|a| a.len()).unwrap_or(0), "missingRefs": rep["missingRefs"], "extraRefs": rep["extraRefs"], "boardFurniture": rep["boardFurniture"]})); r.save().unwrap_or_else(|e| err(&e, &[])); } let fp_hint = if fpd.is_empty() { String::new() } else { format!("Footprints differ (not blocking, but check they are the parts you meant): {}", fpd.join("; ")) };@@ -8331,6 +8451,23 @@ fn main() { written.push(pro_p.display().to_string()); written.push(dru_p.display().to_string()); }+ // issue #293: the project KiCad has open is the one DRC loads: with no --board, write it too+ let mut live_note: Option<String> = None;+ if board.is_none() {+ if let Some(rr) = run.as_ref() {+ match live_project(rr, &cli) {+ Some(Ok((lp, true))) => {+ let (pro_p, dru_p) = netclasses::sync_kicad(&lp.display().to_string(), &plan).unwrap_or_else(|e| err(&e, &[]));+ written.push(winpath::shown(&pro_p));+ written.push(winpath::shown(&dru_p));+ live_note = Some("KiCad reads the project file when it opens it: close and reopen the project (or the board) in KiCad so its DRC uses these net classes, and save the board afterwards only from that reopened session.".into());+ }+ Some(Ok((_, false))) => live_note = Some(format!("Only the run's snapshot was written: the desktop project of {} is not on a drive this workspace mounts. Copy the written .kicad_pro and .kicad_dru beside that board (or apply the classes in KiCad's Board Setup) so KiCad's own DRC uses them.", rr.data["remoteBoard"].as_str().unwrap_or(""))),+ Some(Err(e)) => live_note = Some(format!("Only the run's snapshot was written ({e}).")),+ None => {}+ }+ }+ } let alt_payload = netclasses::altium_rules_payload(&plan); let alt_req = aiflow_bridge::altium::design_rules_request(&board_path, &alt_payload); let alt_path = altium_out.as_ref().map(PathBuf::from)@@ -8348,6 +8485,7 @@ fn main() { } let summary: Vec<String> = plan.classes.iter().map(|c| format!("{} ({} net(s))", c.name, c.nets.len())).collect(); let mut hints = plan.notes;+ if let Some(n) = live_note { hints.push(n); } hints.push("Run `adom-aiflow rules check` or `adom-aiflow gate` to verify native DRC enforces these net classes.".into()); // honest about the Altium half: the rules are written for it, not yet applied in Altium if let Some(ap) = written.iter().find(|w| w.ends_with("altium-design-rules.json")) { hints.push(format!("Altium: the same rules are written to {ap} for the Altium lane; they are not applied in Altium yet, so set them there (net classes, widths, clearances, differential pairs) before trusting Altium's DRC.")); }@@ -8650,10 +8788,26 @@ fn main() { r.save().unwrap_or_else(|e| err(&e.to_string(), &[])); } }- let nc_findings: Vec<String> = nc_check.as_ref()+ let mut nc_findings: Vec<String> = nc_check.as_ref() .filter(|v| v["pass"] == false) .and_then(|v| v["findings"].as_array()) .into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();+ // issue #293: with no --board, the project the bound desktop board belongs to is checked too, so a+ // snapshot that passes does not hide stale net classes in the project KiCad actually loads+ if board.is_none() {+ if let (Some(rr), Some(sv)) = (Run::open(&dir), spec_nc.as_ref()) {+ match live_project(&rr, &cli) {+ Some(Ok((lp, _))) => {+ let lps = lp.display().to_string();+ let live = netclasses::verify_kicad(&lps, Board::load(&lps).ok().as_ref(), sv);+ for f in live["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) { nc_findings.push(format!("desktop project ({}): {f}", rr.data["remoteBoard"].as_str().unwrap_or(""))); }+ eprintln!("rules check: read the run's snapshot {board_path} and the desktop project of {}", rr.data["remoteBoard"].as_str().unwrap_or(""));+ }+ Some(Err(e)) => eprintln!("NOTE: rules check read the run's snapshot only: the desktop project could not be read ({e})"),+ None => {}+ }+ }+ } match (result, nc_findings.is_empty()) { (Ok(m), true) => ok(&m, &[]), (Ok(m), false) => findings(&format!("{m}; native net classes out of sync:\n {}", nc_findings.join("\n ")), &["Run `adom-aiflow rules sync` to write derived net classes into .kicad_pro and .kicad_dru so native DRC enforces them.".into()]),@@ -9105,7 +9259,8 @@ fn main() { let parts = r.data["outcomes"]["parts"]["parts"].as_array().cloned().unwrap_or_default(); match action.as_str() { "inputs" => {- let items = fields_suggest::assumed_inputs(&fd, &parts);+ let (spec_ctx, ctl) = fields_input_ctx(&r);+ let items = fields_suggest::assumed_inputs(&fd, &parts, Some(&spec_ctx), ctl.as_deref()); // adom-fields 0.10.17 (adom/adom-fields#40): the board's bulk capacitors, typed and with their ESR, in spec `capacitors` let fields_ver = aiflow_sys::process::Command::new("adom-fields").arg("--version").output().ok() .and_then(|o| String::from_utf8_lossy(&o.stdout).split_whitespace().last().and_then(fields_versions::parse));@@ -9127,6 +9282,9 @@ fn main() { lines.push(format!("bulk capacitors to describe from datasheets ({}): Fields reads their technology and ESR from spec `capacitors`", caps.len())); lines.extend(cl); }+ // issue #294: the fragment names each net the way the spec already does, so filling it merges+ let renamed = fields_suggest::rekey_to_spec(&spec_ctx, &mut frag);+ if !renamed.is_empty() { lines.push(format!("keyed as the spec names them: {}", renamed.iter().map(|(a, b)| format!("{a} -> {b}")).collect::<Vec<_>>().join(", "))); } write_json(&out, &frag); r.log("fields-inputs", json!({"items": items.len(), "capacitors": caps.len(), "fragment": out})); r.save().unwrap();@@ -9148,6 +9306,10 @@ fn main() { } let mut spec = read_json(&sp); let mut set = Vec::new();+ // issue #294 (Mohit Singh): `switching./SW` fills the spec's `switching.SW`, never a sibling entry+ let mut pv = pv;+ let renamed = fields_suggest::rekey_to_spec(&spec, &mut pv);+ if !renamed.is_empty() { eprintln!("fields fill: merged into the spec's own net keys: {}", renamed.iter().map(|(a, b)| format!("{a} -> {b}")).collect::<Vec<_>>().join(", ")); } fields_suggest::merge(&mut spec, &pv, "", &mut set); write_json(Path::new(&sp), &spec); r.log("fields-inputs-filled", json!({"keys": set, "why": w, "patch": pp}));
crates/adom-aiflow/src/mechanical.rs+1−14@@ -199,20 +199,7 @@ fn close_loops(mut pieces: Vec<Vec<Pt>>, tol: f64) -> (Vec<Vec<Pt>>, Vec<Pt>) { } /// The convex hull (monotone chain), counter-clockwise.-pub fn hull(pts: &[Pt]) -> Vec<Pt> {- let mut p: Vec<Pt> = pts.to_vec();- p.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));- p.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9);- if p.len() < 3 { return p; }- let cross = |o: Pt, a: Pt, b: Pt| (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0);- let mut lower: Vec<Pt> = Vec::new();- for &q in &p { while lower.len() >= 2 && cross(lower[lower.len() - 2], lower[lower.len() - 1], q) <= 0.0 { lower.pop(); } lower.push(q); }- let mut upper: Vec<Pt> = Vec::new();- for &q in p.iter().rev() { while upper.len() >= 2 && cross(upper[upper.len() - 2], upper[upper.len() - 1], q) <= 0.0 { upper.pop(); } upper.push(q); }- lower.pop(); upper.pop();- lower.extend(upper);- lower-}+pub fn hull(pts: &[Pt]) -> Vec<Pt> { aiflow_board::geom::convex_hull(pts) } /// The body of one footprint layer (F.Fab, a courtyard) in the footprint's frame, one outline per part of it. /// Issue #236: a footprint drawn as separate closed shapes with nothing between them (an edge connector's two
crates/adom-aiflow/src/part_check.rs+40−13@@ -120,9 +120,15 @@ pub fn dims(facts: &Value, what: &str, pads: &[Pad], fab: Option<(f64, f64, f64, /// 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> { // #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;+ step_extents(text).map(|e| e[2])+}++/// The x, y and z spread of a STEP model over its solid's vertices (`VERTEX_POINT`), else over every point (issue #293:+/// compared with the page's GLB, so a STEP and a GLB that disagree are said).+pub fn step_extents(text: &str) -> Option<[f64; 3]> {+ let mut points: std::collections::HashMap<&str, [f64; 3]> = std::collections::HashMap::new();+ let mut all_lo = [f64::MAX; 3];+ let mut all_hi = [f64::MIN; 3]; let mut vertex_refs: Vec<&str> = Vec::new(); for stmt in text.split(';') { let s = stmt.trim();@@ -134,22 +140,26 @@ pub fn step_height(text: &str) -> Option<f64> { 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]);+ points.insert(id, [nums[0], nums[1], nums[2]]);+ for k in 0..3 { all_lo[k] = all_lo[k].min(nums[k]); all_hi[k] = all_hi[k].max(nums[k]); } } } 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);+ let vs: Vec<[f64; 3]> = vertex_refs.iter().filter_map(|r| points.get(r).copied()).collect();+ if !vs.is_empty() {+ let span = |k: usize| vs.iter().map(|v| v[k]).fold(f64::MIN, f64::max) - vs.iter().map(|v| v[k]).fold(f64::MAX, f64::min);+ return Some([span(0), span(1), span(2)]); }- (all_hi >= all_lo).then_some(all_hi - all_lo)+ (all_hi[2] >= all_lo[2]).then_some([all_hi[0] - all_lo[0], all_hi[1] - all_lo[1], all_hi[2] - all_lo[2]])+}++/// Issue #293: where a page's STEP and GLB disagree in size (more than 0.1 mm and 2 %), axis by axis.+pub fn model_mismatch(step: [f64; 3], glb: [f64; 3]) -> Vec<String> {+ ["x", "y", "z"].iter().enumerate().filter(|(k, _)| { let d = (step[*k] - glb[*k]).abs(); d > 0.1 && d > 0.02 * step[*k].max(glb[*k]) })+ .map(|(k, a)| format!("{a} {:.3} (STEP) against {:.3} mm (GLB)", step[k], glb[k])).collect() } fn norm(s: &str) -> String {@@ -216,7 +226,11 @@ pub fn compare(facts: &Value, what: &str, pads: &[Pad], height: Option<f64>, pag 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")),+ (None, Some(_)) => f.push(match facts["_modelNamed"].as_str() {+ // issue #293: a page that names a model the check could not read is not a page with no model+ Some(m) => format!("{mpn}: could not read the 3D model {m} of {what}: the body height was not checked (`adom-wiki page bounds {what}` measures the GLB)"),+ None => format!("{mpn}: no 3D model of {what} to measure against the datasheet's body height"),+ }), _ => {} } if facts["source"].as_str().is_none_or(|s| s.trim().is_empty()) { f.push(format!("{mpn}: say where each fact comes from (\"source\": the datasheet, its revision, page and figure)")); }@@ -322,4 +336,17 @@ mod tests { let (_, f) = compare(&facts, "adom/q", &footprint_pads(fp), None, None, None); assert_eq!(f, vec!["Q: pad 9 of adom/q: centre (0.500, 0.000) against the datasheet's (0.500, 0.100), 0.100 mm off, height 1.800 against 1.600"]); }++ /// Issue #293: the x/y/z spread of a STEP over its vertices, and a STEP/GLB size disagreement said per axis.+ #[test]+ fn step_extents_and_glb_mismatch() {+ let t = "#1=CARTESIAN_POINT('',(0.,0.,0.));#2=CARTESIAN_POINT('',(17.17,6.6,7.0));#3=VERTEX_POINT('',#1);#4=VERTEX_POINT('',#2);";+ let e = step_extents(t).unwrap();+ assert!((e[0] - 17.17).abs() < 1e-9 && (e[2] - 7.0).abs() < 1e-9);+ assert_eq!(step_height(t), Some(7.0));+ let m = model_mismatch(e, [19.059, 6.6, 7.0]);+ assert_eq!(m.len(), 1);+ assert!(m[0].starts_with("x 17.170"), "{m:?}");+ assert!(model_mismatch(e, [17.2, 6.61, 7.01]).is_empty());+ } }
crates/adom-aiflow/src/pourverify.rs+4−19@@ -330,24 +330,8 @@ pub fn check_with(board: &Board, plan: &Value, keepouts_landed: bool) -> Result< let mut cleared = Vec::new(); for (index, z) in resolved.iter().enumerate() { let label = z["name"].as_str().unwrap_or("unnamed zone");- let allowed = [- "name",- "net",- "layers",- "polygon",- "polygons",- "boardZoneUuid",- "priority",- "connection",- "clearance",- "minThickness",- "thermalGap",- "thermalBridge",- "islandRemoval",- "islandAreaMin",- "type",- "keepout",- ];+ // issue #294: the same key list `pour` writes from (so a plan it wrote always reads back)+ let allowed = aiflow_pours::ZONE_KEYS; if let Some(key) = z .as_object() .ok_or("zone must be an object")?@@ -489,7 +473,8 @@ pub fn check_with(board: &Board, plan: &Value, keepouts_landed: bool) -> Result< && p.find("pts") .is_some_and(|pts| pts_points(pts).len() >= 3) });- if !filled {+ // issue #293: a higher-priority zone of the same net that wholly contains this one owns the overlap+ if !filled && board.zone_absorbed(n, layer.as_str().unwrap_or("")).is_none() { failed.push(format!("{label}: no saved filled polygon on {layer}")); } }
crates/adom-aiflow/src/schematic_check.rs+7@@ -160,3 +160,10 @@ mod tests { let _ = std::fs::remove_dir_all(&d); } }++/// Issue #294: the symbol library nicknames the project's own sym-lib-table (beside the schematic) registers.+pub fn project_sym_libs(sch: &std::path::Path) -> Vec<String> {+ let Some(t) = sch.parent().map(|d| d.join("sym-lib-table")).and_then(|p| std::fs::read_to_string(p).ok()) else { return Vec::new() };+ let Ok(root) = aiflow_board::sx::parse(&t) else { return Vec::new() };+ root.find_all("lib").filter_map(|l| l.find("name").and_then(|n| n.value()).map(str::to_string)).collect()+}
crates/adom-aiflow/src/silk_polarity.rs+63−7@@ -25,10 +25,38 @@ fn prefix(r: &str) -> String { r.chars().take_while(|c| c.is_ascii_alphabetic()) /// References that are not parts to label (holes, fiducials, logos, machine pins). fn unlabelled(p: &str) -> bool { matches!(p, "H" | "MH" | "FID" | "MP" | "LOGO" | "G" | "REF") || p.is_empty() } -fn polarized(p: &str, lib: &str) -> bool {- let l = lib.to_ascii_lowercase();- matches!(p, "D" | "LED" | "CR" | "ZD" | "U" | "IC" | "BT")- || ((p == "C" || p == "CP") && (l.contains("cp_") || l.contains("elec") || l.contains("tantal") || l.contains("polar") || l.contains("c_pol") || p == "CP"))+/// Issue #294 (Mohit Singh): polarity is the part's, not its library's name. The footprint name (after the library+/// nickname, which can be anything), its pads (`+`/`-`, `A`/`K`) and its value and description decide; a ceramic+/// capacitor is never polarized, whatever its reference.+fn polarized(p: &str, fp: &Node) -> bool {+ let lib = fp.atom(1).unwrap_or("");+ let name = lib.rsplit(':').next().unwrap_or(lib).to_ascii_lowercase();+ let pads: Vec<&str> = fp.find_all("pad").filter_map(|pd| pd.atom(1)).collect();+ if pads.iter().any(|n| matches!(*n, "+" | "-")) { return true; }+ if matches!(p, "D" | "LED" | "CR" | "ZD" | "U" | "IC" | "BT") { return true; }+ if p != "C" && p != "CP" { return false; }+ let text: String = fp.find_all("property").filter(|q| matches!(q.atom(1), Some("Value" | "Description" | "MPN" | "Manufacturer_Part_Number" | "ki_description"))).filter_map(|q| q.atom(2)).chain(std::iter::once(name.as_str())).collect::<Vec<_>>().join(" ");+ match crate::fields_caps::type_from_text(&text) {+ Some("ceramic" | "C0G") => false,+ Some(_) => true,+ None => p == "CP" || name.starts_with("cp_") || name.contains("_elec") || name.contains("tantal") || name.contains("polar") || name.starts_with("c_pol"),+ }+}++/// A `+` drawn from two short silkscreen strokes crossing at their middles (a footprint's own polarity mark).+fn plus_glyph(fp: &Node) -> bool {+ let lines: Vec<(Pt, Pt)> = fp.nodes().filter(|n| n.tag == "fp_line" && on_silk(n)).filter_map(|g| Some((xy(g.find("start"))?, xy(g.find("end"))?))).collect();+ let short: Vec<(Pt, Pt, f64)> = lines.into_iter().map(|(a, z)| (a, z, ((a.0 - z.0).powi(2) + (a.1 - z.1).powi(2)).sqrt())).filter(|(_, _, l)| *l > 0.2 && *l <= 2.5).collect();+ for (i, a) in short.iter().enumerate() {+ for b in &short[i + 1..] {+ let ma = ((a.0 .0 + a.1 .0) / 2.0, (a.0 .1 + a.1 .1) / 2.0);+ let mb = ((b.0 .0 + b.1 .0) / 2.0, (b.0 .1 + b.1 .1) / 2.0);+ let (da, db) = ((a.1 .0 - a.0 .0, a.1 .1 - a.0 .1), (b.1 .0 - b.0 .0, b.1 .1 - b.0 .1));+ let cos = (da.0 * db.0 + da.1 * db.1).abs() / (a.2 * b.2);+ if cos < 0.1 && ((ma.0 - mb.0).powi(2) + (ma.1 - mb.1).powi(2)).sqrt() < 0.15 && (a.2 - b.2).abs() < 0.3 { return true; }+ }+ }+ false } /// Board-level silkscreen points (texts' anchors, line ends, circle centres, polygon corners) and the@@ -55,6 +83,7 @@ fn ref_on_silk(fp: &Node, reference: &str, words: &[String]) -> (bool, bool) { } fn has_mark(fp: &Node, pad1: Pt, centre: Pt) -> bool {+ if plus_glyph(fp) { return true; } let mut weighted = (0.0, 0.0, 0.0); for g in fp.nodes().filter(|n| on_silk(n)) { match g.tag.as_str() {@@ -93,13 +122,13 @@ pub fn warnings(b: &Board) -> Vec<String> { if pads.is_empty() { continue; } let (silk, fab) = ref_on_silk(fp, &reference, &words); if !silk && fab { fab_only.push(reference.clone()); }- if pads.len() < 2 || !polarized(&p, fp.atom(1).unwrap_or("")) { continue; }- let Some(pad1) = ["1", "K", "A"].iter().find_map(|n| pads.iter().find(|(name, _)| name == n)).map(|x| x.1) else { continue };+ if pads.len() < 2 || !polarized(&p, fp) { continue; }+ let Some(pad1) = ["+", "1", "K", "A"].iter().find_map(|n| pads.iter().find(|(name, _)| name == n)).map(|x| x.1) else { continue }; let n = pads.len() as f64; let centre = (pads.iter().map(|x| x.1 .0).sum::<f64>() / n, pads.iter().map(|x| x.1 .1).sum::<f64>() / n); if has_mark(fp, pad1, centre) { continue; } // a board-level mark beside pad 1 (world coordinates)- let near = b.pads_of(&reference).iter().filter(|q| ["1", "K", "A"].contains(&q.name.as_str())).any(|q| silk_pts.iter().any(|s| ((s.0 - q.x).powi(2) + (s.1 - q.y).powi(2)).sqrt() <= q.half_long + 1.5));+ let near = b.pads_of(&reference).iter().filter(|q| ["+", "1", "K", "A"].contains(&q.name.as_str())).any(|q| silk_pts.iter().any(|s| ((s.0 - q.x).powi(2) + (s.1 - q.y).powi(2)).sqrt() <= q.half_long + 1.5)); if !near { unmarked.push(reference.clone()); } } let list = |v: &[String]| format!("{}{}", v.iter().take(12).cloned().collect::<Vec<_>>().join(", "), if v.len() > 12 { ", ..." } else { "" });@@ -344,6 +373,33 @@ mod tests { assert!(warnings(&b).is_empty(), "{:?}", warnings(&b)); } + /// Issue #294: a ceramic in a library whose nickname reads "polar" is not polarized; a polymer cap whose own+ /// footprint draws a `+` from two crossing strokes is marked.+ #[test]+ fn polarity_comes_from_the_part_and_a_drawn_plus_counts() {+ let t = r#"(kicad_pcb (version 20241229)+ (gr_rect (start 0 0) (end 50 20) (layer "Edge.Cuts") (width 0.1))+ (footprint "PCM_bipolar_elec_board:C_1206" (layer "F.Cu") (at 10 10)+ (property "Reference" "C1" (at 0 -2) (layer "F.SilkS") (effects (font (size 1 1))))+ (property "Value" "10uF 50V X7R" (at 0 2) (layer "F.Fab"))+ (pad "1" smd rect (at -1.5 0) (size 1 1.6) (layers "F.Cu")) (pad "2" smd rect (at 1.5 0) (size 1 1.6) (layers "F.Cu")))+ (footprint "PCM_x:CP_Elec_8x10" (layer "F.Cu") (at 30 10)+ (property "Reference" "C2" (at 0 -6) (layer "F.SilkS") (effects (font (size 1 1))))+ (property "Value" "220uF aluminium polymer" (at 0 6) (layer "F.Fab"))+ (fp_line (start -5.5 -2) (end -4.5 -2) (layer "F.SilkS") (stroke (width 0.12) (type solid)))+ (fp_line (start -5 -2.5) (end -5 -1.5) (layer "F.SilkS") (stroke (width 0.12) (type solid)))+ (fp_line (start -4 -4) (end 4 -4) (layer "F.SilkS") (stroke (width 0.12) (type solid)))+ (fp_line (start -4 4) (end 4 4) (layer "F.SilkS") (stroke (width 0.12) (type solid)))+ (pad "1" smd rect (at -3 0) (size 3 2) (layers "F.Cu")) (pad "2" smd rect (at 3 0) (size 3 2) (layers "F.Cu")))+)"#;+ let b = Board::from_text("t.kicad_pcb", t.to_string()).unwrap();+ let w = warnings(&b);+ assert!(!w.iter().any(|x| x.contains("polarized")), "{w:?}");+ let unmarked = t.replace("(fp_line (start -5.5 -2) (end -4.5 -2) (layer \"F.SilkS\") (stroke (width 0.12) (type solid)))", "");+ let w = warnings(&Board::from_text("t.kicad_pcb", unmarked).unwrap());+ assert!(w.iter().any(|x| x.contains("1 polarized part(s)") && x.contains("C2") && !x.contains("C1")), "{w:?}");+ }+ const TP_BOARD: &str = r#"(kicad_pcb (version 20241229) (net 0 "") (net 1 "+3V3") (net 2 "/PH1") (net 3 "/USB_D+") (net 4 "Net-(TP4-Pad1)") (gr_rect (start 0 0) (end 50 20) (layer "Edge.Cuts") (width 0.1))
crates/adom-aiflow/src/verified.rs+3@@ -132,6 +132,9 @@ pub fn from_run(outcomes: &Map<String, Value>, data: &Value, mech: Option<(bool, Item { name: "ERC", state: erc }, Item { name: "DRC", state: drc }, Item { name: "schematic symbols and pin types", state: match (outcomes.get(crate::schematic_symbols::OUTCOME), data["schematic"].as_str()) {+ // issue #294: finish and `schematic check` agree: symbols the check found outside the project library fail here too+ (Some(_), _) if outcomes.get("schematic").and_then(|s| s["notFromProjectLibrary"].as_array()).is_some_and(|a| !a.is_empty()) =>+ State::No(format!("not from the project library: {} (schematic check)", outcomes["schematic"]["notFromProjectLibrary"].as_array().unwrap().iter().filter_map(|v| v.as_str()).collect::<Vec<_>>().join(", "))), (Some(c), _) => yes_no(c["ok"].as_bool(), "symbol polarity or pin-type errors (schematic-check.json)", "not recorded"), (None, Some(_)) => State::Unknown("schematic check not run".into()), (None, None) if no_sch => State::NotApplicable("pattern board, no schematic".into()),
crates/adom-aiflow/src/zone_ownership.rs+12@@ -65,6 +65,18 @@ pub fn still_exists<'a>(live: &'a BTreeSet<String>, saved: &'a [(String, BTreeSe } } +/// The saved desktop board `rb`, pulled fresh into `dir/<tag>-<nanos>/` (issue #293: checks that should judge the board+/// the human has, not the run's last adopted snapshot).+pub fn pull_saved(br: &aiflow_bridge::Bridge, rb: &str, dir: &std::path::Path, tag: &str) -> Result<std::path::PathBuf, String> {+ let pull = dir.join(format!("{tag}-{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)));+ std::fs::create_dir_all(&pull).map_err(|e| e.to_string())?;+ let save_to = aiflow_sys::canonicalize(&pull).map_err(|e| e.to_string())?;+ let reply = br.call("pull_file", &json!({"filePaths": [rb], "saveTo": save_to}));+ let local = save_to.join(rb.rsplit(['/', '\\']).next().unwrap_or("board.kicad_pcb"));+ if !aiflow_bridge::Bridge::ok(&reply) || !local.is_file() { return Err(format!("the saved desktop board {rb} could not be read: {}", reply["error"].as_str().or(reply["message"].as_str()).unwrap_or("pull_file failed"))); }+ Ok(local)+}+ /// The saved boards to read: the run's current snapshot and the desktop file `rb` pulled fresh. /// Err when the desktop file could not be read (then nothing may be dropped). pub fn saved_boards(run_board: &str, br: &aiflow_bridge::Bridge, rb: &str, dir: &std::path::Path) -> Result<Vec<(String, BTreeSet<String>)>, String> {
crates/aiflow-analyze/src/current_acks.rs+1−1@@ -112,7 +112,7 @@ pub fn record(target: &str, why: &str, ai_thread: &str, fields: &Value, board: & let hit = pts.iter().find(|p| p.net == net && near(&a, p.at)); let Some(p) = hit else { let on_net: Vec<String> = pts.iter().filter(|p| p.net == net).map(|p| format!("{:.1} A/mm2 at ({:.2}, {:.2}) on {}", p.peak, p.at.0, p.at.1, p.layer)).collect();- return Err(if on_net.is_empty() { format!("--ack {target}: {net} has no point over the {limit} A/mm2 screen in this Fields report; nothing to acknowledge") } else { format!("--ack {target}: the over-screen point of {net} is not within {TOLERANCE_MM} mm of that place ({})", on_net.join("; ")) });+ return Err(if on_net.is_empty() { format!("--ack {target}: {net} has no point over the {limit} A/mm2 screen in this Fields report; nothing to acknowledge") } else { { let first = pts.iter().find(|p| p.net == net).unwrap(); format!("--ack {target}: the over-screen point of {net} is not within {TOLERANCE_MM} mm of that place ({}); a peak in open copper takes `--ack {net}@{:.2},{:.2}`", on_net.join("; "), first.at.0, first.at.1) } }); }; a["peakJ"] = json!(p.peak); a["peakAt"] = json!([p.at.0, p.at.1]);
crates/aiflow-analyze/src/lib.rs+12−1@@ -460,7 +460,18 @@ pub fn field_screen_with_acks(fields: &Value, spec: &Value, board_bytes: &[u8], let point = current_acks::Point { net: name.clone(), at: (row["peakAt"][0].as_f64().unwrap_or(f64::NAN), row["peakAt"][1].as_f64().unwrap_or(f64::NAN)), layer: row["peakLayer"].as_str().unwrap_or("").to_string(), peak: peak.unwrap() }; match acks.iter().find(|a| current_acks::covers(a, &point)) { Some(a) => covered.push(json!({"net": name, "peakJ": point.peak, "at": [point.at.0, point.at.1], "layer": point.layer, "ack": a["target"], "why": a["why"], "aiThread": a["aiThread"]})),- None => return Err(format!("Fields {name} peak current density exceeds the {density_limit} A/mm2 screen ({:.1} A/mm2 at ({:.2}, {:.2}) on {}; a reviewed part-limited peak takes `analyze current --ack {name}@REF.PAD --why ...`)", point.peak, point.at.0, point.at.1, point.layer)),+ None => {+ // issue #293 (Mohit Singh): name the form that can cover this peak: the pad whose copper it is on, or+ // its own coordinates when it sits in open pour copper (no pad of the net within the tolerance)+ let pad = aiflow_board::Board::from_text("screen.kicad_pcb", String::from_utf8_lossy(board_bytes).to_string()).ok().and_then(|b| b.pads.iter().filter(|q| q.net == *name)+ .map(|q| (q.polys.iter().map(|p| aiflow_board::geom::point_poly_distance(point.at.0, point.at.1, p)).fold(f64::INFINITY, f64::min), format!("{}.{}", q.reference, q.name)))+ .filter(|(d, _)| *d <= current_acks::TOLERANCE_MM).min_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, k)| k));+ let form = match pad {+ Some(k) => format!("`analyze current --ack {name}@{k} --why ...` (the peak is on {k}'s copper)"),+ None => format!("`analyze current --ack {name}@{:.2},{:.2} --why ...` (no {name} pad within {} mm: the peak is in open copper, so the ack names its coordinates)", point.at.0, point.at.1, current_acks::TOLERANCE_MM),+ };+ return Err(format!("Fields {name} peak current density exceeds the {density_limit} A/mm2 screen ({:.1} A/mm2 at ({:.2}, {:.2}) on {}; a reviewed part-limited peak takes {form})", point.peak, point.at.0, point.at.1, point.layer));+ } } } let coupling=&fields["barrelCoupling"];
crates/aiflow-analyze/src/pour_cover.rs+36−5@@ -122,6 +122,9 @@ pub fn ground_like(net: &str) -> bool { n.contains("GND") || n.starts_with("VSS") || n.starts_with("VEE") || n == "0" || n.contains("EARTH") || n.contains("CHASSIS") || n.contains("RTN") || n.contains("RETURN") } +/// Distance from point p to the segment a-b (a point when a == b).+fn seg_gap(a: Pt, b: Pt, p: Pt) -> f64 { geom::seg_distance(p.0, p.1, a.0, a.1, b.0, b.1) }+ /// Issue #176: the indices (into `all`) of the narrow pieces on dead-end stubs. The narrow pieces not /// wholly inside a pour (`open[i]`) join where their ends meet on one layer, or at one via or through /// pad. A connected run of them is a stub when it meets the load path at one place only (within@@ -146,7 +149,9 @@ fn dead_end_stubs(all: &[Piece], open: &[bool], wide_enough: &[bool], in_fill: i if meet { let (a, b) = (find(&mut comp, i), find(&mut comp, j)); comp[a.max(b)] = a.min(b); } } }- let mut places: std::collections::BTreeMap<usize, Vec<Pt>> = std::collections::BTreeMap::new();+ // issue #293 (Mohit Singh): contact is a run, not a point: a branch whose root runs inside the pour for a length+ // (with breaks where the fill is cut back along it) meets the load path at one place, the runs linked within PLACE_MM+ let mut places: std::collections::BTreeMap<usize, Vec<(Pt, Pt)>> = std::collections::BTreeMap::new(); let mut draws_nothing: std::collections::BTreeSet<usize> = std::collections::BTreeSet::new(); for i in (0..n).filter(|&i| open[i]) { let c = find(&mut comp, i);@@ -154,24 +159,37 @@ fn dead_end_stubs(all: &[Piece], open: &[bool], wide_enough: &[bool], in_fill: i let len = (piece.b.0 - piece.a.0).hypot(piece.b.1 - piece.a.1); let steps = (len / STEP_MM).ceil().max(1.0) as usize; let at = places.entry(c).or_default();- let mut inside = false;+ let (mut inside, mut start, mut prev) = (false, piece.a, piece.a); for s in 0..=steps { let t = s as f64 / steps as f64; let p = (piece.a.0 + t * (piece.b.0 - piece.a.0), piece.a.1 + t * (piece.b.1 - piece.a.1)); let now = in_fill(p, &piece.layer);- if now && !inside { at.push(p); }+ if now && !inside { start = p; }+ if !now && inside { at.push((start, prev)); } inside = now;+ prev = p; }+ if inside { at.push((start, piece.b)); } for p in [piece.a, piece.b] { let on_load = terminals.iter().any(|q| pad_on(q, &piece.layer) && in_pad(p, q)) || all.iter().enumerate().any(|(w, o)| wide_enough[w] && o.layer == piece.layer && geom::seg_distance(p.0, p.1, o.a.0, o.a.1, o.b.0, o.b.1) <= o.width / 2. + TOUCH_MM) || vias.iter().any(|v| (p.0 - v.x).hypot(p.1 - v.y) <= v.size / 2.);- if on_load { at.push(p); }+ if on_load { at.push((p, p)); } let idle = |q: &&aiflow_board::Pad| pad_on(q, &piece.layer) && in_pad(p, q) && (sense(q) || !terminals.iter().any(|t| std::ptr::eq(**t, *q))); if pads.iter().any(idle) { draws_nothing.insert(c); } } }- let one_place = |pts: &Vec<Pt>| pts.iter().all(|p| (p.0 - pts[0].0).hypot(p.1 - pts[0].1) <= PLACE_MM);+ let gap = |a: &(Pt, Pt), b: &(Pt, Pt)| [seg_gap(a.0, a.1, b.0), seg_gap(a.0, a.1, b.1), seg_gap(b.0, b.1, a.0), seg_gap(b.0, b.1, a.1)].into_iter().fold(f64::INFINITY, f64::min);+ let one_place = |runs: &Vec<(Pt, Pt)>| {+ if runs.is_empty() { return false; }+ let mut reached = vec![false; runs.len()];+ reached[0] = true;+ let mut stack = vec![0usize];+ while let Some(i) = stack.pop() {+ for j in 0..runs.len() { if !reached[j] && gap(&runs[i], &runs[j]) <= PLACE_MM { reached[j] = true; stack.push(j); } }+ }+ reached.iter().all(|r| *r)+ }; (0..n).filter(|&i| open[i] && { let c = find(&mut comp, i); places.get(&c).is_some_and(one_place) && draws_nothing.contains(&c) }).collect() } @@ -394,6 +412,19 @@ mod tests { let e = check(&Board::from_text("t.kicad_pcb", t).unwrap(), "V", &spec, 1.5, 10.0, 35.0).unwrap_err(); assert!(e.contains("does not carry the load"), "{e}"); }+ /// Issue #293: a stub whose root runs inside the pour for 4.5 mm, the fill cut back once along it, meets the load+ /// path at one place: still a dead-end stub to a pad that draws nothing.+ #[test]+ fn a_stub_overlapping_the_pour_along_a_length_is_one_place() {+ let mut t = sense_board().text;+ t.pop();+ t.push_str(r#"(zone (net 1) (net_name "V") (layer "F.Cu") (polygon (pts (xy 24 9) (xy 26 9) (xy 26 14.5) (xy 24 14.5)))+ (filled_polygon (layer "F.Cu") (pts (xy 24 9) (xy 26 9) (xy 26 12) (xy 24 12)))+ (filled_polygon (layer "F.Cu") (pts (xy 24 12.3) (xy 26 12.3) (xy 26 14.5) (xy 24 14.5)))))"#);+ let spec = serde_json::json!({"loads": {"V": {"amps": 1.5, "terminals": [{"reference": "J1", "pad": "1", "amps": 1.5}, {"reference": "U1", "pad": "1", "amps": -1.5}, {"reference": "S1", "pad": "1", "amps": 0}]}}});+ let how = check(&Board::from_text("t.kicad_pcb", t).unwrap(), "V", &spec, 1.5, 10.0, 35.0).unwrap();+ assert!(how.contains("dead-end stubs"), "{how}");+ } #[test] fn explicit_terminals_name_the_load_and_too_few_are_said_plainly() { let one = serde_json::json!({"loads": {"V": {"amps": 1.5, "terminals": [{"reference": "J1", "pad": "1", "amps": 1.5}]}}});
crates/aiflow-board/src/geom.rs+39@@ -245,6 +245,31 @@ pub fn thick_line_poly(a: Pt, b: Pt, hw: f64) -> Vec<Pt> { vec![(a.0 + nx, a.1 + ny), (b.0 + nx, b.1 + ny), (b.0 - nx, b.1 - ny), (a.0 - nx, a.1 - ny)] } +/// The convex hull of the points, counter-clockwise (Andrew's monotone chain); fewer than three distinct+/// points come back as they are.+pub fn convex_hull(pts: &[Pt]) -> Vec<Pt> {+ let mut p: Vec<Pt> = pts.to_vec();+ p.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));+ p.dedup_by(|a, b| (a.0 - b.0).abs() < 1e-9 && (a.1 - b.1).abs() < 1e-9);+ if p.len() < 3 { return p; }+ let cross = |o: Pt, a: Pt, b: Pt| (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0);+ let mut lower: Vec<Pt> = Vec::new();+ for &q in &p { while lower.len() >= 2 && cross(lower[lower.len() - 2], lower[lower.len() - 1], q) <= 0.0 { lower.pop(); } lower.push(q); }+ let mut upper: Vec<Pt> = Vec::new();+ for &q in p.iter().rev() { while upper.len() >= 2 && cross(upper[upper.len() - 2], upper[upper.len() - 1], q) <= 0.0 { upper.pop(); } upper.push(q); }+ lower.pop(); upper.pop();+ lower.extend(upper);+ lower+}++/// Issue #293: the convex hull of the points grown by `margin` (each point becomes an octagon that holds a circle of+/// that radius), the tight outline `"shape": "hull"` asks for instead of the bounding box, rounded to 0.01 mm.+pub fn hull_around(pts: &[Pt], margin: f64) -> Vec<Pt> {+ let r = margin.max(0.0) / (std::f64::consts::PI / 8.0).cos();+ let grown: Vec<Pt> = pts.iter().flat_map(|&(x, y)| (0..8).map(move |k| { let a = std::f64::consts::PI / 8.0 + k as f64 * std::f64::consts::PI / 4.0; (x + r * a.cos(), y + r * a.sin()) })).collect();+ convex_hull(&grown).into_iter().map(|(x, y)| ((x * 100.0).round() / 100.0, (y * 100.0).round() / 100.0)).collect()+}+ pub fn bbox(pts: &[Pt]) -> (f64, f64, f64, f64) { let mut b = (f64::INFINITY, f64::INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY); for &(x, y) in pts {@@ -277,3 +302,17 @@ mod chain_loop_tests { assert!(chain_loops(vec![seg((0.0, 0.0), (1.0, 0.0)), seg((1.0, 0.0), (1.0, 1.0))], 0.01).is_err(), "an open outline is refused"); } }++#[cfg(test)]+mod hull_tests {+ use super::*;+ #[test]+ fn hull_around_hugs_an_l_shape_where_the_box_does_not() {+ let pts = [(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)];+ let h = hull_around(&pts, 1.0);+ assert!(!point_in_poly(8.0, 8.0, &h), "the far corner of the box is not in the hull");+ let edge = |x: f64, y: f64| (0..h.len()).map(|k| { let (a, b) = (h[k], h[(k + 1) % h.len()]); seg_distance(x, y, a.0, a.1, b.0, b.1) }).fold(f64::INFINITY, f64::min);+ for &(x, y) in &pts { assert!(point_in_poly(x, y, &h) && edge(x, y) >= 0.99, "{x},{y}: {}", edge(x, y)); }+ assert!(polygon_area(&h).abs() < 0.7 * 144.0);+ }+}
crates/aiflow-board/src/lib.rs+22−1@@ -133,6 +133,9 @@ pub struct Zone { pub inner_layers: Vec<String>, pub outline: Vec<Pt>, pub fills: Vec<(usize, Vec<Pt>)>,+ /// Copper layers (by name) where the zone has no fill because a higher-priority zone of the same net,+ /// filled there, wholly contains it: KiCad gave that zone the overlap (issue #293), so nothing is missing.+ pub absorbed: Vec<String>, } impl Zone {@@ -625,11 +628,29 @@ impl Board { if poly.len() >= 3 { fills.push((layer, poly)); } } let inner_layers: Vec<String> = names.iter().filter(|n| n.starts_with("In") && n.ends_with(".Cu")).cloned().collect();- out.push(Zone { net: self.item_net(z), layers, inner_layers, outline, fills });+ let absorbed: Vec<String> = names.iter().flat_map(|n| if n == "*.Cu" || n == "F&B.Cu" { LAYER_NAMES.iter().map(|s| s.to_string()).filter(|l| l.ends_with(".Cu")).collect::<Vec<_>>() } else { vec![n.clone()] })+ .filter(|l| self.zone_absorbed(z, l).is_some()).collect();+ out.push(Zone { net: self.item_net(z), layers, inner_layers, outline, fills, absorbed }); } out } + /// Issue #293 (Mohit Singh): the name of the zone that absorbs `z` on `layer`, when `z` has no fill there+ /// because a higher-priority zone of the same net, filled on that layer, wholly contains its outline. KiCad+ /// gives the higher zone the overlap, so the empty one is covered copper, not a zone nobody refilled.+ pub fn zone_absorbed(&self, z: &Node, layer: &str) -> Option<String> {+ let net_of = |n: &Node| n.find("net_name").and_then(|x| x.value()).map(str::to_string).filter(|s| !s.is_empty()).unwrap_or_else(|| self.item_net(n));+ let prio = |n: &Node| n.find("priority").and_then(|p| p.number(1)).unwrap_or(0.0);+ let outline = |n: &Node| -> Vec<Pt> { n.find("polygon").and_then(|p| p.find("pts")).map(|p| p.find_all("xy").filter_map(|q| Some((q.number(1)?, q.number(2)?))).collect()).unwrap_or_default() };+ let filled_on = |n: &Node| n.find_all("filled_polygon").any(|f| f.find("layer").and_then(|l| l.value()) == Some(layer));+ if z.find("keepout").is_some() || filled_on(z) { return None; }+ let (net, p, pts) = (net_of(z), prio(z), outline(z));+ if net.is_empty() || pts.len() < 3 { return None; }+ self.root.find_all("zone").filter(|o| !std::ptr::eq(*o, z) && o.find("keepout").is_none() && prio(o) > p && filled_on(o) && net_of(o) == net)+ .find(|o| { let poly = outline(o); poly.len() >= 3 && pts.iter().all(|&(x, y)| geom::point_in_poly(x, y, &poly) || geom::point_poly_distance(x, y, &poly) < 0.01) })+ .map(|o| o.find("name").and_then(|n| n.value()).filter(|s| !s.is_empty()).map(str::to_string).unwrap_or_else(|| format!("a {net} zone")))+ }+ /// Pad-box (copper extent) of every pad of a footprint: (x0, y0, x1, y1). pub fn pad_box(&self, reference: &str) -> Option<(f64, f64, f64, f64)> { let pts: Vec<Pt> = self.pads.iter().filter(|p| p.reference == reference).flat_map(|p| p.polys.iter().flatten().copied()).collect();
crates/aiflow-copper/src/lib.rs+3−1@@ -609,7 +609,9 @@ pub fn copy_project_rules(source: &str, destination: &str) -> Result<(), String> for ext in ["kicad_pro", "kicad_dru"] { let src=std::path::Path::new(source).with_extension(ext); let dst=std::path::Path::new(destination).with_extension(ext);- if src.is_file() && src != dst {+ // issue #292: the same file under two spellings (relative and absolute) is never copied onto itself+ let same = src == dst || matches!((std::fs::canonicalize(&src), std::fs::canonicalize(&dst)), (Ok(a), Ok(b)) if a == b);+ if src.is_file() && !same { std::fs::copy(&src,&dst).map_err(|e| format!("copy project rules {}: {e}",src.display()))?; } }
crates/aiflow-pours/src/lib.rs+127−29@@ -8,7 +8,13 @@ pub mod stitch_grid; pub type Box4 = (f64, f64, f64, f64); -fn pad_box(board: &Board, keys: &[String]) -> Option<Box4> {++/// The keys a zone in a pour plan holds: what `pour` writes and `verify-pours` reads back (issue #294). `why` is the+/// reasoning the spec gives for the pour, carried as a note and never compared.+pub const ZONE_KEYS: &[&str] = &["name", "net", "layers", "polygon", "polygons", "boardZoneUuid", "priority", "connection", "clearance", "minThickness",+ "thermalGap", "thermalBridge", "islandRemoval", "islandAreaMin", "type", "keepout", "why"];++fn pad_points(board: &Board, keys: &[String]) -> Vec<Pt> { let mut pts = Vec::new(); for k in keys { if let Some((r, n)) = k.split_once('.') {@@ -21,9 +27,22 @@ fn pad_box(board: &Board, keys: &[String]) -> Option<Box4> { } } }+ pts+}++fn pad_box(board: &Board, keys: &[String]) -> Option<Box4> {+ let pts = pad_points(board, keys); if pts.is_empty() { None } else { Some(geom::bbox(&pts)) } } +/// Issue #293: the pads of other nets a region encloses (their centre inside it), as `REF.PAD (NET)`, at most six.+pub fn foreign_pads_inside(board: &Board, poly: &[Pt], net: &str) -> Vec<String> {+ let mut v: Vec<String> = board.pads.iter().filter(|p| p.net != net && !p.net.is_empty() && geom::point_in_poly(p.x, p.y, poly)).map(|p| format!("{}.{} ({})", p.reference, p.name, p.net)).collect();+ v.dedup();+ if v.len() > 6 { let more = v.len() - 6; v.truncate(6); v.push(format!("and {more} more")); }+ v+}+ fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Value { let r = |v: f64| (v * 100.0).round() / 100.0; json!([[r(x0), r(y0)], [r(x1), r(y0)], [r(x1), r(y1)], [r(x0), r(y1)]])@@ -295,11 +314,14 @@ pub fn build_with(board: &Board, spec: &Value, plan: Option<&Value>, planned: &[ }; pour_layers(board, &net, &e)?; let mut z = serde_json::Map::new();+ // issue #294 (Mohit Singh): only the keys a zone plan holds go into it, so `verify-pours` reads back every plan+ // `pour` writes; the spec's other keys (how the outline is made, notes) stay in the spec+ let mut left_out = Vec::new(); for (k, v) in e.as_object().unwrap() {- if !matches!(k.as_str(), "around" | "margin" | "exclude" | "polygon" | "outline" | "inset") {- z.insert(k.clone(), v.clone());- }+ if ZONE_KEYS.contains(&k.as_str()) { z.insert(k.clone(), v.clone()); }+ else if !matches!(k.as_str(), "around" | "margin" | "exclude" | "polygon" | "outline" | "inset" | "shape") { left_out.push(k.clone()); } }+ if !left_out.is_empty() { eprintln!("NOTE: pour {named}: {} not a zone property, kept in the spec only", left_out.join(", ")); } z.insert("net".into(), json!(net)); z.entry("clearance").or_insert(json!(clearance)); z.entry("minThickness").or_insert(json!(0.25));@@ -323,7 +345,18 @@ pub fn build_with(board: &Board, spec: &Value, plan: Option<&Value>, planned: &[ } } }- z.insert("polygon".into(), rect(b.0, b.1, b.2, b.3));+ // issue #293 (Mohit Singh): `"shape": "hull"` hugs the listed pads instead of their bounding box; either+ // way the outline is printed, and pads of other nets inside it are named before they cost a re-route+ let hull = e.get("shape").and_then(|v| v.as_str()) == Some("hull");+ let poly: Vec<Pt> = if hull {+ if !strs(e.get("exclude")).is_empty() { eprintln!("NOTE: pour {net}: `exclude` clips the box shape only; a hull already follows the listed pads"); }+ geom::hull_around(&pad_points(board, &keys), m).into_iter().map(|(x, y)| (x.clamp(x0 + edge, x1 - edge), y.clamp(y0 + edge, y1 - edge))).collect()+ } else { vec![(b.0, b.1), (b.2, b.1), (b.2, b.3), (b.0, b.3)] };+ let (bx0, by0, bx1, by1) = geom::bbox(&poly);+ eprintln!("pours: {net} pour around {} (margin {m} mm, {}): x {:.2}..{:.2}, y {:.2}..{:.2}, {:.1} mm2", keys.join(","), if hull { "hull" } else { "box; \"shape\": \"hull\" hugs the pads" }, bx0, bx1, by0, by1, geom::polygon_area(&poly).abs());+ let foreign = foreign_pads_inside(board, &poly, &net);+ if !foreign.is_empty() { eprintln!("NOTE: pour {net}: the outline encloses pads of other nets: {} (each keeps only a clearance moat inside the pour; check that is meant)", foreign.join(", ")); }+ z.insert("polygon".into(), if hull { json!(poly) } else { rect(b.0, b.1, b.2, b.3) }); } else { return Err(format!("pour {net} needs outline, polygon or around")); }@@ -333,37 +366,72 @@ pub fn build_with(board: &Board, spec: &Value, plan: Option<&Value>, planned: &[ } // issue #220 (Sven Claar): a key a footprint repeats (a USB-C receptacle's four `SH` shield tabs) means every // pad with that key; patches of one net that overlap become one zone (two same-net zones at one priority- // that overlap are a zones_intersect in KiCad's DRC)+ // that overlap are a zones_intersect in KiCad's DRC). Issue #293 (Mohit Singh): patches merge across keys too,+ // a joint outranks the pour it sits in (one priority above it, or KiCad gives the parent the whole overlap and+ // the joint fills nothing), and a layer whose parent pour already connects solidly gets no joint (it adds nothing)+ let mut patches: Vec<(String, Vec<&'static str>, [f64; 4], Vec<String>, Vec<(f64, f64)>)> = Vec::new(); for key in strs(spec.get("solidAt")) {- let mut patches: Vec<(String, Vec<&'static str>, [f64; 4])> = Vec::new(); for p in board.pads_with_key(&key) { let layers: Vec<&'static str> = if p.thru { vec!["F.Cu", "B.Cu"] } else if p.on_f { vec!["F.Cu"] } else { vec!["B.Cu"] }; let r = if p.thru { p.half_long.max(p.half_short) + 0.6 } else { 0.9 };- patches.push((p.net.clone(), layers, [p.x - r, p.y - r, p.x + r, p.y + r]));+ patches.push((p.net.clone(), layers, [p.x - r, p.y - r, p.x + r, p.y + r], vec![key.clone()], vec![(p.x, p.y)])); }- // merge overlapping patches of the same net until none overlap- loop {- let mut merged = false;- 'outer: for i in 0..patches.len() {- for j in i + 1..patches.len() {- let (a, b) = (&patches[i], &patches[j]);- if a.0 == b.0 && a.2[0] <= b.2[2] && b.2[0] <= a.2[2] && a.2[1] <= b.2[3] && b.2[1] <= a.2[3] {- let bb = patches.remove(j);- let a = &mut patches[i];- a.2 = [a.2[0].min(bb.2[0]), a.2[1].min(bb.2[1]), a.2[2].max(bb.2[2]), a.2[3].max(bb.2[3])];- for l in bb.1 { if !a.1.contains(&l) { a.1.push(l); } }- merged = true;- break 'outer;- }+ }+ // merge overlapping patches of the same net until none overlap+ loop {+ let mut merged = false;+ 'outer: for i in 0..patches.len() {+ for j in i + 1..patches.len() {+ let (a, b) = (&patches[i], &patches[j]);+ if a.0 == b.0 && a.2[0] <= b.2[2] && b.2[0] <= a.2[2] && a.2[1] <= b.2[3] && b.2[1] <= a.2[3] {+ let bb = patches.remove(j);+ let a = &mut patches[i];+ a.2 = [a.2[0].min(bb.2[0]), a.2[1].min(bb.2[1]), a.2[2].max(bb.2[2]), a.2[3].max(bb.2[3])];+ for l in bb.1 { if !a.1.contains(&l) { a.1.push(l); } }+ for k in bb.3 { if !a.3.contains(&k) { a.3.push(k); } }+ a.4.extend(bb.4);+ merged = true;+ break 'outer; } }- if !merged { break; } }- let n = patches.len();- for (k, (net, layers, b)) in patches.into_iter().enumerate() {- let name = if n > 1 { format!("{net} solid joint at {key} ({})", k + 1) } else { format!("{net} solid joint at {key}") };- zones.push(json!({"net": net, "layers": layers, "polygon": rect(b[0], b[1], b[2], b[3]), "priority": 1, "connection": "solid", "clearance": clearance, "minThickness": 0.25, "name": name}));+ if !merged { break; }+ }+ // the spec pours of a net on a layer that cover any of the patch's pads: (highest priority, any solid)+ let parent = |net: &str, layer: &str, pads: &[(f64, f64)]| -> Option<(i64, bool)> {+ let mut best: Option<(i64, bool)> = None;+ for z in zones.iter().filter(|z| z["net"] == net && strs(z.get("layers")).iter().any(|l| l == layer)) {+ let covers = z.get("outline").and_then(|v| v.as_bool()).unwrap_or(false) || { let poly = poly_of(z); poly.len() >= 3 && pads.iter().any(|&(x, y)| geom::point_in_poly(x, y, &poly)) };+ if !covers { continue; }+ let pr = z.get("priority").and_then(|v| v.as_i64()).unwrap_or(0);+ let solid = matches!(z.get("connection").and_then(|v| v.as_str()), Some("solid") | Some("full"));+ best = Some(match best { Some((bp, bs)) => (bp.max(pr), bs || solid), None => (pr, solid) });+ }+ best+ };+ let mut per_name: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();+ let mut planned_joints: Vec<(String, Vec<&'static str>, [f64; 4], i64)> = Vec::new();+ for (net, layers, b, keys, pads) in patches {+ let label = keys.join("+");+ let mut keep: Vec<&'static str> = Vec::new();+ let mut prio = 0i64;+ for l in layers {+ match parent(&net, l, &pads) {+ Some((_, true)) => eprintln!("NOTE: pours: no solid joint for {net} at {label} on {l}: the {net} pour there already connects its pads solidly"),+ Some((pr, false)) => { keep.push(l); prio = prio.max(pr); }+ None => keep.push(l),+ } }+ if keep.is_empty() { continue; }+ *per_name.entry(format!("{net}|{label}")).or_default() += 1;+ planned_joints.push((format!("{net}|{label}"), keep, b, prio + 1));+ }+ let mut seen: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();+ for (id, layers, b, prio) in planned_joints {+ let (net, label) = id.split_once('|').unwrap();+ let k = { let c = seen.entry(id.clone()).or_default(); *c += 1; *c };+ let name = if per_name[&id] > 1 { format!("{net} solid joint at {label} ({k})") } else { format!("{net} solid joint at {label}") };+ zones.push(json!({"net": net, "layers": layers, "polygon": rect(b[0], b[1], b[2], b[3]), "priority": prio, "connection": "solid", "clearance": clearance, "minThickness": 0.25, "name": name})); } let blockers = plan.map(plan_blockers).unwrap_or_default(); let h2h = hole_to_hole(spec);@@ -476,17 +544,25 @@ 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)+ // issue #293: every stitch spot asked for is planned or counted under the reason it was left out+ let (mut st_planned, mut st_holes, mut st_route) = (0usize, 0usize, 0usize); 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 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 !via_clear(x, y, size, drill, net, &holes, h2h, vclr) { st_holes += 1; 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()));- }+ st_planned += 1;+ } else { st_route += 1; }+ }+ if !stitch.is_empty() && !no_vias {+ eprintln!("pours: stitch vias: {st_planned} of {} spot(s) planned{}{}", stitch.len(),+ if st_holes > 0 { format!("; {st_holes} within the hole-to-hole minimum ({h2h} mm) or the {vclr} mm via clearance of a hole or via") } else { String::new() },+ if st_route > 0 { format!("; {st_route} on a path the route plan keeps") } else { String::new() }); } let mut keepouts = spec_keepouts.len(); zones.extend(spec_keepouts);@@ -965,6 +1041,28 @@ mod solid_at_tests { assert_eq!(solid.len(), 1); assert_eq!(solid[0]["name"], "GND solid joint at J1.SH", "a single pad keeps its name"); }++ /// Issue #293: a joint outranks its parent pour, a solid parent needs no joint, and keys of one net merge.+ #[test]+ fn joints_outrank_their_pour_and_skip_solid_ones() {+ let t = r#"(kicad_pcb (version 20240108) (generator "t")+ (layers (0 "F.Cu" signal) (2 "B.Cu" signal) (25 "Edge.Cuts" user))+ (net 0 "") (net 1 "VIN") (net 2 "GND")+ (gr_rect (start 0 0) (end 30 20) (layer "Edge.Cuts") (stroke (width 0.1) (type default)))+ (footprint "Q" (layer "F.Cu") (at 15 10) (property "Reference" "Q1" (at 0 0) (layer "F.SilkS"))+ (pad "1" smd rect (at 0 0) (size 1 1) (layers "F.Cu") (net 1 "VIN"))+ (pad "2" smd rect (at 1 0) (size 1 1) (layers "F.Cu") (net 1 "VIN"))+ (pad "3" smd rect (at 5 0) (size 1 1) (layers "F.Cu") (net 2 "GND"))))"#;+ let b = Board::from_text("t.kicad_pcb", t.to_string()).unwrap();+ let spec = json!({"pours": [{"net": "VIN", "layers": ["F.Cu"], "around": ["Q1.1"], "margin": 2.0, "priority": 2, "connection": "thermal"},+ {"net": "GND", "layers": ["F.Cu"], "around": ["Q1.3"], "margin": 2.0, "priority": 1, "connection": "solid"}],+ "solidAt": ["Q1.1", "Q1.2", "Q1.3"]});+ let (zones, _, _) = build(&b, &spec, None).unwrap();+ let joints: Vec<&Value> = zones.iter().filter(|z| z["name"].as_str().unwrap_or("").contains("solid joint")).collect();+ assert_eq!(joints.len(), 1, "VIN's two patches merge, GND's solid pour needs none: {joints:#?}");+ assert_eq!(joints[0]["name"], "VIN solid joint at Q1.1+Q1.2");+ assert_eq!(joints[0]["priority"], 3, "one above the VIN pour's priority 2");+ } } }
crates/aiflow-pours/src/stitch_grid.rs+39−14@@ -11,25 +11,41 @@ use serde_json::{json, Value}; 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))+ // issue #293 (Mohit Singh): a list may hold grids ({net, pitch}) as well as spots ({net, x, y}); a grid in a+ // list was read as a spot with no x and y and dropped without a word+ Some(Value::Array(a)) => {+ let (mut list, mut notes) = (Vec::new(), Vec::new());+ for (k, e) in a.iter().enumerate() {+ let spot = e.get("x").and_then(|v| v.as_f64()).is_some() && e.get("y").and_then(|v| v.as_f64()).is_some();+ match e.as_object() {+ Some(_) if spot => list.push(e.clone()),+ Some(o) if o.contains_key("pitch") => { let (l, n) = grid_entry(o, board, size, drill, clearance, silk, silk_gap); list.extend(l); notes.push(n); }+ _ => notes.push(format!("stitchVias entry {} has neither \"x\" and \"y\" (a spot) nor \"pitch\" (a grid): left out", k + 1)),+ }+ }+ (list, (!notes.is_empty()).then(|| notes.join("; "))) }+ Some(Value::Object(o)) => { let (l, n) = grid_entry(o, board, size, drill, clearance, silk, silk_gap); (l, Some(n)) } 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)))), } } +/// One grid `{net, pitch, size?, drill?, edge?}`: its clear spots and the line that says how many.+fn grid_entry(o: &serde_json::Map<String, Value>, board: &Board, size: f64, drill: f64, clearance: f64, silk: &[Shape], silk_gap: f64) -> (Vec<Value>, String) {+ 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(), "stitchVias grid without a positive \"pitch\": nothing planned. Give a grid {\"net\": \"GND\", \"pitch\": 8.0} or a list [{\"net\", \"x\", \"y\"}].".to_string());+ };+ if net.is_empty() { return (Vec::new(), "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, note)+}+ fn kind(v: &Value) -> &'static str { match v { Value::String(_) => "a string", Value::Number(_) => "a number", Value::Bool(_) => "a boolean", _ => "not a list" } }@@ -102,6 +118,15 @@ mod tests { assert_eq!(list[0]["size"], 0.6); } + /// Issue #293 (Mohit Singh): a list holding a grid object ({net, pitch}) is a grid, not 0 vias.+ #[test]+ fn a_grid_inside_a_list_is_planned() {+ let b = board();+ let (list, note) = entries(&json!({"stitchVias": [{"net": "GND", "pitch": 5.0}, {"net": "GND", "x": 1.0, "y": 1.0}]}), &b, 0.6, 0.3, 0.2, &[], 0.1);+ assert!(list.len() > 4, "{list:?}");+ assert!(note.unwrap_or_default().contains("every 5 mm"));+ }+ #[test] fn a_list_passes_through_and_other_shapes_are_said() { let b = board();
crates/aiflow-router/src/drive.rs+21−3@@ -330,7 +330,9 @@ impl Router { let allow = cl.allow; let mut widths: Vec<f64> = self.nets[net].widths.iter().copied().filter(|w| *w <= allow).collect(); if widths.is_empty() {- widths = vec![self.nets[net].widths.iter().cloned().fold(f64::INFINITY, f64::min)];+ let narrowest = self.nets[net].widths.iter().cloned().fold(f64::INFINITY, f64::min);+ // issue #293: a fine-pitch pin narrower than the net's width necks down to its pad (never under the fab minimum)+ widths = vec![match self.fine_pitch_neck(net).filter(|_| !cl.escapes.is_empty()) { Some(n) => n.min(narrowest), None => narrowest }]; } let mut allpts: Vec<(i64, i64)> = cl.terminals.iter().map(|t| (t.i as i64, t.j as i64)).collect(); allpts.extend_from_slice(anchor);@@ -453,7 +455,7 @@ impl Router { self.nets[net].last_soft.extend(sr.cells.iter().copied()); } let key = self.nets[net].clusters[c].key(&self.board).to_string();- let why = if let Some(w) = self.off_layer_reason(net, c).or_else(|| self.off_layer_reason(net, k)) { w } else if blockers.is_empty() { if self.rules.default_copper_mode() { "no path".to_string() } else { format!("no path {}", self.mode_words()) } } else {+ let why = if let Some(w) = self.off_layer_reason(net, c).or_else(|| self.off_layer_reason(net, k)) { w } else if let Some(w) = self.fine_pitch_reason(net, c).filter(|_| blockers.is_empty()) { w } else if blockers.is_empty() { if self.rules.default_copper_mode() { "no path".to_string() } else { format!("no path {}", self.mode_words()) } } else { let mut names: Vec<String> = blockers.iter().map(|&b| self.name_of(b)).collect(); names.sort(); format!("blocked by {names:?}")@@ -477,6 +479,22 @@ impl Router { /// Issue #183: why a cluster cannot be reached in single-face mode: its pad has copper only on a /// layer the router may not use. None when the pad is reachable (or in the default mode).+ /// Issue #293 (Mohit Singh): a pin that cannot leave its pad because its escape and its neighbours' are too wide for+ /// the pitch, said as that (with the way out), not a bare "no path".+ fn fine_pitch_reason(&self, net: usize, c: usize) -> Option<String> {+ let cl = &self.nets[net].clusters[c];+ if cl.escapes.is_empty() { return None; }+ let pitch = self.own_pitch(cl.primary)?;+ let w = self.stub_for(net).max(self.nets[net].widths.iter().copied().filter(|x| *x <= cl.allow).fold(0.0, f64::max));+ let w = if self.nets[net].widths.iter().any(|x| *x <= cl.allow) { w.min(cl.allow) } else { w };+ let clr = self.rules.clearance;+ if pitch > 1.0 || w + clr + 0.05 < pitch { return None; }+ Some(match self.rules.min_track {+ Some(mt) => format!("cannot leave its pad: a {w} mm escape beside neighbours at {pitch:.2} mm pitch needs under {:.2} mm with {clr} mm clearance, and the fab minimum track is {mt} mm (narrow the escape with spec \"stub\", or a smaller clearance for this part)", pitch - clr),+ None => format!("cannot leave its pad: a {w} mm escape beside neighbours at {pitch:.2} mm pitch needs under {:.2} mm with {clr} mm clearance; give spec \"minTrackWidth\" (the fab's minimum track) so fine-pitch escapes neck down to the pad width", pitch - clr),+ })+ }+ pub fn off_layer_reason(&self, net: usize, c: usize) -> Option<String> { if self.rules.default_copper_mode() { return None; } let p = &self.board.pads[self.nets[net].clusters[c].primary];@@ -1439,7 +1457,7 @@ impl Router { let mut warnings: Vec<String> = Vec::new(); for net in &self.nets { if net.done_by_board || net.routes.is_empty() { continue; }- let unfilled: Vec<&aiflow_board::Zone> = zones.iter().filter(|z| z.net == net.name && z.fills.is_empty()).collect();+ let unfilled: Vec<&aiflow_board::Zone> = zones.iter().filter(|z| z.net == net.name && z.fills.is_empty() && z.layer_names().iter().any(|l| !z.absorbed.contains(l))).collect(); if unfilled.is_empty() { continue; } let names: Vec<Vec<String>> = unfilled.iter().map(|z| z.layer_names()).collect(); let mut layers: Vec<&str> = names.iter().flatten().map(|s| s.as_str()).collect();
crates/aiflow-router/src/lib.rs+23−2@@ -493,7 +493,13 @@ impl Router { cells += 1; } }- self.log(format!(" planeUnder {}: {:.1} mm2 of {} kept for {} (a keepout for every other net)", reg.label, cells as f64 * RES * RES, plane_under::layer_name(reg.layer), reg.net));+ // issue #293: the outline itself, so a box wider than the loop it protects shows before it costs a re-route,+ // and the pins of other nets it walls in (they leave on the other layer only)+ let (x0, y0, x1, y1) = aiflow_board::geom::bbox(®.poly);+ let pts: Vec<String> = reg.poly.iter().map(|(x, y)| format!("[{x:.2},{y:.2}]")).collect();+ self.log(format!(" planeUnder {}: {:.1} mm2 of {} kept for {} (a keepout for every other net): x {x0:.2}..{x1:.2}, y {y0:.2}..{y1:.2}, polygon [{}]", reg.label, cells as f64 * RES * RES, plane_under::layer_name(reg.layer), reg.net, pts.join(",")));+ let walled: Vec<String> = self.board.pads.iter().filter(|p| p.net != reg.net && !p.net.is_empty() && aiflow_board::geom::point_in_poly(p.x, p.y, ®.poly) && (p.thru || (reg.layer == aiflow_board::F_CU) == p.on_f)).map(|p| format!("{}.{} ({})", p.reference, p.name, p.net)).collect();+ if !walled.is_empty() { self.log(format!(" planeUnder {}: walls in {} pad(s) of other nets: {}{}", reg.label, walled.len(), walled.iter().take(8).cloned().collect::<Vec<_>>().join(", "), if walled.len() > 8 { ", ..." } else { "" })); } } self.keep = regions; }@@ -1288,10 +1294,25 @@ impl Router { pub fn stub_for(&self, net: usize) -> f64 { match self.rules.impedance.get(&self.nets[net].name) { Some(ir) if ir.width > self.rules.stub && self.nets[net].pads.iter().all(|&p| 2.0 * self.board.pads[p].half_short + 1e-9 >= ir.width) => ir.width,- _ => self.rules.stub,+ _ => self.fine_pitch_neck(net).map(|n| n.min(self.rules.stub)).unwrap_or(self.rules.stub), } } + /// Issue #293 (Mohit Singh): the width a fine-pitch pin's escape necks down to: its pad's width class (`allow`),+ /// when that is narrower than the escape and no narrower than the fab's minimum track (`min_track`). None when+ /// the fab minimum is not known (the spec's track is then the floor) or no pad of the net is that narrow.+ pub fn fine_pitch_neck(&self, net: usize) -> Option<f64> {+ let mt = self.rules.min_track?;+ let allow = self.nets[net].clusters.iter().filter(|c| !c.escapes.is_empty()).map(|c| c.allow).fold(f64::INFINITY, f64::min);+ (allow.is_finite() && allow < self.rules.stub && mt <= allow + 1e-9).then_some(allow)+ }++ /// The pitch to the nearest other pad of a pad's own footprint (mm), for the fine-pitch failure message.+ pub fn own_pitch(&self, pad: usize) -> Option<f64> {+ let p = &self.board.pads[pad];+ self.board.pads.iter().enumerate().filter(|(k, q)| *k != pad && q.reference == p.reference && q.half_long < 2.0).map(|(_, q)| (q.x - p.x).hypot(q.y - p.y)).filter(|d| *d > 1e-6).min_by(|a, b| a.total_cmp(b))+ }+ /// The layer an impedance-controlled net is held to (impedance::table chose it). pub fn impedance_layer(&self, net: usize) -> Option<usize> { self.rules.impedance.get(&self.nets[net].name).and_then(|ir| match ir.layer.as_str() { "F.Cu" => Some(F_CU), "B.Cu" => Some(B_CU), _ => None })
crates/aiflow-router/src/plane_under.rs+10@@ -66,6 +66,16 @@ pub fn regions(board: &Board, entries: &[PlaneUnder]) -> Result<Vec<Region>, Str let (x0, y0, x1, y1) = pad_box(board, &e.around).map_err(|m| format!("planeUnder[{k}]: {m}"))?; let m = e.margin.unwrap_or(1.0); let (bx0, by0, bx1, by1) = board.bbox;+ if e.shape.as_deref() == Some("hull") {+ let pts: Vec<Pt> = e.around.iter().flat_map(|k| match k.split_once('.') {+ Some((r, n)) if board.pad_by_key(k).is_some() => board.pads.iter().filter(|p| p.reference == r && p.name == n).flat_map(|p| p.polys.iter().flatten().copied()).collect::<Vec<_>>(),+ _ => board.pads.iter().filter(|p| p.reference == *k).flat_map(|p| p.polys.iter().flatten().copied()).collect(),+ }).collect();+ let poly: Vec<Pt> = geom::hull_around(&pts, m).into_iter().map(|(x, y)| (x.clamp(bx0, bx1), y.clamp(by0, by1))).collect();+ let label = e.name.clone().unwrap_or_else(|| format!("{} {} under {} (hull)", e.net, e.layer, e.around.join(",")));+ out.push(Region { layer, net: e.net.clone(), poly, label });+ continue;+ } let r4 = |v: f64| (v * 10000.0).round() / 10000.0; let (a, b, c, d) = (r4((x0 - m).max(bx0)), r4((y0 - m).max(by0)), r4((x1 + m).min(bx1)), r4((y1 + m).min(by1))); vec![(a, b), (c, b), (c, d), (a, d)]
crates/aiflow-router/src/rules.rs+7−1@@ -8,6 +8,9 @@ use serde::{Deserialize, Serialize}; #[serde(default)] pub struct Rules { pub track: f64,+ /// The fab's minimum track width (spec `minTrackWidth`, else the project's .kicad_dru): issue #293, a fine-pitch+ /// pin whose pad is narrower than the net's width necks its escape down to the pad, never below this+ pub min_track: Option<f64>, pub clearance: f64, /// Per-net clearance overrides (spec "netClearance": {net: mm}), for a net the DRC caught a hair under the rule. pub net_clearance: std::collections::BTreeMap<String, f64>,@@ -97,12 +100,14 @@ pub struct PlaneUnder { pub margin: Option<f64>, pub polygon: Vec<(f64, f64)>, pub name: Option<String>,+ /// "hull": the region hugs the listed pads (their convex hull grown by the margin), not their bounding box+ pub shape: Option<String>, } impl Default for Rules { fn default() -> Rules { Rules {- track: 0.25, clearance: 0.2, net_clearance: Default::default(), via: 0.8, drill: 0.4, via_small: 0.6, drill_small: 0.3, edge: 0.5,+ track: 0.25, min_track: None, clearance: 0.2, net_clearance: Default::default(), via: 0.8, drill: 0.4, via_small: 0.6, drill_small: 0.3, edge: 0.5, stub: 0.25, narrow: 0.5, escape: 0.45, corridor: 0.5, ic_zone: 2.0, channel: 2.5, planes: BTreeMap::new(), wide: BTreeMap::new(), mid: BTreeMap::new(), hole_to_hole: 0.25, via_search_mm: 6.0, kelvin: BTreeMap::new(), signal_priority: Vec::new(), plane_under: Vec::new(), decoupling: Vec::new(), impedance: BTreeMap::new(), clear_regions: Vec::new(), route_layers: Vec::new(), vias: true, allow_via_in_pad: false, hole_clearance: 0.0, isolation: Vec::new(), isolation_exempt: Vec::new(),@@ -149,6 +154,7 @@ impl Rules { // Escape necks inherit the requested track width. An explicit smaller // stub must still satisfy the separately declared manufacturing minimum. r.stub = num("stub").unwrap_or(r.track).max(num("minTrackWidth").unwrap_or(r.track));+ r.min_track = num("minTrackWidth"); // a via is a size, or a [size, drill] pair (the way wideNets gives widths); either form is read, // never silently skipped let pair = |k: &str| spec.get(k).and_then(|v| v.as_array()).and_then(|a| Some((a.first()?.as_f64()?, a.get(1).and_then(|d| d.as_f64()))));
crates/aiflow-router/tests/qfn_escape.rsadded+41@@ -0,0 +1,41 @@+//! Issue #293 (Mohit Singh): every pin of a 0.5 mm-pitch QFN in a clear area found "no path": a 0.3 mm escape+//! beside its neighbours' at 0.5 mm pitch leaves no 0.2 mm clearance. With the fab minimum known, escapes neck+//! down to the pad; without it, the failure says so instead of "no path".+use aiflow_board::Board;+use aiflow_router::{Router, Rules};++/// A row of `n` pins at 0.5 mm pitch (pads 0.25 x 0.8), each on its own net to a test pad below.+fn board(n: usize) -> String {+ let mut nets = String::new();+ let mut pads = String::new();+ let mut tps = String::new();+ for k in 0..n {+ let x = -(n as f64 - 1.0) * 0.25 + k as f64 * 0.5;+ nets.push_str(&format!("(net {} \"S{k}\") ", k + 1));+ pads.push_str(&format!("(pad \"{}\" smd rect (at {x} 2) (size 0.25 0.8) (layers \"F.Cu\") (net {} \"S{k}\")) ", k + 1, k + 1));+ tps.push_str(&format!("(footprint \"tp\" (layer \"F.Cu\") (at {} 17) (property \"Reference\" \"TP{k}\") (pad \"1\" smd circle (at 0 0) (size 0.8 0.8) (layers \"F.Cu\") (net {} \"S{k}\"))) ", 15.0 + x * 3.0, k + 1));+ }+ format!(r#"(kicad_pcb (layers (0 "F.Cu" signal) (31 "B.Cu" signal)) {nets}+ (gr_rect (start 0 0) (end 30 25) (layer "Edge.Cuts"))+ (footprint "QFN" (layer "F.Cu") (at 15 10) (property "Reference" "U1")+ (pad "EP" smd rect (at 0 0) (size 3 3) (layers "F.Cu")) {pads})+ {tps})"#)+}++fn route(spec: serde_json::Value) -> Vec<String> {+ let mut r = Router::new(Board::from_text("qfn.kicad_pcb", board(6)).unwrap(), Rules::from_spec(&spec), false);+ r.run(false, 2, 20, &[]);+ r.nets.iter().flat_map(|n| n.failed.iter().map(|f| f.1.clone())).collect()+}++#[test]+fn fine_pitch_pins_neck_down_to_their_pads() {+ let f = route(serde_json::json!({"track": 0.3, "clearance": 0.2, "minTrackWidth": 0.127}));+ assert!(f.is_empty(), "{f:?}");+}++#[test]+fn without_the_fab_minimum_the_failure_says_why() {+ let f = route(serde_json::json!({"track": 0.3, "clearance": 0.2}));+ assert!(!f.is_empty() && f.iter().all(|w| w.contains("cannot leave its pad") && w.contains("minTrackWidth")), "{f:?}");+}
docs/release-0.2.152.mdadded+45@@ -0,0 +1,45 @@+# adom-aiflow 0.2.152++Twenty findings from one full prompt-to-board run, all reported by Mohit Singh: issues #292, #293 and #294. In each case a check or a planner was wrong, not the board.++## Adopting a board (#292)++- **`adopt-board` never truncates the board you pass.** It used to copy the board onto itself when you passed the run's own `board-<n>.kicad_pcb`, leaving a 0-byte file. Now it stages a copy, runs the DRC on that copy, and moves it into the run only when the DRC passes. A failed check leaves your file untouched and says so.+- **The DRC uses the right rules.** It reads the project rules beside the board. When there are none, it uses the run's current project rules and says so, instead of quietly using KiCad's defaults.++## Pours (#293, #294)++- **Stitch vias.** A `stitchVias` list that holds a grid (`{net, pitch}`) is planned as that grid; before, it planned none. `pour` now says how many spots it planned out of how many it asked for.+- **Solid joints.**+ - Patches of one net that overlap merge into one zone, across `solidAt` keys too.+ - A joint sits one priority above the pour it is in. At priority 1 under a higher-priority pour, KiCad gave it no fill.+ - A pad whose pour already connects solidly gets no joint.+- **A zone with no fill is not reported missing** when a higher-priority zone of the same net wholly covers it and is filled on that layer. KiCad gives that zone the overlap. This applies to `export`, `finish`, `verify-pours` and the `route` warning.+- **`"shape": "hull"`** on a pour or `planeUnder` entry with `around` makes the outline hug the listed pads, instead of their bounding box. `pour` and `route` print the outline they made and name the pads of other nets inside it.+- **`verify-pours` reads the plan `pour` wrote.** The `why` note is accepted; other spec-only keys stay in the spec and are named.++## Checks that read the wrong board (#293)++- **`silkscreen fab-check`** reads the saved desktop board when the run has one bound, and says which board it read. `fab-tidy` keeps the project rules beside its output.+- **`rules check`** with no `--board` also checks the desktop project the board belongs to. **`rules sync`** writes that project too when its drive is mounted, and says so when it cannot.+- **Molecule `fixedRefs`.** The interface positions are taken from the first board of the run whose interface sits inside the outline. A start board that stages every part beside the outline no longer locks the interface off the board. The report names the parts that moved with MP1.++## Routing and analysis (#293)++- **Fine-pitch pins.** A pin narrower than the net's width (a 0.5 mm QFN beside 0.3 mm tracks) narrows its escape track to the pad's width, never below the fab's minimum: spec `minTrackWidth`, or the project's `.kicad_dru`. Without a known minimum, the failure says why and what to set, instead of "no path".+- **`analyze current`, dead-end stubs.** A stub whose root overlaps the pour along a length counts as meeting the pour at one place.+- **`analyze current`, the over-screen message.** It names the ack form that fits: the pad whose copper the peak is on, or the peak's own `NET@x,y` in open copper. Several `--ack` each take their own `--why`, in the same order.+- **`part-check`** reads the page's `step_path` and `model_3d_path`, uses the wiki's measured GLB size when the STEP cannot be read, and says "could not read" rather than "no 3D model". It also reports a STEP and a GLB on the same page that disagree in size.+- **Skill aiflow-power-layout.**+ - `kicad_plan_route` does not see `planeUnder` regions; the skill says how to keep a hand-planned route out of them.+ - With KiCad Bridge 1.1.16, a hop to the other layer is one `kicad_route_net` call.+ - It also documents the hull shape and the joint rules.++## Fields, silkscreen and the schematic (#294)++- **`fields fill`** merges into the spec's own spelling of a net (`switching./SW` fills `switching.SW`) and never adds a sibling entry. **`fields inputs`** labels a value the spec gives as the spec's, not as "(default)", and names the controller as the part that sets the switching frequency.+- **Polarized parts.** Polarity is decided by the part, not its library's nickname: the footprint name, `+`/`-` pads, and the value and description. A ceramic capacitor is never polarized. A `+` the footprint draws from two crossing strokes counts as a mark.+- **`schematic check`** accepts the flow's own test points, and parts with nothing to buy, from a library the project's `sym-lib-table` registers. `finish` now agrees with `schematic check` on symbols outside the project library.+- **`netlist check`.** Footprints on no net (fiducials, logos, unplated holes) and footprints with KiCad's `board_only` attribute are listed apart as board furniture, not as a mismatch.++Still open: `kicad_plan_route` taking keepout regions is a KiCad Bridge request.
package.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.151",+ "version": "0.2.152", "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.151",+ "version": "0.2.152", "title": "AI Flow", "description": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. One Rust binary with a crate per step (placement helpers, a grid router with Kelvin taps, pours with keepouts, KiCad's DRC gate, live landing through the KiCad Bridge, copper measurement, current and thermal analysis) and a finish line that refuses an unfinished board. Every command answers with hints for the AI; every turn, its thinking time and every rework loop go into run.jsonl, so Claude, Codex and any other engine are compared on the same flow. KiCad, Fusion 360 and Altium Designer today (the same steps and gates through each tool's bridge); Adom's own web apps next.", "summary": "Adom's AI Flow: a tool to help the AI follow all of the steps it takes to build a board. The AI thinks its way from placement through routing, pours, current and thermal analysis to a delivered video; the binary does the fast, deterministic parts of every step, hands back hints, and keeps a ledger of every turn, every return to an earlier step, and the clock from the prompt to done.",
skills/adom-aiflow/SKILL.md+1−1@@ -767,7 +767,7 @@ A drilled pad with no copper layer (an NPTH that lists only `*.Mask`, such as a ### Reviewed current peaks and board-face sinks -`analyze current --ack [email protected]|NET@x,y --why "..."` records a reviewed part-limited density peak (net, place, peak, reason, ai thread). It covers only that pad or 0.5 mm around the point, keeps the number reported, shows in `finish`, and expires when the copper fingerprint (the one copper carry-over uses) or the spec changes. A whole-net acknowledgement is refused. Read `docs/current-peak-acknowledgements.md`.+`analyze current --ack [email protected]|NET@x,y --why "..."` records a reviewed part-limited density peak (net, place, peak, reason, ai thread). It covers only that pad or 0.5 mm around the point, keeps the number reported, shows in `finish`, and expires when the copper fingerprint (the one copper carry-over uses) or the spec changes. A whole-net acknowledgement is refused. Several places take several `--ack`, each with its own `--why` in the same order (or one `--why` for all). The over-screen message names the form that fits: the pad whose copper the peak is on, or the peak's own `NET@x,y` when it sits in open pour copper. Read `docs/current-peak-acknowledgements.md`. `spec.boardSink` declares a pedestal or plate on a board face for named tabless parts: a conservative via, mask, interface and sink series estimate in `analyze thermal`, or the same-input Fields solve with the named conducting block. Both record their assumption in the run summary and `finish`; other parts keep the still-air check. Read `docs/board-sink.md`.
skills/aiflow-power-layout/SKILL.md+3−3@@ -18,7 +18,7 @@ Write `aiflow/spec.json` from the schematic before `start`, with a note on every - `hot`: watts per part from calcs.json (aiflow-circuit-design) with the arithmetic in `hotNote`, and `tabNet` only for a part with an exposed pad or tab (its net). A SOT-23, SOIC or TDFN without one gets no tabNet: adom-fields (0.10.20+) then spreads its heat through every pin by pad area, while a one-pin tabNet puts all its watts through that pin and reads far too hot (`analyze thermal` names such a part). - `planes`: each plane net and its layer (`{"GND": "B.Cu"}`). adom-fields (0.10.21+) counts these as return planes for its no-reference and decoupling checks; on a board with an isolated converter, list the primary-side return too (return-named nets such as RTN or `_RET`, and the converter's power-stage ground, count without it). - `pours`: GND on both layers from the outline; VIN and VOUT as `around` pours on F.Cu; SW as an explicit small `polygon`; `notPoured` for BOOT, FB and dividers.-- `solidAt` for the IC GND pin and the inductor pads; thermal and stitch vias.+- `solidAt` for the IC GND pin and the inductor pads; thermal and stitch vias. A solid joint sits one priority above the pour it is in (or it fills nothing), joints of one net that overlap merge, and a pad whose pour is already `connection: solid` gets none. - `decoupling` for each local cap and the supply pin it serves (`{"cap": "C2", "pin": "U1.2", "returnPins": ["U1.1"], "maxLengthMm": 3}`): `route` lays that connection before the rail and `gate` reports its copper path against the budget (adom-aiflow SKILL, Spec intent checked by the binary). - `placement.proximity` / `placement.cluster` for the hot loop: the input cap within a few mm of VIN and GND, the hot-loop parts in one cluster. `place check` and `place verify` fail with the distance and pin named. - Read the `start` WARNING lines and the design-rule card on the dashboard before placement: a 0.025 that should be 0.25 shows there.@@ -50,9 +50,9 @@ Without a layer policy the grid router treats B.Cu as free space: on the buck it "planeUnder": [{"layer": "B.Cu", "net": "GND", "around": ["U1", "C2", "C3", "C4"], "margin": 1.0}] ``` -`around` is the pad box of the listed parts or pads grown by `margin` (default 1.0 mm); `polygon: [[x, y], ...]` gives the region exactly. `planeUnder` accepts any copper layer on the board (`F.Cu`, `B.Cu`, `In1.Cu`, `In2.Cu`, ...): on outer layers it keeps foreign tracks and vias out, and on inner planes it keeps foreign inner tracks, zones, and piercing vias out so reference planes stay unbroken on 4+ layer boards. The gate fails on any other-net track, via or zone inside a region (`planeUnderIssues` in gate.json) and `finish` refuses until it is clear.+`around` is the pad box of the listed parts or pads grown by `margin` (default 1.0 mm); `"shape": "hull"` makes it their convex hull grown by the margin instead, which hugs a loop whose parts sit at the extremes; `polygon: [[x, y], ...]` gives the region exactly. `route` prints each region's extents and outline, and names other-net pads a region walls in. The same `"shape": "hull"` works on a `pours` entry with `around` (a tight switch-node patch); `pour` prints the outline it made and the other-net pads inside it. `planeUnder` accepts any copper layer on the board (`F.Cu`, `B.Cu`, `In1.Cu`, `In2.Cu`, ...): on outer layers it keeps foreign tracks and vias out, and on inner planes it keeps foreign inner tracks, zones, and piercing vias out so reference planes stay unbroken on 4+ layer boards. The gate fails on any other-net track, via or zone inside a region (`planeUnderIssues` in gate.json) and `finish` refuses until it is clear. -A region is a hard wall: a pin of another net inside it (the IC's EN or FB pin under U1) can only leave on the other layer, and a Kelvin sense may find no path. When `route` closes short with a region in place, shrink the margin, list fewer parts, or draw a polygon that leaves those pins a way out, before taking the nets by hand. If you do route by hand (`take route=ai`, `step routing --back --why "..."`): FB on F.Cu inside the quiet side, the VOUT sense along an edge, not across the plane, and land hand routes one at a time with a dry run first (`tools/route_live.py routes.json` calls `kicad_route_net` with `dryRun`, commits only on 0 DRC errors, and chains `expectedRevision` from each reply). After `adopt-board` of the reworked board, `route` keeps that copper and plans only what is still open (an empty plan when nothing is), and the gate checks the regions on it. Filled zones count as that copper: a net the board's pours already join is not tracked (refill unfilled zones first; `route` warns when it tracks a net that has one). A pad on its plane's own layer (`planes: {"GND": "F.Cu"}`, an F.Cu pad) gets no via.+A region is a hard wall: a pin of another net inside it (the IC's EN or FB pin under U1) can only leave on the other layer, and a Kelvin sense may find no path. When `route` closes short with a region in place, shrink the margin, list fewer parts, or draw a polygon that leaves those pins a way out, before taking the nets by hand. If you do route by hand (`take route=ai`, `step routing --back --why "..."`): FB on F.Cu inside the quiet side, the VOUT sense along an edge, not across the plane. `kicad_plan_route` does not know `spec.planeUnder`: it plans straight through a region. `route` prints each region's outline (`planeUnder ...: x a..b, y c..d, polygon [...]`); for a net near one, pass the planner `layers` without the region's layer (and `allowVias: false` when the path would cross it), or draw the region as a KiCad rule area (no tracks, pours allowed) before planning; use `gridMm: 0.1` at fine pitch; and run `gate` after landing (its planeUnder check reads the regions). A hop to the other layer is one `kicad_route_net` call with the layer on each point (`[{F@a},{B@a},{B@b},{F@b}]` lands two vias; KiCad Bridge 1.1.16), not two calls. Land hand routes one at a time with a dry run first (`tools/route_live.py routes.json` calls `kicad_route_net` with `dryRun`, commits only on 0 DRC errors, and chains `expectedRevision` from each reply). After `adopt-board` of the reworked board, `route` keeps that copper and plans only what is still open (an empty plan when nothing is), and the gate checks the regions on it. Filled zones count as that copper: a net the board's pours already join is not tracked (refill unfilled zones first; `route` warns when it tracks a net that has one). A pad on its plane's own layer (`planes: {"GND": "F.Cu"}`, an F.Cu pad) gets no via. Kelvin keepouts follow the tap's own layer (both layers only at its vias) and stop short of the power pin, so the IC GND pin keeps its pour (fixed in adom-aiflow 0.1.33; check older runs).