← Commit history

Merge PR #549: Audit via-in-pad (VIPPO) and board-level via hygiene (#217) (feat/vippo-and-via-hygiene -> main) merge

Colby Knox ·79247eb959 · ·parents f717383, af71cae

Showing changes introduced by the merge (against its first parent).

9 files changed +745−12
crates/adom-aiflow/src/gate_eval.rs+4
@@ -101,6 +101,10 @@ pub fn evaluate(r: &Run, b: &Board, plan_v: &Value, routed: &Path, base: &Value,     let quality = rb().map(|rb| crate::route_quality::of_board(&rb, &spec_g)).unwrap_or_else(|e| (json!({"error": e}), Vec::new()));     s["routeQuality"] = crate::route_quality::outcome(&quality.0, "route-quality.json");     s["netClasses"] = crate::netclasses::verify_kicad(&r.current_board(), rb().ok().as_ref(), &spec_g);+    if let Ok(rb) = rb() {+        s["vippo"] = crate::vippo::audit_vippo(&rb, &spec_g);+        s["viaHygiene"] = crate::vippo::via_hygiene(&rb, &spec_g);+    }     Ok(GateEval { s, pu, pu_issues, sw_issues, dec, mech, stairs, quality }) } 
crates/adom-aiflow/src/main.rs+65−2
@@ -42,6 +42,7 @@ mod led_states; mod programming; mod project_lib; mod netclasses;+mod vippo;  /// The timeline dashboard (tools/timeline/index.html): it receives state over SSE from its run server. const TIMELINE_PAGE: &str = include_str!("../../../tools/timeline/index.html");@@ -4018,11 +4019,28 @@ fn main() {                         }                     }                     let mut hints = order_hints;+                    // issue #217: board-wide VIPPO audit on export + IPC-4761 Type VII fab note when approved+                    let mut vippo_unapproved: Vec<String> = Vec::new();+                    if let Ok(b_exp) = Board::load(&board_path) {+                        let va = vippo::audit_vippo(&b_exp, &spec_soft(&r));+                        report["vippo"] = va.clone();+                        if va["pass"] == false {+                            vippo_unapproved = va["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();+                        } else if let Ok(Some(vp)) = vippo::write_vippo_fab_note(&out_dir, &va) {+                            if let Some(fs) = report["files"].as_array_mut() { fs.push(json!(vp.display().to_string())); }+                            hints.push(format!("IPC-4761 Type VII VIPPO fab note written: {}", vp.display()));+                        }+                        write_json(&out_dir.join("export-check.json"), &report);+                        r.outcome("export", report.clone());+                    }                     hints.extend(report["files"].as_array().into_iter().flatten().filter_map(|f| f.as_str()).map(|f| format!("file: {f}")));                     hints.push(format!("file: {}", out_dir.join(export::ORDER_NOTE).display()));                     hints.extend(report["notes"].as_array().into_iter().flatten().filter_map(|n| n.as_str()).map(str::to_string));                     hints.push("Tell the human where every file is and which ones a fab's upload takes (the gerbers folder only), and that the BOM and CPL here are for review.".into());                     if let Some(h) = molecule_publish_hint(&r) { hints.push(h); }+                    if !vippo_unapproved.is_empty() {+                        findings(&format!("manufacturing files written to {}, but unapproved via-in-pad (VIPPO) found:\n  {}", out_dir.display(), vippo_unapproved.join("\n  ")), &hints);+                    }                     // issue #160: the saved fills are older than the copper: a finding, the files are written                     if report["fillsCurrent"]["pass"] == false {                         let fc = &report["fillsCurrent"];@@ -4034,17 +4052,30 @@ fn main() {                     let checked = verified::run_items(&r, facts.as_ref());                     ok(&format!("manufacturing files in {}, checked against the board: Gerbers ({} copper layers of {}, pours present as regions on {} poured layer(s)), drill ({} hits = vias and drilled pads), pick and place ({} parts) and BOM ({} lines) for review, not a fab's upload format (a fab's own come from its ordering stage; {} says which file goes where)\n{}", winpath::shown(&out_dir), report["gerbers"]["copperLayers"], report["gerbers"]["boardCopperLayers"], report["fillsGerbers"]["layersWithPours"].as_object().map(|o| o.len()).unwrap_or(0), report["drill"]["hits"], report["cpl"]["refs"], report["bom"]["lines"], export::ORDER_NOTE, verified::message(&checked)), &hints);                 }-                Err((report, problems)) => {+                Err((mut report, problems)) => {                     let _ = std::fs::create_dir_all(&out_dir);                     write_json(&out_dir.join("export-check.json"), &report);                     let fill_hint = if problems.iter().any(|p| p.contains("filled polygon") || p.contains("G36")) { fills::HINT.to_string() } else { String::new() };                     // a dynamic skill: a set that was written but does not match the board is a finding, recorded                     // (the verified list says NO), never a stop; only kicad-cli not running is an error                     if report.get("files").is_some() {+                        let mut hints = vec![fill_hint, "Fix the board or its footprint attributes (DNP, exclude from BOM/position files) and run `export` again. Until then, tell the human which files do not match the board and why before anything is ordered.".into()];+                        if let Ok(b_exp) = Board::load(&board_path) {+                            let va = vippo::audit_vippo(&b_exp, &spec_soft(&r));+                            report["vippo"] = va.clone();+                            if va["pass"] == false {+                                for vf in va["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                                    hints.push(format!("VIPPO: {vf}"));+                                }+                            } else if let Ok(Some(vp)) = vippo::write_vippo_fab_note(&out_dir, &va) {+                                if let Some(fs) = report["files"].as_array_mut() { fs.push(json!(vp.display().to_string())); }+                                hints.push(format!("IPC-4761 Type VII VIPPO fab note written: {}", vp.display()));+                            }+                            write_json(&out_dir.join("export-check.json"), &report);+                        }                         r.outcome("export", report.clone());                         r.log("export-findings", json!({"board": board_path, "dir": out_dir, "problems": problems}));                         record_verified(&mut r, "export");-                        let mut hints = vec![fill_hint, "Fix the board or its footprint attributes (DNP, exclude from BOM/position files) and run `export` again. Until then, tell the human which files do not match the board and why before anything is ordered.".into()];                         hints.extend(report["files"].as_array().into_iter().flatten().filter_map(|f| f.as_str()).map(|f| format!("file: {f}")));                         findings(&format!("manufacturing files written to {}, but they do not check out against the board: {}", out_dir.display(), problems.join("; ")), &hints);                     }@@ -5349,6 +5380,15 @@ fn main() {             if !sf_issues.is_empty() {                 findings(&format!("gate: DRC is recorded, but the plan has {} thing(s) this board's process cannot make ({}):\n  {}", sf_issues.len(), mode.describe(), sf_issues.iter().take(12).cloned().collect::<Vec<_>>().join("\n  ")), &["Route again (`adom-aiflow route` plans no vias and changes face only on through-hole pads), or edit the plan: end the path on a through-hole pad of the net and start the next one there on the other face.".into(), "If this board can have vias after all, say \"vias\": true in the spec (and drop `disallow via` from the .kicad_dru).".into()]);             }+            if s["vippo"]["pass"] == false {+                let vf: Vec<String> = s["vippo"]["findings"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();+                findings(&format!("gate failed: unapproved via-in-pad (VIPPO):\n  {}", vf.join("\n  ")), &[+                    "Move the via outside the SMD pad (default router allowViaInPad is false), or on a VIPPO-capable 4+ layer fab set spec.fab.viaInPad = \"filled-capped\" with spec.fab.viaInPadWhy so export emits an IPC-4761 Type VII fill/cap note.".into(),+                ]);+            }+            for hf in s["viaHygiene"]["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                eprintln!("Warning (via hygiene): {hf}");+            }             let silk_n = s["silkAdvisories"].as_u64().unwrap_or(0) as usize;             if silk_n > 0 { eprintln!("Warning: {}", silk_policy::advisory_line(silk_n, &s["silkAdvisoryList"].as_array().cloned().unwrap_or_default().iter().filter_map(|v| v.as_str().map(str::to_string)).collect::<Vec<_>>())); }             if !stairs.is_empty() { eprintln!("Warning: {} staircase run(s) left in the copper (tiny alternating 0/90 degree steps; redraw as one 45 degree segment):\n  {}", stairs.len(), stairs.iter().take(8).cloned().collect::<Vec<_>>().join("\n  ")); }@@ -6104,6 +6144,29 @@ fn main() {                 let n = rows.iter().filter(|x| x["wiki"].is_string() || x["projectLib"].is_object()).filter(|x| x["mpn"].as_str().is_some_and(|m| !checked.contains(&m.to_ascii_uppercase()))).count();                 if n > 0 { quality_lines.push(format!("parts: {n} part(s) not checked against their datasheets (land, body height, maker): `adom-aiflow part-check` (aiflow-sourcing)")); }             }+            // issue #217: board-wide VIPPO audit and via-count hygiene+            {+                let b_now = board_now();+                let va = vippo::audit_vippo(&b_now, &spec_v);+                let vh = vippo::via_hygiene(&b_now, &spec_v);+                if va["pass"] == false {+                    for f in va["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                        missing.push(format!("vippo: {f}"));+                    }+                }+                let by = &vh["byClass"];+                if vh["totalVias"].as_u64().unwrap_or(0) > 0 {+                    quality_lines.push(format!(+                        "vias: {} total ({} signal-routing, {} power-fanout, {} thermal, {} stitching; avg {:.2} signal vias/net)",+                        vh["totalVias"], by["signal-routing"], by["power-fanout"], by["thermal"], by["stitching"],+                        vh["avgSignalViasPerNet"].as_f64().unwrap_or(0.0)+                    ));+                }+                for f in vh["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) {+                    quality_lines.push(format!("via hygiene: {f}"));+                }+                r.outcome("vippo-hygiene", json!({"vippo": va, "viaHygiene": vh}));+            }             // every required step before the finish line, done in order and proven             let flow_full: Value = serde_json::from_str(include_str!("../../../flows/board.json")).unwrap();             // issue #60: declared mechanical and wiring reviews, bound to this board, spec and review file
crates/adom-aiflow/src/route_variants.rs+12−5
@@ -27,7 +27,9 @@ pub struct Routed {  /// The issue #39 simplify line, from the report's "simplify" block. pub fn simp_line(simp: &Value) -> String {-    format!("simplified: {} staircase(s) replaced, {} kept (no clear 45 degree path), {} collinear point(s) merged, {} right-angle corner(s) chamfered, {} wiggle(s) made one 45 degree step; vertices {} -> {} (per net in plan-route-report.json \"simplify\")", simp["staircasesReplaced"], simp["staircasesKept"], simp["collinearMerged"], simp["cornersChamfered"].as_u64().unwrap_or(0), simp["wigglesStepped"].as_u64().unwrap_or(0), simp["verticesBefore"], simp["verticesAfter"])+    let ve = simp["viasEliminated"].as_u64().unwrap_or(0);+    let ve_s = if ve > 0 { format!(", {ve} redundant via(s) eliminated") } else { String::new() };+    format!("simplified: {} staircase(s) replaced, {} kept (no clear 45 degree path), {} collinear point(s) merged, {} right-angle corner(s) chamfered, {} wiggle(s) made one 45 degree step{ve_s}; vertices {} -> {} (per net in plan-route-report.json \"simplify\")", simp["staircasesReplaced"], simp["staircasesKept"], simp["collinearMerged"], simp["cornersChamfered"].as_u64().unwrap_or(0), simp["wigglesStepped"].as_u64().unwrap_or(0), simp["verticesBefore"], simp["verticesAfter"]) }  /// One route of `b` with `levers` (rules already carry the spec): the router, the 45 degree@@ -121,18 +123,22 @@ fn gate_summary(g: &gate_eval::GateEval) -> Value {     let mech = g.mech.as_ref().map(|m| m.errors().len() as u64).unwrap_or(0);     let dec = g.dec.as_ref().map(|d| d.errors).unwrap_or(0);     let issues = n("newErrors") + n("unconnected") + g.pu_issues.len() as u64 + g.sw_issues.len() as u64 + mech + dec;-    json!({"newErrors": n("newErrors"), "unconnected": n("unconnected"), "inheritedErrors": n("inheritedErrors"), "planeUnderIssues": g.pu_issues.len(), "switchNodeIssues": g.sw_issues.len(), "mechanicalErrors": mech, "decouplingErrors": dec, "staircases": g.stairs.len(), "routeQuality": g.s["routeQuality"], "issues": issues, "newErrorTypes": g.s["newErrorTypes"]})+    json!({"newErrors": n("newErrors"), "unconnected": n("unconnected"), "inheritedErrors": n("inheritedErrors"), "planeUnderIssues": g.pu_issues.len(), "switchNodeIssues": g.sw_issues.len(), "mechanicalErrors": mech, "decouplingErrors": dec, "staircases": g.stairs.len(), "routeQuality": g.s["routeQuality"], "vippo": g.s["vippo"], "viaHygiene": g.s["viaHygiene"], "issues": issues, "newErrorTypes": g.s["newErrorTypes"]}) }  /// The compact table `route --variants` prints and the run page shows. pub fn table(rec: &Value) -> String {-    let mut out = format!("{:<4} {:<44} {:>8} {:>6} {:>10} {:>5} {:>7} {:>4}\n", "v", "levers", "unrouted", "gate", "length mm", "vias", "fields", "rank");+    let mut out = format!("{:<4} {:<44} {:>8} {:>6} {:>10} {:>9} {:>7} {:>4}\n", "v", "levers", "unrouted", "gate", "length mm", "vias(sig)", "fields", "rank");     for v in rec["variants"].as_array().into_iter().flatten() {         let k = v["variant"].as_u64().unwrap_or(0);         let mark = if rec["chosen"].as_u64() == Some(k) { "*" } else { " " };         let gate = if !v["planError"].is_null() { "no-apply".to_string() } else if v["gate"].is_null() { if v["gateError"].is_null() { "-".to_string() } else { "error".into() } } else { v["gate"]["issues"].to_string() };         let fields = if v["fields"].is_null() { "-".to_string() } else { format!("{} fail", v["fields"]["failed"]) };-        out.push_str(&format!("{:<4} {:<44} {:>8} {:>6} {:>10.2} {:>5} {:>7} {:>4}{}\n", format!("{k}{mark}"), v["label"].as_str().unwrap_or(""), v["unrouted"].to_string(), gate, v["copperLengthMm"].as_f64().unwrap_or(0.0), v["vias"].to_string(), fields, v["rank"].to_string(), v["sameCopperAs"].as_u64().map(|j| format!("  (same copper as v{j})")).unwrap_or_default()));+        let vias_col = match v["signalVias"].as_u64() {+            Some(sv) => format!("{}({sv})", v["vias"]),+            None => v["vias"].to_string(),+        };+        out.push_str(&format!("{:<4} {:<44} {:>8} {:>6} {:>10.2} {:>9} {:>7} {:>4}{}\n", format!("{k}{mark}"), v["label"].as_str().unwrap_or(""), v["unrouted"].to_string(), gate, v["copperLengthMm"].as_f64().unwrap_or(0.0), vias_col, fields, v["rank"].to_string(), v["sameCopperAs"].as_u64().map(|j| format!("  (same copper as v{j})")).unwrap_or_default()));     }     for v in rec["variants"].as_array().into_iter().flatten() {         if let Some(e) = v["planError"].as_str() {@@ -191,11 +197,12 @@ pub fn run(r: &Run, dir: &Path, rules: &Rules, plane_under: &[String], n: usize,             Err(_) => (Value::Null, Value::Null, aiflow_copper::apply(&b, &plan_v, false).map(|x| x.1).unwrap_or(Value::Null), Value::Null),         };         let fields = routed_s.as_str().map(|p| fields_for(r, p)).unwrap_or(Value::Null);+        let sig_vias = gate["viaHygiene"]["byClass"]["signal-routing"].clone();         let v = json!({             "variant": k, "label": lv.label(), "levers": lv.to_json(rules),             "plan": planp.display().to_string(), "report": repp.display().to_string(), "planSha256": sha, "sameCopperAs": same,             "routedBoard": routed_s, "unrouted": rt.failed, "gate": gate, "gateError": gate_error, "planError": plan_error,-            "copperLengthMm": stats["copperLengthMm"], "vias": stats["vias"], "segments": stats["segments"],+            "copperLengthMm": stats["copperLengthMm"], "vias": stats["vias"], "signalVias": sig_vias, "segments": stats["segments"],             "fields": fields, "simplify": rt.simp_line, "routeSeconds": (route_s * 10.0).round() / 10.0, "seconds": (t0.elapsed().as_secs_f64() * 10.0).round() / 10.0,         });         eprintln!("  unrouted {}, gate {}, {} mm, {} vias, {:.1} s", rt.failed, if v["gate"].is_null() { "-".into() } else { v["gate"]["issues"].to_string() }, v["copperLengthMm"], v["vias"], t0.elapsed().as_secs_f64());
crates/adom-aiflow/src/vippo.rsadded+409
@@ -0,0 +1,409 @@+//! Via-in-pad (VIPPO) audit and board-level via-count hygiene (issue #217).+//!+//! 1. Board-wide VIPPO audit (`audit_vippo`):+//!    - Detects every via whose drill or pad intersects a non-through-hole SMD copper pad on a+//!      layer pierced by the via.+//!    - Separates large exposed thermal pads (pad area >= 4.0 mm^2, e.g. QFN EPAD where tented or+//!      plugged thermal via arrays may be intentional) from standard SMD component pads (0603,+//!      SOT-23, QFN/SOIC/USB signal pins).+//!    - Flags any via in a non-EPAD SMD pad unless `spec.fab.viaInPad == "filled-capped"` with a+//!      non-empty `spec.fab.viaInPadWhy` on a VIPPO-capable fab profile.+//!    - Emits an explicit IPC-4761 Type VII fill/cap note when VIPPO is approved.+//! 2. Via classification and board-level via hygiene (`via_hygiene`):+//!    - Classifies every board via into `signal-routing`, `power-fanout`, `thermal`, or `stitching`.+//!    - Reports per-class counts, signal vias per routed signal net (flagging avg > 1.0 when >= 3+//!      signal nets are routed, or any non-bus signal net with > 2 vias), and dense via clusters+//!      perforating reference planes (> 4 non-thermal vias within a 3.0 mm radius).++use std::collections::{BTreeMap, BTreeSet};+use std::path::{Path, PathBuf};++use aiflow_board::{geom, Board, Pad, Pt, Via};+use serde_json::{json, Value};++/// Pads at or above this copper area (mm^2) are classified as exposed thermal pads (e.g. QFN EPAD).+pub const EPAD_MIN_AREA_MM2: f64 = 4.0;+/// Dense non-thermal via cluster radius (mm) and count threshold (> 4 vias within 3.0 mm).+pub const CLUSTER_RADIUS_MM: f64 = 3.0;+pub const CLUSTER_MAX_VIAS: usize = 4;+/// Signal-via budget thresholds.+pub const MAX_AVG_SIGNAL_VIAS_PER_NET: f64 = 1.0;+pub const MAX_VIAS_PER_NON_BUS_NET: usize = 2;++fn r2(v: f64) -> f64 { (v * 100.0).round() / 100.0 }+fn r3(v: f64) -> f64 { (v * 1000.0).round() / 1000.0 }++fn poly_area(poly: &[Pt]) -> f64 {+    if poly.len() < 3 { return 0.0; }+    let mut sum = 0.0;+    for i in 0..poly.len() {+        let (x0, y0) = poly[i];+        let (x1, y1) = poly[(i + 1) % poly.len()];+        sum += x0 * y1 - x1 * y0;+    }+    sum.abs() * 0.5+}++pub fn pad_area_mm2(p: &Pad) -> f64 {+    let a: f64 = p.polys.iter().map(|q| poly_area(q)).sum();+    if a > 1e-6 { a } else { (2.0 * p.half_long) * (2.0 * p.half_short) }+}++fn via_touches_smd_pad(v: &Via, p: &Pad) -> bool {+    if p.thru { return false; }+    // Through-hole vias pierce both F.Cu (depth 0) and B.Cu (COPPER_BOTTOM); blind vias check span.+    let touches_layer = (p.on_f && v.span.0 == 0) || (p.on_b && v.span.1 >= aiflow_board::COPPER_BOTTOM);+    if !touches_layer { return false; }+    let r = (v.size * 0.5).max(v.drill * 0.5);+    if !p.polys.is_empty() {+        p.polys.iter().any(|q| geom::point_in_poly(v.x, v.y, q) || geom::point_poly_distance(v.x, v.y, q) < r - 1e-4)+    } else {+        (v.x - p.x).hypot(v.y - p.y) < p.half_long + r - 1e-4+    }+}++fn is_non_vippo_fab(spec: &Value, board: &Board) -> Option<String> {+    let rules = spec["fab"]["rules"].as_str().unwrap_or("").to_ascii_lowercase();+    let target = spec["fab"]["target"].as_str().unwrap_or("").to_ascii_lowercase();+    let layers = board.copper_layers.len().max(2);+    if rules.contains("3rdparty") || rules == "fab" || target.contains("3rdparty") || target == "fab" {+        return Some("3rdPartyFab does not offer resin-filled/copper-capped VIPPO".into());+    }+    if layers <= 2 && (rules.contains("jlcpcb") || target.contains("jlcpcb")) {+        return Some("budget 2-layer JLCPCB service does not include IPC-4761 Type VII VIPPO (4+ layers required)".into());+    }+    None+}++/// Audit every via on `board` for via-in-pad (VIPPO) intersections with SMD copper pads.+pub fn audit_vippo(board: &Board, spec: &Value) -> Value {+    let vias = board.vias();+    let mut smd_hits = Vec::new();+    let mut epad_hits = Vec::new();++    for v in &vias {+        for p in &board.pads {+            if !via_touches_smd_pad(v, p) { continue; }+            let area = pad_area_mm2(p);+            let entry = json!({+                "viaAt": [r3(v.x), r3(v.y)],+                "viaSizeMm": r3(v.size),+                "viaDrillMm": r3(v.drill),+                "viaNet": v.net,+                "pad": format!("{}.{}", p.reference, p.name),+                "padNet": p.net,+                "padAreaMm2": r2(area),+                "layer": if p.on_f { "F.Cu" } else { "B.Cu" },+            });+            if area >= EPAD_MIN_AREA_MM2 {+                epad_hits.push(entry);+            } else {+                smd_hits.push(entry);+            }+            break;+        }+    }++    let fab_mode = spec["fab"]["viaInPad"].as_str().unwrap_or("");+    let fab_why = spec["fab"]["viaInPadWhy"].as_str().unwrap_or("").trim();+    let fab_blocker = is_non_vippo_fab(spec, board);+    let approved = fab_mode.eq_ignore_ascii_case("filled-capped") && !fab_why.is_empty() && fab_blocker.is_none();++    let mut findings = Vec::new();+    let mut ipc4761_note: Option<String> = None;++    if !smd_hits.is_empty() {+        if approved {+            let locs: Vec<String> = smd_hits.iter().take(12).map(|h| {+                format!("{} at ({}, {})", h["pad"].as_str().unwrap_or("?"), h["viaAt"][0], h["viaAt"][1])+            }).collect();+            ipc4761_note = Some(format!(+                "IPC-4761 Type VII (filled and copper-capped VIPPO) required for {} approved via-in-pad location(s): {} (reason: {}).",+                smd_hits.len(), locs.join(", "), fab_why+            ));+        } else {+            let sample: Vec<String> = smd_hits.iter().take(8).map(|h| {+                format!("{} ({} mm2, net {}) at ({}, {})", h["pad"].as_str().unwrap_or("?"), h["padAreaMm2"], h["viaNet"].as_str().unwrap_or(""), h["viaAt"][0], h["viaAt"][1])+            }).collect();+            let reason = if let Some(b) = &fab_blocker {+                b.clone()+            } else if fab_mode.eq_ignore_ascii_case("filled-capped") {+                "spec.fab.viaInPad is \"filled-capped\" but spec.fab.viaInPadWhy is empty".into()+            } else {+                "open vias inside standard SMD pads wick solder during reflow; move vias outside the pad, or if VIPPO is intentional on a capable fab set spec.fab.viaInPad = \"filled-capped\" with spec.fab.viaInPadWhy".into()+            };+            findings.push(format!(+                "via-in-pad (VIPPO) on {} standard SMD pad(s) (< {:.1} mm2): {} ({reason})",+                smd_hits.len(), EPAD_MIN_AREA_MM2, sample.join("; ")+            ));+        }+    }++    json!({+        "pass": findings.is_empty(),+        "approvedVippo": approved,+        "fabMode": if fab_mode.is_empty() { Value::Null } else { json!(fab_mode) },+        "fabBlocker": fab_blocker,+        "smdViaInPadCount": smd_hits.len(),+        "smdViaInPad": smd_hits,+        "thermalEpadViaCount": epad_hits.len(),+        "thermalEpadVias": epad_hits,+        "ipc4761Note": ipc4761_note,+        "findings": findings,+    })+}++/// Write `vippo-fab-note.md` into `out_dir` during `export` when VIPPO is approved.+pub fn write_vippo_fab_note(out_dir: &Path, audit: &Value) -> Result<Option<PathBuf>, String> {+    let Some(note) = audit["ipc4761Note"].as_str() else { return Ok(None) };+    let path = out_dir.join("vippo-fab-note.md");+    let mut md = String::new();+    md.push_str("# Via-in-Pad (VIPPO) Fabrication Note\n\n");+    md.push_str(&format!("- **Specification:** IPC-4761 Type VII (resin-filled and copper-capped / planarized)\n"));+    md.push_str(&format!("- **Summary:** {note}\n\n"));+    md.push_str("| Pad | Net | Layer | Via X (mm) | Via Y (mm) | Via Dia / Drill (mm) |\n|---|---|---|---|---|---|\n");+    for h in audit["smdViaInPad"].as_array().into_iter().flatten() {+        md.push_str(&format!(+            "| {} | {} | {} | {} | {} | {} / {} |\n",+            h["pad"].as_str().unwrap_or(""),+            h["viaNet"].as_str().unwrap_or(""),+            h["layer"].as_str().unwrap_or(""),+            h["viaAt"][0], h["viaAt"][1],+            h["viaSizeMm"], h["viaDrillMm"]+        ));+    }+    std::fs::write(&path, md).map_err(|e| format!("{}: {e}", path.display()))?;+    Ok(Some(path))+}++fn is_bus_net(name: &str) -> bool {+    let u = name.trim_start_matches('/').to_ascii_uppercase();+    let u = u.rsplit('/').next().unwrap_or(&u);+    ["SPI", "QSPI", "I2C", "SDA", "SCL", "UART", "TX", "RX", "CAN", "USB", "ETH", "SDIO", "DDR", "DATA", "ADDR", "SWD", "JTAG"]+        .iter().any(|k| u.contains(k))+}++fn is_gnd(name: &str) -> bool {+    let u = name.trim_start_matches('/').to_ascii_uppercase();+    let u = u.rsplit('/').next().unwrap_or(&u);+    u == "GND" || u == "AGND" || u == "DGND" || u == "PGND" || u == "VSS" || u.contains("GND")+}++/// Classify board vias into `signal-routing`, `power-fanout`, `thermal`, and `stitching`, and+/// audit signal-via ratio, per-net signal via count, and dense plane-perforating via clusters.+pub fn via_hygiene(board: &Board, spec: &Value) -> Value {+    let vias = board.vias();+    let tracks = board.copper_tracks();+    let spec_pwr = crate::route_quality::spec_power(spec);++    // Thermal target pads: large EPADs (>= 4 mm^2), spec.hot references, and spec.thermalVias targets+    let mut thermal_refs: BTreeSet<String> = BTreeSet::new();+    if let Some(o) = spec["hot"].as_object() {+        for k in o.keys() { thermal_refs.insert(k.clone()); }+    }+    for tv in spec["thermalVias"].as_array().into_iter().flatten() {+        if let Some(r) = tv["ref"].as_str().or(tv["part"].as_str()) { thermal_refs.insert(r.to_string()); }+        if let Some(p) = tv["pad"].as_str() {+            if let Some(r) = p.split('.').next() { thermal_refs.insert(r.to_string()); }+        }+    }+    let thermal_pads: Vec<&Pad> = board.pads.iter().filter(|p| {+        (!p.thru && pad_area_mm2(p) >= EPAD_MIN_AREA_MM2) || thermal_refs.contains(&p.reference)+    }).collect();++    let mut counts: BTreeMap<&'static str, usize> = BTreeMap::from([+        ("signal-routing", 0),+        ("power-fanout", 0),+        ("thermal", 0),+        ("stitching", 0),+    ]);+    let mut signal_vias_by_net: BTreeMap<String, usize> = BTreeMap::new();+    let mut non_thermal_vias: Vec<(usize, &Via, &'static str)> = Vec::new();++    for (idx, v) in vias.iter().enumerate() {+        let on_thermal_pad = thermal_pads.iter().any(|p| {+            via_touches_smd_pad(v, p)+                || (p.net == v.net && !p.net.is_empty() && (v.x - p.x).hypot(v.y - p.y) <= p.half_long + 1.5 && pad_area_mm2(p) >= 1.5)+        });+        let class: &'static str = if on_thermal_pad {+            "thermal"+        } else if is_gnd(&v.net) || spec_pwr.contains(&v.net) || crate::route_quality::power_like(&v.net) {+            let touches_track = tracks.iter().any(|t| {+                t.net == v.net && ((t.a.0 - v.x).hypot(t.a.1 - v.y) <= v.size * 0.6 || (t.b.0 - v.x).hypot(t.b.1 - v.y) <= v.size * 0.6)+            });+            if is_gnd(&v.net) && !touches_track {+                "stitching"+            } else {+                "power-fanout"+            }+        } else {+            "signal-routing"+        };+        *counts.entry(class).or_insert(0) += 1;+        if class == "signal-routing" && !v.net.is_empty() {+            *signal_vias_by_net.entry(v.net.clone()).or_insert(0) += 1;+        }+        if class != "thermal" {+            non_thermal_vias.push((idx, v, class));+        }+    }++    // Count distinct routed signal nets (from tracks + signal vias)+    let mut routed_signal_nets: BTreeSet<String> = BTreeSet::new();+    for t in &tracks {+        if !t.net.is_empty() && !is_gnd(&t.net) && !spec_pwr.contains(&t.net) && !crate::route_quality::power_like(&t.net) {+            routed_signal_nets.insert(t.net.clone());+        }+    }+    for n in signal_vias_by_net.keys() { routed_signal_nets.insert(n.clone()); }+    let sig_vias = counts["signal-routing"];+    let sig_nets = routed_signal_nets.len();+    let avg_sig_vias = if sig_nets > 0 { sig_vias as f64 / sig_nets as f64 } else { 0.0 };++    // Non-bus signal nets with > 2 vias+    let mut high_via_nets = Vec::new();+    for (net, &cnt) in &signal_vias_by_net {+        if cnt > MAX_VIAS_PER_NON_BUS_NET && !is_bus_net(net) {+            high_via_nets.push(json!({"net": net, "vias": cnt}));+        }+    }++    // Dense via clusters (> 4 non-thermal vias within 3.0 mm radius), deduplicated greedily+    let mut dense_clusters = Vec::new();+    let mut used = vec![false; non_thermal_vias.len()];+    let mut order: Vec<(usize, Vec<usize>)> = (0..non_thermal_vias.len()).map(|i| {+        let vi = non_thermal_vias[i].1;+        let neigh: Vec<usize> = (0..non_thermal_vias.len())+            .filter(|&j| (non_thermal_vias[j].1.x - vi.x).hypot(non_thermal_vias[j].1.y - vi.y) <= CLUSTER_RADIUS_MM)+            .collect();+        (i, neigh)+    }).collect();+    order.sort_by(|a, b| b.1.len().cmp(&a.1.len()));+    for (_center_i, neigh) in order {+        let fresh: Vec<usize> = neigh.into_iter().filter(|&j| !used[j]).collect();+        if fresh.len() > CLUSTER_MAX_VIAS {+            let cx = fresh.iter().map(|&j| non_thermal_vias[j].1.x).sum::<f64>() / fresh.len() as f64;+            let cy = fresh.iter().map(|&j| non_thermal_vias[j].1.y).sum::<f64>() / fresh.len() as f64;+            let nets: BTreeSet<String> = fresh.iter().map(|&j| non_thermal_vias[j].1.net.clone()).collect();+            for j in &fresh { used[*j] = true; }+            dense_clusters.push(json!({+                "center": [r2(cx), r2(cy)],+                "radiusMm": CLUSTER_RADIUS_MM,+                "count": fresh.len(),+                "nets": nets.into_iter().collect::<Vec<_>>(),+            }));+        }+    }++    let mut findings = Vec::new();+    if sig_nets >= 3 && avg_sig_vias > MAX_AVG_SIGNAL_VIAS_PER_NET + 1e-6 {+        findings.push(format!(+            "high signal via ratio: {sig_vias} signal-routing via(s) across {sig_nets} signal net(s) ({avg_sig_vias:.2} vias/net, target <= {:.1})",+            MAX_AVG_SIGNAL_VIAS_PER_NET+        ));+    }+    if !high_via_nets.is_empty() {+        let list: Vec<String> = high_via_nets.iter().take(6).map(|x| format!("{} ({} vias)", x["net"].as_str().unwrap_or(""), x["vias"])).collect();+        findings.push(format!("excessive vias on non-bus signal net(s) (> {MAX_VIAS_PER_NON_BUS_NET}): {}", list.join(", ")));+    }+    for c in &dense_clusters {+        findings.push(format!(+            "dense via cluster perforating reference plane: {} vias within {:.1} mm radius around ({}, {})",+            c["count"], CLUSTER_RADIUS_MM, c["center"][0], c["center"][1]+        ));+    }++    json!({+        "pass": findings.is_empty(),+        "totalVias": vias.len(),+        "byClass": {+            "signal-routing": counts["signal-routing"],+            "power-fanout": counts["power-fanout"],+            "thermal": counts["thermal"],+            "stitching": counts["stitching"],+        },+        "signalNetsRouted": sig_nets,+        "avgSignalViasPerNet": r2(avg_sig_vias),+        "highViaSignalNets": high_via_nets,+        "denseClusters": dense_clusters,+        "findings": findings,+    })+}++#[cfg(test)]+mod tests {+    use super::*;++    fn mk_board(vias: &str, segs: &str, layers: &str) -> Board {+        let pcb = format!(+            "(kicad_pcb (version 20241229) (generator \"test\") (general (thickness 1.6)) \+             (layers {layers} (25 \"Edge.Cuts\" user)) \+             (net 0 \"\") (net 1 \"SIG_A\") (net 2 \"SIG_B\") (net 3 \"SIG_C\") (net 4 \"GND\") (net 5 \"VIN\") \+             (footprint \"Resistor_SMD:R_0603\" (layer \"F.Cu\") (at 10 10) (property \"Reference\" \"R1\") \+              (pad \"1\" smd rect (at -0.8 0) (size 0.8 0.9) (layers \"F.Cu\") (net 1 \"SIG_A\")) \+              (pad \"2\" smd rect (at 0.8 0) (size 0.8 0.9) (layers \"F.Cu\") (net 4 \"GND\"))) \+             (footprint \"Package_DFN_QFN:QFN-24\" (layer \"F.Cu\") (at 25 10) (property \"Reference\" \"U1\") \+              (pad \"25\" smd rect (at 0 0) (size 3.0 3.0) (layers \"F.Cu\") (net 4 \"GND\"))) \+             {segs} {vias} \+             (gr_rect (start 0 0) (end 40 20) (layer \"Edge.Cuts\") (stroke (width 0.1) (type solid))))"+        );+        Board::from_text("vippo-test.kicad_pcb", pcb).unwrap()+    }++    #[test]+    fn vippo_separates_smd_pad_from_qfn_epad_and_enforces_fab_approval() {+        let l4 = "(0 \"F.Cu\" signal) (4 \"In1.Cu\" signal) (6 \"In2.Cu\" signal) (2 \"B.Cu\" signal)";+        // One via inside R1.1 (0.72 mm^2 SMD pad) and one via inside U1.25 (9.0 mm^2 EPAD)+        let b = mk_board(+            "(via (at 9.2 10) (size 0.5) (drill 0.25) (layers \"F.Cu\" \"B.Cu\") (net 1)) \+             (via (at 25 10) (size 0.5) (drill 0.25) (layers \"F.Cu\" \"B.Cu\") (net 4))",+            "", l4+        );+        let unapproved = audit_vippo(&b, &json!({"fab": {"rules": "jlcpcb-4L"}}));+        assert_eq!(unapproved["pass"], false, "{unapproved}");+        assert_eq!(unapproved["smdViaInPadCount"], 1);+        assert_eq!(unapproved["thermalEpadViaCount"], 1);++        // Approved on 4L JLCPCB with reason -> passes and emits IPC-4761 Type VII note+        let approved = audit_vippo(&b, &json!({"fab": {"rules": "jlcpcb-4L", "viaInPad": "filled-capped", "viaInPadWhy": "0.4mm BGA/QFN escape"}}));+        assert_eq!(approved["pass"], true, "{approved}");+        assert!(approved["ipc4761Note"].as_str().unwrap().contains("IPC-4761 Type VII"));++        // Refused on 3rdPartyFab even if filled-capped requested+        let bad_fab = audit_vippo(&b, &json!({"fab": {"rules": "fab", "viaInPad": "filled-capped", "viaInPadWhy": "test"}}));+        assert_eq!(bad_fab["pass"], false, "{bad_fab}");++        // Thermal EPAD via alone passes without VIPPO approval+        let b_epad_only = mk_board("(via (at 25 10) (size 0.5) (drill 0.25) (layers \"F.Cu\" \"B.Cu\") (net 4))", "", l4);+        let epad_ok = audit_vippo(&b_epad_only, &json!({"fab": {"rules": "jlcpcb-4L"}}));+        assert_eq!(epad_ok["pass"], true, "{epad_ok}");+        assert_eq!(epad_ok["thermalEpadViaCount"], 1);+    }++    #[test]+    fn via_hygiene_classifies_vias_and_catches_dense_cluster_and_high_signal_ratio() {+        let l4 = "(0 \"F.Cu\" signal) (4 \"In1.Cu\" signal) (6 \"In2.Cu\" signal) (2 \"B.Cu\" signal)";+        let segs = "(segment (start 2 5) (end 15 5) (width 0.2) (layer \"F.Cu\") (net 1)) \+                    (segment (start 2 7) (end 15 7) (width 0.2) (layer \"F.Cu\") (net 2)) \+                    (segment (start 2 9) (end 15 9) (width 0.2) (layer \"F.Cu\") (net 3)) \+                    (segment (start 2 15) (end 15 15) (width 0.5) (layer \"F.Cu\") (net 5))";+        // 5 clustered vias within 2 mm around (15, 5) + 1 thermal via on EPAD + 1 stitching GND via + 1 power fanout via+        let vias = "(via (at 15.0 5.0) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 1)) \+                    (via (at 15.8 5.0) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 1)) \+                    (via (at 16.6 5.0) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 1)) \+                    (via (at 15.0 6.0) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 2)) \+                    (via (at 15.8 6.0) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 3)) \+                    (via (at 25.0 10.0) (size 0.5) (drill 0.25) (layers \"F.Cu\" \"B.Cu\") (net 4)) \+                    (via (at 35.0 15.0) (size 0.6) (drill 0.3) (layers \"F.Cu\" \"B.Cu\") (net 4)) \+                    (via (at 15.0 15.0) (size 0.8) (drill 0.4) (layers \"F.Cu\" \"B.Cu\") (net 5))";+        let b = mk_board(vias, segs, l4);+        let h = via_hygiene(&b, &json!({}));+        assert_eq!(h["pass"], false, "{h}");+        assert_eq!(h["byClass"]["signal-routing"], 5);+        assert_eq!(h["byClass"]["thermal"], 1);+        assert_eq!(h["byClass"]["stitching"], 1);+        assert_eq!(h["byClass"]["power-fanout"], 1);+        assert_eq!(h["highViaSignalNets"].as_array().unwrap().len(), 1);+        assert_eq!(h["denseClusters"].as_array().unwrap().len(), 1);+    }+}
crates/aiflow-router/src/drive.rs+1−1
@@ -330,7 +330,7 @@ impl Router {         let mut allpts: Vec<(i64, i64)> = cl.terminals.iter().map(|t| (t.i as i64, t.j as i64)).collect();         allpts.extend_from_slice(anchor);         let mut vip_src = Vec::new();-        let vip = vip && self.rules.vias_allowed();   // issue #183: via-in-pad is a via+        let vip = vip && self.rules.vias_allowed() && self.rules.allow_via_in_pad;   // issues #183, #217: via-in-pad requires opt-in         if vip {             vip_src = self.vip_cells(net, &[cluster]);             let connected: Vec<usize> = self.nets[net].clusters.iter().filter(|c| c.connected).map(|c| c.idx).collect();
crates/aiflow-router/src/rules.rs+11−1
@@ -49,6 +49,11 @@ pub struct Rules {     /// same net, where the component lead joins both faces.     #[serde(skip_serializing_if = "is_true")]     pub vias: bool,+    /// Issue #217: default false so the grid router does not silently fall back to via-in-pad on+    /// SMD signal pads. Set `"allowViaInPad": true` (or `"fab": {"viaInPad": "filled-capped"}`) to+    /// opt in on a VIPPO-capable fab.+    #[serde(default)]+    pub allow_via_in_pad: bool, }  fn is_true(b: &bool) -> bool { *b }@@ -85,7 +90,7 @@ impl Default for 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(),-            route_layers: Vec::new(), vias: true,+            route_layers: Vec::new(), vias: true, allow_via_in_pad: false,         }     } }@@ -118,6 +123,11 @@ impl Rules {         }         if let Some(v) = num("edgeClearance") { r.edge = v; }         if let Some(v) = num("holeToHoleClearance").or_else(||num("holeToHole")) { r.hole_to_hole = v; }+        if spec.get("allowViaInPad").and_then(|v| v.as_bool()) == Some(true)+            || spec.get("fab").and_then(|f| f.get("viaInPad")).and_then(|v| v.as_str()).is_some_and(|s| s.eq_ignore_ascii_case("filled-capped"))+        {+            r.allow_via_in_pad = true;+        }         // `trackWidth` is read as `track` (issue #165), `track` wins when both are there         if let Some(v) = num("track").or_else(|| num("trackWidth")) { r.track = v; }         // Escape necks inherit the requested track width. An explicit smaller
crates/aiflow-router/src/simplify.rs+105−2
@@ -544,12 +544,83 @@ fn resolve(board: &Board, v: &Value) -> Option<Wp> {  fn round(v: f64) -> f64 { (v * 1e6).round() / 1e6 } +/// Post-route via-elimination pass (issue #217): flattens short layer-flip via pairs+/// (`layer_A -> via -> layer_B (<= 15 mm, no pads/joins) -> via -> layer_A`) back onto `layer_A`+/// whenever every flattened segment passes the router's own obstacle clearance check.+fn eliminate_redundant_vias(+    router: &mut Router,+    net: &str,+    width: f64,+    entry_layer: &Option<String>,+    path: &mut Vec<Value>,+    joins: &[(Pt, f64)],+) -> usize {+    const MAX_FLIP_MM: f64 = 15.0;+    let mut removed_vias = 0usize;+    loop {+        if path.len() < 4 { break; }+        let rs: Vec<Option<Wp>> = path.iter().map(|v| resolve(&router.board, v)).collect();+        if rs.iter().any(|w| w.is_none()) { break; }+        let rs: Vec<Wp> = rs.into_iter().map(Option::unwrap).collect();+        let mut cur_layer = entry_layer.clone().or_else(|| rs[0].layer.clone()).unwrap_or_else(|| {+            let pad_of = |v: &Value| v.as_str().or_else(|| v.get("pad").and_then(|p| p.as_str())).and_then(|k| router.board.pad_by_key(k));+            Board::path_start_layer(path.iter().zip(&rs).map(|(v, w)| (pad_of(v), w.layer.is_some()))).into()+        });+        let mut seg_layer = Vec::with_capacity(rs.len());+        let mut flips = Vec::new();+        for (idx, w) in rs.iter().enumerate() {+            let nxt = w.layer.clone().unwrap_or_else(|| cur_layer.clone());+            if nxt != cur_layer {+                flips.push(idx);+                cur_layer = nxt;+            }+            seg_layer.push(cur_layer.clone());+        }+        let mut did_flatten = false;+        for win in flips.windows(2) {+            let (i, j) = (win[0], win[1]);+            if i == 0 || j >= rs.len() { continue; }+            let layer_before = &seg_layer[i - 1];+            let layer_mid = &seg_layer[i];+            let layer_after = &seg_layer[j];+            if layer_before != layer_after || layer_before == layer_mid { continue; }+            let Some(la) = (match layer_before.as_str() { "F.Cu" => Some(F_CU), "B.Cu" => Some(B_CU), _ => None }) else { continue };+            // Do not flatten across a named pad or an external branch join+            let touches_pad = (i..=j).any(|q| path[q].is_string() || path[q].get("pad").is_some());+            if touches_pad { continue; }+            let touches_join = (i..=j).any(|q| joins.iter().any(|&(jp, jr)| len(rs[q].xy, jp) <= jr.max(0.05)));+            if touches_join { continue; }+            let excursion_len: f64 = (i..j).map(|q| len(rs[q].xy, rs[q + 1].xy)).sum();+            if excursion_len > MAX_FLIP_MM { continue; }+            let all_clear = (i..j).all(|q| router.segment_clear(net, la, rs[q].xy, rs[q + 1].xy, width));+            if !all_clear { continue; }+            // Flatten waypoints i..=j onto layer_before (drop layer override objects)+            for q in i..=j {+                if let Some(o) = path[q].as_object() {+                    if o.contains_key("layer") && o.get("pad").is_none() {+                        path[q] = json!([round(rs[q].xy.0), round(rs[q].xy.1)]);+                    }+                }+            }+            for q in i..j {+                router.stamp_segment(net, la, rs[q].xy, rs[q + 1].xy, width);+            }+            removed_vias += 2;+            did_flatten = true;+            break;+        }+        if !did_flatten { break; }+    }+    removed_vias+}+ /// Simplify every path of a plan in place; returns the report (vertex count per net before and-/// after, staircases replaced and kept, collinear points merged).+/// after, staircases replaced and kept, collinear points merged, redundant vias eliminated). pub fn simplify_plan(router: &mut Router, plan: &mut [Value]) -> Value {     let mut per_net: BTreeMap<String, (usize, usize)> = BTreeMap::new();     let mut total = Counts::default();     let mut smooth = Smooth::default();+    let mut vias_eliminated = 0usize;     // every point another path of a net can join at, per net: each path's ends and layer changes     let mut path_joins: HashMap<String, Vec<Vec<Pt>>> = HashMap::new();     for e in plan.iter() {@@ -669,6 +740,9 @@ pub fn simplify_plan(router: &mut Router, plan: &mut [Value]) -> Value {                 }                 i = k;             }+            if !pair {+                vias_eliminated += eliminate_redundant_vias(router, &net, width, &entry_layer, &mut new_path, &joins);+            }             entry.1 += new_path.len();             out_paths.push(Value::Array(new_path));         }@@ -676,7 +750,7 @@ pub fn simplify_plan(router: &mut Router, plan: &mut [Value]) -> Value {     }     let nets: serde_json::Map<String, Value> = per_net.iter().map(|(n, (b, a))| (n.clone(), json!({"before": b, "after": a}))).collect();     let (b, a): (usize, usize) = per_net.values().fold((0, 0), |s, v| (s.0 + v.0, s.1 + v.1));-    json!({"verticesBefore": b, "verticesAfter": a, "staircasesReplaced": total.replaced, "staircasesKept": total.kept, "collinearMerged": total.merged, "cornersChamfered": smooth.chamfered, "segmentsSquared": smooth.squared, "runsTightened": smooth.tightened, "wigglesStepped": smooth.jogs, "smoothKept": smooth.kept, "padsEnteredOnAxis": entered, "jogsSlid": slid, "nets": nets,+    json!({"verticesBefore": b, "verticesAfter": a, "staircasesReplaced": total.replaced, "staircasesKept": total.kept, "collinearMerged": total.merged, "cornersChamfered": smooth.chamfered, "segmentsSquared": smooth.squared, "runsTightened": smooth.tightened, "wigglesStepped": smooth.jogs, "smoothKept": smooth.kept, "padsEnteredOnAxis": entered, "jogsSlid": slid, "viasEliminated": vias_eliminated, "nets": nets,         "rule": format!("staircase = {STAIR_MIN_STEPS}+ alternating 0/90 degree segments each <= {STAIR_FACTOR} x track width; replaced by a 45 degree segment plus at most one orthogonal leg only where the router's obstacle check keeps clearance. Then (not on impedance pairs) a sideways step <= {JOG_MM} mm between two opposite right angles becomes one 45 degree step, and a right-angle corner at a free point is cut into two 45 degree turns (leg <= {CHAMFER_FACTOR} x width and half of either leg), each only where the same check keeps clearance. A trace into a pad is rebuilt as a straight stub along the pad's own axis out past its edge and one 45 degree leg back onto the route (no new hard corner or wiggle, at most {ENTRY_SLACK_MM} mm longer), and a short leg between two parallel runs is slid along them (the same two legs in the other order) until it merges, both only where the same check keeps clearance")}) } @@ -1034,4 +1108,33 @@ mod tests {         assert_eq!(found.len(), 1, "{found:?}");         assert!(found[0].contains("5-step staircase"), "{found:?}");     }++    #[test]+    fn post_route_via_elimination_flattens_clear_flip_and_keeps_blocked_flip() {+        let pads = [("J1", "A", 2.0, 5.0, false), ("J2", "A", 18.0, 5.0, false), ("J3", "B", 10.0, 12.0, false)];+        let mut r = Router::new(crate::board_copper::tests::board(&pads, ""), crate::Rules::default(), false);+        // Redundant F.Cu -> B.Cu -> F.Cu hop on an open path+        let mut plan = vec![json!({"net": "A", "width": 0.25, "paths": [[+            "J1.1",+            {"x": 6.0, "y": 5.0, "layer": "B.Cu"},+            {"x": 14.0, "y": 5.0, "layer": "F.Cu"},+            "J2.1"+        ]]})];+        let rep = simplify_plan(&mut r, &mut plan);+        assert_eq!(rep["viasEliminated"], 2, "{rep}");+        assert!(!plan[0]["paths"][0].to_string().contains("\"B.Cu\""), "{}", plan[0]);++        // Now place a foreign pad directly on F.Cu at (10, 5) blocking the flattened segment -> flip stays on B.Cu+        let blocked_pads = [("J1", "A", 2.0, 5.0, false), ("J2", "A", 18.0, 5.0, false), ("J3", "B", 10.0, 5.0, false)];+        let mut r2 = Router::new(crate::board_copper::tests::board(&blocked_pads, ""), crate::Rules::default(), false);+        let mut plan2 = vec![json!({"net": "A", "width": 0.25, "paths": [[+            "J1.1",+            {"x": 6.0, "y": 5.0, "layer": "B.Cu"},+            {"x": 14.0, "y": 5.0, "layer": "F.Cu"},+            "J2.1"+        ]]})];+        let rep2 = simplify_plan(&mut r2, &mut plan2);+        assert_eq!(rep2["viasEliminated"], 0, "{rep2}");+        assert!(plan2[0]["paths"][0].to_string().contains("\"B.Cu\""), "{}", plan2[0]);+    } }
skills/aiflow-power-layout/SKILL.md+1−1
@@ -56,7 +56,7 @@ Kelvin keepouts follow the tap's own layer (both layers only at its vias) and st  - **SW is a small solid patch** from the IC's SW pin to the inductor, widening toward the inductor, never a large pour: small area, small radiated field, no neck. Open the polygon right after the pad; the first patch had a 0.95 mm throat at 60 A/mm2. - **Solid, not thermal-relief, at heat paths**: the IC GND pin and the inductor pads (`solidAt`).-- **Thermal vias beside small pins.** A SOT-23 or 0603 pad is too small for a via; an open via in it wicks solder. Put 0.6/0.3 mm vias in the solid pour just outside the pad, clear of other nets (`pour` now does this and says how many of `count` fit).+- **Thermal vias beside small pins.** A SOT-23 or 0603 pad is too small for a via; an open via in it wicks solder. Put 0.6/0.3 mm vias in the solid pour just outside the pad, clear of other nets (`pour` now does this and says how many of `count` fit). `aiflow-router` keeps `allowViaInPad` off by default, and `gate`, `finish`, and `export` run a board-wide VIPPO audit separating large thermal EPADs (>= 4 mm2) from standard SMD pads; standard SMD via-in-pad requires `"fab": {"viaInPad": "filled-capped", "viaInPadWhy": "..."}` on a VIPPO-capable fab (emitting an IPC-4761 Type VII note on `export`). `gate` and `finish` also classify board vias (`signal-routing`, `power-fanout`, `thermal`, `stitching`), flag dense plane-perforating clusters (> 4 non-thermal vias within 3 mm) and high signal-via ratios (> 1.0/net or > 2 on a non-bus net), and `route` runs a post-route via-elimination pass. - **Count the vias a pad already has.** `pour` counts the pad's existing vias (an exposed pad's datasheet in-pad pattern too) toward `thermalVias[].count` and keeps planned vias clear of them; `land vias` refuses a via within the hole-to-hole minimum or via-to-via clearance of any via or hole before anything lands. - **Check every landed via's net.** A planned GND via whose pad touched the SW trace landed as SW and DRC passed. After `land vias`, read each via's net on the live board against the plan. 
tests/vippo-via-hygiene-workflow.pyadded+137
@@ -0,0 +1,137 @@+"""VIPPO (via-in-pad) audit and board-level via hygiene end to end (issue #217):+1. Unapproved open via in standard 0603 SMD pad is caught by gate -> fixed when moved off-pad+2. QFN exposed thermal pad (>= 4 mm^2) via passes without VIPPO approval and classifies as thermal+3. Approved VIPPO on 4L JLCPCB (fab.viaInPad = "filled-capped" + viaInPadWhy) passes gate and+   writes IPC-4761 Type VII note (vippo-fab-note.md) on export+4. Dense via cluster (> 4 non-thermal vias within 3 mm) and excessive non-bus signal vias (> 2)+   are reported in gate.json viaHygiene+5. route --variants exposes signalVias alongside vias in the table and outcome JSON+Usage: python3 tests/vippo-via-hygiene-workflow.py <adom-aiflow binary>"""+import json, os, pathlib, shutil, subprocess, sys, tempfile++binary = str(pathlib.Path(sys.argv[1]).resolve())+++def make_4l_board(path, segs="", vias=""):+    path.write_text(+        '(kicad_pcb (version 20241229) (generator "test") (general (thickness 1.6)) '+        '(layers (0 "F.Cu" signal) (4 "In1.Cu" signal) (6 "In2.Cu" signal) (2 "B.Cu" signal) (25 "Edge.Cuts" user)) '+        '(net 0 "") (net 1 "SIG_A") (net 2 "SIG_B") (net 3 "SIG_C") (net 4 "GND") (net 5 "VIN") '+        '(footprint "Resistor_SMD:R_0603" (layer "F.Cu") (at 8 10) (property "Reference" "R1") (property "Value" "10k") '+        '(fp_rect (start -1.5 -0.7) (end 1.5 0.7) (layer "F.CrtYd") (stroke (width 0.05) (type solid))) '+        '(pad "1" smd rect (at -0.8 0) (size 0.8 0.9) (layers "F.Cu") (net 1 "SIG_A")) '+        '(pad "2" smd rect (at 0.8 0) (size 0.8 0.9) (layers "F.Cu") (net 4 "GND"))) '+        '(footprint "Resistor_SMD:R_0603" (layer "F.Cu") (at 32 10) (property "Reference" "R2") (property "Value" "10k") '+        '(fp_rect (start -1.5 -0.7) (end 1.5 0.7) (layer "F.CrtYd") (stroke (width 0.05) (type solid))) '+        '(pad "1" smd rect (at -0.8 0) (size 0.8 0.9) (layers "F.Cu") (net 1 "SIG_A")) '+        '(pad "2" smd rect (at 0.8 0) (size 0.8 0.9) (layers "F.Cu") (net 4 "GND"))) '+        '(footprint "Package_DFN_QFN:QFN-24" (layer "F.Cu") (at 20 15) (property "Reference" "U1") (property "Value" "IC") '+        '(fp_rect (start -2.5 -2.5) (end 2.5 2.5) (layer "F.CrtYd") (stroke (width 0.05) (type solid))) '+        '(pad "25" smd rect (at 0 0) (size 3.0 3.0) (layers "F.Cu") (net 4 "GND"))) '+        f'{segs} {vias} '+        '(gr_rect (start 0 0) (end 40 22) (layer "Edge.Cuts") (stroke (width 0.1) (type solid))))'+    )+++with tempfile.TemporaryDirectory(prefix='aiflow-vippo-') as td:+    p = pathlib.Path(td)+    env = dict(os.environ, AIFLOW_DASHBOARD='off', XDG_CONFIG_HOME=str(p / 'xdg'))++    def call(run, *args):+        return subprocess.run(+            [binary, '--run', str(run), '--ai-thread', 'vippo-test', *args],+            env=env, capture_output=True, text=True, timeout=120+        )++    base_segs = (+        '(segment (start 7.2 10) (end 7.2 8.0) (width 0.25) (layer "F.Cu") (net 1)) '+        '(segment (start 7.2 8.0) (end 31.2 8.0) (width 0.25) (layer "F.Cu") (net 1)) '+        '(segment (start 31.2 8.0) (end 31.2 10) (width 0.25) (layer "F.Cu") (net 1)) '+        '(segment (start 8.8 10) (end 8.8 15) (width 0.25) (layer "F.Cu") (net 4)) '+        '(segment (start 8.8 15) (end 20 15) (width 0.25) (layer "F.Cu") (net 4)) '+        '(segment (start 20 15) (end 32.8 15) (width 0.25) (layer "F.Cu") (net 4)) '+        '(segment (start 32.8 15) (end 32.8 10) (width 0.25) (layer "F.Cu") (net 4))'+    )+    # Via directly inside R1.1 (0603 SMD pad) + thermal via inside U1.25 (3x3 mm EPAD)+    vias_smd_and_epad = (+        '(via (at 7.2 10) (size 0.5) (drill 0.25) (layers "F.Cu" "B.Cu") (net 1)) '+        '(via (at 20.0 15.0) (size 0.5) (drill 0.25) (layers "F.Cu" "B.Cu") (net 4))'+    )+    b_vip = p / 'vip.kicad_pcb'+    make_4l_board(b_vip, segs=base_segs, vias=vias_smd_and_epad)+    spec_unapp = p / 'spec_unapp.json'+    spec_unapp.write_text(json.dumps({"clearance": 0.15, "minTrackWidth": 0.127, "track": 0.25, "fab": {"rules": "jlcpcb-4L"}}))+    b_vip.with_suffix('.kicad_dru').write_text('(version 1)\n# adom-aiflow rules: jlcpcb 4L (from test)\n(rule "c" (constraint clearance (min 0.127mm)))\n')++    # 1. Unapproved open via in 0603 SMD pad fails gate+    run1 = p / 'run-unapp'+    assert call(run1, 'start', '--board', str(b_vip), '--spec', str(spec_unapp), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+    rg = call(run1, 'gate')+    assert 'unapproved via-in-pad (VIPPO)' in rg.stdout, rg.stdout + rg.stderr+    g1 = json.loads((run1 / 'gate.json').read_text())+    assert g1['vippo']['pass'] is False and g1['vippo']['smdViaInPadCount'] == 1 and g1['vippo']['thermalEpadViaCount'] == 1, g1['vippo']+    print('  [1/5] unapproved via in 0603 SMD pad caught by gate; QFN EPAD separated as thermal')++    # 2. Moving via off-pad (keeping only the thermal EPAD via) passes gate+    b_ok = p / 'epad-only.kicad_pcb'+    make_4l_board(b_ok, segs=base_segs, vias='(via (at 20.0 15.0) (size 0.5) (drill 0.25) (layers "F.Cu" "B.Cu") (net 4))')+    b_ok.with_suffix('.kicad_dru').write_text('(version 1)\n# adom-aiflow rules: jlcpcb 4L (from test)\n(rule "c" (constraint clearance (min 0.127mm)))\n')+    run2 = p / 'run-ok'+    assert call(run2, 'start', '--board', str(b_ok), '--spec', str(spec_unapp), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+    rg2 = call(run2, 'gate')+    assert rg2.returncode == 0 and rg2.stdout.startswith('OK:'), rg2.stdout + rg2.stderr+    g2 = json.loads((run2 / 'gate.json').read_text())+    assert g2['vippo']['pass'] is True and g2['vippo']['thermalEpadViaCount'] == 1, g2['vippo']+    print('  [2/5] QFN EPAD thermal via passes without VIPPO approval')++    # 3. Approved VIPPO on 4L JLCPCB passes gate AND writes IPC-4761 Type VII fab note on export+    spec_app = p / 'spec_app.json'+    spec_app.write_text(json.dumps({+        "clearance": 0.15, "minTrackWidth": 0.127, "track": 0.25,+        "fab": {"rules": "jlcpcb-4L", "viaInPad": "filled-capped", "viaInPadWhy": "dense BGA/QFN escape on 4L"}+    }))+    run3 = p / 'run-app'+    assert call(run3, 'start', '--board', str(b_vip), '--spec', str(spec_app), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+    rg3 = call(run3, 'gate')+    assert rg3.returncode == 0 and rg3.stdout.startswith('OK:'), rg3.stdout + rg3.stderr+    if shutil.which('kicad-cli'):+        out_dir = p / 'mfg-vippo'+        re = call(run3, 'export', '--out', str(out_dir))+        assert re.returncode == 0, re.stdout + re.stderr+        note_md = out_dir / 'vippo-fab-note.md'+        assert note_md.exists() and 'IPC-4761 Type VII' in note_md.read_text(), list(out_dir.iterdir())+        print('  [3/5] approved VIPPO passed gate and export emitted IPC-4761 Type VII vippo-fab-note.md')+    else:+        print('  [3/5] SKIP kicad-cli export check')++    # 4. Dense via cluster (> 4 non-thermal vias within 3 mm) + > 2 vias on non-bus net caught in viaHygiene+    vias_cluster = (+        '(via (at 15.0 6.0) (size 0.5) (drill 0.25) (layers "F.Cu" "B.Cu") (net 1)) '+        '(via (at 15.8 6.0) (size 0.5) (drill 0.25) (layers "F.Cu" "B.Cu") (net 1)) '+        '(via (at 16.6 6.0) (size 0.5) (drill 0.25) (layers "F.Cu" "B.Cu") (net 1)) '+        '(via (at 15.0 7.0) (size 0.5) (drill 0.25) (layers "F.Cu" "B.Cu") (net 2)) '+        '(via (at 15.8 7.0) (size 0.5) (drill 0.25) (layers "F.Cu" "B.Cu") (net 3))'+    )+    b_cl = p / 'cluster.kicad_pcb'+    make_4l_board(b_cl, segs=base_segs, vias=vias_cluster)+    b_cl.with_suffix('.kicad_dru').write_text('(version 1)\n# adom-aiflow rules: jlcpcb 4L (from test)\n(rule "c" (constraint clearance (min 0.127mm)))\n')+    run4 = p / 'run-cluster'+    assert call(run4, 'start', '--board', str(b_cl), '--spec', str(spec_unapp), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+    rg4 = call(run4, 'gate')+    g4 = json.loads((run4 / 'gate.json').read_text())+    assert g4['viaHygiene']['pass'] is False and len(g4['viaHygiene']['denseClusters']) == 1 and len(g4['viaHygiene']['highViaSignalNets']) == 1, g4['viaHygiene']+    print('  [4/5] viaHygiene caught dense 5-via cluster and non-bus SIG_A with 3 vias')++    # 5. route --variants exposes vias(sig) column and signalVias metric+    b_clean = p / 'clean-unrouted.kicad_pcb'+    make_4l_board(b_clean)+    b_clean.with_suffix('.kicad_dru').write_text('(version 1)\n# adom-aiflow rules: jlcpcb 4L (from test)\n(rule "c" (constraint clearance (min 0.127mm)))\n')+    run5 = p / 'run-vars'+    assert call(run5, 'start', '--board', str(b_clean), '--spec', str(spec_unapp), '--engine', 'test', '--prompt-time', '2026-11-19T00:00:00Z').returncode == 0+    rv = call(run5, 'route', '--variants', '2')+    assert rv.returncode == 0 and 'vias(sig)' in rv.stderr + rv.stdout, rv.stdout + rv.stderr+    ro = json.loads((run5 / 'run.json').read_text())['outcomes']['route']['variants']['variants'][0]+    assert 'signalVias' in ro and 'vias' in ro, ro+    print('  [5/5] route --variants exposes signalVias alongside vias')++print('PASS: VIPPO audit, allowViaInPad default false, IPC-4761 Type VII note, via classification, cluster detection, and route --variants via metrics verified.')