← Commit history
AI Flow 0.2.107: router fixes for multilayer boards (#250)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
13 files changed
+375−21
Cargo.lock+11−10Cargo.toml+1−1bin/adom-aiflowcrates/adom-aiflow/src/main.rs+63−5crates/aiflow-bridge/src/fusion.rs+15crates/aiflow-router/Cargo.toml+1crates/aiflow-router/src/board_copper.rs+43crates/aiflow-router/src/lib.rs+58−2crates/aiflow-router/src/project_rules.rs+160crates/aiflow-router/src/rules.rs+4−1docs/release-0.2.107.md+17package.json+1−1page.json+1−1Cargo.lock+11−10@@ -4,7 +4,7 @@ version = 4 [[package]] name = "adom-aiflow"-version = "0.2.106"+version = "0.2.107" dependencies = [ "aiflow-analyze", "aiflow-board",@@ -25,7 +25,7 @@ dependencies = [ [[package]] name = "aiflow-analyze"-version = "0.2.106"+version = "0.2.107" dependencies = [ "aiflow-board", "serde",@@ -35,7 +35,7 @@ dependencies = [ [[package]] name = "aiflow-board"-version = "0.2.106"+version = "0.2.107" dependencies = [ "roxmltree", "serde",@@ -44,7 +44,7 @@ dependencies = [ [[package]] name = "aiflow-bridge"-version = "0.2.106"+version = "0.2.107" dependencies = [ "aiflow-board", "serde",@@ -53,7 +53,7 @@ dependencies = [ [[package]] name = "aiflow-copper"-version = "0.2.106"+version = "0.2.107" dependencies = [ "aiflow-board", "aiflow-grid",@@ -63,7 +63,7 @@ dependencies = [ [[package]] name = "aiflow-grid"-version = "0.2.106"+version = "0.2.107" dependencies = [ "aiflow-board", "serde",@@ -72,7 +72,7 @@ dependencies = [ [[package]] name = "aiflow-place"-version = "0.2.106"+version = "0.2.107" dependencies = [ "aiflow-board", "serde",@@ -81,7 +81,7 @@ dependencies = [ [[package]] name = "aiflow-pours"-version = "0.2.106"+version = "0.2.107" dependencies = [ "aiflow-board", "aiflow-copper",@@ -91,17 +91,18 @@ dependencies = [ [[package]] name = "aiflow-router"-version = "0.2.106"+version = "0.2.107" dependencies = [ "aiflow-board", "aiflow-grid",+ "regex-lite", "serde", "serde_json", ] [[package]] name = "aiflow-run"-version = "0.2.106"+version = "0.2.107" dependencies = [ "serde", "serde_json",
Cargo.toml+1−1@@ -14,7 +14,7 @@ members = [ ] [workspace.package]-version = "0.2.106"+version = "0.2.107" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
bin/adom-aiflow⋯ 1 unchanged line ⋯
crates/adom-aiflow/src/main.rs+63−5@@ -305,7 +305,9 @@ enum Cmd { /// Replay live through the bridge: route, vias, pours, moves Land { what: String, #[arg(long)] plan: Option<String>, #[arg(long)] moves: Option<String>, #[arg(long, default_value_t = 600)] pause_ms: u64, /// route/vias: start at this trace number (1-based, as the progress lines count); traces already on the live board are skipped anyway #[arg(long)] from: Option<usize>, /// moves: parts whose body may overhang the outline (also spec placement.edgeOverhang); their pads stay inside- #[arg(long = "allow-outside", value_delimiter = ',')] allow_outside: Vec<String> },+ #[arg(long = "allow-outside", value_delimiter = ',')] allow_outside: Vec<String>,+ /// route: land a plan the gate found new DRC errors in anyway, saying why (issue #250: otherwise refused)+ #[arg(long = "accept-gate-errors")] accept_gate_errors: Option<String> }, /// Verify existing saved filled zones against an explicit reviewed plan, without landing or claiming ownership (--adopt --why takes ownership; --record-plan records a reviewed plan before the zones change) VerifyPours { /// the zone plan: the one `pour` wrote, or a reviewed plan recorded with --record-plan before the zones changed@@ -769,6 +771,12 @@ fn inner_layers_note(copper: &[String]) -> Option<String> { copper.len(), inner.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", "), aiflow_router::drive::net_time_limit().as_secs())) } +/// Issue #250: `land route` refuses the plan the gate found new DRC errors in, unless the AI accepts them with a+/// reason. Open connections alone never refuse (a partial route lands).+fn gate_refuses_landing(gate: &Value, gated: bool, accept: Option<&str>) -> bool {+ gated && gate["newErrors"].as_u64().unwrap_or(0) > 0 && accept.map_or(true, |w| w.trim().is_empty())+}+ fn run_dir(cli: &Cli) -> PathBuf { cli.run.clone().unwrap_or_else(|| std::env::var("AIFLOW_RUN").map(PathBuf::from).unwrap_or_else(|_| PathBuf::from("./aiflow-run"))) }@@ -5593,6 +5601,22 @@ fn main() { let missing=aiflow_pours::missing_planes(&b,&spec); if !missing.is_empty(){err(&format!("declared reference planes do not exist: {}",missing.join(", ")), &["Create the listed net/layer zones through the EDA bridge, fill and save them, then `adom-aiflow adopt-board --board <saved.kicad_pcb> --evidence <native review notes>` before route. A spec.planes declaration alone is not copper.".into()]);} let mut rules = aiflow_router::Rules::from_spec(&spec);+ // issue #250: the clearances KiCad's DRC will judge by, from the board's own project: net classes+ // (.kicad_pro) and custom rules (.kicad_dru), by net class or by rule area+ {+ let cb = r.current_board();+ 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);+ 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();+ if !pc.nets.is_empty() || !pc.regions.is_empty() {+ eprintln!("project rules: {} net(s) with a wider clearance from net classes or rules{}{}", pc.nets.len(),+ if pc.regions.is_empty() { String::new() } else { format!("; clearance region(s) {}", pc.regions.iter().map(|g| format!("{} {} mm", g.name, g.clearance)).collect::<Vec<_>>().join(", ")) },+ if pc.nets.is_empty() { String::new() } else { format!(" ({})", pc.nets.iter().take(6).map(|(n, v)| format!("{n} {v} mm")).collect::<Vec<_>>().join(", ")) });+ }+ for n in &pc.not_applied { eprintln!("NOTE: project clearance rule not applied by the router (the gate's DRC still checks it): {n}"); }+ } // issue #52: impedance targets set their nets' width (and pair pitch) and hold them to one layer let imp_choice = impedance_cmd::for_route(&b, &spec, &r.current_board(), &mut rules).unwrap_or_else(|(m, h)| err(&m, &h)); // issue #165: say the sizes the router actually uses, so a spec key it did not read shows at once@@ -5872,7 +5896,7 @@ fn main() { if !mol_errors.is_empty() { findings(&format!("gate: 0 new DRC errors ({inh} inherited), 0 unconnected, but {} molecule finding(s) are open:\n {}", mol_errors.len(), mol_errors.join("\n ")), &["DRC is recorded (gate.json). Fix the molecule findings above (`adom-aiflow molecule check` lists them with suggestions), then gate again; finish lists whatever is still open.".into()]); } ok(&format!("gate passed: 0 new DRC errors ({inh} inherited), 0 unconnected{}{checked}; copper {}\nThis is the routing gate (DRC, connectivity, courtyards, bodies), not a fabrication check: pours in the saved board, Gerbers and human review come later.", if pu.is_empty() { String::new() } else { format!(", {} planeUnder region(s) clear", pu.len()) }, s["copper"]), &[if empty { "The plan is empty: the board's own copper already joins every net. Next: adom-aiflow land route (records that nothing needs landing), then pour, land vias, land pours.".into() } else { "Next: adom-aiflow land route (then pour, land vias, land pours).".into() }]); }- Cmd::Land { what, plan, moves, pause_ms, from, allow_outside } => {+ Cmd::Land { what, plan, moves, pause_ms, from, allow_outside, accept_gate_errors } => { let mut r = load_run(&cli); if what == "route" { // a gated empty plan (the board's own copper already joins every net): nothing to land, no bridge call@@ -5929,10 +5953,29 @@ fn main() { "route" | "vias" => { let planp = if what == "route" { let gate_ok = r.outcomes().get("gate").and_then(|g| g.get("newErrors")).and_then(|v| v.as_u64()) == Some(0) && r.outcomes().get("gate").and_then(|g| g.get("unconnected")).and_then(|v| v.as_u64()) == Some(0) && r.outcomes().get("gate").and_then(|g| g.get("planeUnderIssues")).and_then(|v| v.as_u64()).unwrap_or(0) == 0 && r.outcomes().get("gate").map(mechanical::gate_clear).unwrap_or(false);- if !gate_ok && plan.is_none() {- note("the gate has not passed for this plan", &["Run `adom-aiflow gate` first; the finish line needs it.".into()]);+ let chosen = plan.clone().or_else(|| r.outcomes().get("gate").and_then(|g| g.get("plan")).and_then(|p| p.as_str()).map(str::to_string)).unwrap_or_else(|| err("no plan", &[]));+ // issue #250: a plan the gate found new DRC errors in (shorts, clearances) is not landed: that+ // copper would go onto the human's board. Open connections still land (a partial route is fine).+ let gate = r.outcomes().get("gate").cloned().unwrap_or(Value::Null);+ let same_plan = |a: &str, b: &str| std::fs::canonicalize(a).ok().zip(std::fs::canonicalize(b).ok()).map(|(x, y)| x == y).unwrap_or(a == b);+ let gated = gate["plan"].as_str().is_some_and(|gp| same_plan(gp, &chosen));+ let new_errors = gate["newErrors"].as_u64().unwrap_or(0);+ if gate_refuses_landing(&gate, gated, accept_gate_errors.as_deref()) {+ err(&format!("not landed: the gate found {new_errors} new DRC error(s) in this plan ({chosen}); landing it puts that copper on the board"), &[+ "Read gate.json for each error, fix the plan (route again with the rules that apply, or move the copper), `gate`, then land.".into(),+ "To land it anyway (you will fix the errors live), say why: `land route --accept-gate-errors \"<why>\"`.".into()]);+ }+ if gated && new_errors > 0 {+ match accept_gate_errors.as_deref().filter(|w| !w.trim().is_empty()) {+ None => err(&format!("not landed: the gate found {new_errors} new DRC error(s) in this plan ({chosen}); landing it puts that copper on the board"), &[+ "Read gate.json for each error, fix the plan (route again with the rules that apply, or move the copper), `gate`, then land.".into(),+ "To land it anyway (you will fix the errors live), say why: `land route --accept-gate-errors \"<why>\"`.".into()]),+ Some(w) => { r.log("land-route-gate-errors-accepted", json!({"plan": chosen, "newErrors": new_errors, "why": w})); eprintln!("WARNING: landing a plan with {new_errors} gate error(s), accepted: {w}"); }+ }+ } else if !gate_ok {+ note(if gated { "the gate has not passed for this plan (open connections)" } else { "this plan was not the one gated" }, &["Run `adom-aiflow gate` on it first; the finish line needs it.".into()]); }- plan.clone().or_else(|| r.outcomes().get("gate").and_then(|g| g.get("plan")).and_then(|p| p.as_str()).map(str::to_string)).unwrap_or_else(|| err("no plan", &[]))+ chosen } else { plan.clone().or_else(|| r.outcomes().get("pour").and_then(|p| p.get("vias")).and_then(|p| p.as_str()).map(str::to_string)).unwrap_or_else(|| err("no vias plan; run `adom-aiflow pour` first", &[])) };@@ -9407,3 +9450,18 @@ mod inner_layers_tests { assert!(super::inner_layers_note(&["F.Cu".to_string(), "B.Cu".to_string()]).is_none()); } }++#[cfg(test)]+mod land_gate_tests {+ /// Issue #250: errors in the gated plan refuse the landing unless accepted with a why; open connections and an+ /// ungated plan only note.+ #[test]+ fn errors_in_the_gated_plan_refuse_the_landing_unless_accepted() {+ let g = |e: u64, u: u64| serde_json::json!({"newErrors": e, "unconnected": u});+ assert!(super::gate_refuses_landing(&g(180, 217), true, None));+ assert!(super::gate_refuses_landing(&g(1, 0), true, Some(" ")));+ assert!(!super::gate_refuses_landing(&g(1, 0), true, Some("fixing the two clearances live")));+ assert!(!super::gate_refuses_landing(&g(0, 172), true, None), "open connections land");+ assert!(!super::gate_refuses_landing(&g(5, 0), false, None), "another plan: a note, not a refusal");+ }+}
crates/aiflow-bridge/src/fusion.rs+15@@ -400,9 +400,14 @@ pub fn main_hwnd(call: &dyn Fn(&str, &Value) -> Value) -> Option<i64> { #[cfg(test)] mod tests { use super::*;+ /// translate() keeps the board id, document and bottom layer in process-wide state: tests that drive it take+ /// turns, or a multilayer test changes the bottom layer under a two-layer one (a flake seen twice).+ static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(());+ fn serial() -> std::sync::MutexGuard<'static, ()> { SERIAL.lock().unwrap_or_else(|e| e.into_inner()) } /// Issue #142: a bottom part's move carries the MR angle land_moves worked out; a plain number would flip it. #[test] fn a_bottom_part_is_sent_its_mirrored_rotation() {+ let _serial = serial(); let sent = std::cell::RefCell::new(Vec::<(String, Value)>::new()); let call = |v: &str, a: &Value| -> Value { sent.borrow_mut().push((v.to_string(), a.clone())); json!({"success": true, "boardId": "B", "revision": "r1"}) }; let _ = translate("kicad_move_footprint", &json!({"expectedRevision": "r1", "refs": [{"ref": "U1", "x": 10.0, "y": -8.0, "rotation": 90.0, "eagleRot": "MR270"}]}), "Doc-brd", &call);@@ -412,6 +417,7 @@ mod tests { } #[test] fn route_net_waypoints_and_moves_flip_y_and_keep_rotation() {+ let _serial = serial(); let sent = std::cell::RefCell::new(Vec::<(String, Value)>::new()); let call = |v: &str, a: &Value| -> Value { sent.borrow_mut().push((v.to_string(), a.clone()));@@ -448,6 +454,7 @@ mod tests { } #[test] fn inner_copper_is_measured_and_read_under_its_own_name() {+ let _serial = serial(); let sent = std::cell::RefCell::new(Vec::new()); let call = |v: &str, a: &Value| four_layer(&sent, v, a); let z = translate("kicad_zone_state", &json!({}), "Doc-brd", &call);@@ -461,6 +468,7 @@ mod tests { } #[test] fn inner_routes_go_to_the_bridge_by_name_and_a_bad_layer_is_refused() {+ let _serial = serial(); let sent = std::cell::RefCell::new(Vec::new()); let call = |v: &str, a: &Value| four_layer(&sent, v, a); let r = translate("kicad_route_net", &json!({"expectedRevision": "r1", "net": "A", "layer": "In1.Cu", "paths": [["R1.1", {"x": 1.0, "y": -1.0, "layer": "In2.Cu"}, {"x": 2.0, "y": -1.0, "layer": "F.Cu"}]]}), "Doc-brd", &call);@@ -477,6 +485,7 @@ mod tests { } #[test] fn an_inner_pour_lands_by_name_beside_the_outer_ones() {+ let _serial = serial(); let sent = std::cell::RefCell::new(Vec::new()); let landed = std::cell::RefCell::new(Vec::<Value>::new()); let call = |v: &str, a: &Value| {@@ -504,6 +513,7 @@ mod tests { fn pour_row(net: &str, layer: i64, outline: Value) -> Value { json!({"net": net, "layer": layer, "outline": outline, "filledMm2": 1.0, "filled": true}) } #[test] fn a_changed_pour_replaces_the_old_one_the_run_owns() {+ let _serial = serial(); let (old, new, theirs) = (json!([[0.0, 0.0], [5.0, 0.0], [5.0, 5.0], [0.0, 5.0]]), json!([[0.0, 0.0], [8.0, 0.0], [8.0, 5.0], [0.0, 5.0]]), json!([[20.0, 0.0], [25.0, 0.0], [25.0, 5.0]])); let rows = std::cell::RefCell::new(vec![pour_row("GND", 1, old.clone()), pour_row("GND", 1, theirs.clone())]); let sent = std::cell::RefCell::new(Vec::<(String, Value)>::new());@@ -535,6 +545,7 @@ mod tests { } #[test] fn a_pour_the_board_started_with_is_not_claimed_when_the_plan_matches_it() {+ let _serial = serial(); let shape = json!([[0.0, 0.0], [5.0, 0.0], [5.0, 5.0], [0.0, 5.0]]); let row = pour_row("GND", 1, shape.clone()); let call = |v: &str, _: &Value| -> Value {@@ -550,6 +561,7 @@ mod tests { } #[test] fn a_pour_that_does_not_land_puts_the_old_one_back() {+ let _serial = serial(); let old = json!([[0.0, 0.0], [5.0, 0.0], [5.0, 5.0]]); let sent = std::cell::RefCell::new(Vec::<(String, Value)>::new()); let call = |v: &str, a: &Value| -> Value {@@ -572,6 +584,7 @@ mod tests { /// What the live run found on bridge 1.13.73: the bridge's remove answered verified, and the wrong pour had gone. #[test] fn the_result_is_read_back_by_id_not_taken_on_the_bridges_word() {+ let _serial = serial(); let (old, new) = (json!([[1.0, 1.0], [19.0, 1.0], [19.0, 9.0], [1.0, 9.0]]), [[1.0, -1.0], [19.0, -1.0], [19.0, -14.0], [1.0, -14.0]]); let call = |v: &str, _: &Value| -> Value { match v {@@ -597,6 +610,7 @@ mod tests { } #[test] fn a_pour_the_bridge_refuses_comes_back_as_the_bridges_answer() {+ let _serial = serial(); let call = |v: &str, a: &Value| -> Value { if v == "fusion_apply_pours" { json!({"success": false, "errorCode": "readback_mismatch", "missing": ["PGND"]}) } else { four_layer(&std::cell::RefCell::new(Vec::new()), v, a) } };@@ -619,6 +633,7 @@ mod tests { /// Issue #203: on a board whose bottom is 304, B.Cu goes to Fusion as 304 and 304 reads back as B.Cu. #[test] fn the_bottom_layer_follows_the_board() {+ let _serial = serial(); set_bottom(304); assert_eq!(layer_arg(&json!("B.Cu")), Some(json!(304))); assert_eq!(layer_label(304, &HashMap::new()), "B.Cu");
crates/aiflow-router/Cargo.toml+1@@ -6,6 +6,7 @@ license.workspace = true description = "adom-aiflow: router" [dependencies]+regex-lite = "0.1" serde = { workspace = true } serde_json = { workspace = true } aiflow-board = { workspace = true }
crates/aiflow-router/src/board_copper.rs+43@@ -229,6 +229,16 @@ impl Router { self.fixed_raw[t.layer][c] = nid; } }+ // issue #250: inner-layer tracks block through vias of other nets (stamped apart: the router plans+ // tracks on F.Cu and B.Cu only)+ for t in tracks.iter().filter(|t| t.layer > B_CU) {+ let nid = nid_of(self, &t.net);+ for c in g.segment_cells(t.a, t.b, t.width / 2.0, Some(1e-6)) { self.inner_raw[c] = nid; }+ }+ for v in vias.iter().filter(|v| !(v.on_copper(F_CU) && v.on_copper(B_CU))) {+ let nid = nid_of(self, &v.net);+ for c in g.disk_cells((v.x, v.y), v.size / 2.0, Some(1e-6)) { self.inner_raw[c] = nid; }+ } for v in &vias { let nid = nid_of(self, &v.net); for c in g.disk_cells((v.x, v.y), v.size / 2.0, Some(1e-6)) {@@ -676,6 +686,39 @@ pub(crate) mod tests { assert!(!r.fixed_blocks("A", None, 10.0, 8.0, 0.5)); } + /// Issue #250: inside a project rule area every net keeps the area's clearance (0.6 mm here, against the+ /// 0.2 mm global): a cell 0.5 mm from B's pad edge is free for A's track without the area and blocked with it.+ #[test]+ fn a_rule_area_widens_the_clearance_inside_it() {+ let pads = [("J1", "A", 2.0, 2.0, false), ("J2", "A", 18.0, 2.0, false), ("J3", "B", 10.0, 5.0, false), ("J4", "B", 10.0, 8.0, false)];+ let free_at = |regions: Vec<crate::project_rules::ClearRegion>, x: f64, y: f64| {+ let mut rules = Rules::default(); rules.clearance = 0.2; rules.clear_regions = regions;+ let mut r = Router::new(board(&pads, ""), rules, false);+ let g = r.grid.clone(); let a = r.net_ids["A"];+ let (o, _, _, _) = r.obstacle_maps(a, 0.25, (0, 0, g.w as i64 - 1, g.h as i64 - 1), false);+ let (i, j) = g.to_cell(x, y); !o[F_CU].bits[j as usize * g.w + i as usize]+ };+ let hv = || vec![crate::project_rules::ClearRegion { name: "HV".into(), poly: vec![(6.0, 3.0), (14.0, 3.0), (14.0, 9.5), (6.0, 9.5)], clearance: 0.6 }];+ assert!(free_at(vec![], 11.0, 5.0), "0.5 mm from B's pad edge: clear of the 0.2 mm rule");+ assert!(!free_at(hv(), 11.0, 5.0), "inside the 0.6 mm area: blocked");+ assert!(free_at(hv(), 12.0, 5.0), "1.5 mm away: clear even in the area");+ }++ /// Issue #250: the search's own via mask refuses a cell on another net's inner track (a through via there+ /// is a short); the same net's inner track and a cell away from it are free.+ #[test]+ fn the_search_never_places_a_via_on_another_nets_inner_track() {+ let pads = [("J1", "A", 2.0, 2.0, true), ("J2", "A", 18.0, 2.0, true), ("J3", "B", 1.0, 5.0, true), ("J4", "B", 19.0, 5.0, true)];+ let mut r = Router::new(board(&pads, &seg_w("B", "In1.Cu", (1.0, 5.0), (19.0, 5.0), 0.25)), Rules::default(), false);+ let g = r.grid.clone();+ let (a, b) = (r.net_ids["A"], r.net_ids["B"]);+ let (wi, wj) = (g.w as i64 - 1, g.h as i64 - 1);+ let ok_at = |r: &mut Router, net: usize, x: f64, y: f64| { let (_, _, _, via_ok) = r.obstacle_maps(net, 0.25, (0, 0, wi, wj), false); let (i, j) = g.to_cell(x, y); via_ok.bits[j as usize * g.w + i as usize] };+ assert!(!ok_at(&mut r, a, 10.0, 5.0), "a via of A on B's inner track");+ assert!(ok_at(&mut r, a, 10.0, 8.0), "a via of A clear of it");+ assert!(ok_at(&mut r, b, 10.0, 5.0), "B's own via on its own inner track");+ }+ #[test] fn a_large_routed_board_joins_fast() { // the size of the board in issue #103: about 13k track pieces, 1.4k vias, 960 pads; 480 two-pad
crates/aiflow-router/src/lib.rs+58−2@@ -24,6 +24,7 @@ pub mod neckdown; pub mod drive; pub mod impedance; pub mod plane_under;+pub mod project_rules; pub mod rules; pub mod simplify; pub mod variants;@@ -239,6 +240,12 @@ pub struct Router { pub keep_raw: [Vec<i16>; 2], /// inner-layer planeUnder region index per cell (-1 none): blocks foreign through-vias without blocking outer tracks pub keep_inner_raw: Vec<i16>,+ /// Issue #250: the board's inner-layer tracks and blind/buried vias, per cell (the net id; -2 for copper of+ /// no routed net): a through via of another net crosses every layer and must keep clear of them. Inner zone+ /// fills are not here: a refill clears a plane around a new via, a track cannot move.+ pub inner_raw: Vec<i16>,+ /// Issue #250: each project rule area as grid cells, with its clearance (mm)+ pub region_masks: Vec<(Mask, f64)>, /// Spec decoupling pairs resolved on this board (decoupling.rs). pub pairs: Vec<decoupling::PairState>, /// The signal-net order (`route --variants`, variants.rs); the default is shortest first.@@ -296,7 +303,7 @@ impl Router { pad_cells: HashMap::new(), inside, edge_dist, inside_w: HashMap::new(), rip_total: 0, flat_turns: false, net_deadline: None, net_timed_out: false, stats: HashMap::new(), kelvin_owner: HashMap::new(), kelvin_clusters: HashSet::new(), body_owner: vec![-1; n], ic_zone: grid.mask(), ic_nets: HashMap::new(), log_lines: Vec::new(), fixed_raw: [vec![-1; n], vec![-1; n]], fixed_tracks: Vec::new(), fixed_vias: Vec::new(), pad_comp: Vec::new(), comp_copper: HashMap::new(), fixed_targets: HashMap::new(),- keep: Vec::new(), keep_raw: [vec![-1; n], vec![-1; n]], ko_track: [grid.mask(), grid.mask()], ko_via: grid.mask(), keep_inner_raw: vec![-1; n], pairs: Vec::new(), order: variants::NetOrder::default(), board,+ keep: Vec::new(), keep_raw: [vec![-1; n], vec![-1; n]], ko_track: [grid.mask(), grid.mask()], ko_via: grid.mask(), keep_inner_raw: vec![-1; n], inner_raw: vec![-1; n], region_masks: Vec::new(), pairs: Vec::new(), order: variants::NetOrder::default(), board, }; r.big_clr_val = r.rules.clearance; // issue #183: a board with no vias has no plane to stitch down to; its plane nets are routed as@@ -313,6 +320,11 @@ impl Router { r.stamp_holes(); r.stamp_board_copper(); r.stamp_plane_under();+ for reg in r.rules.clear_regions.clone() {+ let mut m = r.grid.mask();+ r.grid.poly_mask(®.poly, &mut m);+ if m.any() { r.log(format!(" clearance region {}: {:.2} mm for every net inside it", reg.name, reg.clearance)); r.region_masks.push((m, reg.clearance)); }+ } r.stamp_keepouts(); r.build_clusters(); r.build_ic_zones();@@ -963,7 +975,9 @@ impl Router { let r_o = (clr + width / 2.0 + slop()) / RES; let r_d = r_o + 0.0707 / RES; let r_big = (self.big_clr_val + width / 2.0 + slop()) / RES;- let pad_r = (r_d.max(r_big)).ceil() as i64 + 1;+ // issue #250: a project rule area's clearance reaches as far as its own radius+ let r_reg_max = self.region_masks.iter().map(|(_, c)| (c + width.max(self.nets[net].via) / 2.0 + slop() + 0.0707) / RES).fold(0.0, f64::max);+ let pad_r = (r_d.max(r_big).max(r_reg_max)).ceil() as i64 + 1; let (pi0, pj0) = ((i0 - pad_r).max(0), (j0 - pad_r).max(0)); let (pi1, pj1) = ((i1 + pad_r).min(g.w as i64 - 1), (j1 + pad_r).min(g.h as i64 - 1)); let ww = (pi1 - pi0 + 1) as usize;@@ -1006,6 +1020,35 @@ impl Router { o.or_with(&sub.dilate(&big, r_big)); let mut d = sub.dilate(&hard, r_d); d.or_with(&sub.dilate(&big, r_big + 0.0707 / RES));+ // issue #250: in a project rule area every net keeps the area's clearance: from obstacles inside it,+ // and (for a track inside or touching it) from any obstacle+ for (rm, rc) in &self.region_masks {+ let mut rsub = Mask::new(ww, hh);+ for jj in 0..hh { for ii in 0..ww { rsub.bits[jj * ww + ii] = rm.bits[(pj0 as usize + jj) * g.w + pi0 as usize + ii]; } }+ if !rsub.any() { continue; }+ let r_reg = (rc + width / 2.0 + slop()) / RES;+ let mut hin = hard.clone();+ for (b, rr) in hin.bits.iter_mut().zip(&rsub.bits) { *b = *b && *rr; }+ o.or_with(&sub.dilate(&hin, r_reg));+ d.or_with(&sub.dilate(&hin, r_reg + 0.0707 / RES));+ let halo = sub.dilate(&rsub, (width / 2.0) / RES);+ for (k, (dl, near)) in [(r_reg, &mut o), (r_reg + 0.0707 / RES, &mut d)].into_iter().enumerate() {+ let _ = k;+ let mut far = sub.dilate(&hard, dl);+ for (b, h) in far.bits.iter_mut().zip(&halo.bits) { *b = *b && *h; }+ near.or_with(&far);+ }+ let mut hrin = hard.clone();+ hrin.or_with(&other_routes);+ let rv = (rc + via / 2.0 + slop() + 0.0707) / RES;+ let mut vin = hrin.clone();+ for (b, rr) in vin.bits.iter_mut().zip(&rsub.bits) { *b = *b && *rr; }+ via_block.or_with(&sub.dilate(&vin, rv));+ let vhalo = sub.dilate(&rsub, (via / 2.0) / RES);+ let mut vfar = sub.dilate(&hrin, rv);+ for (b, h) in vfar.bits.iter_mut().zip(&vhalo.bits) { *b = *b && *h; }+ via_block.or_with(&vfar);+ } // issue #237: a keepout that forbids tracks: the track's own half width stays out (a rule area has // no clearance of its own), so a pad in the area's notch is still reached from outside let mut ko = Mask::new(ww, hh);@@ -1063,6 +1106,19 @@ impl Router { } via_block.or_with(&sub.dilate(&inner_keep, (clr + via / 2.0 + slop() + 0.0707) / RES)); }+ // issue #250: other nets' inner-layer tracks and blind/buried vias: a through via never lands on them+ {+ let mut inner = Mask::new(ww, hh);+ let mut any = false;+ for jj in 0..hh {+ let base = (pj0 as usize + jj) * g.w + pi0 as usize;+ for ii in 0..ww {+ let ir = self.inner_raw[base + ii];+ if ir != -1 && ir != nid { inner.bits[jj * ww + ii] = true; any = true; }+ }+ }+ if any { via_block.or_with(&sub.dilate(&inner, (clr + via / 2.0 + slop() + 0.0707) / RES)); }+ } if let Some(own) = self.smd_pad_cells.get(&(nid as usize)) { let mut m = Mask::new(ww, hh); for jj in 0..hh {
crates/aiflow-router/src/project_rules.rsadded+160@@ -0,0 +1,160 @@+//! Issue #250: the clearances KiCad's DRC will judge the routes by, from the board's project. The router used one+//! global clearance (plus the spec's `netClearance`); a board with a 0.6 mm high-voltage rule area got 135+//! clearance errors. Here:+//!+//! - `<board>.kicad_pro`: each net class's clearance (`net_settings.classes`), for the nets its patterns+//! (`netclass_patterns`) or assignments (`netclass_assignments`) put in it. The Default class is left out: the+//! spec's clearance stands for the rest (a board's Default can be looser than the fab's floor).+//! - `<board>.kicad_dru`: each custom rule with a `clearance` constraint and a condition the router can place:+//! `A.NetClass == 'X'` (its nets) or `insideArea('X')` / `intersectsArea('X')` (the board's rule area named X,+//! a region every net keeps that clearance in).+//!+//! Only rules that raise a clearance are taken; a condition the router cannot place is listed as not applied.+use aiflow_board::{Board, Pt};+use serde_json::Value;+use std::collections::BTreeMap;++/// A region of the board where every item keeps `clearance` (mm) from every other net's copper.+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]+pub struct ClearRegion { pub name: String, pub poly: Vec<Pt>, pub clearance: f64 }++#[derive(Debug, Default, Clone, PartialEq)]+pub struct ProjectClearances {+ /// net name -> clearance (mm), the largest that applies+ pub nets: BTreeMap<String, f64>,+ pub regions: Vec<ClearRegion>,+ /// rules with a clearance the router could not place, as written+ pub not_applied: Vec<String>,+}++/// A KiCad net class pattern (`*` and `?` wildcards) against a net name; a leading "/" is ignored on both sides.+fn glob(pat: &str, name: &str) -> bool {+ let (p, n): (Vec<char>, Vec<char>) = (pat.trim_start_matches('/').chars().collect(), name.trim_start_matches('/').chars().collect());+ fn m(p: &[char], n: &[char]) -> bool {+ match (p.first(), n.first()) {+ (None, None) => true,+ (Some('*'), _) => m(&p[1..], n) || (!n.is_empty() && m(p, &n[1..])),+ (Some('?'), Some(_)) => m(&p[1..], &n[1..]),+ (Some(a), Some(b)) if a == b => m(&p[1..], &n[1..]),+ _ => false,+ }+ }+ m(&p, &n)+}++/// The class(es) each net is in, from the project file.+fn classes_of(pro: &Value, nets: &[String]) -> BTreeMap<String, Vec<String>> {+ let mut out: BTreeMap<String, Vec<String>> = BTreeMap::new();+ let ns = &pro["net_settings"];+ if let Some(a) = ns["netclass_assignments"].as_object() {+ for (net, c) in a {+ let cs: Vec<String> = c.as_str().map(|s| vec![s.to_string()]).or_else(|| c.as_array().map(|v| v.iter().filter_map(|x| x.as_str().map(str::to_string)).collect())).unwrap_or_default();+ out.entry(net.clone()).or_default().extend(cs);+ }+ }+ for p in ns["netclass_patterns"].as_array().into_iter().flatten() {+ let (Some(pat), Some(class)) = (p["pattern"].as_str(), p["netclass"].as_str()) else { continue };+ for n in nets.iter().filter(|n| glob(pat, n)) { out.entry(n.clone()).or_default().push(class.to_string()); }+ }+ out+}++fn mm(v: &str) -> Option<f64> {+ let v = v.trim();+ if let Some(m) = v.strip_suffix("mil") { return m.trim().parse::<f64>().ok().map(|x| x * 0.0254); }+ v.trim_end_matches("mm").trim().parse::<f64>().ok()+}++/// Each `(rule ...)` of a .kicad_dru with a `clearance` minimum: (name, condition, mm).+fn dru_clearance_rules(dru: &str) -> Vec<(String, String, f64)> {+ let re_rule = regex_lite::Regex::new(r#"\(rule\s+"?([^"\s)]*)"?"#).unwrap();+ let re_cond = regex_lite::Regex::new(r#"\(condition\s+"((?:[^"\\]|\\.)*)"\)"#).unwrap();+ let re_clr = regex_lite::Regex::new(r#"\(constraint\s+clearance\s+\(min\s+([0-9.]+\s*(?:mm|mil)?)\)"#).unwrap();+ let starts: Vec<usize> = re_rule.find_iter(dru).map(|m| m.start()).collect();+ let mut out = Vec::new();+ for (k, &s) in starts.iter().enumerate() {+ let block = &dru[s..starts.get(k + 1).copied().unwrap_or(dru.len())];+ let name = re_rule.captures(block).and_then(|c| c.get(1)).map(|m| m.as_str().to_string()).unwrap_or_default();+ let (Some(c), Some(v)) = (re_cond.captures(block), re_clr.captures(block)) else { continue };+ let Some(v) = mm(&v[1]) else { continue };+ out.push((name, c[1].replace("\\'", "'").replace("\\\"", "\""), v));+ }+ out+}++/// The rule area (or any zone) named `name` on the board, as its outline.+fn area(board: &Board, name: &str) -> Option<Vec<Pt>> {+ board.root.find_all("zone").find(|z| z.find("name").and_then(|n| n.value()) == Some(name))+ .and_then(|z| z.find("polygon").and_then(|p| p.find("pts")).map(|p| p.find_all("xy").filter_map(|xy| Some((xy.number(1)?, xy.number(2)?))).collect::<Vec<Pt>>()))+ .filter(|p| p.len() >= 3)+}++/// The project's clearances for this board: `pro` and `dru` are the .kicad_pro and .kicad_dru texts (when there+/// are any), `base` the clearance the router already uses everywhere.+pub fn read(board: &Board, pro: Option<&str>, dru: Option<&str>, base: f64) -> ProjectClearances {+ let mut out = ProjectClearances::default();+ let nets: Vec<String> = board.nets.keys().cloned().collect();+ let pro: Value = pro.and_then(|t| serde_json::from_str(t).ok()).unwrap_or(Value::Null);+ let class_clr: BTreeMap<String, f64> = pro["net_settings"]["classes"].as_array().into_iter().flatten()+ .filter_map(|c| Some((c["name"].as_str()?.to_string(), c["clearance"].as_f64()?))).filter(|(n, _)| n != "Default").collect();+ let member = classes_of(&pro, &nets);+ let raise = |out: &mut ProjectClearances, net: &str, v: f64| { if v > base + 1e-9 { let e = out.nets.entry(net.to_string()).or_insert(v); if v > *e { *e = v; } } };+ for (net, cs) in &member {+ for c in cs { if let Some(&v) = class_clr.get(c) { raise(&mut out, net, v); } }+ }+ let re_class = regex_lite::Regex::new(r#"[AB]\.NetClass\s*==\s*'([^']+)'"#).unwrap();+ let re_area = regex_lite::Regex::new(r#"(?:insideArea|intersectsArea|enclosedByArea)\('([^']+)'\)"#).unwrap();+ for (name, cond, v) in dru.map(dru_clearance_rules).unwrap_or_default() {+ if v <= base + 1e-9 { continue; }+ if let Some(c) = re_area.captures(&cond) {+ match area(board, &c[1]) {+ Some(poly) => out.regions.push(ClearRegion { name: c[1].to_string(), poly, clearance: v }),+ None => out.not_applied.push(format!("rule {name}: {cond} (no board zone named {})", &c[1])),+ }+ } else if let Some(c) = re_class.captures(&cond) {+ let class = c[1].to_string();+ for (net, cs) in &member { if cs.contains(&class) { raise(&mut out, net, v); } }+ } else {+ out.not_applied.push(format!("rule {name}: {cond}"));+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ const BOARD: &str = r#"(kicad_pcb (layers (0 "F.Cu" signal) (31 "B.Cu" signal))+ (net 1 "/HV_BUS") (net 2 "/SENSE") (net 3 "GND")+ (zone (net 0) (net_name "") (layers "F&B.Cu") (name "HV") (keepout (tracks allowed) (vias allowed) (pads allowed) (copperpour allowed) (footprints allowed))+ (polygon (pts (xy 0 0) (xy 20 0) (xy 20 10) (xy 0 10))))+ (footprint "R" (layer "F.Cu") (at 5 5) (property "Reference" "R1") (pad "1" smd rect (at 0 0) (size 1 1) (layers "F.Cu") (net 1 "/HV_BUS")) (pad "2" smd rect (at 2 0) (size 1 1) (layers "F.Cu") (net 2 "/SENSE")))+ (footprint "C" (layer "F.Cu") (at 30 5) (property "Reference" "C1") (pad "1" smd rect (at 0 0) (size 1 1) (layers "F.Cu") (net 3 "GND")))+ (gr_rect (start 0 0) (end 40 20) (layer "Edge.Cuts")))"#;++ #[test]+ fn net_classes_and_rule_areas_raise_clearances_where_they_apply() {+ let b = Board::from_text("t.kicad_pcb", BOARD.to_string()).unwrap();+ let pro = r#"{"net_settings": {"classes": [{"name": "Default", "clearance": 0.1}, {"name": "Power", "clearance": 0.4}, {"name": "Tight", "clearance": 0.1}],+ "netclass_patterns": [{"netclass": "Power", "pattern": "/HV_*"}], "netclass_assignments": {"GND": "Tight"}}}"#;+ let dru = r#"(version 1)+(rule "HV area" (condition "A.insideArea('HV')") (constraint clearance (min 0.6mm)))+(rule HVnets (condition "A.NetClass == 'Power'") (constraint clearance (min 0.5mm)))+(rule weird (condition "A.Type == 'Via'") (constraint clearance (min 0.3mm)))+(rule missing (condition "A.insideArea('NOPE')") (constraint clearance (min 1.0mm)))"#;+ let c = read(&b, Some(pro), Some(dru), 0.2);+ assert_eq!(c.nets.get("/HV_BUS"), Some(&0.5), "the class's 0.4, raised to the dru rule's 0.5");+ assert!(c.nets.get("GND").is_none(), "a class tighter than the base changes nothing");+ assert_eq!(c.regions.len(), 1);+ assert_eq!((c.regions[0].name.as_str(), c.regions[0].clearance, c.regions[0].poly.len()), ("HV", 0.6, 4));+ assert_eq!(c.not_applied.len(), 2, "{:?}", c.not_applied);+ assert!(c.not_applied.iter().any(|n| n.contains("NOPE")));+ assert_eq!(read(&b, None, None, 0.2), ProjectClearances::default());+ }++ #[test]+ fn patterns_match_like_kicad() {+ assert!(glob("/HV_*", "/HV_BUS") && glob("HV_*", "/HV_BUS") && glob("V?", "V5") && !glob("HV_*", "/LV_BUS"));+ }+}
crates/aiflow-router/src/rules.rs+4−1@@ -40,6 +40,9 @@ pub struct Rules { /// net is routed on (no vias), and for a pair its partner and centre pitch. Filled by `route` /// from impedance::table, never from the spec directly. pub impedance: BTreeMap<String, ImpedanceRoute>,+ /// Issue #250: regions of the board where every item keeps a wider clearance (the project's rule areas)+ #[serde(default)]+ pub clear_regions: Vec<crate::project_rules::ClearRegion>, /// Issue #183: the copper layers the router may use (spec "routeLayers", or the project's /// `.kicad_dru` `disallow track` on a layer). Empty means both outer layers (the default). #[serde(skip_serializing_if = "Vec::is_empty")]@@ -89,7 +92,7 @@ impl Default for 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, 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(),+ 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, } }
docs/release-0.2.107.mdadded+17@@ -0,0 +1,17 @@+# AI Flow 0.2.107++Router fixes from John's 8-layer board (#250). Routing on the inner layers belongs to AI Flow: Routing+(adom/adom-aiflow-routing); these fix what AI Flow's own router got wrong on a multilayer board.++- **No through via on another net's inner track.** The board's inner-layer tracks and blind or buried vias block+ the router's through vias (a via crosses every layer): they were read for connectivity only, and 45 vias shorted+ to inner tracks. Inner zone fills stay free, since a refill clears a plane around a new via.+- **The project's clearances.** `route` reads the board's own `.kicad_pro` net classes and `.kicad_dru` custom rules:+ a class clearance or an `A.NetClass == '...'` rule widens its nets' clearance, and an `insideArea('...')` rule+ (a 0.6 mm high-voltage area, say) makes a region where every net keeps that clearance, for tracks and vias. Rules+ only widen; a rule the router cannot place is named (the gate's DRC still checks it).+- **A plan with gate errors does not land.** `land route` refuses the plan the gate found new DRC errors in+ (shorts, clearances): that copper would go onto the board. Open connections still land. `--accept-gate-errors+ "<why>"` lands it anyway, recorded.+- Tests: the Fusion translation tests that share process-wide state take turns, ending an intermittent failure when+ the suite runs in parallel.
package.json+1−1@@ -1,7 +1,7 @@ { "slug": "adom-aiflow", "type": "app",- "version": "0.2.106",+ "version": "0.2.107", "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.106",+ "version": "0.2.107", "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.",