← Commit history
Cargo.lock+10−10
@@ -4,7 +4,7 @@ version = 4  [[package]] name = "adom-aiflow"-version = "0.2.97"+version = "0.2.98" dependencies = [  "aiflow-analyze",  "aiflow-board",@@ -25,7 +25,7 @@ dependencies = [  [[package]] name = "aiflow-analyze"-version = "0.2.97"+version = "0.2.98" dependencies = [  "aiflow-board",  "serde",@@ -35,7 +35,7 @@ dependencies = [  [[package]] name = "aiflow-board"-version = "0.2.97"+version = "0.2.98" dependencies = [  "roxmltree",  "serde",@@ -44,7 +44,7 @@ dependencies = [  [[package]] name = "aiflow-bridge"-version = "0.2.97"+version = "0.2.98" dependencies = [  "aiflow-board",  "serde",@@ -53,7 +53,7 @@ dependencies = [  [[package]] name = "aiflow-copper"-version = "0.2.97"+version = "0.2.98" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -63,7 +63,7 @@ dependencies = [  [[package]] name = "aiflow-grid"-version = "0.2.97"+version = "0.2.98" dependencies = [  "aiflow-board",  "serde",@@ -72,7 +72,7 @@ dependencies = [  [[package]] name = "aiflow-place"-version = "0.2.97"+version = "0.2.98" dependencies = [  "aiflow-board",  "serde",@@ -81,7 +81,7 @@ dependencies = [  [[package]] name = "aiflow-pours"-version = "0.2.97"+version = "0.2.98" dependencies = [  "aiflow-board",  "aiflow-copper",@@ -91,7 +91,7 @@ dependencies = [  [[package]] name = "aiflow-router"-version = "0.2.97"+version = "0.2.98" dependencies = [  "aiflow-board",  "aiflow-grid",@@ -101,7 +101,7 @@ dependencies = [  [[package]] name = "aiflow-run"-version = "0.2.97"+version = "0.2.98" dependencies = [  "serde",  "serde_json",
Cargo.toml+1−1
@@ -14,7 +14,7 @@ members = [ ]  [workspace.package]-version = "0.2.97"+version = "0.2.98" edition = "2021" license = "MIT" repository = "https://wiki.adom.inc/adom/adom-aiflow"
SKILL.md+1−1
@@ -75,7 +75,7 @@ The flow is a file, `flows/board.json`: the steps in order (intake, rules, test- 4. **`route [--passes N]`**: the grid router on the current board with the spec's rules (wide nets, planes, per-net vias, Kelvin taps). If it closes short, the ERROR names the pins and the blockers and the three levers: more passes, back to placement (`place pack` the parts it names or the test points and indicators in the escape band, `place check`, route again), or take the stage yourself. Every open connection is counted, also a net the router never got back to after a rip-up (reason "never routed"), so the summary and the variant ranking see it. 5. **`gate`**: KiCad's DRC offline on the plan, inherited errors separated. Nothing lands until it passes. 6. **`land route`**, then **`pour`**, **`land vias`**, **`land pours`**: live through the bridge as native undo steps, each DRC-checked before it lands. A refused pour's ERROR says why (starved thermal reliefs, intersecting zones, clearance) and what to change in the spec. Both landings converge the live board on the plan, so you change the spec, run `pour` and land again: a via or trace already on the live board (same net, same points) is not landed twice, so a rerun after a stop resumes where it stopped (`--from <n>` starts at trace n), a reply lost to the transport is answered by reading the board and sending that one trace once more only if it did not land, a zone with its planned name and outline is kept, and every zone the flow landed that the plan no longer describes (renamed, reshaped, dropped) is removed first. Zones the board started with are never touched. A via whose copper would touch another net's track, via or pad (planned or on the board) is refused before anything lands, and so is a via within the spec's hole-to-hole minimum (`holeToHole`, default 0.2 mm) of any via or hole, or within `clearance` of another via's copper, whatever its net (the ERROR names the clash), and every landed via is read back: one that came back on another net than planned is taken back and the command errors with both nets.-4. **`route [--passes N]`**: the grid router on the current board with the spec's rules (wide nets, planes, per-net vias, Kelvin taps, `planeUnder` regions that no other net may cross on their layer). Copper already on the board (an `adopt-board` of a partly or fully routed board) is kept: its tracks and vias are obstacles, and only the connections it leaves open are planned; with nothing open it writes an empty plan with a note, which gate, `land route` and `finish` accept. Filled zones are that copper too: a pad inside a fill of its net on its layer (a through-hole pad on either layer) is joined, so a net its pours already join is skipped and named in the note. A net with a zone that has no fill in the board file is still tracked, with a WARNING to refill the zones and route again. With `planes`, a pad on the plane's own outer layer (an F.Cu pad on an F.Cu plane) sits in the pour and gets no stub or via; through-hole pads reach any plane. If it closes short, the ERROR names the pins and the blockers and the three levers: more passes, back to placement (`place pack` the parts it names or the test points and indicators in the escape band, `place check`, route again), or take the stage yourself. Every open connection is counted, also a net the router never got back to after a rip-up (reason "never routed"), so the summary and the variant ranking see it.+4. **`route [--passes N]`**: the grid router on the current board with the spec's rules (wide nets, planes, per-net vias, Kelvin taps, `planeUnder` regions that no other net may cross on their layer). The router also keeps every net out of keepout areas, the board's and those inside footprints (a sensor's no-copper body), on the layers each names: no track where tracks are forbidden, no via where vias are (issue #237). Castellated (half-hole) edge pads (`pad_prop_castellated`) sit on the outline by design: `place land`, `place verify` and the router accept them and the route lands on the pad's inner half (issue #236). It plans F.Cu and B.Cu only: on a 4- or 6-layer board it says so before routing and the inner layers are fixed copper; route inner-layer nets yourself (`take route=ai`). One net searches at most `AIFLOW_ROUTE_NET_SECONDS` (default 180) per pass, and the passes stop early when one leaves many connections open and barely improves (issue #235). Copper already on the board (an `adopt-board` of a partly or fully routed board) is kept: its tracks and vias are obstacles, and only the connections it leaves open are planned; with nothing open it writes an empty plan with a note, which gate, `land route` and `finish` accept. Filled zones are that copper too: a pad inside a fill of its net on its layer (a through-hole pad on either layer) is joined, so a net its pours already join is skipped and named in the note. A net with a zone that has no fill in the board file is still tracked, with a WARNING to refill the zones and route again. With `planes`, a pad on the plane's own outer layer (an F.Cu pad on an F.Cu plane) sits in the pour and gets no stub or via; through-hole pads reach any plane. If it closes short, the ERROR names the pins and the blockers and the three levers: more passes, back to placement (`place pack` the parts it names or the test points and indicators in the escape band, `place check`, route again), or take the stage yourself. Every open connection is counted, also a net the router never got back to after a rip-up (reason "never routed"), so the summary and the variant ranking see it.    **`route --variants N`** (issue #55, at most 8): route the same board N times with different levers and let the gates pick. The levers are the ones kicad-place-route-loop lists, in a fixed order so a rerun gives the same variants: v1 is a plain `route` (shortest nets first, the spec's vias, `--passes`), then longest first, signal vias at the spec's power via size (left out when the spec's two vias are the same), most pads first, seeded orders (seed 1, 2), shortest first with 4 more passes, longest first with power-size vias and 4 more passes; more than that are more seeds. Each variant writes `plan-route-v<k>.json`, `plan-route-v<k>-report.json` and `router-v<k>.log`, and is gated with the checks `gate` runs (the same function, routed board `board-routed-v<k>.kicad_pcb`). The ranking uses the gates alone, in order: unrouted connections; gate issues (new DRC errors, unconnected, planeUnder, switch node, courtyards and bodies, decoupling errors); copper length of the plan; via count; then the failed current and thermal screens, only when a Fields solve of that exact routed board is on the run (a Fields solve per variant is not run: it takes minutes per board, so in practice this column is empty and `analyze` runs on the winner as usual); the lower variant number breaks a full tie. Without kicad-cli the variants are ranked without the gate column and the table says so. The winner becomes `plan-route.json` exactly as a plain route would, and every variant (levers, scores, plan paths, rank) is on the route outcome under `variants`, in the ledger as `route-variants`, and in the run README as a table. **`route --pick K --why "..."`** makes variant K the route plan instead (the board must be unchanged); the reason, the thread and the gates' own pick stay on the record. Then `gate` as usual. A plain `route` is unchanged.    **Single-face / no-via boards** (issue #183, a CNC-milled one-layer board of through-hole parts): spec `"routeLayers": ["B.Cu"]` (or `["F.Cu"]`, or both) limits the router's layers, and `"vias": false` forbids every via: a layer change is made only on a through-hole pad of the same net, where the lead joins both faces. With both layers and `"vias": false`, F.Cu copper is wire jumpers on the component side (the router takes one only when B.Cu has no way through). Both keys are optional; when the spec is silent, the project's `.kicad_dru` decides (`(constraint disallow via)` turns vias off, `disallow track` on one layer leaves the other) and a NOTE says so. The rules-used line shows the layers and vias; `route` says how many connections closed on the single face and lists every jumper (`singleFace` on the route outcome and in `plan-route-report.json`, `jumpers` in route quality). Plane nets are routed as tracks, and pours, `thermal-vias` and stitch vias plan no via. Paths are cut on the pad (one path per face), so `gate` and `land route` see no via; a hand-written plan with a via, or copper on a face the board does not route, is a gate finding and `land route` lands nothing. Connections that cannot close are findings with suggestions (allow F.Cu jumpers, move or rotate a part, widen the channel), never a refusal. 5. **`gate`**: KiCad's DRC offline on the plan, inherited errors separated, plus any other-net copper inside a `planeUnder` region. Pours (and their vias) that `pour` planned and that are not landed yet go into the gate copy, so a net only the planned pours join is not read as unconnected (`plannedPours` in gate.json). Nothing lands until it passes.
bin/adom-aiflow
⋯ 1 unchanged line ⋯
crates/adom-aiflow/src/main.rs+35−1
@@ -754,6 +754,13 @@ fn flow_file(dir: &Path) -> PathBuf {     f } +/// Issue #235: the line a board with inner copper layers gets before `route` (the router plans F.Cu and B.Cu).+fn inner_layers_note(copper: &[String]) -> Option<String> {+    let inner: Vec<&String> = copper.iter().filter(|l| l.starts_with("In")).collect();+    (!inner.is_empty()).then(|| format!("this board has {} copper layers; the router plans F.Cu and B.Cu only. Its inner layers ({}) are read as fixed copper for connectivity, not routed on, so a dense board can leave many connections open. A net that cannot find a path in {} s stops (AIFLOW_ROUTE_NET_SECONDS), and the passes stop early when one barely improves on the last.",+        copper.len(), inner.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", "), aiflow_router::drive::net_time_limit().as_secs()))+}+ 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"))) }@@ -5525,6 +5532,9 @@ fn main() {             // issue #183: the copper mode (layers, vias) and where it came from, with any note on the .kicad_dru             let mode = copper_mode_of(&r);             for n in &mode.notes { note(n, &[]); }+            // issue #235: say before a long route that the inner layers of a 4- or 6-layer board are not routed+            let inner = inner_layers_note(&b.copper_layers);+            if let Some(n) = &inner { eprintln!("NOTE: {n}"); }             eprintln!("route rules used: track {} mm, clearance {} mm, via {} mm; {}; per-net widths: wide {}, mid {}{}", rules.track, rules.clearance, rules.via, mode.describe(),                 if rules.wide.is_empty() { "none".to_string() } else { rules.wide.iter().map(|(n, w)| format!("{n} {w:?}")).collect::<Vec<_>>().join(", ") },                 if rules.mid.is_empty() { "none".to_string() } else { rules.mid.iter().map(|(n, w)| format!("{n} {w:?}")).collect::<Vec<_>>().join(", ") },@@ -5608,6 +5618,7 @@ fn main() {                 let region_hint = if regions.is_empty() { String::new() } else { "A planeUnder region is a keepout for every other net on its layer: a pin inside it can only leave on the other layer. Shrink the margin, list fewer parts, or give the region a polygon that leaves that pin a way out.".to_string() };                 let mut hints = vec![format!("More passes: --passes {}.", passes + 4), format!("Or go back to placement: the blockers are {:?}; move the parts on those nets, or the test points and indicators in the escape band, with `place pack` and `place check`, then route again.", blockers.iter().take(8).collect::<Vec<_>>()), region_hint, policy_hint];                 hints.extend(single_face_hints(&mode, &unrouted, &routed_on));+                if let Some(n) = &inner { hints.insert(0, format!("{n} If the failures need the inner layers, route those nets yourself on them (`take route=ai`, the KiCad bridge's kicad_route_net with a layer), or route on the inner layers in KiCad, then route the rest.")); }                 hints.push("Or take the stage yourself: `adom-aiflow take route=ai`.".into());                 let sf = if sf_line.is_empty() { String::new() } else { format!("\n{sf_line}") };                 findings(&format!("routing closed {failed} connection(s) short after {passes} passes: {}{sf}", detail.join("; ")), &hints);@@ -7180,7 +7191,17 @@ fn main() {             }             let acked: Vec<String> = r.data["thermalViaAcks"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default();             // a Fusion run plans on the live board (the copper landed since the last snapshot), as the finish step reads it-            let b = if action == "plan" { live_board(&r, &cli, &dir).map(|l| Board::load(&l.1).unwrap_or_else(|e| err(&e, &[]))) } else { None }.unwrap_or_else(|| board_of(&r));+            let mut live_note = String::new();+            let b = if action == "plan" { live_board(&r, &cli, &dir).map(|l| Board::load(&l.1).unwrap_or_else(|e| err(&e, &[]))) } else { None }.unwrap_or_else(|| {+                let saved = board_of(&r);+                if action != "plan" { return saved; }+                // issue #230: on KiCad the copper `land route` put on the live board is not in the snapshot until+                // adopt-board: read it (kicad_routing_state) and keep the planned vias clear of it+                match r.data["remoteBoard"].as_str().filter(|s| !s.is_empty()).and_then(|rb| bridge_of(&r, &cli).live_copper(rb)) {+                    Some(live) => { let (nb, n) = thermalvias::with_live_copper(saved, &live); if n > 0 { live_note = format!("  live board: {n} track piece(s) and via(s) landed since the last adopt-board read as obstacles"); } nb }+                    None => { if r.outcomes().get("land-route").is_some() { live_note = "  NOTE: the live board could not be read (kicad_routing_state): planned on the saved board, which lacks the copper landed since the last adopt-board; `thermal-vias land` still refuses a via that would touch live copper".into(); } saved }+                }+            });             let sw = switchnode::nets(&spec, &b);             if action == "plan" {                 let (parts, plan) = thermalvias::plan_with_acknowledgements(&aiflow_pours::with_project_rules(&spec, &r.current_board()), &b, &sw, &acked);@@ -7197,6 +7218,7 @@ fn main() {                 if board_zones.is_empty() { lines.push("  board zones: none filled on the saved board; only spec.pours was read as copper".into()); }                 else { lines.push(format!("  board zones read as copper ({} filled on the saved board): {}", board_zones.len(), board_zones.join("; "))); }                 lines.extend(freshness.iter().map(|f| format!("  {f}")));+                if !live_note.is_empty() { lines.push(live_note.clone()); }                 r.outcome("thermal-vias-plan", json!({"plan": pp, "parts": parts.iter().map(|p| json!({"ref": p.reference, "net": p.net, "target": p.target, "existing": p.existing, "planned": p.planned.len(), "note": p.note, "copper": p.copper})).collect::<Vec<_>>(), "pourFreshness": freshness, "boardZones": board_zones}));                 r.save().unwrap();                 if spec["hot"].as_object().map(|o| o.is_empty()).unwrap_or(true) {@@ -9017,3 +9039,15 @@ mod compose_out_tests {         assert!(ffmpeg_ok(std::process::Command::new("sh").args(["-c", "exit 0"])));     } }++#[cfg(test)]+mod inner_layers_tests {+    /// Issue #235: a 4-layer board is told its inner layers are not routed; a 2-layer board hears nothing.+    #[test]+    fn a_board_with_inner_layers_is_told_before_routing() {+        let four: Vec<String> = ["F.Cu", "In1.Cu", "In2.Cu", "B.Cu"].iter().map(|s| s.to_string()).collect();+        let n = super::inner_layers_note(&four).unwrap();+        assert!(n.contains("4 copper layers") && n.contains("In1.Cu, In2.Cu") && n.contains("F.Cu and B.Cu only"), "{n}");+        assert!(super::inner_layers_note(&["F.Cu".to_string(), "B.Cu".to_string()]).is_none());+    }+}
crates/adom-aiflow/src/mechanical.rs+36−5
@@ -214,6 +214,24 @@ pub fn hull(pts: &[Pt]) -> Vec<Pt> {     lower } +/// 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+/// pin columns on opposite board edges) is one body per shape, never one hull spanning the board between them;+/// any other drawing is one convex hull, as before.+pub fn body_parts(fp: &sx::Node, layer: &str) -> Vec<Vec<Pt>> {+    let (mut closed, open) = layer_geometry(fp, layer);+    let (more, left) = close_loops(open, 0.01);+    closed.extend(more);+    let boxes: Vec<(f64, f64, f64, f64)> = closed.iter().map(|l| geom::bbox(l)).collect();+    let apart = |a: &(f64, f64, f64, f64), b: &(f64, f64, f64, f64)| a.2 < b.0 || b.2 < a.0 || a.3 < b.1 || b.3 < a.1;+    let separate = closed.len() >= 2 && (0..boxes.len()).all(|i| (i + 1..boxes.len()).all(|j| apart(&boxes[i], &boxes[j])))+        && left.iter().all(|q| boxes.iter().any(|b| q.0 >= b.0 - 1e-6 && q.0 <= b.2 + 1e-6 && q.1 >= b.1 - 1e-6 && q.1 <= b.3 + 1e-6));+    if separate { return closed.iter().map(|l| hull(l)).filter(|h| h.len() >= 3).collect(); }+    let all: Vec<Pt> = closed.into_iter().flatten().chain(left).collect();+    let h = hull(&all);+    if h.len() >= 3 { vec![h] } else { Vec::new() }+}+ /// Issue #153: each footprint's fitted body in board coordinates, as `check` judges bodies: the convex /// hull of its F.Fab (B.Fab) graphics, else of its courtyard; net ties and padless art have none. pub fn body_outlines(b: &Board) -> Vec<Shape> {@@ -224,11 +242,10 @@ pub fn body_outlines(b: &Board) -> Vec<Shape> {         let at = fp.find("at");         let (x, y, rot) = (at.and_then(|a| a.number(1)).unwrap_or(0.0), at.and_then(|a| a.number(2)).unwrap_or(0.0), at.and_then(|a| a.number(3)).unwrap_or(0.0));         for (fab, crt, front) in [("F.Fab", "F.CrtYd", true), ("B.Fab", "B.CrtYd", false)] {-            let pts = |layer: &str| { let (c, o) = layer_geometry(fp, layer); c.into_iter().chain(o).flatten().collect::<Vec<Pt>>() };-            let mut p = pts(fab);-            if p.len() < 3 { p = pts(crt); }-            let h = hull(&p);-            if h.len() >= 3 { out.push(Shape { reference: reference.clone(), front, polys: place(vec![h], x, y, rot) }); }+            // issue #236: separate shapes stay separate bodies (body_parts)+            let mut parts = body_parts(fp, fab);+            if parts.is_empty() { parts = body_parts(fp, crt); }+            if !parts.is_empty() { out.push(Shape { reference: reference.clone(), front, polys: place(parts, x, y, rot) }); }         }     }     out@@ -570,6 +587,20 @@ pub(crate) mod tests {         assert_eq!(r.bodies_checked, 1);     } +    #[test]+    fn two_separate_fab_shapes_are_two_bodies_and_one_shape_with_marks_is_one() {+        // issue #236: an edge connector's two pin columns 20 mm apart+        let two = sx::parse(r#"(footprint "Edge" (at 0 0)+          (fp_rect (start -11 -5) (end -9 5) (layer "F.Fab")) (fp_rect (start 9 -5) (end 11 5) (layer "F.Fab")))"#).unwrap();+        let parts = body_parts(&two, "F.Fab");+        assert_eq!(parts.len(), 2);+        assert!(parts.iter().all(|p| { let b = geom::bbox(p); b.2 - b.0 <= 2.0 + 1e-6 }), "{parts:?}");+        // one body rectangle with a pin-1 mark inside it stays one hull+        let one = sx::parse(r#"(footprint "IC" (at 0 0)+          (fp_rect (start -2 -2) (end 2 2) (layer "F.Fab")) (fp_line (start -2 -1) (end -1 -2) (layer "F.Fab")))"#).unwrap();+        assert_eq!(body_parts(&one, "F.Fab").len(), 1);+    }+     #[test]     fn a_courtyard_drawn_with_lines_is_closed_and_an_l_shape_is_not_hulled() {         // an L-shaped courtyard: a part tucked into the notch must not count as overlapping
crates/adom-aiflow/src/placement_verify.rs+6
@@ -58,6 +58,12 @@ fn edge_connector(board: &Board, p: &Value, spec: &Value) -> bool { edge_connect /// `aiflow_place::copper_outside`, the same check `placement.edgeOverhang` (#95) applies before landing. pub fn edge_connector_why(board: &Board, p: &Value, spec: &Value) -> Result<(),String> {     let reference=p["ref"].as_str().ok_or("missing reference")?;+    // issue #236: castellated (half-hole) edge pads sit on the outline by design: the part is accepted when every+    // other pad and its footprint copper are inside+    if board.pads.iter().any(|q| q.reference==reference && board.castellated_on_edge(q)) {+        let outside=aiflow_place::copper_outside(board,&[reference.to_string()]);+        return if outside.is_empty() { Ok(()) } else { Err(format!("{reference}: castellated edge pads may cross the outline, its other copper may not: {}",outside.join("; "))) };+    }     let c=&spec["placement"]["edgeConnectors"][reference];     if c.is_null() {         let overhang=aiflow_place::edge_overhang(spec).unwrap_or_default();
crates/adom-aiflow/src/testplan.rs+9−3
@@ -418,10 +418,16 @@ pub fn sided_bodies(b: &Board) -> Vec<(String, bool, (f64, f64, f64, f64))> {             if let Some(bb) = b.pad_box(r) { out.push((r.clone(), !fp.layer.starts_with("B."), bb)); }             continue;         }-        for (is_front, pts) in [(true, &front), (false, &back)] {+        for (is_front, pts, layer) in [(true, &front, "F.Fab"), (false, &back, "B.Fab")] {             if pts.len() < 2 { continue; }-            let placed: Vec<(f64, f64)> = pts.iter().map(|&(dx, dy)| { let (a, c) = geom::rot_kicad(dx, dy, fp.rot); (fp.x + a, fp.y + c) }).collect();-            out.push((r.clone(), is_front, geom::bbox(&placed)));+            let place = |ps: &[(f64, f64)]| -> Vec<(f64, f64)> { ps.iter().map(|&(dx, dy)| { let (a, c) = geom::rot_kicad(dx, dy, fp.rot); (fp.x + a, fp.y + c) }).collect() };+            // issue #236: a body drawn as separate shapes (an edge connector's two pin columns) is one box each+            let parts = crate::mechanical::body_parts(&node, layer);+            if parts.len() >= 2 {+                for part in parts { out.push((r.clone(), is_front, geom::bbox(&place(&part)))); }+                continue;+            }+            out.push((r.clone(), is_front, geom::bbox(&place(pts))));         }     }     out
crates/adom-aiflow/src/thermalvias.rs+59
@@ -312,6 +312,34 @@ pub fn short(spec: &Value, b: &Board, acked: &[String]) -> Vec<(String, usize, u /// and not yet in the saved snapshot). Vias come from the live kicad_routing_state; a part's heat pads /// from the live state too when it reports them (`REF.pad` with net and centre), else from the saved /// board (landing vias moves no part). The outline is the saved board's.+/// Issue #230: the saved board with the live editor's tracks and vias added (copper `land route` put there+/// since the last adopt-board), for the planner to keep clear of. Planned holes are through vias, so a live+/// track is an obstacle whatever its layer: each goes in on F.Cu. Copper already in the saved file and nets+/// the board does not know are left out. Returns the board and how many pieces were added.+pub fn with_live_copper(b: Board, live: &aiflow_bridge::landing::LiveCopper) -> (Board, usize) {+    let have_segs = b.copper_tracks();+    let have_vias = b.vias();+    let same = |a: (f64, f64), c: (f64, f64)| (a.0 - c.0).abs() < 0.01 && (a.1 - c.1).abs() < 0.01;+    let mut extra = String::new();+    let mut n = 0;+    for sg in &live.segments {+        if sg.net.is_empty() || have_segs.iter().any(|t| (same(t.a, sg.a) && same(t.b, sg.b)) || (same(t.a, sg.b) && same(t.b, sg.a))) { continue; }+        let Ok(net) = b.net_ref_sexpr(&sg.net) else { continue };+        extra.push_str(&format!("\t(segment\n\t\t(start {} {})\n\t\t(end {} {})\n\t\t(width {})\n\t\t(layer \"F.Cu\")\n{net}\t)\n", sg.a.0, sg.a.1, sg.b.0, sg.b.1, sg.width.max(0.1)));+        n += 1;+    }+    for v in &live.vias {+        if v.net.is_empty() || have_vias.iter().any(|h| same((h.x, h.y), v.at)) { continue; }+        let Ok(net) = b.net_ref_sexpr(&v.net) else { continue };+        extra.push_str(&format!("\t(via\n\t\t(at {} {})\n\t\t(size {})\n\t\t(drill {})\n\t\t(layers \"F.Cu\" \"B.Cu\")\n{net}\t)\n", v.at.0, v.at.1, v.size.max(0.2), v.drill.max(0.1)));+        n += 1;+    }+    if n == 0 { return (b, 0); }+    let t = b.text.trim_end();+    let text = format!("{}{}\n)\n", &t[..t.len() - 1], extra);+    match Board::from_text(&b.path, text) { Ok(nb) => (nb, n), Err(_) => (b, 0) }+}+ pub fn short_live(spec: &Value, b: &Board, live: &aiflow_bridge::landing::LiveCopper, acked: &[String]) -> Vec<(String, usize, usize)> {     let vias: Vec<(String, f64, f64, f64)> = live.vias.iter().map(|v| (v.net.clone(), v.at.0, v.at.1, v.size)).collect();     let pads = |reference: &str, net: &str| -> Option<Vec<(f64, f64)>> {@@ -426,6 +454,37 @@ mod tests {         assert_eq!(super::short(&spec, &saved, &[])[0].1, 0);     } +    /// Issue #230: a track `land route` put on the live board (not yet adopted) is an obstacle for the plan.+    #[test]+    fn live_tracks_not_yet_adopted_are_kept_clear_of() {+        let text = r#"(kicad_pcb (net 0 "") (net 1 "GND") (net 2 "SIG") (layers (0 "F.Cu" signal)(31 "B.Cu" signal))+ (gr_rect (start 0 0)(end 30 30)(layer "Edge.Cuts"))+ (footprint "x" (layer "F.Cu") (at 10 10) (property "Reference" "U1")+ (pad "1" smd rect (at 0 0)(size 1 1)(layers "F.Cu")(net 1 "GND"))))"#;+        let spec = serde_json::json!({"hot":{"U1":{"watts":0.6,"tabNet":"GND"}},+            "pours":[{"net":"GND","layers":["F.Cu","B.Cu"],"polygon":[[5,5],[15,5],[15,15],[5,15]]}]});+        let saved = aiflow_board::Board::from_text("fixture", text.into()).unwrap();+        let (before, _) = super::plan(&spec, &saved, &[]);+        assert!(!before[0].planned.is_empty());+        // SIG runs live through every spot the plan chose, on a layer the snapshot does not have+        let mut segs = Vec::new();+        for (k, &(x, y)) in before[0].planned.iter().enumerate() {+            segs.push(serde_json::json!({"start": {"x": x - 0.5, "y": y}, "end": {"x": x + 0.5, "y": y}, "width": 0.25, "net_name": "SIG", "uuid": format!("s{k}")}));+        }+        segs.push(serde_json::json!({"start": {"x": 1, "y": 1}, "end": {"x": 2, "y": 1}, "width": 0.25, "net_name": "NOT_ON_BOARD", "uuid": "x"}));+        let live = aiflow_bridge::landing::LiveCopper::from_state(&serde_json::json!({"segments": segs, "vias": [], "pads": []}));+        let (merged, n) = super::with_live_copper(saved, &live);+        assert_eq!(n, before[0].planned.len(), "the unknown net is left out");+        let (after, _) = super::plan(&spec, &merged, &[]);+        for &(x, y) in &after[0].planned {+            assert!(!before[0].planned.iter().any(|&(px, py)| (px - x).hypot(py - y) < 0.3), "a via planned on the live SIG track at ({x}, {y})");+        }+        // copper already in the file is not added twice+        let (again, n2) = super::with_live_copper(merged, &live);+        assert_eq!(n2, 0);+        assert_eq!(again.copper_tracks().len(), before[0].planned.len());+    }+     #[test]     fn short_live_counts_the_vias_on_the_live_board() {         // issue #101: the saved snapshot has no vias yet; the live routing state has the landed ones
crates/aiflow-board/src/keepout.rsadded+112
@@ -0,0 +1,112 @@+//! Issue #237: keepout (rule) areas, on the board and inside footprints. A sensor footprint whose datasheet+//! forbids copper under its body ships `(zone ... (keepout (tracks not_allowed) (vias not_allowed) ...))`; the+//! router keeps tracks and vias out of them on the layers they name, and KiCad's DRC (`items_not_allowed`)+//! agrees. A footprint's zone is written in board coordinates in a .kicad_pcb (it moves with the part); a+//! polygon that sits around the origin while its part is elsewhere is read as footprint-relative instead.+use crate::{geom, reference_of, sx::{Item, Node}, Board, Pt, B_CU, F_CU};++/// One keepout area: the copper layers it covers (F.Cu 0, B.Cu 1), its outline, what it forbids, and the+/// footprint it came with (None for a board-level area).+#[derive(Debug, Clone, PartialEq)]+pub struct Keepout {+    pub layers: Vec<usize>,+    pub poly: Vec<Pt>,+    pub tracks: bool,+    pub vias: bool,+    pub owner: Option<String>,+}++fn atoms(n: &Node) -> Vec<String> {+    n.items.iter().filter_map(|it| if let Item::Atom { text, .. } = it { Some(text.clone()) } else { None }).collect()+}++fn layers_of(z: &Node) -> Vec<usize> {+    let mut names: Vec<String> = Vec::new();+    if let Some(l) = z.find("layer").and_then(|l| l.value()) { names.push(l.to_string()); }+    if let Some(ls) = z.find("layers") { names.extend(atoms(ls).into_iter().filter(|t| t != "layers")); }+    let mut out = Vec::new();+    for n in names {+        let both = n == "*.Cu" || n == "F&B.Cu";+        if (both || n == "F.Cu") && !out.contains(&F_CU) { out.push(F_CU); }+        if (both || n == "B.Cu") && !out.contains(&B_CU) { out.push(B_CU); }+    }+    out+}++fn forbids(k: &Node, what: &str) -> bool {+    k.find(what).and_then(|n| n.value()).is_some_and(|v| v == "not_allowed")+}++fn area(z: &Node, owner: Option<(String, f64, f64, f64)>) -> Option<Keepout> {+    let k = z.find("keepout")?;+    let (tracks, vias) = (forbids(k, "tracks"), forbids(k, "vias"));+    if !tracks && !vias { return None; }+    let layers = layers_of(z);+    if layers.is_empty() { return None; }+    let mut poly: Vec<Pt> = 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()).unwrap_or_default();+    if poly.len() < 3 { return None; }+    let name = owner.as_ref().map(|o| o.0.clone());+    if let Some((_, fx, fy, rot)) = owner {+        // board coordinates are the rule; a polygon centred near the origin while its part is far away is the+        // footprint's own frame (a hand-written board): place it with the part+        let (cx, cy) = poly.iter().fold((0.0, 0.0), |a, p| (a.0 + p.0, a.1 + p.1));+        let (cx, cy) = (cx / poly.len() as f64, cy / poly.len() as f64);+        let (x0, y0, x1, y1) = geom::bbox(&poly);+        let span = (x1 - x0).max(y1 - y0).max(1.0);+        if fx.hypot(fy) > 3.0 * span && cx.hypot(cy) < span && (cx - fx).hypot(cy - fy) > 3.0 * span {+            let (s, c) = (-rot.to_radians()).sin_cos();+            poly = poly.iter().map(|&(x, y)| (fx + x * c - y * s, fy + x * s + y * c)).collect();+        }+    }+    Some(Keepout { layers, poly, tracks, vias, owner: name })+}++impl Board {+    /// Every keepout area that forbids tracks or vias on F.Cu or B.Cu: the board's own, then each footprint's.+    pub fn keepouts(&self) -> Vec<Keepout> {+        let mut out: Vec<Keepout> = self.root.find_all("zone").filter_map(|z| area(z, None)).collect();+        for fp in self.root.find_all("footprint") {+            let at = fp.find("at");+            let (fx, fy, rot) = (at.and_then(|a| a.number(1)).unwrap_or(0.0), at.and_then(|a| a.number(2)).unwrap_or(0.0), at.and_then(|a| a.number(3)).unwrap_or(0.0));+            let r = reference_of(fp).unwrap_or_default();+            out.extend(fp.find_all("zone").filter_map(|z| area(z, Some((r.clone(), fx, fy, rot)))));+        }+        out+    }+}++#[cfg(test)]+mod tests {+    use super::*;++    const BOARD: &str = r#"(kicad_pcb (layers (0 "F.Cu" signal) (31 "B.Cu" signal))+  (net 1 "GND")+  (zone (net 0) (net_name "") (layers "F&B.Cu") (hatch edge 0.5)+    (keepout (tracks not_allowed) (vias allowed) (pads allowed) (copperpour allowed) (footprints allowed))+    (polygon (pts (xy 1 1) (xy 3 1) (xy 3 3) (xy 1 3))))+  (footprint "Sensor_Humidity:Sensirion_DFN-4" (layer "F.Cu") (at 20 20) (property "Reference" "U3")+    (zone (net 0) (net_name "") (layer "F.Cu") (hatch edge 0.5)+      (keepout (tracks not_allowed) (vias not_allowed) (pads allowed) (copperpour not_allowed) (footprints allowed))+      (polygon (pts (xy 19.5 19.5) (xy 20.5 19.5) (xy 20.5 20.5) (xy 19.5 20.5))))+    (pad "1" smd rect (at -0.4 0) (size 0.3 0.3) (layers "F.Cu") (net 1 "GND")))+  (footprint "Hand:Rel" (layer "F.Cu") (at 40 40 90) (property "Reference" "U4")+    (zone (net 0) (net_name "") (layers "*.Cu") (keepout (tracks allowed) (vias not_allowed))+      (polygon (pts (xy -0.5 -0.5) (xy 0.5 -0.5) (xy 0.5 0.5) (xy -0.5 0.5)))))+  (zone (net 1) (net_name "GND") (layer "B.Cu") (polygon (pts (xy 0 0) (xy 9 0) (xy 9 9) (xy 0 9))))+  (gr_rect (start 0 0) (end 50 50) (layer "Edge.Cuts")))"#;++    #[test]+    fn board_and_footprint_keepouts_are_read_with_their_layers_and_rules() {+        let b = Board::from_text("t.kicad_pcb", BOARD.to_string()).unwrap();+        let k = b.keepouts();+        assert_eq!(k.len(), 3, "{k:?}");+        assert_eq!((k[0].layers.clone(), k[0].tracks, k[0].vias, k[0].owner.clone()), (vec![F_CU, B_CU], true, false, None));+        assert_eq!((k[1].layers.clone(), k[1].tracks, k[1].vias, k[1].owner.as_deref()), (vec![F_CU], true, true, Some("U3")));+        assert_eq!(k[1].poly[0], (19.5, 19.5), "board coordinates are kept");+        // a polygon around the origin while U4 sits at (40, 40): placed with the part+        assert!(k[2].poly.iter().all(|p| (p.0 - 40.0).abs() <= 0.51 && (p.1 - 40.0).abs() <= 0.51), "{:?}", k[2].poly);+        assert!(!k[2].tracks && k[2].vias);+        // an ordinary copper zone is not a keepout+        assert!(k.iter().all(|z| z.poly[0] != (0.0, 0.0)));+    }+}
crates/aiflow-board/src/lib.rs+16−1
@@ -4,6 +4,7 @@ pub mod altium; pub mod eagle; pub mod geom;+pub mod keepout; pub mod netname; pub mod silk; pub mod sx;@@ -59,6 +60,9 @@ pub struct Pad {     pub uuid: String,     pub polys_centre: Pt,     pub clearance: f64,+    /// Issue #236: a castellated (half-hole) edge pad, KiCad's `(property pad_prop_castellated)`: centred on the+    /// board edge on purpose, the fab routes through its plated hole+    pub castellated: bool, }  impl Pad {@@ -407,6 +411,7 @@ impl Board {                     key, reference: reference.clone(), name, net, x, y, angle: pang, shape, size: (sx_, sy_), drill, thru,                     on_f: on_f && (thru || true) && on_f, on_b: on_b || thru, polys, fp_x: fx, fp_y: fy, long_axis: axis, half_long, half_short,                     uuid: pn.find("uuid").and_then(|u| u.value()).unwrap_or("").to_string(), polys_centre: (x + ccx, y + ccy), clearance: fp_clearance.max(pclr),+                    castellated: pn.find("property").and_then(|p| p.value()).is_some_and(|v| v == "pad_prop_castellated"),                 });             }         }@@ -621,6 +626,15 @@ impl Board {     }      /// A point outside the board: outside the Edge.Cuts outline (when there is one) or inside a cutout.+    /// Issue #236: a castellated pad that straddles the outline, as it should: its centre within half its size of+    /// an outline edge (the half-hole sits on the edge). Such a pad may cross the outline.+    pub fn castellated_on_edge(&self, p: &Pad) -> bool {+        if !p.castellated || self.outline.len() < 3 { return false; }+        let n = self.outline.len();+        let d = (0..n).map(|i| { let (a, b) = (self.outline[i], self.outline[(i + 1) % n]); geom::seg_distance(p.x, p.y, a.0, a.1, b.0, b.1) }).fold(f64::INFINITY, f64::min);+        d <= p.size.0.max(p.size.1) / 2.0 + 1e-6+    }+     pub fn point_outside(&self, x: f64, y: f64) -> bool {         (self.outline.len() >= 3 && !geom::point_in_poly(x, y, &self.outline)) || self.outline_cutouts.iter().any(|c| geom::point_in_poly(x, y, c))     }@@ -632,7 +646,8 @@ impl Board {         if self.outline.len() < 3 { return Vec::new(); }         self.footprints.keys().filter(|r| {             let mut pads = self.pads.iter().filter(|p| &p.reference == *r).peekable();-            pads.peek().is_some() && pads.all(|p| self.point_outside(p.x, p.y))+            // issue #236: a castellated pad centred on the edge is on the board+            pads.peek().is_some() && pads.all(|p| self.point_outside(p.x, p.y) && !self.castellated_on_edge(p))         }).cloned().collect()     } }
crates/aiflow-place/src/lib.rs+22−4
@@ -527,7 +527,8 @@ pub fn copper_outside(board: &Board, refs: &[String]) -> Vec<String> {     let mut out = Vec::new();     for r in refs {         if !board.footprints.contains_key(r) { out.push(format!("{r} is not on the board")); continue; }-        for p in board.pads.iter().filter(|p| &p.reference == r) {+        // issue #236: a castellated pad on the edge crosses the outline by design+        for p in board.pads.iter().filter(|p| &p.reference == r && !board.castellated_on_edge(p)) {             if let Some(q) = p.polys.iter().flatten().find(|q| outside(**q)) { out.push(format!("pad {} reaches outside the outline at ({:.2}, {:.2})", p.key, q.0, q.1)); }         }     }@@ -556,12 +557,14 @@ pub fn parts_outside(board: &Board, overhang: &[String]) -> Vec<(String, String)             out.push((r.clone(), format!("{r} is outside the board outline (at {:.2}, {:.2}; the outline spans x {:.2}..{:.2}, y {:.2}..{:.2})", fp.x, fp.y, x0, x1, y0, y1)));             continue;         }-        let pad_out = board.pads.iter().filter(|p| &p.reference == r).find_map(|p| p.polys.iter().flatten().find(|q| board.point_outside(q.0, q.1)).map(|q| (p.key.clone(), *q)));+        let pad_out = board.pads.iter().filter(|p| &p.reference == r && !board.castellated_on_edge(p)).find_map(|p| p.polys.iter().flatten().find(|q| board.point_outside(q.0, q.1)).map(|q| (p.key.clone(), *q)));         if let Some((k, q)) = pad_out {             out.push((r.clone(), format!("{r} reaches past the board outline: pad {k} at ({:.2}, {:.2})", q.0, q.1)));             continue;         }-        if let Some(b) = boxes.get(r) {+        // issue #236: a castellated module sits on the edge by design: its courtyard may cross it+        let on_edge = board.pads.iter().any(|p| &p.reference == r && board.castellated_on_edge(p));+        if let Some(b) = boxes.get(r).filter(|_| !on_edge) {             if b.0 < x0 - 1e-6 || b.1 < y0 - 1e-6 || b.2 > x1 + 1e-6 || b.3 > y1 + 1e-6 {                 out.push((r.clone(), format!("{r}'s courtyard reaches past the board outline (x {:.2}..{:.2}, y {:.2}..{:.2}; the outline spans x {:.2}..{:.2}, y {:.2}..{:.2})", b.0, b.2, b.1, b.3, x0, x1, y0, y1)));             }@@ -575,7 +578,7 @@ pub fn parts_outside(board: &Board, overhang: &[String]) -> Vec<(String, String) /// router sets aside, and the parts whose courtyard alone crosses the edge: their pads are inside and are routed. pub fn split_courtyard_only(board: &Board, outside: Vec<(String, String)>) -> (Vec<(String, String)>, Vec<(String, String)>) {     let whole = board.parts_outside();-    outside.into_iter().partition(|(r, _)| whole.contains(r) || board.pads.iter().any(|p| &p.reference == r && p.polys.iter().flatten().any(|q| board.point_outside(q.0, q.1))))+    outside.into_iter().partition(|(r, _)| whole.contains(r) || board.pads.iter().any(|p| &p.reference == r && !board.castellated_on_edge(p) && p.polys.iter().flatten().any(|q| board.point_outside(q.0, q.1)))) }  /// AF69: the hint for a part whose courtyard alone crosses the edge.@@ -807,4 +810,19 @@ mod tests {         std::fs::remove_dir_all(&tmp).ok();         assert!(verdict[0].1, "{verdict:?}");     }++    /// Issue #236: castellated pads on the edge are not copper outside the outline; a plain pad there is.+    #[test]+    fn castellated_edge_pads_are_not_copper_outside() {+        let t = |prop: &str| format!(r#"(kicad_pcb (layers (0 "F.Cu" signal) (31 "B.Cu" signal)) (net 1 "A")+  (gr_rect (start 0 0) (end 20 10) (layer "Edge.Cuts"))+  (footprint "M" (layer "F.Cu") (at 10 0) (property "Reference" "U1")+    (fp_rect (start -4 -1) (end 4 3) (layer "F.CrtYd") (stroke (width 0.05)))+    (pad "1" thru_hole oval (at 0 0) (size 1 1.6) (drill 0.6) {prop} (layers "*.Cu") (net 1 "A"))))"#);+        let castellated = Board::from_text("c.kicad_pcb", t("(property pad_prop_castellated)")).unwrap();+        assert!(copper_outside(&castellated, &["U1".to_string()]).is_empty());+        assert!(parts_outside(&castellated, &[]).is_empty(), "{:?}", parts_outside(&castellated, &[]));+        let plain = Board::from_text("p.kicad_pcb", t("")).unwrap();+        assert!(!copper_outside(&plain, &["U1".to_string()]).is_empty());+    } }
crates/aiflow-router/src/drive.rs+38−1
@@ -153,6 +153,11 @@ impl Router {                     break;                 }             }+            // issue #235: the net's time is up (checked every 4096 expansions)+            if expanded % 4096 == 0 && self.net_deadline.is_some_and(|d| std::time::Instant::now() > d) {+                self.net_timed_out = true;+                break;+            }             let l = n / nl;             let m = n - l * nl;             let jl = (m / ww) as i64;@@ -866,6 +871,9 @@ impl Router {         if g.in_bounds(i, j) && (0..2).any(|l| self.kept_from(&name, l, j as usize * g.w + i as usize)) {             return false;         }+        if self.via_in_keepout(x, y, rv) {+            return false;+        }         let nid = self.nets[net].idx;         for (oi, other) in self.nets.iter().enumerate() {             if other.idx == nid || oi == net {@@ -979,13 +987,17 @@ impl Router {                 self.rip(net);             }             let t1 = std::time::Instant::now();+            self.net_timed_out = false;+            self.net_deadline = Some(t1 + net_time_limit());             let blockers = self.route_net(net);+            self.net_deadline = None;             order_no += 1;             self.nets[net].routed_order = Some(order_no);             {                 let n = &self.nets[net];                 let widths: Vec<String> = n.widths.iter().map(|w| format!("{w}")).collect();-                let line = format!("  {:<28} {:>2} clusters  {}  {} routes, {} failed, {:.1}s{}", n.name, n.clusters.len(), widths.join("/"), n.routes.len(), n.failed.len(), t1.elapsed().as_secs_f64(), if n.failed.is_empty() { String::new() } else { format!("  FAILED {:?}", n.failed) });+                let line = format!("  {:<28} {:>2} clusters  {}  {} routes, {} failed, {:.1}s{}{}", n.name, n.clusters.len(), widths.join("/"), n.routes.len(), n.failed.len(), t1.elapsed().as_secs_f64(), if n.failed.is_empty() { String::new() } else { format!("  FAILED {:?}", n.failed) },+                    if self.net_timed_out { format!("  (time limit {} s reached: AIFLOW_ROUTE_NET_SECONDS raises it)", net_time_limit().as_secs()) } else { String::new() });                 self.log(line);             }             let score = self.nets.iter().filter(|n| !queue.contains(&n.idx)).map(|n| n.failed.len()).sum::<usize>() + queue.iter().map(|&q| self.nets[q].clusters.len().saturating_sub(1)).sum::<usize>();@@ -1459,6 +1471,17 @@ pub fn route_segments(g: &aiflow_grid::Grid, cells: &[Term]) -> Vec<(f64, f64, f     out } +/// Issue #235: how long one net may search in a pass, AIFLOW_ROUTE_NET_SECONDS (default 180).+pub fn net_time_limit() -> std::time::Duration {+    std::time::Duration::from_secs(std::env::var("AIFLOW_ROUTE_NET_SECONDS").ok().and_then(|v| v.parse::<u64>().ok()).filter(|v| *v > 0).unwrap_or(180))+}++/// Issue #235: a pass that leaves many connections open and barely improves on the best pass so far (under 5 %)+/// ends the passes: the board, not another pass, is what needs changing. A few hard nets keep every pass.+pub fn passes_stalled(best: usize, now: usize) -> bool {+    best > 20 && now * 100 >= best * 95+}+ /// Route a board: passes with the failed nets first; keeps the best pass. Returns (plan entries, report, failed). pub fn route_board(router: &mut Router, passes: usize, rip_per_net: usize, rip_global: usize) -> (Vec<Value>, Value, usize) {     let mut best: Option<(usize, Snapshot, usize)> = None;@@ -1475,12 +1498,17 @@ pub fn route_board(router: &mut Router, passes: usize, rip_per_net: usize, rip_g         names.sort();         names.dedup();         router.log(format!("=== pass {k}: {failed} failed connections in {names:?}"));+        let stalled = best.as_ref().is_some_and(|b| passes_stalled(b.0, failed));         if best.as_ref().map(|b| failed < b.0).unwrap_or(true) {             best = Some((failed, router.snapshot(), k));         }         if failed == 0 {             break;         }+        if stalled && k < passes {+            router.log(format!("=== pass {k} barely improved on the best pass ({failed} failed): stopping early, {} pass(es) not run; the board needs a change, not another pass", passes - k));+            break;+        }         priority = names;     }     let (failed, snap, k) = best.unwrap();@@ -1702,6 +1730,15 @@ mod single_face_tests {         assert!(sf["withJumper"].as_u64().unwrap() <= sf["singleLayer"].as_u64().unwrap(), "{sf}");     } +    #[test]+    fn passes_stop_early_only_when_many_stay_open_and_little_improves() {+        // issue #235: 287 then 280 of 370 is a stall; 12 then 12 is a few hard nets (keep passing); 287 then 200 improves+        assert!(super::passes_stalled(287, 280));+        assert!(!super::passes_stalled(12, 12));+        assert!(!super::passes_stalled(287, 200));+        assert_eq!(super::net_time_limit().as_secs() > 0, true);+    }+     #[test]     fn with_vias_off_a_via_is_never_possible_except_on_an_own_pth_pad() {         let mut r = Router::new(strip(), crate::Rules::from_spec(&json!({"vias": false})), false);
crates/aiflow-router/src/lib.rs+79−4
@@ -210,6 +210,10 @@ pub struct Router {     pub rip_total: usize,     /// Every turn costs the same in the search: the later passes of a board that will not close (issue #127).     pub flat_turns: bool,+    /// Issue #235: the wall-clock limit for one net in a pass (AIFLOW_ROUTE_NET_SECONDS, default 180 s): past it the+    /// net's searches stop and its open connections fail with that reason, so one unroutable net cannot hold a pass+    pub net_deadline: Option<std::time::Instant>,+    pub net_timed_out: bool,     pub stats: HashMap<String, i64>,     pub kelvin_owner: HashMap<usize, usize>,     pub kelvin_clusters: HashSet<(usize, usize)>,@@ -228,6 +232,10 @@ pub struct Router {     pub fixed_targets: HashMap<usize, Vec<(usize, Term)>>,     /// planeUnder regions and, per layer, the region index owning each cell (-1 none).     pub keep: Vec<plane_under::Region>,+    /// Issue #237: keepout areas (the board's and its footprints'): cells no track may cross, per layer, and+    /// cells no via may sit in+    pub ko_track: [Mask; 2],+    pub ko_via: Mask,     pub keep_raw: [Vec<i16>; 2],     /// Spec decoupling pairs resolved on this board (decoupling.rs).     pub pairs: Vec<decoupling::PairState>,@@ -283,10 +291,10 @@ impl Router {             pad_raw: [vec![-1; n], vec![-1; n]], pad_owner: [vec![-1; n], vec![-1; n]], route_raw: [vec![-1; n], vec![-1; n]],             big_clr: [grid.mask(), grid.mask()], big_clr_val: 0.0, smd_pad_cells: HashMap::new(), thru_cells: grid.mask(),             history: [vec![0; n], vec![0; n]], chan_count: vec![0; n], chan_lines: HashMap::new(), vias: Vec::new(), fp_index,-            pad_cells: HashMap::new(), inside, edge_dist, inside_w: HashMap::new(), rip_total: 0, flat_turns: false, stats: HashMap::new(), kelvin_owner: HashMap::new(), kelvin_clusters: HashSet::new(),+            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]], 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(), 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@@ -303,6 +311,7 @@ impl Router {         r.stamp_holes();         r.stamp_board_copper();         r.stamp_plane_under();+        r.stamp_keepouts();         r.build_clusters();         r.build_ic_zones();         r.init_decoupling();@@ -439,8 +448,37 @@ impl Router {         self.keep = regions;     } -    /// Is this cell of the layer inside a planeUnder region that belongs to another net?+    /// Issue #237: the board's and its footprints' keepout areas, marked per layer for tracks and for vias.+    fn stamp_keepouts(&mut self) {+        let g = self.grid.clone();+        for k in self.board.keepouts() {+            let mut m = g.mask();+            g.poly_mask(&k.poly, &mut m);+            let cells = m.bits.iter().filter(|b| **b).count();+            if cells == 0 { continue; }+            if k.tracks { for &l in &k.layers { self.ko_track[l].or_with(&m); } }+            if k.vias { self.ko_via.or_with(&m); }+            let forbids = match (k.tracks, k.vias) { (true, true) => "tracks and vias", (true, false) => "tracks", _ => "vias" };+            self.log(format!("  keepout{}: {:.1} mm2 on {}, no {forbids}", k.owner.map(|o| format!(" of {o}")).unwrap_or_default(), cells as f64 * RES * RES,+                k.layers.iter().map(|&l| aiflow_board::LAYER_NAMES[l]).collect::<Vec<_>>().join("+")));+        }+    }++    /// Issue #237: does a via of radius rv at (x, y) touch a keepout area that forbids vias? Its centre and+    /// eight points on its rim.+    pub fn via_in_keepout(&self, x: f64, y: f64, rv: f64) -> bool {+        let g = &self.grid;+        (0..9).any(|k| {+            let (px, py) = if k == 8 { (x, y) } else { let t = k as f64 * std::f64::consts::FRAC_PI_4; (x + rv * t.cos(), y + rv * t.sin()) };+            let (i, j) = g.to_cell(px, py);+            g.in_bounds(i, j) && self.ko_via.bits[j as usize * g.w + i as usize]+        })+    }++    /// Is this cell of the layer inside a planeUnder region that belongs to another net, or inside a keepout+    /// area that forbids tracks (issue #237)?     pub fn kept_from(&self, net_name: &str, l: usize, c: usize) -> bool {+        if self.ko_track[l].bits[c] { return true; }         let k = self.keep_raw[l][c];         k >= 0 && self.keep[k as usize].net != net_name     }@@ -748,6 +786,28 @@ impl Router {         let p = self.board.pads[primary].clone();         let md = p.min_dim();         self.nets[net].clusters[c].allow = if md >= 1.0 { 1.0 } else if md >= 0.5 { 0.5 } else { 0.25 };+        // issue #236: a castellated pad's centre is on the board edge, outside the routable area: the route ends+        // on the pad's own copper nearest its centre that a track of this net may reach (its inner half)+        if self.board.castellated_on_edge(&p) {+            // the widest track the net may use first, then its narrowest+            let ws = &self.nets[net].widths;+            let (wmax, wmin) = (ws.iter().cloned().fold(0.0, f64::max), ws.iter().cloned().fold(f64::INFINITY, f64::min));+            let (pi, pj) = g.to_cell(p.x, p.y);+            let mut best = None;+            for w in [wmax, wmin].into_iter().filter(|w| w.is_finite() && *w > 0.0) {+                let inside = self.inside_for(w).clone();+                best = self.pad_cells.get(&primary).and_then(|cells| cells.iter().copied().filter(|&k| inside.bits[k])+                    .min_by_key(|&k| { let (i, j) = ((k % g.w) as i64, (k / g.w) as i64); (i - pi).pow(2) + (j - pj).pow(2) }));+                if best.is_some() { break; }+            }+            if let Some(k) = best {+                let (i, j) = ((k % g.w) as i64, (k / g.w) as i64);+                let layers: Vec<usize> = if p.thru { vec![F_CU, B_CU] } else if p.on_f { vec![F_CU] } else { vec![B_CU] };+                self.nets[net].clusters[c].terminals = layers.into_iter().map(|l| Term::new(l, i, j)).collect();+                self.log(format!("  castellated {}: the route lands on its inner half at ({:.2}, {:.2})", p.key, g.to_xy(i, j).0, g.to_xy(i, j).1));+                return;+            }+        }         if p.thru {             let (i, j) = g.to_cell(p.x, p.y);             self.nets[net].clusters[c].terminals = vec![Term::new(F_CU, i, j), Term::new(B_CU, i, j)];@@ -833,7 +893,7 @@ impl Router {         samples.push((b.0, b.1, track / 2.0));         let reach = 2.5;         let net_name = self.nets[net].name.clone();-        if !self.fixed_tracks.is_empty() || !self.fixed_vias.is_empty() || !self.keep.is_empty() {+        if !self.fixed_tracks.is_empty() || !self.fixed_vias.is_empty() || !self.keep.is_empty() || self.ko_track.iter().any(|m| m.bits.iter().any(|b| *b)) {             for &(x, y, hw) in &samples {                 if self.fixed_blocks(&net_name, Some(l), x, y, hw + self.rules.clearance) {                     return false;@@ -933,6 +993,15 @@ 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 #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);+            for jj in 0..hh { for ii in 0..ww { ko.bits[jj * ww + ii] = self.ko_track[l].bits[(pj0 as usize + jj) * g.w + pi0 as usize + ii]; } }+            if ko.bits.iter().any(|b| *b) {+                let r_k = (width / 2.0 + slop()) / RES;+                o.or_with(&sub.dilate(&ko, r_k));+                d.or_with(&sub.dilate(&ko, r_k + 0.0707 / RES));+            }             for jj in 0..hh {                 for ii in 0..ww {                     let c = (pj0 as usize + jj) * g.w + pi0 as usize + ii;@@ -986,6 +1055,12 @@ impl Router {             }             via_block.or_with(&sub.dilate(&m, (via / 2.0 + slop()) / RES));         }+        // issue #237: no via in a keepout that forbids vias (its copper stays out of the area)+        {+            let mut m = Mask::new(ww, hh);+            for jj in 0..hh { for ii in 0..ww { m.bits[jj * ww + ii] = self.ko_via.bits[(pj0 as usize + jj) * g.w + pi0 as usize + ii]; } }+            if m.bits.iter().any(|b| *b) { via_block.or_with(&sub.dilate(&m, (via / 2.0 + slop()) / RES)); }+        }         // other vias: annular ring plus clearance for another net, hole to hole for this net         let mut groups: HashMap<i64, Vec<(usize, usize)>> = HashMap::new();         for &(vi, vj, vnid, dia, drill) in &self.vias {
crates/aiflow-router/src/plane_under.rs+52
@@ -170,4 +170,56 @@ mod tests {         // GND itself may use its own region         assert!(r.nets[r.net_ids["GND"]].failed.is_empty());     }++    /// Issue #236: a castellated module's half-hole pads sit on the board edge on purpose. They are on the board+    /// (not set aside, not outside), the outline checks accept them, and the router lands on their inner half.+    #[test]+    fn castellated_edge_pads_are_on_the_board_and_routed_from_inside() {+        let module = r#"(footprint "Module:Castellated" (layer "F.Cu") (at 10 0) (property "Reference" "U1")+          (fp_rect (start -4 -1) (end 4 3) (layer "F.CrtYd") (stroke (width 0.05)))+          (pad "1" thru_hole oval (at -2 0) (size 1 1.6) (drill 0.6) (property pad_prop_castellated) (layers "*.Cu" "*.Mask") (net "A"))+          (pad "2" thru_hole oval (at 2 0) (size 1 1.6) (drill 0.6) (property pad_prop_castellated) (layers "*.Cu" "*.Mask") (net "B")))"#;+        let b = board(&[("J1", "A", 4.0, 6.0, true), ("J2", "B", 16.0, 6.0, true)], module);+        let u1: Vec<_> = b.pads.iter().filter(|p| p.reference == "U1").collect();+        assert!(u1.iter().all(|p| p.castellated && b.castellated_on_edge(p)));+        assert!(b.parts_outside().is_empty(), "{:?}", b.parts_outside());+        assert!(aiflow_place_free_check(&b));+        let mut r = Router::new(b, Rules::default(), false);+        let (_, _, failed) = crate::drive::route_board(&mut r, 2, 4, 50);+        assert_eq!(failed, 0, "{}", r.log_lines.join("\n"));+        assert!(r.log_lines.iter().any(|l| l.contains("castellated U1.1")), "{}", r.log_lines.join("\n"));+    }++    /// The pads of U1 that a plain outline check would call outside: none once castellated pads are allowed.+    fn aiflow_place_free_check(b: &Board) -> bool {+        b.pads.iter().filter(|p| p.reference == "U1").all(|p| b.castellated_on_edge(p) || !p.polys.iter().flatten().any(|q| b.point_outside(q.0, q.1)))+    }++    /// Issue #237: a footprint's keepout (tracks and vias not allowed, both layers) is kept by every net: A goes+    /// around it, never through it on either layer and with no via inside.+    #[test]+    fn the_router_keeps_every_net_out_of_a_footprint_keepout() {+        let ko = r#"(footprint "Sensor:Keepout" (layer "F.Cu") (at 10 5) (property "Reference" "U9")+          (zone (net 0) (net_name "") (layers "F&B.Cu")+            (keepout (tracks not_allowed) (vias not_allowed) (pads allowed) (copperpour not_allowed) (footprints allowed))+            (polygon (pts (xy 8 2) (xy 12 2) (xy 12 8) (xy 8 8)))))"#;+        let pads = [("J1", "A", 2.0, 5.0, false), ("J2", "A", 18.0, 5.0, false)];+        let mut r = Router::new(board(&pads, ko), Rules::default(), false);+        assert!(r.ko_track[F_CU].bits.iter().any(|b| *b) && r.ko_via.bits.iter().any(|b| *b));+        let (_, _, failed) = crate::drive::route_board(&mut r, 2, 4, 50);+        assert_eq!(failed, 0);+        let a = r.net_ids["A"];+        let g = r.grid.clone();+        let inside = |x: f64, y: f64| (8.0..=12.0).contains(&x) && (2.0..=8.0).contains(&y);+        for route in &r.nets[a].routes {+            for c in &route.cells {+                let (x, y) = g.to_xy(c.i as i64, c.j as i64);+                assert!(!inside(x, y), "A runs through U9's keepout at ({x:.2}, {y:.2}) on layer {}", c.layer());+            }+        }+        for &(vi, vj, _, _, _) in &r.vias {+            let (x, y) = g.to_xy(vi as i64, vj as i64);+            assert!(!inside(x, y), "a via inside U9's keepout at ({x:.2}, {y:.2})");+        }+    } }
docs/release-0.2.98.mdadded+22
@@ -0,0 +1,22 @@+# AI Flow 0.2.98++Router fixes from user runs.++- **Footprint keepouts** (#237, chetw77cruiser). The router now keeps every net out of keepout areas, the+  board's own and those inside footprints (a humidity or pressure sensor whose datasheet forbids copper under+  its body): no track on a layer the area forbids tracks on, no via where it forbids vias. A track keeps only its+  own half width out (a rule area has no clearance), so a pad in the area's notch is still reached from outside.+  The gate's `items_not_allowed` from these areas no longer comes from the router's own plan.+- **Castellated edge pads** (#236, mohamed amine Saddi). A pad with KiCad's `pad_prop_castellated` that sits on+  the board edge is on the board: `place land`, `place check`, `place verify` and the router accept it, the+  module's courtyard may cross the edge, and the route lands on the pad's inner half. A footprint body drawn as+  separate shapes (two pin columns on opposite edges) is one body per shape in the silkscreen audit, the+  mechanical check and the test plan, so labels and bottom test points between them are no longer flagged.+- **Thermal vias and live copper** (#230, RobInMaine). `thermal-vias plan` reads the tracks and vias `land route`+  put on the live board (kicad_routing_state) and keeps the planned vias clear of them, so the plan no longer+  proposes a via on a live track of another net before `adopt-board`.+- **4-layer boards and long routes** (#235, John). `route` says before routing when a board has inner copper+  layers: the router plans F.Cu and B.Cu only and reads the inner layers as fixed copper. One net searches at most+  `AIFLOW_ROUTE_NET_SECONDS` (default 180) per pass and then fails with that reason. The passes stop early when+  one leaves more than 20 connections open and improves on the best pass by less than 5 %. Routing on the inner+  layers themselves is still to come.
package.json+1−1
@@ -1,7 +1,7 @@ {   "slug": "adom-aiflow",   "type": "app",-  "version": "0.2.97",+  "version": "0.2.98",   "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.97",+  "version": "0.2.98",   "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
@@ -65,7 +65,7 @@ The flow is a file, `flows/board.json`: the steps in order (intake, rules, test- 4. **`route [--passes N]`**: the grid router on the current board with the spec's rules (wide nets, planes, per-net vias, Kelvin taps). If it closes short, the ERROR names the pins and the blockers and the three levers: more passes, back to placement (`place pack` the parts it names or the test points and indicators in the escape band, `place check`, route again), or take the stage yourself. Every open connection is counted, also a net the router never got back to after a rip-up (reason "never routed"), so the summary and the variant ranking see it. 5. **`gate`**: KiCad's DRC offline on the plan, inherited errors separated. Nothing lands until it passes. 6. **`land route`**, then **`pour`**, **`land vias`**, **`land pours`**: live through the bridge as native undo steps, each DRC-checked before it lands. A refused pour's ERROR says why (starved thermal reliefs, intersecting zones, clearance) and what to change in the spec. Both landings converge the live board on the plan, so you change the spec, run `pour` and land again: a via or trace already on the live board (same net, same points) is not landed twice, so a rerun after a stop resumes where it stopped (`--from <n>` starts at trace n), a reply lost to the transport is answered by reading the board and sending that one trace once more only if it did not land, a zone with its planned name and outline is kept, and every zone the flow landed that the plan no longer describes (renamed, reshaped, dropped) is removed first. Zones the board started with are never touched. A via whose copper would touch another net's track, via or pad (planned or on the board) is refused before anything lands, and so is a via within the spec's hole-to-hole minimum (`holeToHole`, default 0.2 mm) of any via or hole, or within `clearance` of another via's copper, whatever its net (the ERROR names the clash), and every landed via is read back: one that came back on another net than planned is taken back and the command errors with both nets.-4. **`route [--passes N]`**: the grid router on the current board with the spec's rules (wide nets, planes, per-net vias, Kelvin taps, `planeUnder` regions that no other net may cross on their layer). Copper already on the board (an `adopt-board` of a partly or fully routed board) is kept: its tracks and vias are obstacles, and only the connections it leaves open are planned; with nothing open it writes an empty plan with a note, which gate, `land route` and `finish` accept. Filled zones are that copper too: a pad inside a fill of its net on its layer (a through-hole pad on either layer) is joined, so a net its pours already join is skipped and named in the note. A net with a zone that has no fill in the board file is still tracked, with a WARNING to refill the zones and route again. With `planes`, a pad on the plane's own outer layer (an F.Cu pad on an F.Cu plane) sits in the pour and gets no stub or via; through-hole pads reach any plane. If it closes short, the ERROR names the pins and the blockers and the three levers: more passes, back to placement (`place pack` the parts it names or the test points and indicators in the escape band, `place check`, route again), or take the stage yourself. Every open connection is counted, also a net the router never got back to after a rip-up (reason "never routed"), so the summary and the variant ranking see it.+4. **`route [--passes N]`**: the grid router on the current board with the spec's rules (wide nets, planes, per-net vias, Kelvin taps, `planeUnder` regions that no other net may cross on their layer). The router also keeps every net out of keepout areas, the board's and those inside footprints (a sensor's no-copper body), on the layers each names: no track where tracks are forbidden, no via where vias are (issue #237). Castellated (half-hole) edge pads (`pad_prop_castellated`) sit on the outline by design: `place land`, `place verify` and the router accept them and the route lands on the pad's inner half (issue #236). It plans F.Cu and B.Cu only: on a 4- or 6-layer board it says so before routing and the inner layers are fixed copper; route inner-layer nets yourself (`take route=ai`). One net searches at most `AIFLOW_ROUTE_NET_SECONDS` (default 180) per pass, and the passes stop early when one leaves many connections open and barely improves (issue #235). Copper already on the board (an `adopt-board` of a partly or fully routed board) is kept: its tracks and vias are obstacles, and only the connections it leaves open are planned; with nothing open it writes an empty plan with a note, which gate, `land route` and `finish` accept. Filled zones are that copper too: a pad inside a fill of its net on its layer (a through-hole pad on either layer) is joined, so a net its pours already join is skipped and named in the note. A net with a zone that has no fill in the board file is still tracked, with a WARNING to refill the zones and route again. With `planes`, a pad on the plane's own outer layer (an F.Cu pad on an F.Cu plane) sits in the pour and gets no stub or via; through-hole pads reach any plane. If it closes short, the ERROR names the pins and the blockers and the three levers: more passes, back to placement (`place pack` the parts it names or the test points and indicators in the escape band, `place check`, route again), or take the stage yourself. Every open connection is counted, also a net the router never got back to after a rip-up (reason "never routed"), so the summary and the variant ranking see it.    **`route --variants N`** (issue #55, at most 8): route the same board N times with different levers and let the gates pick. The levers are the ones kicad-place-route-loop lists, in a fixed order so a rerun gives the same variants: v1 is a plain `route` (shortest nets first, the spec's vias, `--passes`), then longest first, signal vias at the spec's power via size (left out when the spec's two vias are the same), most pads first, seeded orders (seed 1, 2), shortest first with 4 more passes, longest first with power-size vias and 4 more passes; more than that are more seeds. Each variant writes `plan-route-v<k>.json`, `plan-route-v<k>-report.json` and `router-v<k>.log`, and is gated with the checks `gate` runs (the same function, routed board `board-routed-v<k>.kicad_pcb`). The ranking uses the gates alone, in order: unrouted connections; gate issues (new DRC errors, unconnected, planeUnder, switch node, courtyards and bodies, decoupling errors); copper length of the plan; via count; then the failed current and thermal screens, only when a Fields solve of that exact routed board is on the run (a Fields solve per variant is not run: it takes minutes per board, so in practice this column is empty and `analyze` runs on the winner as usual); the lower variant number breaks a full tie. Without kicad-cli the variants are ranked without the gate column and the table says so. The winner becomes `plan-route.json` exactly as a plain route would, and every variant (levers, scores, plan paths, rank) is on the route outcome under `variants`, in the ledger as `route-variants`, and in the run README as a table. **`route --pick K --why "..."`** makes variant K the route plan instead (the board must be unchanged); the reason, the thread and the gates' own pick stay on the record. Then `gate` as usual. A plain `route` is unchanged.    **Single-face / no-via boards** (issue #183, a CNC-milled one-layer board of through-hole parts): spec `"routeLayers": ["B.Cu"]` (or `["F.Cu"]`, or both) limits the router's layers, and `"vias": false` forbids every via: a layer change is made only on a through-hole pad of the same net, where the lead joins both faces. With both layers and `"vias": false`, F.Cu copper is wire jumpers on the component side (the router takes one only when B.Cu has no way through). Both keys are optional; when the spec is silent, the project's `.kicad_dru` decides (`(constraint disallow via)` turns vias off, `disallow track` on one layer leaves the other) and a NOTE says so. The rules-used line shows the layers and vias; `route` says how many connections closed on the single face and lists every jumper (`singleFace` on the route outcome and in `plan-route-report.json`, `jumpers` in route quality). Plane nets are routed as tracks, and pours, `thermal-vias` and stitch vias plan no via. Paths are cut on the pad (one path per face), so `gate` and `land route` see no via; a hand-written plan with a via, or copper on a face the board does not route, is a gate finding and `land route` lands nothing. Connections that cannot close are findings with suggestions (allow F.Cu jumpers, move or rotate a part, widen the channel), never a refusal. 5. **`gate`**: KiCad's DRC offline on the plan, inherited errors separated, plus any other-net copper inside a `planeUnder` region. Pours (and their vias) that `pour` planned and that are not landed yet go into the gate copy, so a net only the planned pours join is not read as unconnected (`plannedPours` in gate.json). Nothing lands until it passes.