← Commit history
Merge PR #657: Add assembly (DFA) solderability, tombstone, fiducial, and bottom-side reflow check stage and gate (feat/dfa-solderability-gate -> main) merge
Showing changes introduced by the merge (against its first parent).
7 files changed
+2914−4
SKILL.md+7@@ -275,6 +275,13 @@ The clock starts at the prompt even when there is no board yet. - Hints name the lighter layer and suggest rebalancing pours, adding a hatched fill, or placing non-functional copper thieving (keeping thieving at least `1.5 mm` from high-speed traces). - Never blocks a finished board by default. Opt in to blocking with `"fab": {"copperBalanceBlocking": true}` in the spec or `# adom-aiflow: copperBalanceBlocking` in the board's `.kicad_dru` rules profile (an explicit `"copperBalanceBlocking": false` in the spec wins over the rules file). Results are recorded in `gate.json`, `run.json` (`pour`, `gate`, `copper-balance`, `summary.copperBalance`) and `export-check.json`. +**Assembly (DFA) solderability, tombstone, fiducial, and bottom-side reflow checks.** `adom-aiflow dfa check [--board B] [--spec S] [--bom M] [--json]` and `adom-aiflow analyze dfa` check four SMT assembly rules and return `OK:`/`ERROR:` with fix `Hint:` lines. `place check` and `place verify` run the placement subset (fiducials and bottom-side reflow), while `gate` and `finish` run the full audit and record it in `gate.json` (`dfa`) and `run.json`.+- **Thermal relief on small SMD pads:** flags 0201/0402/0603 chip pads, fine-pitch IC pins, and small SMD pads (`< 2.0 mm2`) tied solid (`connect_pads yes`, `thru_hole_only`, or pad/footprint `zone_connect 2/3`) to large outer copper pours (`>= 15 mm2`). Intentional solid connections are exempted automatically: `spec.solidAt`, `spec.hot` thermal tabs, high-current `spec.loads` terminals, small local copper patches, mechanical/shield pads, and molecule pins/contacts (`MP*`/`MC*`).+- **0402/0201/01005 tombstone asymmetry:** compares both pads for solid-pour mismatch, exact drill-based one-sided via-in-pad, pad-area mismatch, or large connected copper-width imbalance (default ratio `>= 2.5:1` with wide side `>= 0.35 mm`, crediting thermal-relieved pours and pass-through traces).+- **Global and local fiducials:** checks each assembled face for global fiducials (default 3 asymmetric per board/panel, 2 diagonal on compact `<= 45 mm` molecules, `>= 3.8 mm` from edge or `2.5 mm` on compact molecules, bare copper with no paste) and 2 diagonal local fiducials near `<= 0.50 mm` pitch BGAs/QFNs (skipping mechanically keyed connectors with NPTH alignment pegs, tiny boards without fine-pitch ICs, no-assembly/pattern boards, and hand/`self` assembly profiles).+- **Bottom-side reflow rules:** notes double-sided SMT counts and flags heavy (`> 4.6 g/cm2` from BOM `mass_g` or heavy package class such as power inductors, electrolytic cans, relays, or large connectors) or tall (`> 5.0 mm` from `spec.bodies`, BOM `height_mm`, or footprint name) parts on `B.Cu`. Single-sided bottom-only boards and bare pogo/contact pads are not flagged.+- **Warn by default, opt in to blocking:** findings warn without blocking unless enabled via `"dfa": {"blocking": true}`, `"fab": {"dfaBlocking": true}`, `"strictDfa": true`, a strict assembly profile (`"assembly": {"profile": "production"}`), or `# adom-aiflow: dfaBlocking` in `<board>.kicad_dru` (an explicit `"blocking": false` wins over the rules file). Threshold knobs live under `spec.dfa` (`smallPadMaxAreaMm2`, `minPourAreaMm2`, `tombstoneWidthRatio`, `tombstoneMinWideMm`, `minGlobalFiducials`, `fiducialEdgeClearanceMm`, `localFiducialMaxPitchMm`, `fiducialsOnPanel`, `bottomMaxMassPerAreaGPerCm2`, `bottomMaxHeightMm`, `singleSidedOnly`, `solidExempt`, `bottomExempt`).+ ## The fields step (adom-fields) After the pours and the analyses: `adom-fields analyze --board <the current board> --spec <spec> --out fields` (about two minutes; `adom-wiki pkg install adom/adom-fields` if it is missing), `adom-fields serve --fields fields --port 8874 &`, then `step fields` and `tour fields`: the binary opens the app in a pup window on the test box, films that window while `adom-fields tour` walks the board gently (the app paces itself: slow eased moves about nine seconds long, the board drifting a few degrees through every held beat, one copper pour isolated at a time, a quick turn-over to the bottom layer, because the flow plays this clip back at ten times speed, where a snap reads as frenetic) (each net lit, the hot parts, the issues flown to; the app's toasts are the captions), and records the issues in the run. When the Fields URL is a localhost proxy (an Adom Hydrogen desktop container's `VSCODE_PROXY_URI` is `http://{{port}}.localhost:<port>/`, reachable only on the machine hosting the container), the window opens on the user's primary machine (`adom-bridge targets` names it) instead of the test box, and the answer says so; `--on <box>` overrides. The issues (a current neck, a tab over its rise budget, a chip missing its thermal vias) are yours to answer before delivery; the app's screenshots are drawings you can register with `artifact`.
crates/adom-aiflow/src/dfa.rsadded+2597@@ -0,0 +1,2597 @@+//! Design for Assembly (DFA) solderability, tombstone, fiducial, and bottom-side reflow checks.+//!+//! Covers four SMT assembly checks with fix hints:+//! 1. Small SMD pads (0201/0402/0603 chips, fine-pitch IC pins, and small SMD pads) tied solid+//! to copper pours without thermal relief (exempting explicit `spec.solidAt`, `spec.hot` tabs,+//! high-current `spec.loads` terminals, small local copper patches, mechanical/shield pads,+//! and molecule machine pins/contacts).+//! 2. 0402/0201/01005 pad-connection asymmetry (tombstone risk): one pad solid-to-pour vs non-solid,+//! exact drill-based one-sided via-in-pad, pad-area mismatch, or large connected copper-width+//! imbalance (accounting for pass-through traces and thermal-relief balance).+//! 3. Global fiducials (per assembled face, per board and per panel) and local fiducials near+//! fine-pitch packages, with molecule, compact-board, panel, and no-assembly awareness.+//! 4. Bottom-side reflow rules: double-sided SMT notice plus heavy (> 4.6 g/cm^2 from BOM mass or+//! heavy package class) and tall (> 5.0 mm) component checks on `B.Cu`.+//!+//! Warn by default; a spec knob (`spec.dfa.blocking`, `spec.fab.dfaBlocking`, `spec.strictDfa`,+//! `spec.assembly.blocking`), a strict fab/assembly profile, or a `.kicad_dru` comment line+//! `# adom-aiflow: dfaBlocking` makes findings blocking.++use std::collections::{BTreeMap, BTreeSet};+use std::path::Path;++use aiflow_board::{geom, sx, Board, Pad, Pt, Track, Via, B_CU, F_CU};+use serde_json::{json, Value};++/// Marker comment in `<board>.kicad_dru` that makes DFA findings blocking.+pub const DRU_MARKER: &str = "adom-aiflow: dfaBlocking";++pub const DEFAULT_SMALL_PAD_MAX_AREA_MM2: f64 = 2.0;+pub const DEFAULT_MIN_POUR_AREA_MM2: f64 = 15.0;+pub const DEFAULT_TOMBSTONE_SOLID_POUR_MM2: f64 = 3.0;+pub const DEFAULT_TOMBSTONE_WIDTH_RATIO: f64 = 2.5;+pub const DEFAULT_TOMBSTONE_MIN_WIDE_MM: f64 = 0.35;+pub const DEFAULT_FIDUCIAL_EDGE_MM: f64 = 3.8;+pub const DEFAULT_MOLECULE_FIDUCIAL_EDGE_MM: f64 = 2.5;+pub const DEFAULT_LOCAL_FIDUCIAL_PITCH_MM: f64 = 0.50;+pub const DEFAULT_LOCAL_FIDUCIAL_RADIUS_MM: f64 = 15.0;+pub const DEFAULT_BOTTOM_MAX_G_PER_CM2: f64 = 4.6;+pub const DEFAULT_BOTTOM_MAX_HEIGHT_MM: f64 = 5.0;+pub const DEFAULT_TINY_BOARD_AREA_MM2: f64 = 625.0;++#[derive(Debug, Clone)]+pub struct DfaConfig {+ pub enabled: bool,+ pub blocking: bool,+ pub assembly_profile: String,+ pub skip_machine_smt: bool,+ pub small_pad_max_area_mm2: f64,+ pub min_pour_area_mm2: f64,+ pub tombstone_width_ratio: f64,+ pub tombstone_min_wide_mm: f64,+ pub min_global_fiducials: Option<usize>,+ pub fiducial_edge_mm: Option<f64>,+ pub local_fiducial_max_pitch_mm: f64,+ pub local_fiducials_always: bool,+ pub fiducials_on_panel: bool,+ pub panel_declared: bool,+ pub panel_boards: usize,+ pub bottom_max_g_per_cm2: f64,+ pub bottom_max_height_mm: f64,+ pub single_sided_only: bool,+ pub solid_exempt: BTreeSet<String>,+ pub bottom_exempt: BTreeSet<String>,+}++/// True when a `.kicad_dru` file carries `# adom-aiflow: dfaBlocking` on a comment line.+pub fn dru_declares(text: &str) -> bool {+ text.lines().any(|l| {+ let l = l.trim_start();+ l.starts_with('#') && l.contains(DRU_MARKER)+ })+}++fn is_strict_profile(name: &str) -> bool {+ let l = name.trim().to_ascii_lowercase();+ matches!(+ l.as_str(),+ "strict" | "production" | "pcba-strict" | "ipc-class-3" | "class3" | "class-3" | "blocking"+ )+}++fn read_dru_blocking(board_path: &str) -> bool {+ if board_path.is_empty() {+ return false;+ }+ let dru = Path::new(board_path).with_extension("kicad_dru");+ std::fs::read_to_string(dru)+ .map(|t| dru_declares(&t))+ .unwrap_or(false)+}++impl DfaConfig {+ pub fn from_sources(spec: &Value, req: &Value, board_path: &str) -> DfaConfig {+ let dfa = &spec["dfa"];+ let enabled = dfa["enabled"].as_bool().unwrap_or(true);++ let profile_raw = dfa["profile"]+ .as_str()+ .or_else(|| spec["assembly"]["profile"].as_str())+ .or_else(|| spec["fab"]["assemblyProfile"].as_str())+ .or_else(|| req["assembly"]["profile"].as_str())+ .or_else(|| req["dfa"]["profile"].as_str())+ .or_else(|| spec["assembly"]["mode"].as_str())+ .or_else(|| req["assembly"]["mode"].as_str());++ let sourcing_profile = crate::preboard::named_profile(spec)+ .or_else(|| crate::preboard::named_profile(req));++ let assembly_profile = profile_raw+ .map(|s| s.trim().to_ascii_lowercase())+ .or_else(|| sourcing_profile.clone())+ .unwrap_or_else(|| "default".to_string());++ let is_no_assembly = matches!(assembly_profile.as_str(), "none" | "bare" | "no-assembly");+ let is_hand = matches!(assembly_profile.as_str(), "self" | "hand" | "diy" | "hand-assembly");++ let explicit_blocking = dfa["blocking"]+ .as_bool()+ .or_else(|| spec["fab"]["dfaBlocking"].as_bool())+ .or_else(|| spec["strictDfa"].as_bool())+ .or_else(|| spec["assembly"]["blocking"].as_bool())+ .or_else(|| req["dfa"]["blocking"].as_bool())+ .or_else(|| req["assembly"]["blocking"].as_bool())+ .or_else(|| req["fab"]["dfaBlocking"].as_bool());++ let blocking = explicit_blocking.unwrap_or_else(|| {+ read_dru_blocking(board_path) || is_strict_profile(&assembly_profile)+ });++ let mut solid_exempt = BTreeSet::new();+ for src in [spec.get("solidAt"), dfa.get("solidExempt")] {+ for s in src.and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str) {+ solid_exempt.insert(s.trim().to_string());+ }+ }+ let mut bottom_exempt = BTreeSet::new();+ for s in dfa["bottomExempt"].as_array().into_iter().flatten().filter_map(Value::as_str) {+ bottom_exempt.insert(s.trim().to_string());+ }++ let panel_v = if spec["panel"].is_object() {+ &spec["panel"]+ } else if dfa["panel"].is_object() {+ &dfa["panel"]+ } else {+ &req["panel"]+ };+ let panel_boards = panel_v["boards"]+ .as_u64()+ .or_else(|| panel_v["count"].as_u64())+ .unwrap_or(0) as usize;+ let panel_declared = panel_v["enabled"].as_bool().unwrap_or(false)+ || panel_boards > 1+ || panel_v["rails"].as_bool().unwrap_or(false);++ let fiducials_on_panel = dfa["fiducialsOnPanel"]+ .as_bool()+ .or_else(|| panel_v["fiducials"].as_bool())+ .unwrap_or(false);++ DfaConfig {+ enabled: enabled && !is_no_assembly,+ blocking,+ assembly_profile,+ skip_machine_smt: is_hand,+ small_pad_max_area_mm2: dfa["smallPadMaxAreaMm2"]+ .as_f64()+ .filter(|v| *v > 0.0)+ .unwrap_or(DEFAULT_SMALL_PAD_MAX_AREA_MM2),+ min_pour_area_mm2: dfa["minPourAreaMm2"]+ .as_f64()+ .filter(|v| *v >= 0.0)+ .unwrap_or(DEFAULT_MIN_POUR_AREA_MM2),+ tombstone_width_ratio: dfa["tombstoneWidthRatio"]+ .as_f64()+ .filter(|v| *v > 1.0)+ .unwrap_or(DEFAULT_TOMBSTONE_WIDTH_RATIO),+ tombstone_min_wide_mm: dfa["tombstoneMinWideMm"]+ .as_f64()+ .filter(|v| *v > 0.0)+ .unwrap_or(DEFAULT_TOMBSTONE_MIN_WIDE_MM),+ min_global_fiducials: dfa["minGlobalFiducials"].as_u64().map(|v| v as usize),+ fiducial_edge_mm: dfa["fiducialEdgeClearanceMm"].as_f64().filter(|v| *v >= 0.0),+ local_fiducial_max_pitch_mm: dfa["localFiducialMaxPitchMm"]+ .as_f64()+ .filter(|v| *v > 0.0)+ .unwrap_or(DEFAULT_LOCAL_FIDUCIAL_PITCH_MM),+ local_fiducials_always: dfa["localFiducialsAlways"].as_bool().unwrap_or(false),+ fiducials_on_panel,+ panel_declared,+ panel_boards,+ bottom_max_g_per_cm2: dfa["bottomMaxMassPerAreaGPerCm2"]+ .as_f64()+ .filter(|v| *v > 0.0)+ .unwrap_or(DEFAULT_BOTTOM_MAX_G_PER_CM2),+ bottom_max_height_mm: dfa["bottomMaxHeightMm"]+ .as_f64()+ .filter(|v| *v > 0.0)+ .unwrap_or(DEFAULT_BOTTOM_MAX_HEIGHT_MM),+ single_sided_only: dfa["singleSidedOnly"]+ .as_bool()+ .or_else(|| spec["assembly"]["singleSidedOnly"].as_bool())+ .unwrap_or(false),+ solid_exempt,+ bottom_exempt,+ }+ }++ pub fn to_json(&self) -> Value {+ json!({+ "enabled": self.enabled,+ "blocking": self.blocking,+ "assemblyProfile": self.assembly_profile,+ "skipMachineSmt": self.skip_machine_smt,+ "smallPadMaxAreaMm2": self.small_pad_max_area_mm2,+ "minPourAreaMm2": self.min_pour_area_mm2,+ "tombstoneWidthRatio": self.tombstone_width_ratio,+ "tombstoneMinWideMm": self.tombstone_min_wide_mm,+ "minGlobalFiducials": self.min_global_fiducials,+ "fiducialEdgeClearanceMm": self.fiducial_edge_mm,+ "localFiducialMaxPitchMm": self.local_fiducial_max_pitch_mm,+ "fiducialsOnPanel": self.fiducials_on_panel,+ "bottomMaxMassPerAreaGPerCm2": self.bottom_max_g_per_cm2,+ "bottomMaxHeightMm": self.bottom_max_height_mm,+ "singleSidedOnly": self.single_sided_only,+ })+ }+}++fn r2(v: f64) -> f64 {+ (v * 100.0).round() / 100.0+}++fn r3(v: f64) -> f64 {+ (v * 1000.0).round() / 1000.0+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum ZoneConnectMode {+ None,+ Thermal,+ Solid,+ ThruHoleOnly,+}++impl ZoneConnectMode {+ fn from_int(v: i64) -> Option<Self> {+ match v {+ 0 => Some(Self::None),+ 1 => Some(Self::Thermal),+ 2 => Some(Self::Solid),+ 3 => Some(Self::ThruHoleOnly),+ _ => None,+ }+ }++ fn is_solid_for_smd(self) -> bool {+ matches!(self, Self::Solid | Self::ThruHoleOnly)+ }++ fn is_thermal_for_smd(self) -> bool {+ matches!(self, Self::Thermal)+ }+}++#[derive(Debug, Clone)]+struct ParsedZone {+ net: String,+ layer: usize,+ priority: i64,+ connect: ZoneConnectMode,+ thermal_bridge_mm: f64,+ filled: bool,+ area_mm2: f64,+ bbox: (f64, f64, f64, f64),+ poly: Vec<Pt>,+}++fn parse_zones(board: &Board) -> Vec<ParsedZone> {+ let mut out = Vec::new();+ let pts_of = |n: &sx::Node| -> Vec<Pt> {+ n.find("pts")+ .map(|p| {+ p.find_all("xy")+ .filter_map(|xy| Some((xy.number(1)?, xy.number(2)?)))+ .collect()+ })+ .unwrap_or_default()+ };++ for z in board.root.find_all("zone") {+ if z.find("keepout").is_some() {+ continue;+ }+ if let Some(attr) = z.find("attr") {+ if attr.find("teardrop").is_some() {+ continue;+ }+ }+ let net = z+ .find("net_name")+ .and_then(|n| n.value())+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ .unwrap_or_else(|| board.item_net(z));+ if net.is_empty() {+ continue;+ }+ let priority = z+ .find("priority")+ .and_then(|p| p.number(1))+ .map(|v| v as i64)+ .unwrap_or(0);+ let connect = match z.find("connect_pads").and_then(|c| c.atom(1)) {+ Some("yes") => ZoneConnectMode::Solid,+ Some("no") => ZoneConnectMode::None,+ Some("thru_hole_only") => ZoneConnectMode::ThruHoleOnly,+ _ => ZoneConnectMode::Thermal,+ };+ let thermal_bridge_mm = z+ .find("fill")+ .and_then(|f| f.find("thermal_bridge_width"))+ .and_then(|w| w.number(1))+ .filter(|v| *v > 0.0)+ .unwrap_or(0.35);++ // Skip tiny high-priority teardrop-like zones (e.g. KiCad exported priority >= 30000 patches)+ let outline = z.find("polygon").map(pts_of).unwrap_or_default();+ let outline_area = geom::polygon_area(&outline).abs();+ if priority >= 30000 && outline_area < 2.5 {+ continue;+ }++ let mut added_fill = false;+ for fp in z.find_all("filled_polygon") {+ let Some(layer) = fp+ .find("layer")+ .and_then(|l| l.value())+ .and_then(aiflow_board::copper_layer)+ .filter(|&l| l <= B_CU)+ else {+ continue;+ };+ let poly = pts_of(fp);+ if poly.len() < 3 {+ continue;+ }+ let area = geom::polygon_area(&poly).abs();+ let bbox = geom::bbox(&poly);+ out.push(ParsedZone {+ net: net.clone(),+ layer,+ priority,+ connect,+ thermal_bridge_mm,+ filled: true,+ area_mm2: area,+ bbox,+ poly,+ });+ added_fill = true;+ }++ // Fallback to outline when the zone has not been filled yet (e.g., pre-refill gate check)+ if !added_fill && outline.len() >= 3 {+ let mut layer_names: Vec<String> = Vec::new();+ if let Some(l) = z.find("layer").and_then(|l| l.value()) {+ layer_names.push(l.to_string());+ }+ if let Some(ls) = z.find("layers") {+ for it in &ls.items {+ if let sx::Item::Atom { text, .. } = it {+ if text != "layers" {+ layer_names.push(text.clone());+ }+ }+ }+ }+ let mut layers = Vec::new();+ for n in &layer_names {+ if n == "F.Cu" || n == "*.Cu" || n == "F&B.Cu" {+ if !layers.contains(&F_CU) {+ layers.push(F_CU);+ }+ }+ if n == "B.Cu" || n == "*.Cu" || n == "F&B.Cu" {+ if !layers.contains(&B_CU) {+ layers.push(B_CU);+ }+ }+ }+ let bbox = geom::bbox(&outline);+ for layer in layers {+ out.push(ParsedZone {+ net: net.clone(),+ layer,+ priority,+ connect,+ thermal_bridge_mm,+ filled: false,+ area_mm2: outline_area,+ bbox,+ poly: outline.clone(),+ });+ }+ }+ }++ // Higher priority wins when zones overlap+ out.sort_by(|a, b| b.priority.cmp(&a.priority));+ out+}++#[derive(Debug, Clone)]+struct PadMeta {+ zone_connect: Option<ZoneConnectMode>,+ on_f_mask: bool,+ on_b_mask: bool,+ on_f_paste: bool,+ on_b_paste: bool,+ mask_margin_mm: f64,+}++#[derive(Debug, Clone)]+struct FootprintMeta {+ reference: String,+ value: String,+ lib: String,+ layer: usize,+ x: f64,+ y: f64,+ dnp: bool,+ exclude_from_bom: bool,+ exclude_from_pos: bool,+ board_only: bool,+ is_net_tie: bool,+ is_fiducial: bool,+ is_testpoint: bool,+ is_machine_furniture: bool,+ fp_zone_connect: Option<ZoneConnectMode>,+ has_paste: bool,+ has_3d_model: bool,+ fab_bbox: Option<(f64, f64, f64, f64)>,+ pad_indices: Vec<usize>,+ pad_meta: BTreeMap<usize, PadMeta>,+}++fn has_attr_flag(fp: &sx::Node, flag_name: &str) -> bool {+ let in_attr = fp+ .find("attr")+ .map(|a| {+ a.items+ .iter()+ .any(|it| matches!(it, sx::Item::Atom { text, .. } if text == flag_name))+ })+ .unwrap_or(false);+ in_attr || fp.find(flag_name).map(|n| n.value() != Some("no")).unwrap_or(false)+}++fn prop_of(fp: &sx::Node, key: &str, legacy_key: &str) -> String {+ for p in fp.find_all("property") {+ if p.atom(1) == Some(key) {+ if let Some(v) = p.atom(2) {+ return v.to_string();+ }+ }+ }+ for t in fp.find_all("fp_text") {+ if t.atom(1) == Some(legacy_key) {+ if let Some(v) = t.atom(2) {+ return v.to_string();+ }+ }+ }+ String::new()+}++fn board_mask_margin(board: &Board) -> f64 {+ board+ .root+ .find("setup")+ .and_then(|s| s.find("pad_to_mask_clearance"))+ .and_then(|c| c.number(1))+ .unwrap_or(0.0)+}++fn parse_footprint_meta(board: &Board) -> Vec<FootprintMeta> {+ let default_mask = board_mask_margin(board);+ let mut out = Vec::new();++ // Map each board.pads index by (ref, pad_name, x_i, y_i) for reliable lookup+ let mut pad_lookup: BTreeMap<(String, String, i64, i64), Vec<usize>> = BTreeMap::new();+ for (idx, p) in board.pads.iter().enumerate() {+ let k = (+ p.reference.clone(),+ p.name.clone(),+ (p.x * 1000.0).round() as i64,+ (p.y * 1000.0).round() as i64,+ );+ pad_lookup.entry(k).or_default().push(idx);+ }++ for fp in board.root.find_all("footprint") {+ let Some(reference) = aiflow_board::reference_of(fp) else {+ continue;+ };+ let value = prop_of(fp, "Value", "value");+ let lib = fp.value().unwrap_or("").to_string();+ let layer_s = fp.find("layer").and_then(|l| l.value()).unwrap_or("F.Cu");+ let layer = if layer_s == "B.Cu" { B_CU } else { F_CU };+ let at = fp.find("at");+ let fx = at.and_then(|a| a.number(1)).unwrap_or(0.0);+ let fy = at.and_then(|a| a.number(2)).unwrap_or(0.0);+ let frot = at.and_then(|a| a.number(3)).unwrap_or(0.0);++ let dnp = has_attr_flag(fp, "dnp");+ let exclude_from_bom = has_attr_flag(fp, "exclude_from_bom");+ let exclude_from_pos = has_attr_flag(fp, "exclude_from_pos_files");+ let board_only = has_attr_flag(fp, "board_only");+ let is_net_tie = fp.find("net_tie_pad_groups").is_some();+ let fp_zone_connect = fp+ .find("zone_connect")+ .and_then(|z| z.number(1))+ .and_then(|v| ZoneConnectMode::from_int(v.round() as i64));+ let has_3d_model = fp.find("model").is_some();++ // Fab-layer graphic bounding box (local frame) for body span estimates+ let fab_layer = if layer == B_CU { "B.Fab" } else { "F.Fab" };+ let mut fab_pts: Vec<Pt> = Vec::new();+ for n in fp.nodes() {+ if n.find("layer").and_then(|l| l.value()) != Some(fab_layer) {+ continue;+ }+ match n.tag.as_str() {+ "fp_line" | "fp_rect" => {+ if let (Some(s), Some(e)) = (n.find("start"), n.find("end")) {+ if let (Some(x0), Some(y0), Some(x1), Some(y1)) =+ (s.number(1), s.number(2), e.number(1), e.number(2))+ {+ fab_pts.push((x0, y0));+ fab_pts.push((x1, y1));+ }+ }+ }+ "fp_circle" => {+ if let (Some(c), Some(e)) = (n.find("center"), n.find("end")) {+ if let (Some(cx), Some(cy), Some(ex), Some(ey)) =+ (c.number(1), c.number(2), e.number(1), e.number(2))+ {+ let r = (ex - cx).hypot(ey - cy);+ fab_pts.push((cx - r, cy - r));+ fab_pts.push((cx + r, cy + r));+ }+ }+ }+ "fp_poly" => {+ if let Some(pts) = n.find("pts") {+ for xy in pts.find_all("xy") {+ if let (Some(x), Some(y)) = (xy.number(1), xy.number(2)) {+ fab_pts.push((x, y));+ }+ }+ }+ }+ _ => {}+ }+ }+ let fab_bbox = if fab_pts.len() >= 2 {+ Some(geom::bbox(&fab_pts))+ } else {+ None+ };++ let mut pad_indices = Vec::new();+ let mut pad_meta = BTreeMap::new();+ let mut has_paste = false;+ let mut smd_copper_pads = 0usize;+ let mut mask_fp_circle_max_d = 0.0f64;++ // Check fp_circle on F.Mask/B.Mask (some fiducial footprints draw their mask opening as fp_circle)+ let mask_layer = if layer == B_CU { "B.Mask" } else { "F.Mask" };+ for n in fp.find_all("fp_circle") {+ if n.find("layer").and_then(|l| l.value()) == Some(mask_layer) {+ if let (Some(c), Some(e)) = (n.find("center"), n.find("end")) {+ if let (Some(cx), Some(cy), Some(ex), Some(ey)) =+ (c.number(1), c.number(2), e.number(1), e.number(2))+ {+ mask_fp_circle_max_d = mask_fp_circle_max_d.max(2.0 * (ex - cx).hypot(ey - cy));+ }+ }+ }+ }++ for pn in fp.find_all("pad") {+ let pname = pn.value().unwrap_or("").to_string();+ let ptype = pn.atom(2).unwrap_or("");+ let pat = pn.find("at");+ let plx = pat.and_then(|a| a.number(1)).unwrap_or(0.0);+ let ply = pat.and_then(|a| a.number(2)).unwrap_or(0.0);+ let (ox, oy) = geom::rot_kicad(plx, ply, frot);+ let (px, py) = (fx + ox, fy + oy);++ let mut on_f_mask = false;+ let mut on_b_mask = false;+ let mut on_f_paste = false;+ let mut on_b_paste = false;+ let mut has_cu = false;+ if let Some(ln) = pn.find("layers") {+ for it in &ln.items {+ if let sx::Item::Atom { text, .. } = it {+ match text.as_str() {+ "F.Mask" => on_f_mask = true,+ "B.Mask" => on_b_mask = true,+ "*.Mask" => {+ on_f_mask = true;+ on_b_mask = true;+ }+ "F.Paste" => on_f_paste = true,+ "B.Paste" => on_b_paste = true,+ "*.Paste" => {+ on_f_paste = true;+ on_b_paste = true;+ }+ s if s.ends_with(".Cu") => has_cu = true,+ _ => {}+ }+ }+ }+ }+ if on_f_paste || on_b_paste {+ has_paste = true;+ }+ if !has_cu {+ continue;+ }+ if ptype == "smd" {+ smd_copper_pads += 1;+ }+ let zc = pn+ .find("zone_connect")+ .and_then(|z| z.number(1))+ .and_then(|v| ZoneConnectMode::from_int(v.round() as i64));+ let mm = pn+ .find("solder_mask_margin")+ .and_then(|m| m.number(1))+ .unwrap_or(default_mask);+ let key = (+ reference.clone(),+ pname,+ (px * 1000.0).round() as i64,+ (py * 1000.0).round() as i64,+ );+ if let Some(idxs) = pad_lookup.get_mut(&key) {+ if !idxs.is_empty() {+ let idx = idxs.remove(0);+ pad_indices.push(idx);+ pad_meta.insert(+ idx,+ PadMeta {+ zone_connect: zc,+ on_f_mask,+ on_b_mask,+ on_f_paste,+ on_b_paste,+ mask_margin_mm: mm,+ },+ );+ }+ }+ }++ let txt_l = format!("{reference} {value} {lib}").to_ascii_lowercase();+ let ref_u = reference.trim().to_ascii_uppercase();++ let is_fid_by_name = txt_l.contains("fiducial")+ || (ref_u.starts_with("FID") && ref_u[3..].chars().all(|c| c.is_ascii_digit() || c == '_'));+ let is_fid_by_geom = if !is_fid_by_name && smd_copper_pads == 1 && pad_indices.len() == 1 {+ let pidx = pad_indices[0];+ let p = &board.pads[pidx];+ let pm = &pad_meta[&pidx];+ let mask_d = (p.size.0 + 2.0 * pm.mask_margin_mm).max(mask_fp_circle_max_d);+ !p.thru+ && p.shape == "circle"+ && (0.7..=2.0).contains(&p.size.0)+ && (p.size.0 - p.size.1).abs() < 0.05+ && p.net.is_empty()+ && !pm.on_f_paste+ && !pm.on_b_paste+ && (pm.on_f_mask || pm.on_b_mask || mask_fp_circle_max_d > 0.0)+ && mask_d >= p.size.0 + 0.8+ } else {+ false+ };+ let is_fiducial = is_fid_by_name || is_fid_by_geom;++ let is_testpoint = ref_u.starts_with("TP")+ && ref_u[2..].chars().all(|c| c.is_ascii_digit())+ || txt_l.contains("testpoint")+ || txt_l.contains("test_point")+ || txt_l.contains("pogo");++ let is_machine_furniture = crate::molecule_pins::machine_pin_name(&reference)+ || crate::molecule_pins::machine_contact_name(&reference)+ || (ref_u.starts_with("MS") && ref_u[2..].chars().all(|c| c.is_ascii_digit()) && ref_u.len() > 2)+ || txt_l.contains("machinepin")+ || txt_l.contains("machinecontact")+ || txt_l.contains("mach_pin")+ || txt_l.contains("mpincontact");++ out.push(FootprintMeta {+ reference,+ value,+ lib,+ layer,+ x: fx,+ y: fy,+ dnp,+ exclude_from_bom,+ exclude_from_pos,+ board_only,+ is_net_tie,+ is_fiducial,+ is_testpoint,+ is_machine_furniture,+ fp_zone_connect,+ has_paste,+ has_3d_model,+ fab_bbox,+ pad_indices,+ pad_meta,+ });+ }++ out+}++fn is_fitted_smd_part(fp: &FootprintMeta, board: &Board) -> bool {+ if fp.dnp || fp.board_only || fp.is_net_tie || fp.is_fiducial || fp.is_testpoint || fp.is_machine_furniture {+ return false;+ }+ if fp.exclude_from_bom && fp.exclude_from_pos {+ return false;+ }+ let lib_l = fp.lib.to_ascii_lowercase();+ if lib_l.contains("solderjumper") || lib_l.contains("mountinghole") || lib_l.contains("logo") || lib_l.contains("graphic") {+ return false;+ }+ let smd_pads: Vec<&Pad> = fp+ .pad_indices+ .iter()+ .map(|&i| &board.pads[i])+ .filter(|p| !p.thru)+ .collect();+ if smd_pads.is_empty() {+ return false;+ }+ // Bare contact pads (e.g. SWD pogo pads, edge fingers) have no paste and no 3D model+ if !fp.has_paste && !fp.has_3d_model && (lib_l.contains("pad") || lib_l.contains("contact") || fp.value.to_ascii_lowercase().contains("pad")) {+ return false;+ }+ true+}++fn is_mechanical_pad(p: &Pad) -> bool {+ let n = p.name.trim().to_ascii_uppercase();+ let r = p.reference.trim().to_ascii_uppercase();+ if n.is_empty() || n == "MP" || n.starts_with("MP") || n == "SH" || n == "SHIELD" || n == "MH" || n.starts_with("MTG") {+ return true;+ }+ let is_conn = r.starts_with('J') || r.starts_with("CN") || r.starts_with("CON") || r.starts_with('H') || r.starts_with("MH") || r.starts_with("SW");+ is_conn && matches!(n.as_str(), "S1" | "S2" | "S3" | "S4" | "S5" | "S6" | "G1" | "G2" | "G3" | "G4" | "SHELL" | "TAB" | "CASE")+}++fn lib_has_chip_code(lib: &str, code: &str) -> bool {+ let bytes = lib.as_bytes();+ let pat = code.as_bytes();+ if pat.len() > bytes.len() {+ return false;+ }+ for i in 0..=bytes.len() - pat.len() {+ if bytes[i..i + pat.len()].eq_ignore_ascii_case(pat) {+ let left_ok = i == 0 || !bytes[i - 1].is_ascii_digit();+ let right_ok = i + pat.len() == bytes.len() || !bytes[i + pat.len()].is_ascii_digit();+ if left_ok && right_ok {+ return true;+ }+ }+ }+ false+}++/// True for 01005 / 0201 / 0402 two-pad SMD chips.+fn is_tombstone_chip(fp: &FootprintMeta, board: &Board) -> Option<(&'static str, usize, usize)> {+ if !is_fitted_smd_part(fp, board) {+ return None;+ }+ let smd: Vec<usize> = fp+ .pad_indices+ .iter()+ .copied()+ .filter(|&i| !board.pads[i].thru && !is_mechanical_pad(&board.pads[i]))+ .collect();+ if smd.len() != 2 {+ return None;+ }+ let (p0, p1) = (&board.pads[smd[0]], &board.pads[smd[1]]);+ if (p0.on_f && !p1.on_f) || (p0.on_b && !p1.on_b) {+ return None;+ }+ if lib_has_chip_code(&fp.lib, "01005") {+ return Some(("01005", smd[0], smd[1]));+ }+ if lib_has_chip_code(&fp.lib, "0201") {+ return Some(("0201", smd[0], smd[1]));+ }+ if lib_has_chip_code(&fp.lib, "0402") {+ return Some(("0402", smd[0], smd[1]));+ }+ // Geometric fallback for vendor-named 0402/0201 footprints (e.g. CR0402, 0402B104, IN-S42ATG)+ let pitch = (p0.x - p1.x).hypot(p0.y - p1.y);+ let max_dim = p0.size.0.max(p0.size.1).max(p1.size.0).max(p1.size.1);+ let max_area = crate::vippo::pad_area_mm2(p0).max(crate::vippo::pad_area_mm2(p1));+ if (0.28..=1.25).contains(&pitch) && max_dim <= 0.85 && max_area <= 0.55 {+ let pkg = if pitch <= 0.65 && max_dim <= 0.45 {+ "0201"+ } else {+ "0402"+ };+ return Some((pkg, smd[0], smd[1]));+ }+ None+}++fn is_small_chip_package(fp: &FootprintMeta, board: &Board) -> bool {+ if is_tombstone_chip(fp, board).is_some() {+ return true;+ }+ if lib_has_chip_code(&fp.lib, "0603") {+ return true;+ }+ let smd: Vec<&Pad> = fp+ .pad_indices+ .iter()+ .map(|&i| &board.pads[i])+ .filter(|p| !p.thru && !is_mechanical_pad(p))+ .collect();+ if smd.len() == 2 {+ let pitch = (smd[0].x - smd[1].x).hypot(smd[0].y - smd[1].y);+ let max_dim = smd[0].size.0.max(smd[0].size.1).max(smd[1].size.0).max(smd[1].size.1);+ return (0.28..=1.85).contains(&pitch) && max_dim <= 1.15;+ }+ false+}++/// True median nearest-neighbor pitch among distinct-numbered perimeter SMD pads (< 4 mm^2).+fn footprint_pin_pitch(fp: &FootprintMeta, board: &Board) -> Option<(f64, usize)> {+ let perim: Vec<&Pad> = fp+ .pad_indices+ .iter()+ .map(|&i| &board.pads[i])+ .filter(|p| !p.thru && !is_mechanical_pad(p) && crate::vippo::pad_area_mm2(p) < crate::vippo::EPAD_MIN_AREA_MM2)+ .collect();+ if perim.len() < 8 {+ return None;+ }+ let mut nn_dists = Vec::with_capacity(perim.len());+ for (i, a) in perim.iter().enumerate() {+ let mut best = f64::INFINITY;+ for (j, b) in perim.iter().enumerate() {+ if i == j {+ continue;+ }+ // Skip duplicate sub-pads of the same pin number+ if !a.name.is_empty() && a.name == b.name {+ continue;+ }+ let d = (a.x - b.x).hypot(a.y - b.y);+ if d > 0.08 && d < best {+ best = d;+ }+ }+ if best.is_finite() {+ nn_dists.push(best);+ }+ }+ if nn_dists.is_empty() {+ return None;+ }+ nn_dists.sort_by(|a, b| a.total_cmp(b));+ let median = nn_dists[nn_dists.len() / 2];+ Some((median, perim.len()))+}++fn winning_zone<'a>(zones: &'a [ParsedZone], x: f64, y: f64, layer: usize, net: &str) -> Option<&'a ParsedZone> {+ if net.is_empty() {+ return None;+ }+ for z in zones {+ if z.layer != layer || z.net != net {+ continue;+ }+ if x < z.bbox.0 || x > z.bbox.2 || y < z.bbox.1 || y > z.bbox.3 {+ continue;+ }+ if geom::point_in_poly(x, y, &z.poly) {+ return Some(z);+ }+ }+ None+}++fn effective_zone_connect(pad_zc: Option<ZoneConnectMode>, fp_zc: Option<ZoneConnectMode>, zone_zc: ZoneConnectMode) -> ZoneConnectMode {+ pad_zc.or(fp_zc).unwrap_or(zone_zc)+}++fn via_drill_in_smd_pad(v: &Via, p: &Pad) -> bool {+ if p.thru {+ return false;+ }+ 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.drill * 0.5).max(0.05);+ 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 seg_seg_dist(a0: Pt, a1: Pt, b0: Pt, b1: Pt) -> f64 {+ let cross = |o: Pt, a: Pt, b: Pt| (a.0 - o.0) * (b.1 - o.1) - (a.1 - o.1) * (b.0 - o.0);+ let c1 = cross(a0, a1, b0);+ let c2 = cross(a0, a1, b1);+ let c3 = cross(b0, b1, a0);+ let c4 = cross(b0, b1, a1);+ if ((c1 > 0.0 && c2 < 0.0) || (c1 < 0.0 && c2 > 0.0))+ && ((c3 > 0.0 && c4 < 0.0) || (c3 < 0.0 && c4 > 0.0))+ {+ return 0.0;+ }+ geom::seg_distance(a0.0, a0.1, b0.0, b0.1, b1.0, b1.1)+ .min(geom::seg_distance(a1.0, a1.1, b0.0, b0.1, b1.0, b1.1))+ .min(geom::seg_distance(b0.0, b0.1, a0.0, a0.1, a1.0, a1.1))+ .min(geom::seg_distance(b1.0, b1.1, a0.0, a0.1, a1.0, a1.1))+}++/// Effective connected copper width (mm) of tracks leaving `p` on `layer`.+///+/// Follows connected same-net segments starting from those touching `p`, then measures+/// perpendicular chord widths where that copper crosses a probe circle centered on `p`+/// outside the pad and outside wide-trace endcaps. Internal bends, grid staircases, and+/// wide-trace endcaps never double-count; straight traces measure `W` and pass-through+/// buses measure `2 * W`.+fn pad_track_exit_width(p: &Pad, layer: usize, tracks: &[Track]) -> (f64, f64) {+ if p.net.is_empty() {+ return (0.0, 0.0);+ }+ let tol = 0.05;+ let search_r = p.half_long + 1.8;+ let mut nearby: Vec<&Track> = Vec::new();+ let mut touching_idx: Vec<usize> = Vec::new();+ let mut touch_max_w = 0.0f64;++ for t in tracks {+ if t.layer != layer || t.net != p.net || t.width <= 0.0 {+ continue;+ }+ if geom::seg_distance(p.x, p.y, t.a.0, t.a.1, t.b.0, t.b.1) > search_r + t.width * 0.5 {+ continue;+ }+ let idx = nearby.len();+ nearby.push(t);+ let hits = if !p.polys.is_empty() {+ p.polys.iter().any(|q| geom::seg_poly_distance(t.a, t.b, q) <= tol)+ } else {+ geom::seg_distance(p.x, p.y, t.a.0, t.a.1, t.b.0, t.b.1) <= p.half_long + tol+ };+ if hits {+ touching_idx.push(idx);+ touch_max_w = touch_max_w.max(t.width);+ }+ }+ if touching_idx.is_empty() {+ return (0.0, 0.0);+ }++ // Probe radius stays outside both the pad body and any wide trace's rounded endcap at pad center.+ let probe_r = (p.half_long + 0.25).max(touch_max_w * 0.65).min(1.50);++ // Flood-fill connected same-net segments starting from touching tracks (bounded near probe_r)+ let mut visited = vec![false; nearby.len()];+ let mut queue = std::collections::VecDeque::new();+ for idx in touching_idx {+ visited[idx] = true;+ queue.push_back(idx);+ }+ while let Some(i) = queue.pop_front() {+ let ti = nearby[i];+ for (j, tj) in nearby.iter().enumerate() {+ if visited[j] {+ continue;+ }+ if geom::seg_distance(p.x, p.y, tj.a.0, tj.a.1, tj.b.0, tj.b.1) > probe_r + tj.width * 0.5 + 0.20 {+ continue;+ }+ let d = seg_seg_dist(ti.a, ti.b, tj.a, tj.b);+ if d <= (ti.width + tj.width) * 0.5 + 0.02 {+ visited[j] = true;+ queue.push_back(j);+ }+ }+ }+ let connected: Vec<&Track> = nearby+ .iter()+ .enumerate()+ .filter(|(i, _)| visited[*i])+ .map(|(_, t)| *t)+ .collect();++ // Sample the probe circle and convert each contiguous angular copper run into its chord width+ const SAMPLES: usize = 128;+ let mut hit = [false; SAMPLES];+ let mut any_hit = false;+ for (s, h) in hit.iter_mut().enumerate() {+ let theta = (s as f64 + 0.5) * (std::f64::consts::TAU / SAMPLES as f64);+ let qx = p.x + probe_r * theta.cos();+ let qy = p.y + probe_r * theta.sin();+ if connected+ .iter()+ .any(|t| geom::seg_distance(qx, qy, t.a.0, t.a.1, t.b.0, t.b.1) <= t.width * 0.5)+ {+ *h = true;+ any_hit = true;+ }+ }+ if !any_hit {+ // Connected stub terminates inside probe_r (e.g. short fanout to nearby via)+ return (touch_max_w, touch_max_w);+ }++ // Collect contiguous runs on the circular sample array+ let mut runs: Vec<usize> = Vec::new();+ let mut cur = 0usize;+ for &h in &hit {+ if h {+ cur += 1;+ } else if cur > 0 {+ runs.push(cur);+ cur = 0;+ }+ }+ if cur > 0 {+ if hit[0] && !runs.is_empty() {+ runs[0] += cur;+ } else {+ runs.push(cur);+ }+ }++ let mut total_w = 0.0f64;+ for k in runs {+ if k >= SAMPLES {+ total_w += std::f64::consts::TAU * probe_r;+ } else {+ let dtheta = (k as f64 / SAMPLES as f64) * std::f64::consts::TAU;+ if dtheta <= std::f64::consts::PI {+ total_w += 2.0 * probe_r * (dtheta * 0.5).sin();+ } else {+ total_w += probe_r * dtheta;+ }+ }+ }+ let effective = if total_w > 1e-4 { total_w } else { touch_max_w };+ (effective, touch_max_w)+}++/// Compute distance from `(x, y)` to the board outline (outer loop + cutouts).+fn edge_distance(board: &Board, x: f64, y: f64) -> f64 {+ let mut best = f64::INFINITY;+ let mut check_loop = |poly: &[Pt]| {+ if poly.len() < 2 {+ return;+ }+ for i in 0..poly.len() {+ let a = poly[i];+ let b = poly[(i + 1) % poly.len()];+ best = best.min(geom::seg_distance(x, y, a.0, a.1, b.0, b.1));+ }+ };+ check_loop(&board.outline);+ for c in &board.outline_cutouts {+ check_loop(c);+ }+ if best.is_finite() { best } else { 0.0 }+}++/// Detect whether the board contains multiple non-nested board outlines (panelized PCB) or+/// multiple large board cutouts inside a panel frame.+fn detect_panel_sub_boards(board: &Board, cfg: &DfaConfig) -> Vec<Vec<Pt>> {+ // Board.outline is the largest closed Edge.Cuts loop; outline_cutouts are any other closed loops.+ // On a panelized board:+ // Case A: independent sub-board outlines sitting side-by-side (non-nested, similar size >= 150 mm^2).+ // Case B: a panel frame containing >= 2 sub-board loops or declared via spec.panel.+ let outer_area = geom::polygon_area(&board.outline).abs();+ let mut external_siblings = Vec::new();+ for c in &board.outline_cutouts {+ let a = geom::polygon_area(c).abs();+ if a < 150.0 || c.is_empty() {+ continue;+ }+ // If loop is OUTSIDE board.outline, it's a side-by-side sub-board in a panel!+ if !geom::point_in_poly(c[0].0, c[0].1, &board.outline) {+ external_siblings.push(c.clone());+ }+ }+ if !external_siblings.is_empty() && outer_area >= 150.0 {+ let mut all = vec![board.outline.clone()];+ all.extend(external_siblings);+ return all;+ }+ if cfg.panel_declared && cfg.panel_boards > 1 {+ return Vec::new();+ }+ Vec::new()+}++/// Parse optional BOM CSV for per-reference mass_g/weight_g and height_mm columns.+fn parse_bom_props(bom_csv: Option<&str>) -> (BTreeMap<String, f64>, BTreeMap<String, f64>) {+ let mut mass_g = BTreeMap::new();+ let mut height_mm = BTreeMap::new();+ let Some(text) = bom_csv else {+ return (mass_g, height_mm);+ };+ let rows = crate::preboard::parse_csv(text);+ let Some(header) = rows.first() else {+ return (mass_g, height_mm);+ };+ let norm = |s: &str| s.trim().to_ascii_lowercase().replace([' ', '-', '#'], "_");+ let find_col = |names: &[&str]| header.iter().position(|h| names.iter().any(|n| norm(h) == *n));+ let Some(ref_col) = find_col(&["ref", "reference", "designator", "refs", "designators"]) else {+ return (mass_g, height_mm);+ };+ let mass_col = find_col(&["mass_g", "weight_g", "mass", "weight"]);+ let height_col = find_col(&["height_mm", "body_height_mm", "max_height_mm", "height"]);+ for row in rows.iter().skip(1) {+ let Some(refs_cell) = row.get(ref_col) else {+ continue;+ };+ let refs: Vec<String> = refs_cell+ .split(|c: char| c == ',' || c == ';' || c.is_whitespace())+ .map(|s| s.trim().to_string())+ .filter(|s| !s.is_empty())+ .collect();+ if let Some(mc) = mass_col {+ if let Some(v) = row.get(mc).and_then(|s| parse_leading_f64(s)) {+ if v > 0.0 {+ for r in &refs {+ mass_g.insert(r.clone(), v);+ }+ }+ }+ }+ if let Some(hc) = height_col {+ if let Some(v) = row.get(hc).and_then(|s| parse_leading_f64(s)) {+ if v > 0.0 {+ for r in &refs {+ height_mm.insert(r.clone(), v);+ }+ }+ }+ }+ }+ (mass_g, height_mm)+}++fn parse_leading_f64(s: &str) -> Option<f64> {+ let t = s.trim();+ let end = t+ .find(|c: char| !(c.is_ascii_digit() || c == '.' || c == '-'))+ .unwrap_or(t.len());+ t[..end].parse::<f64>().ok().filter(|v| v.is_finite())+}++/// Extract height encoded in standard KiCad footprint names (e.g. `_H6.5mm`, `_H10.5mm`, `D6.3x7.7mm`).+fn height_from_footprint_name(lib: &str) -> Option<f64> {+ let bytes = lib.as_bytes();+ // Pattern 1: _H<num>mm or -H<num>mm+ for i in 0..bytes.len().saturating_sub(3) {+ if (bytes[i] == b'_' || bytes[i] == b'-') && (bytes[i + 1] == b'H' || bytes[i + 1] == b'h') {+ let rest = &lib[i + 2..];+ if let Some(end) = rest.find("mm") {+ if let Ok(v) = rest[..end].parse::<f64>() {+ if v > 0.0 && v < 100.0 {+ return Some(v);+ }+ }+ }+ }+ }+ // Pattern 2: D<dia>x<height>mm (electrolytic radial/SMD cans, e.g. CP_Elec_6.3x7.7)+ let low = lib.to_ascii_lowercase();+ if low.contains("cp_elec") || low.contains("c_elec") {+ if let Some(pos) = low.rfind('x') {+ let rest = &low[pos + 1..];+ if let Some(v) = parse_leading_f64(rest) {+ if v > 0.5 && v < 100.0 {+ return Some(v);+ }+ }+ }+ }+ None+}++fn heavy_bottom_package_reason(fp: &FootprintMeta, body_span_mm: f64, pad_area_mm2: f64) -> Option<String> {+ let ref_u = fp.reference.trim().to_ascii_uppercase();+ let txt = format!("{} {}", fp.lib, fp.value).to_ascii_lowercase();++ // Small chip packages (0201/0402/0603/0805/1206/2512, SOT-23, TSSOP, SOIC, QFN) hang reliably by surface tension+ if ["0201", "0402", "0603", "0805", "1206", "1210", "2512", "sot-23", "sot23", "sod-", "tssop", "msop", "soic", "dfn", "qfn", "uson", "wson"]+ .iter()+ .any(|k| txt.contains(k))+ && !txt.contains("inductor")+ && !txt.contains("elec")+ && !txt.contains("relay")+ {+ return None;+ }++ if txt.contains("cp_elec") || txt.contains("c_elec") || (txt.contains("electrolytic") && body_span_mm >= 4.0) {+ return Some("aluminum/polymer electrolytic can on B.Cu (heavy/tall reflow drop risk)".into());+ }+ if (ref_u.starts_with('L') && !ref_u.starts_with("LD") && !ref_u.starts_with("LED"))+ || txt.contains("inductor")+ || txt.contains("choke")+ || txt.contains("we-pd")+ || txt.contains("srp")+ || txt.contains("srr")+ || txt.contains("ihlp")+ || txt.contains("xal")+ {+ if body_span_mm >= 4.0 || pad_area_mm2 >= 12.0 {+ return Some(format!(+ "power inductor on B.Cu ({:.1} mm body; heavy winding risks detaching during second reflow)",+ body_span_mm+ ));+ }+ }+ if ref_u.starts_with('K') || txt.contains("relay") {+ return Some("relay on B.Cu (heavy/tall component risks detaching during second reflow)".into());+ }+ if txt.contains("transformer") || (ref_u.starts_with('T') && !ref_u.starts_with("TP") && !ref_u.starts_with("TH") && txt.contains("xfmr")) {+ return Some("transformer on B.Cu (heavy component risks detaching during second reflow)".into());+ }+ if ref_u.starts_with("BT") || txt.contains("battery") || txt.contains("coin_cell") || txt.contains("buzzer") {+ return Some("battery holder or buzzer on B.Cu (heavy/tall component risks detaching during reflow)".into());+ }+ if txt.contains("fuse_holder") || txt.contains("fuseholder") {+ return Some("fuse holder on B.Cu (heavy/tall component risks detaching during reflow)".into());+ }+ let is_conn = ref_u.starts_with('J') || ref_u.starts_with("CN") || ref_u.starts_with("CON");+ if is_conn+ && !txt.contains("pogo")+ && !txt.contains("testpoint")+ && (txt.contains("usb")+ || txt.contains("jst")+ || txt.contains("molex")+ || txt.contains("header")+ || txt.contains("terminalblock")+ || txt.contains("rj45")+ || txt.contains("hdmi")+ || txt.contains("barrel")+ || txt.contains("sd_card")+ || txt.contains("sma")+ || txt.contains("bnc")+ || body_span_mm >= 8.0)+ {+ return Some(format!(+ "connector on B.Cu ({:.1} mm span; heavy/tall part risks detaching or hitting stencil/conveyor supports)",+ body_span_mm+ ));+ }+ let is_sw = ref_u.starts_with("SW") || txt.contains("switch") || txt.contains("tactile") || txt.contains("pushbutton");+ if is_sw && body_span_mm >= 5.5 {+ return Some(format!("large switch on B.Cu ({:.1} mm span; tall/heavy underside part)", body_span_mm));+ }+ None+}++fn build_hot_and_high_current_exemptions(spec: &Value) -> (BTreeMap<String, Option<String>>, BTreeSet<(String, String)>, BTreeSet<String>) {+ // 1. spec.hot: ref -> optional tabNet (or tabPad handled separately)+ let mut hot_tab_net: BTreeMap<String, Option<String>> = BTreeMap::new();+ let mut hot_tab_pads: BTreeSet<(String, String)> = BTreeSet::new();+ if let Some(o) = spec["hot"].as_object() {+ for (r, v) in o {+ if let Some(tp) = v["tabPad"].as_str().filter(|s| !s.is_empty()) {+ hot_tab_pads.insert((r.clone(), tp.to_string()));+ } else {+ hot_tab_net.insert(r.clone(), v["tabNet"].as_str().map(str::to_string));+ }+ }+ }+ // 2. High-current terminals from spec.loads+ let mut high_current_nets: BTreeSet<String> = BTreeSet::new();+ if let Some(o) = spec["loads"].as_object() {+ for (net, v) in o {+ let amps = v["amps"].as_f64().unwrap_or(0.0).abs();+ let is_gnd = net.eq_ignore_ascii_case("GND") || net.to_ascii_uppercase().ends_with("/GND");+ if amps >= 2.0 && !is_gnd {+ high_current_nets.insert(net.clone());+ }+ if let Some(terms) = v["terminals"].as_array() {+ for t in terms {+ let ta = t["amps"].as_f64().unwrap_or(0.0).abs();+ if ta >= 0.5 {+ if let (Some(r), Some(p)) = (t["reference"].as_str(), t["pad"].as_str()) {+ hot_tab_pads.insert((r.to_string(), p.to_string()));+ }+ }+ }+ }+ }+ }+ (hot_tab_net, hot_tab_pads, high_current_nets)+}++fn is_power_carrying_ref(reference: &str) -> bool {+ let r = reference.trim().to_ascii_uppercase();+ r.starts_with('Q')+ || r.starts_with('L')+ || r.starts_with('F')+ || r.starts_with('J')+ || r.starts_with("CN")+ || r.starts_with("RS")+ || r.starts_with("SHUNT")+}++/// Run the full DFA audit (all 4 checks) or placement-only subset (`placement_only = true`).+fn run_audit(+ board: &Board,+ spec: &Value,+ req: &Value,+ bom_csv: Option<&str>,+ board_path: &str,+ placement_only: bool,+) -> Value {+ let cfg = DfaConfig::from_sources(spec, req, board_path);+ let (x0, y0, x1, y1) = board.bbox;+ let bw = (x1 - x0).max(0.0);+ let bh = (y1 - y0).max(0.0);+ let board_area = {+ let a = geom::polygon_area(&board.outline).abs();+ let holes: f64 = board.outline_cutouts.iter().map(|c| geom::polygon_area(c).abs()).sum();+ if a > 1.0 { (a - holes).max(1.0) } else { bw * bh }+ };+ let board_diag = bw.hypot(bh);++ let fps = parse_footprint_meta(board);+ let is_molecule = spec["molecule"].is_object()+ || fps.iter().any(|f| f.is_machine_furniture);++ let mut fitted_top_smd = 0usize;+ let mut fitted_bot_smd = 0usize;+ for fp in &fps {+ if is_fitted_smd_part(fp, board) {+ if fp.layer == B_CU {+ fitted_bot_smd += 1;+ } else {+ fitted_top_smd += 1;+ }+ }+ }+ let total_fitted_smd = fitted_top_smd + fitted_bot_smd;++ let is_pattern = req["boardKind"] == "pattern" || spec["boardKind"] == "pattern";+ let panel_sub_boards = detect_panel_sub_boards(board, &cfg);+ let is_panel = cfg.panel_declared || panel_sub_boards.len() > 1;+ let panel_board_count = if panel_sub_boards.len() > 1 {+ panel_sub_boards.len()+ } else if cfg.panel_boards > 1 {+ cfg.panel_boards+ } else {+ 1+ };+ let is_tiny_board = board_area < DEFAULT_TINY_BOARD_AREA_MM2 || bw.min(bh) < 20.0;++ let context = json!({+ "isMolecule": is_molecule,+ "isTinyBoard": is_tiny_board,+ "isPanel": is_panel,+ "panelBoardCount": panel_board_count,+ "assemblyProfile": cfg.assembly_profile,+ "boardSizeMm": [r2(bw), r2(bh)],+ "boardAreaMm2": r2(board_area),+ "fittedTopSmd": fitted_top_smd,+ "fittedBottomSmd": fitted_bot_smd,+ "placementOnly": placement_only,+ });++ if !cfg.enabled {+ return json!({+ "pass": true,+ "blocking": cfg.blocking,+ "applicable": false,+ "notApplicableReason": "DFA checks disabled by spec/profile (no assembly)",+ "context": context,+ "config": cfg.to_json(),+ "findings": [],+ "notices": [],+ "hints": [],+ });+ }+ if is_pattern || total_fitted_smd == 0 {+ let reason = if is_pattern {+ "pattern board (no SMT assembly)"+ } else {+ "no fitted SMD components on board (through-hole or bare board)"+ };+ return json!({+ "pass": true,+ "blocking": cfg.blocking,+ "applicable": false,+ "notApplicableReason": reason,+ "context": context,+ "config": cfg.to_json(),+ "findings": [],+ "notices": [],+ "hints": [],+ });+ }++ let zones = if placement_only { Vec::new() } else { parse_zones(board) };+ let tracks = if placement_only { Vec::new() } else { board.tracks() };+ let vias = if placement_only { Vec::new() } else { board.vias() };+ let (bom_mass, bom_height) = parse_bom_props(bom_csv);++ let mut all_findings: Vec<String> = Vec::new();+ let mut all_notices: Vec<String> = Vec::new();+ let mut all_hints: Vec<String> = Vec::new();+ let mut push_hint = |h: String| {+ if !h.is_empty() && !all_hints.contains(&h) {+ all_hints.push(h);+ }+ };++ // ---- 1. Small SMD pads tied solid to copper pours without thermal relief ----+ let solid_report = if placement_only {+ json!({"checked": false, "pass": true, "count": 0, "items": [], "findings": [], "hints": []})+ } else {+ let (hot_tab_net, hot_tab_pads, high_current_nets) = build_hot_and_high_current_exemptions(spec);+ let mut items = Vec::new();+ let mut by_cat: BTreeMap<&'static str, usize> = BTreeMap::from([+ ("smallChip", 0),+ ("finePitchIc", 0),+ ("otherSmallSmd", 0),+ ]);+ let mut exempt_counts: BTreeMap<&'static str, usize> = BTreeMap::from([+ ("solidAt", 0),+ ("hotTab", 0),+ ("highCurrent", 0),+ ("smallPatch", 0),+ ("largePad", 0),+ ]);+ let mut nets_layers: BTreeSet<String> = BTreeSet::new();++ for fp in &fps {+ if !is_fitted_smd_part(fp, board) {+ continue;+ }+ let chip_small = is_small_chip_package(fp, board);+ let fp_pitch = footprint_pin_pitch(fp, board);+ let is_fine_ic = fp_pitch.is_some_and(|(pitch, cnt)| cnt >= 8 && pitch <= 0.80);++ for &pidx in &fp.pad_indices {+ let p = &board.pads[pidx];+ if p.thru || p.net.is_empty() || is_mechanical_pad(p) {+ continue;+ }+ let pmeta = fp.pad_meta.get(&pidx);+ let pad_zc = pmeta.and_then(|m| m.zone_connect);+ let layer = if p.on_f { F_CU } else if p.on_b { B_CU } else { continue };+ let Some(z) = winning_zone(&zones, p.x, p.y, layer, &p.net) else {+ continue;+ };+ let eff = effective_zone_connect(pad_zc, fp.fp_zone_connect, z.connect);+ if !eff.is_solid_for_smd() {+ continue;+ }+ let area = crate::vippo::pad_area_mm2(p);+ if area >= crate::vippo::EPAD_MIN_AREA_MM2 {+ *exempt_counts.entry("largePad").or_insert(0) += 1;+ continue;+ }+ // Exemptions for intentional solid connections+ if cfg.solid_exempt.contains(&p.key) || cfg.solid_exempt.contains(&p.reference) {+ *exempt_counts.entry("solidAt").or_insert(0) += 1;+ continue;+ }+ if hot_tab_pads.contains(&(p.reference.clone(), p.name.clone()))+ || hot_tab_net+ .get(&p.reference)+ .is_some_and(|tn| tn.as_deref().is_none_or(|n| n == p.net))+ {+ *exempt_counts.entry("hotTab").or_insert(0) += 1;+ continue;+ }+ if high_current_nets.contains(&p.net) && is_power_carrying_ref(&p.reference) {+ *exempt_counts.entry("highCurrent").or_insert(0) += 1;+ continue;+ }+ if z.area_mm2 < cfg.min_pour_area_mm2 {+ *exempt_counts.entry("smallPatch").or_insert(0) += 1;+ continue;+ }+ let category = if chip_small {+ "smallChip"+ } else if is_fine_ic && area < cfg.small_pad_max_area_mm2 {+ "finePitchIc"+ } else if area < cfg.small_pad_max_area_mm2 {+ "otherSmallSmd"+ } else {+ *exempt_counts.entry("largePad").or_insert(0) += 1;+ continue;+ };+ *by_cat.entry(category).or_insert(0) += 1;+ let lname = aiflow_board::LAYER_NAMES[layer];+ nets_layers.insert(format!("{} on {lname}", p.net));+ items.push(json!({+ "pad": p.key,+ "ref": p.reference,+ "lib": fp.lib.rsplit(':').next().unwrap_or(&fp.lib),+ "net": p.net,+ "layer": lname,+ "category": category,+ "padAreaMm2": r2(area),+ "pourAreaMm2": r2(z.area_mm2),+ "pourFilled": z.filled,+ }));+ }+ }++ let mut f_lines = Vec::new();+ let mut h_lines = Vec::new();+ if !items.is_empty() {+ let sample: Vec<String> = items+ .iter()+ .take(8)+ .map(|it| format!("{} ({})", it["pad"].as_str().unwrap_or("?"), it["net"].as_str().unwrap_or("")))+ .collect();+ let suffix = if items.len() > 8 {+ format!(" and {} more", items.len() - 8)+ } else {+ String::new()+ };+ f_lines.push(format!(+ "solid pour without thermal relief on {} small SMD pad(s) ({} chip, {} fine-pitch IC, {} other small SMD): {}{suffix}",+ items.len(),+ by_cat["smallChip"],+ by_cat["finePitchIc"],+ by_cat["otherSmallSmd"],+ sample.join(", ")+ ));+ let nl: Vec<String> = nets_layers.into_iter().take(4).collect();+ let hint = format!(+ "Switch outer copper pour(s) ({}) to thermal relief (\"connection\": \"thermal\", thermalGap 0.25-0.30 mm, thermalBridge 0.25-0.35 mm) and keep solid connections only on high-current or thermal pads via spec.solidAt or per-pad (zone_connect 2).",+ nl.join(", ")+ );+ h_lines.push(hint.clone());+ push_hint(hint);+ all_findings.extend(f_lines.clone());+ }+ let exempt_total: usize = exempt_counts.values().sum();+ json!({+ "checked": true,+ "pass": f_lines.is_empty(),+ "count": items.len(),+ "byCategory": by_cat,+ "exemptCount": exempt_total,+ "exemptBreakdown": exempt_counts,+ "items": items,+ "findings": f_lines,+ "hints": h_lines,+ })+ };++ // ---- 2. 0402 / 0201 / 01005 pad-connection asymmetry (tombstone risk) ----+ let tombstone_report = if placement_only {+ json!({"checked": false, "pass": true, "checkedChips": 0, "count": 0, "items": [], "findings": [], "hints": []})+ } else {+ let mut checked_chips = 0usize;+ let mut items = Vec::new();+ for fp in &fps {+ let Some((pkg, idx0, idx1)) = is_tombstone_chip(fp, board) else {+ continue;+ };+ checked_chips += 1;+ let (p0, p1) = (&board.pads[idx0], &board.pads[idx1]);+ let layer = fp.layer;++ let eval_pad = |pidx: usize, p: &Pad| -> (bool, bool, f64, bool, f64, f64, f64) {+ let pmeta = fp.pad_meta.get(&pidx);+ let z = winning_zone(&zones, p.x, p.y, layer, &p.net);+ let (solid, thermal, bridge) = match z {+ Some(z) => {+ let eff = effective_zone_connect(pmeta.and_then(|m| m.zone_connect), fp.fp_zone_connect, z.connect);+ let is_s = eff.is_solid_for_smd() && z.area_mm2 >= DEFAULT_TOMBSTONE_SOLID_POUR_MM2;+ let is_t = eff.is_thermal_for_smd() && z.area_mm2 >= DEFAULT_TOMBSTONE_SOLID_POUR_MM2;+ (is_s, is_t, z.thermal_bridge_mm)+ }+ None => (false, false, 0.0),+ };+ let has_vip = vias.iter().any(|v| v.net == p.net && !p.net.is_empty() && via_drill_in_smd_pad(v, p));+ let (eff_w, max_w) = pad_track_exit_width(p, layer, &tracks);+ let area = crate::vippo::pad_area_mm2(p);+ (solid, thermal, bridge, has_vip, eff_w, max_w, area)+ };++ let s0 = eval_pad(idx0, p0);+ let s1 = eval_pad(idx1, p1);+ let mut reasons: Vec<String> = Vec::new();+ let mut kind = "";++ if s0.0 != s1.0 {+ kind = "solid-pour-asymmetry";+ let solid_p = if s0.0 { p0 } else { p1 };+ let other_p = if s0.0 { p1 } else { p0 };+ reasons.push(format!(+ "pad {} ({}) is tied solid to pour while pad {} ({}) is not",+ solid_p.name, solid_p.net, other_p.name, other_p.net+ ));+ }+ if s0.3 != s1.3 {+ if kind.is_empty() {+ kind = "one-sided-via-in-pad";+ }+ let vip_p = if s0.3 { p0 } else { p1 };+ reasons.push(format!("via-in-pad on pad {} ({}) only", vip_p.name, vip_p.net));+ }+ let area_hi = s0.6.max(s1.6);+ let area_lo = s0.6.min(s1.6);+ if area_lo > 1e-4 && area_hi / area_lo >= 1.5 {+ if kind.is_empty() {+ kind = "pad-area-asymmetry";+ }+ reasons.push(format!("pad copper areas differ ({:.2} vs {:.2} mm2)", area_hi, area_lo));+ }+ if !s0.0 && !s1.0 {+ // Compare effective connected copper widths; thermal-relieved pour contributes ~2 spoke widths+ // so a power trace balanced by a thermal-relieved GND pad is not falsely flagged.+ let eff0 = if s0.1 { s0.4.max(s0.2 * 2.0) } else { s0.4 };+ let eff1 = if s1.1 { s1.4.max(s1.2 * 2.0) } else { s1.4 };+ let w_hi = eff0.max(eff1);+ let w_lo = eff0.min(eff1);+ let min_wide = if pkg == "0402" {+ cfg.tombstone_min_wide_mm+ } else {+ (cfg.tombstone_min_wide_mm * 0.72).max(0.20)+ };+ // Skip flagging pure thermal-relieved GND pour vs normal signal trace unless the+ // thermal bridge itself is oversized (> 0.45 mm) against a very thin trace (< 0.14 mm)+ let thermal_vs_normal = (s0.1 != s1.1)+ && ((s0.1 && s0.4 < min_wide && s0.2 <= 0.45 && s1.4.max(s1.5) >= 0.14)+ || (s1.1 && s1.4 < min_wide && s1.2 <= 0.45 && s0.4.max(s0.5) >= 0.14));+ // Require the wide side to actually carry a wide trace (or thermal pour)+ // so ordinary 0.15-0.20 mm signal T-junctions on both pads do not false-positive.+ let wide_max_track = if eff0 >= eff1 { s0.5 } else { s1.5 };+ let wide_has_thermal = if eff0 >= eff1 { s0.1 } else { s1.1 };+ let min_wide_track = if pkg == "0402" { 0.25 } else { 0.20 };+ let genuine_wide = wide_has_thermal || wide_max_track >= min_wide_track;+ if !thermal_vs_normal+ && genuine_wide+ && w_lo > 0.01+ && w_hi >= min_wide+ && (w_hi / w_lo) >= cfg.tombstone_width_ratio+ {+ if kind.is_empty() {+ kind = "copper-width-asymmetry";+ }+ reasons.push(format!(+ "connected copper width {:.2} mm vs {:.2} mm ({:.1}:1)",+ w_hi,+ w_lo,+ w_hi / w_lo+ ));+ }+ }++ if !reasons.is_empty() {+ items.push(json!({+ "ref": fp.reference,+ "package": pkg,+ "lib": fp.lib.rsplit(':').next().unwrap_or(&fp.lib),+ "layer": aiflow_board::LAYER_NAMES[layer],+ "kind": kind,+ "reason": reasons.join("; "),+ "pad0": {"name": p0.name, "net": p0.net, "solidPour": s0.0, "thermalPour": s0.1, "viaInPad": s0.3, "exitWidthMm": r2(s0.4), "maxTrackMm": r2(s0.5)},+ "pad1": {"name": p1.name, "net": p1.net, "solidPour": s1.0, "thermalPour": s1.1, "viaInPad": s1.3, "exitWidthMm": r2(s1.4), "maxTrackMm": r2(s1.5)},+ }));+ }+ }++ let mut f_lines = Vec::new();+ let mut h_lines = Vec::new();+ if !items.is_empty() {+ let mut by_kind: BTreeMap<String, usize> = BTreeMap::new();+ for it in &items {+ *by_kind.entry(it["kind"].as_str().unwrap_or("other").to_string()).or_insert(0) += 1;+ }+ let sample: Vec<String> = items+ .iter()+ .take(8)+ .map(|it| format!("{} ({})", it["ref"].as_str().unwrap_or("?"), it["reason"].as_str().unwrap_or("")))+ .collect();+ let suffix = if items.len() > 8 {+ format!(" and {} more", items.len() - 8)+ } else {+ String::new()+ };+ f_lines.push(format!(+ "0402/0201 tombstone risk on {} of {} small chip(s): {}{suffix}",+ items.len(),+ checked_chips,+ sample.join("; ")+ ));+ let hint = "Balance thermal mass on both pads of 0402/0201 parts: use thermal relief instead of solid pour, move one-sided via-in-pad off-pad with a short neck trace, and neck wide power traces down to <= 0.25 mm for >= 0.5 mm before entering the pad.".to_string();+ h_lines.push(hint.clone());+ push_hint(hint);+ all_findings.extend(f_lines.clone());+ }+ json!({+ "checked": true,+ "pass": f_lines.is_empty(),+ "checkedChips": checked_chips,+ "count": items.len(),+ "items": items,+ "findings": f_lines,+ "hints": h_lines,+ })+ };++ // ---- 3. Global fiducials (per board and per panel) and local fiducials near fine-pitch parts ----+ let fiducial_report = if cfg.skip_machine_smt {+ let note = "hand/self assembly profile: optical fiducial checks skipped".to_string();+ all_notices.push(note.clone());+ json!({+ "checked": false,+ "pass": true,+ "skipped": note,+ "global": [],+ "finePitchParts": [],+ "findings": [],+ "hints": [],+ })+ } else {+ #[derive(Clone)]+ struct FidInfo {+ reference: String,+ layer: usize,+ x: f64,+ y: f64,+ pad_dia: f64,+ has_paste: bool,+ edge_mm: f64,+ }++ let mut fids: Vec<FidInfo> = Vec::new();+ for fp in &fps {+ if !fp.is_fiducial {+ continue;+ }+ let (pad_dia, has_paste) = if let Some(&pidx) = fp.pad_indices.first() {+ let p = &board.pads[pidx];+ let pm = fp.pad_meta.get(&pidx);+ (+ p.size.0.max(p.size.1),+ pm.is_some_and(|m| m.on_f_paste || m.on_b_paste),+ )+ } else {+ (0.0, fp.has_paste)+ };+ fids.push(FidInfo {+ reference: fp.reference.clone(),+ layer: fp.layer,+ x: fp.x,+ y: fp.y,+ pad_dia,+ has_paste,+ edge_mm: edge_distance(board, fp.x, fp.y),+ });+ }++ // Identify fine-pitch SMD packages (for local fiducial and tiny-board checks)+ let max_dim = bw.max(bh);+ let mut fine_pitch_parts = Vec::new();+ let mut missing_local_refs = Vec::new();++ for fp in &fps {+ if !is_fitted_smd_part(fp, board) {+ continue;+ }+ let Some((pitch, pin_count)) = footprint_pin_pitch(fp, board) else {+ continue;+ };+ let lib_l = fp.lib.to_ascii_lowercase();+ let is_bga_csp = lib_l.contains("bga") || lib_l.contains("wlcsp") || lib_l.contains("csp") || lib_l.contains("lga");+ // Mechanically keyed connectors with >= 2 NPTH alignment pegs self-align+ let npth_pegs = board.holes.iter().filter(|h| h.reference == fp.reference && !h.plated).count();+ let is_keyed_conn = (fp.reference.to_ascii_uppercase().starts_with('J') || lib_l.contains("usb") || lib_l.contains("connector")) && npth_pegs >= 2;+ if is_keyed_conn {+ continue;+ }++ let pitch_limit = if is_bga_csp {+ cfg.local_fiducial_max_pitch_mm.max(0.65)+ } else if max_dim <= 50.0 && !cfg.local_fiducials_always {+ cfg.local_fiducial_max_pitch_mm.min(0.40)+ } else {+ cfg.local_fiducial_max_pitch_mm+ };+ let min_pins = if is_bga_csp { 9 } else { 16 };+ if pitch > pitch_limit + 1e-4 || pin_count < min_pins {+ continue;+ }++ // Compute pad bbox of this fine-pitch part+ let pb = board.pad_box(&fp.reference).unwrap_or((fp.x - 2.0, fp.y - 2.0, fp.x + 2.0, fp.y + 2.0));+ let part_diag = (pb.2 - pb.0).hypot(pb.3 - pb.1);+ let near_fids: Vec<&FidInfo> = fids+ .iter()+ .filter(|f| {+ f.layer == fp.layer && {+ let dx = if f.x < pb.0 { pb.0 - f.x } else if f.x > pb.2 { f.x - pb.2 } else { 0.0 };+ let dy = if f.y < pb.1 { pb.1 - f.y } else if f.y > pb.3 { f.y - pb.3 } else { 0.0 };+ dx.hypot(dy) <= DEFAULT_LOCAL_FIDUCIAL_RADIUS_MM+ }+ })+ .collect();+ let has_local_pair = near_fids.len() >= 2 && {+ let mut max_sep = 0.0f64;+ for i in 0..near_fids.len() {+ for j in (i + 1)..near_fids.len() {+ max_sep = max_sep.max((near_fids[i].x - near_fids[j].x).hypot(near_fids[i].y - near_fids[j].y));+ }+ }+ max_sep >= (part_diag * 0.5).max(2.0)+ };+ if !has_local_pair {+ missing_local_refs.push(format!("{} ({} pins, {:.2} mm pitch)", fp.reference, pin_count, pitch));+ }+ fine_pitch_parts.push(json!({+ "ref": fp.reference,+ "lib": fp.lib.rsplit(':').next().unwrap_or(&fp.lib),+ "layer": aiflow_board::LAYER_NAMES[fp.layer],+ "pinCount": pin_count,+ "pitchMm": r3(pitch),+ "isBgaCsp": is_bga_csp,+ "nearbyFiducials": near_fids.iter().map(|f| f.reference.clone()).collect::<Vec<_>>(),+ "hasLocalFiducialPair": has_local_pair,+ }));+ }++ let mut f_lines = Vec::new();+ let mut h_lines = Vec::new();++ // Compact molecules (<= 45 mm with MP1..MP4 corner pins) accept 2 diagonal fiducials and 2.5 mm edge margin+ let compact_molecule = is_molecule && max_dim <= 45.0;+ let req_global = cfg.min_global_fiducials.unwrap_or(if compact_molecule { 2 } else { 3 });+ let req_edge_mm = cfg.fiducial_edge_mm.unwrap_or(if compact_molecule {+ DEFAULT_MOLECULE_FIDUCIAL_EDGE_MM+ } else {+ DEFAULT_FIDUCIAL_EDGE_MM+ });++ let has_any_fine_pitch_ic = fps.iter().any(|fp| {+ is_fitted_smd_part(fp, board) && footprint_pin_pitch(fp, board).is_some_and(|(p, c)| c >= 12 && p <= 0.65)+ });++ if cfg.fiducials_on_panel {+ all_notices.push("global fiducials declared on panel rails (spec.dfa.fiducialsOnPanel = true)".into());+ } else if is_tiny_board && !has_any_fine_pitch_ic {+ all_notices.push(format!(+ "tiny board ({:.1} x {:.1} mm) with no fine-pitch ICs: per-board global fiducials not required (carry global fiducials on panel rails if machine-assembled)",+ bw, bh+ ));+ } else {+ for (layer, smd_cnt) in [(F_CU, fitted_top_smd), (B_CU, fitted_bot_smd)] {+ if smd_cnt == 0 {+ continue;+ }+ let lname = aiflow_board::LAYER_NAMES[layer];+ let side_fids: Vec<&FidInfo> = fids.iter().filter(|f| f.layer == layer).collect();+ if side_fids.len() < req_global {+ f_lines.push(format!(+ "global fiducials on {lname}: found {} (recommend >= {} for {} fitted SMD part(s){})",+ side_fids.len(),+ req_global,+ smd_cnt,+ if is_panel { format!(", panel with {panel_board_count} boards") } else { String::new() }+ ));+ }+ // Quality checks on existing fiducials+ for f in &side_fids {+ if f.has_paste {+ f_lines.push(format!("fiducial {} on {lname} has solder paste enabled (must be bare copper, no paste)", f.reference));+ }+ if f.edge_mm < req_edge_mm - 1e-3 && !is_panel {+ f_lines.push(format!(+ "fiducial {} on {lname} is {:.2} mm from board edge (recommend >= {:.1} mm for conveyor rail clearance)",+ f.reference, f.edge_mm, req_edge_mm+ ));+ }+ }+ // Collinearity check when >= 3 fiducials exist+ if side_fids.len() >= 3 {+ let mut max_d = 0.0f64;+ let mut max_tri = 0.0f64;+ for i in 0..side_fids.len() {+ for j in (i + 1)..side_fids.len() {+ let d = (side_fids[i].x - side_fids[j].x).hypot(side_fids[i].y - side_fids[j].y);+ max_d = max_d.max(d);+ for k in (j + 1)..side_fids.len() {+ let tri = 0.5+ * ((side_fids[j].x - side_fids[i].x) * (side_fids[k].y - side_fids[i].y)+ - (side_fids[k].x - side_fids[i].x) * (side_fids[j].y - side_fids[i].y))+ .abs();+ max_tri = max_tri.max(tri);+ }+ }+ }+ if max_d > 1.0 && max_tri < 0.05 * max_d * max_d {+ f_lines.push(format!(+ "global fiducials on {lname} are nearly collinear (place them in an asymmetric triangle spanning the board)"+ ));+ }+ } else if side_fids.len() == 2 && req_global == 2 && board_diag > 1.0 {+ let sep = (side_fids[0].x - side_fids[1].x).hypot(side_fids[0].y - side_fids[1].y);+ if sep < 0.40 * board_diag {+ f_lines.push(format!(+ "global fiducials on {lname} are only {:.1} mm apart (< 40% of {:.1} mm board diagonal); place on opposite corners",+ sep, board_diag+ ));+ }+ }+ }++ // Per-sub-board fiducials on detected panels+ if panel_sub_boards.len() > 1 {+ let mut missing_sub = 0usize;+ for sb in &panel_sub_boards {+ let has_fine_in_sub = fine_pitch_parts.iter().any(|fp_v| {+ let r = fp_v["ref"].as_str().unwrap_or("");+ board.footprints.get(r).is_some_and(|f| geom::point_in_poly(f.x, f.y, sb))+ });+ if !has_fine_in_sub {+ continue;+ }+ let sb_fids = fids.iter().filter(|f| geom::point_in_poly(f.x, f.y, sb)).count();+ if sb_fids < 2 {+ missing_sub += 1;+ }+ }+ if missing_sub > 0 {+ f_lines.push(format!(+ "panelized layout ({} boards): {} sub-board(s) with fine-pitch parts lack >= 2 per-board fiducials",+ panel_sub_boards.len(),+ missing_sub+ ));+ }+ }+ }++ if !missing_local_refs.is_empty() {+ let sample: Vec<String> = missing_local_refs.iter().take(6).cloned().collect();+ let suffix = if missing_local_refs.len() > 6 {+ format!(" and {} more", missing_local_refs.len() - 6)+ } else {+ String::new()+ };+ f_lines.push(format!(+ "local fiducials missing near {} fine-pitch IC(s) (<= {:.2} mm pitch): {}{suffix}",+ missing_local_refs.len(),+ cfg.local_fiducial_max_pitch_mm,+ sample.join(", ")+ ));+ }++ if !f_lines.is_empty() {+ let hint = if compact_molecule {+ format!(+ "Add >= {req_global} diagonal 1.0 mm bare-copper global fiducials (2.0-3.0 mm mask opening, no paste, >= {req_edge_mm:.1} mm from edge) per assembled side, or declare \"dfa\": {{\"fiducialsOnPanel\": true}} when global fiducials are placed on panel rails."+ )+ } else {+ format!(+ "Add >= {req_global} asymmetric global fiducials per assembled side (1.0 mm bare copper circle, 2.0-3.0 mm solder mask opening, no paste, >= {req_edge_mm:.1} mm from board/panel edge), and 2 diagonal local fiducials beside <= {:.2} mm pitch BGAs/QFNs.",+ cfg.local_fiducial_max_pitch_mm+ )+ };+ h_lines.push(hint.clone());+ push_hint(hint);+ all_findings.extend(f_lines.clone());+ }++ json!({+ "checked": true,+ "pass": f_lines.is_empty(),+ "requiredGlobalPerSide": req_global,+ "requiredEdgeClearanceMm": req_edge_mm,+ "panelBoardCount": panel_board_count,+ "globalCount": fids.len(),+ "global": fids.iter().map(|f| json!({+ "ref": f.reference,+ "layer": aiflow_board::LAYER_NAMES[f.layer],+ "at": [r2(f.x), r2(f.y)],+ "padDiaMm": r2(f.pad_dia),+ "hasPaste": f.has_paste,+ "edgeDistanceMm": r2(f.edge_mm),+ })).collect::<Vec<_>>(),+ "finePitchParts": fine_pitch_parts,+ "findings": f_lines,+ "hints": h_lines,+ })+ };++ // ---- 4. Bottom-side reflow rules (double-sided SMT, heavy or tall parts on B.Cu) ----+ let bottom_report = if cfg.skip_machine_smt {+ let note = "hand/self assembly profile: bottom-side reflow checks skipped".to_string();+ all_notices.push(note.clone());+ json!({+ "checked": false,+ "pass": true,+ "skipped": note,+ "bottomSmdCount": fitted_bot_smd,+ "doubleSided": fitted_top_smd > 0 && fitted_bot_smd > 0,+ "heavyOrTall": [],+ "findings": [],+ "notices": [note],+ "hints": [],+ })+ } else {+ let double_sided = fitted_top_smd > 0 && fitted_bot_smd > 0;+ let mut heavy_or_tall = Vec::new();+ let mut f_lines = Vec::new();+ let mut n_lines = Vec::new();+ let mut h_lines = Vec::new();++ if double_sided {+ let notice = format!(+ "double-sided SMT assembly: {} fitted SMD part(s) on B.Cu (adds second stencil/reflow pass and requires bottom-side CPL rotation verification)",+ fitted_bot_smd+ );+ n_lines.push(notice.clone());+ all_notices.push(notice);++ if cfg.single_sided_only {+ f_lines.push(format!(+ "bottom-side SMT parts present ({} on B.Cu) while singleSidedOnly is set",+ fitted_bot_smd+ ));+ }++ // Check every fitted SMD footprint on B.Cu for mass/pad-area, height, or heavy package class+ for fp in &fps {+ if fp.layer != B_CU || !is_fitted_smd_part(fp, board) {+ continue;+ }+ if cfg.bottom_exempt.contains(&fp.reference) {+ continue;+ }+ let smd_pad_area_mm2: f64 = fp+ .pad_indices+ .iter()+ .map(|&i| &board.pads[i])+ .filter(|p| !p.thru)+ .map(crate::vippo::pad_area_mm2)+ .sum();+ let pad_area_cm2 = (smd_pad_area_mm2 / 100.0).max(1e-6);++ let body_span_mm = fp+ .fab_bbox+ .map(|(bx0, by0, bx1, by1)| (bx1 - bx0).abs().max((by1 - by0).abs()))+ .or_else(|| {+ board+ .pad_box(&fp.reference)+ .map(|(px0, py0, px1, py1)| (px1 - px0).abs().max((py1 - py0).abs()))+ })+ .unwrap_or(0.0);++ // Mass from spec.dfa.partMassG or BOM CSV+ let mass_g = spec["dfa"]["partMassG"][&fp.reference]+ .as_f64()+ .or_else(|| bom_mass.get(&fp.reference).copied());+ // Height from spec.bodies[ref], spec.dfa.partHeightMm, BOM CSV, or KiCad lib name+ let height_mm = spec["dfa"]["partHeightMm"][&fp.reference]+ .as_f64()+ .or_else(|| spec["bodies"][&fp.reference]["heightMm"].as_f64())+ .or_else(|| spec["bodies"][&fp.reference]["height"].as_f64())+ .or_else(|| spec["bodies"][&fp.reference]["z"].as_f64())+ .or_else(|| bom_height.get(&fp.reference).copied())+ .or_else(|| height_from_footprint_name(&fp.lib));++ let mut reasons = Vec::new();+ let mut g_per_cm2 = None;+ if let Some(m) = mass_g {+ let ratio = m / pad_area_cm2;+ g_per_cm2 = Some(ratio);+ if ratio > cfg.bottom_max_g_per_cm2 {+ reasons.push(format!(+ "mass/pad-area {:.1} g/cm2 exceeds {:.1} g/cm2 limit ({:.2} g on {:.2} mm2 solder area)",+ ratio, cfg.bottom_max_g_per_cm2, m, smd_pad_area_mm2+ ));+ }+ } else if let Some(pkg_why) = heavy_bottom_package_reason(fp, body_span_mm, smd_pad_area_mm2) {+ reasons.push(pkg_why);+ }+ if let Some(h) = height_mm {+ if h > cfg.bottom_max_height_mm {+ reasons.push(format!(+ "height {:.1} mm exceeds {:.1} mm bottom-side reflow/conveyor clearance limit",+ h, cfg.bottom_max_height_mm+ ));+ }+ }+ if !reasons.is_empty() {+ heavy_or_tall.push(json!({+ "ref": fp.reference,+ "value": fp.value,+ "lib": fp.lib.rsplit(':').next().unwrap_or(&fp.lib),+ "solderPadAreaMm2": r2(smd_pad_area_mm2),+ "bodySpanMm": r2(body_span_mm),+ "massG": mass_g.map(r3),+ "massPerAreaGPerCm2": g_per_cm2.map(r2),+ "heightMm": height_mm.map(r2),+ "reason": reasons.join("; "),+ }));+ }+ }++ if !heavy_or_tall.is_empty() {+ let sample: Vec<String> = heavy_or_tall+ .iter()+ .take(6)+ .map(|it| format!("{} ({})", it["ref"].as_str().unwrap_or("?"), it["reason"].as_str().unwrap_or("")))+ .collect();+ f_lines.push(format!(+ "heavy or tall bottom-side SMD part(s) on B.Cu ({}): {}",+ heavy_or_tall.len(),+ sample.join("; ")+ ));+ let hint = "Move heavy or tall SMD components to F.Cu so they do not detach during second-pass reflow or collide with stencil/conveyor supports, or specify SMT adhesive dots and list them in spec.dfa.bottomExempt.".to_string();+ h_lines.push(hint.clone());+ push_hint(hint);+ all_findings.extend(f_lines.clone());+ } else if cfg.single_sided_only {+ let hint = "Move bottom-side SMD parts to F.Cu to keep assembly single-sided, or remove spec.dfa.singleSidedOnly.".to_string();+ h_lines.push(hint.clone());+ push_hint(hint);+ all_findings.extend(f_lines.clone());+ }+ } else if fitted_bot_smd > 0 && fitted_top_smd == 0 {+ let notice = format!(+ "single-sided bottom assembly ({fitted_bot_smd} SMD part(s) on B.Cu, 0 on F.Cu): reflowed face-up in one pass, no underside hang risk"+ );+ n_lines.push(notice.clone());+ all_notices.push(notice);+ }++ json!({+ "checked": true,+ "pass": f_lines.is_empty(),+ "bottomSmdCount": fitted_bot_smd,+ "doubleSided": double_sided,+ "heavyOrTall": heavy_or_tall,+ "findings": f_lines,+ "notices": n_lines,+ "hints": h_lines,+ })+ };++ let pass = all_findings.is_empty();+ json!({+ "pass": pass,+ "blocking": cfg.blocking,+ "applicable": true,+ "notApplicableReason": Value::Null,+ "context": context,+ "config": cfg.to_json(),+ "solidPads": solid_report,+ "tombstone": tombstone_report,+ "fiducials": fiducial_report,+ "bottomReflow": bottom_report,+ "findings": all_findings,+ "notices": all_notices,+ "hints": all_hints,+ })+}++/// Full DFA audit (solid pours on small pads, 0402/0201 tombstone risk, fiducials, bottom-side reflow).+pub fn audit_board(+ board: &Board,+ spec: &Value,+ req: &Value,+ bom_csv: Option<&str>,+ board_path: &str,+) -> Value {+ run_audit(board, spec, req, bom_csv, board_path, false)+}++/// Placement-stage DFA audit (fiducials and bottom-side reflow only; skips routing/pour checks).+pub fn audit_placement(+ board: &Board,+ spec: &Value,+ req: &Value,+ bom_csv: Option<&str>,+ board_path: &str,+) -> Value {+ run_audit(board, spec, req, bom_csv, board_path, true)+}++/// Non-empty findings only when DFA is configured as blocking and failed.+pub fn blocking_findings(report: &Value) -> Vec<String> {+ if report["blocking"] != true || report["pass"] == true {+ return Vec::new();+ }+ report["findings"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .map(str::to_string)+ .collect()+}++/// Human- and AI-readable summary text and deduplicated fix hints.+pub fn format_summary(report: &Value) -> (String, Vec<String>) {+ if report["applicable"] == false {+ let why = report["notApplicableReason"].as_str().unwrap_or("not applicable");+ return (format!("DFA check not applicable ({why})"), Vec::new());+ }+ let findings: Vec<String> = report["findings"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .map(str::to_string)+ .collect();+ let notices: Vec<String> = report["notices"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .map(str::to_string)+ .collect();+ let mut hints: Vec<String> = report["hints"]+ .as_array()+ .into_iter()+ .flatten()+ .filter_map(Value::as_str)+ .map(str::to_string)+ .collect();++ let blocking = report["blocking"] == true;+ let ctx = &report["context"];+ let header = format!(+ "top SMD {}, bottom SMD {}, size {}x{} mm{}",+ ctx["fittedTopSmd"],+ ctx["fittedBottomSmd"],+ ctx["boardSizeMm"][0],+ ctx["boardSizeMm"][1],+ if ctx["isMolecule"] == true { ", molecule" } else { "" }+ );++ if findings.is_empty() {+ let mut msg = format!("DFA check clean ({header})");+ if !notices.is_empty() {+ msg.push_str(&format!("\n note: {}", notices.join("\n note: ")));+ }+ return (msg, hints);+ }++ let mode = if blocking { "blocking" } else { "advisory, non-blocking" };+ let mut msg = format!(+ "DFA check found {} finding(s) ({mode}; {header}):\n {}",+ findings.len(),+ findings.join("\n ")+ );+ if !notices.is_empty() {+ msg.push_str(&format!("\n note: {}", notices.join("\n note: ")));+ }+ if !blocking {+ hints.push(+ "DFA findings warn by default. To make them blocking, set \"dfa\": {\"blocking\": true} (or \"fab\": {\"dfaBlocking\": true}) in spec.json, use a strict assembly profile, or add `# adom-aiflow: dfaBlocking` to <board>.kicad_dru.".into()+ );+ }+ (msg, hints)+}++#[cfg(test)]+mod tests {+ use super::*;++ const LAYERS_2L: &str = "(0 \"F.Cu\" signal) (2 \"B.Cu\" signal) (25 \"Edge.Cuts\" user)";++ fn fiducial_sexpr(r: &str, layer: &str, x: f64, y: f64) -> String {+ let mask = if layer == "B.Cu" { "B.Mask" } else { "F.Mask" };+ format!(+ "(footprint \"Fiducial:Fiducial_1mm_Mask2mm\" (layer \"{layer}\") (at {x} {y}) (property \"Reference\" \"{r}\") (property \"Value\" \"Fiducial\") \+ (pad \"\" smd circle (at 0 0) (size 1.0 1.0) (layers \"{layer}\" \"{mask}\") (solder_mask_margin 0.5)))"+ )+ }++ fn three_fids(layer: &str) -> String {+ format!(+ "{} {} {}",+ fiducial_sexpr("FID1", layer, 5.0, 5.0),+ fiducial_sexpr("FID2", layer, 55.0, 5.0),+ fiducial_sexpr("FID3", layer, 5.0, 35.0),+ )+ }++ fn mk_board(w: f64, h: f64, body: &str) -> Board {+ let pcb = format!(+ "(kicad_pcb (version 20241229) (generator \"test\") (general (thickness 1.6)) \+ (layers {LAYERS_2L}) \+ (net 0 \"\") (net 1 \"GND\") (net 2 \"SIG\") (net 3 \"VIN\") (net 4 \"V3V3\") \+ {body} \+ (gr_rect (start 0 0) (end {w} {h}) (layer \"Edge.Cuts\") (stroke (width 0.1) (type solid))))"+ );+ Board::from_text("dfa-test.kicad_pcb", pcb).unwrap()+ }++ #[test]+ fn flags_solid_pour_on_small_smd_pads_and_exempts_solid_at_hot_and_high_current() {+ let body = format!(+ "{} \+ (footprint \"Resistor_SMD:R_0603_1608Metric\" (layer \"F.Cu\") (at 20 20) (property \"Reference\" \"R1\") (property \"Value\" \"10k\") \+ (pad \"1\" smd rect (at -0.8 0) (size 0.8 0.9) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 2 \"SIG\")) \+ (pad \"2\" smd rect (at 0.8 0) (size 0.8 0.9) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 1 \"GND\"))) \+ (footprint \"Resistor_SMD:R_0603_1608Metric\" (layer \"F.Cu\") (at 25 20) (property \"Reference\" \"R2\") (property \"Value\" \"0R\") \+ (pad \"1\" smd rect (at -0.8 0) (size 0.8 0.9) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 2 \"SIG\")) \+ (pad \"2\" smd rect (at 0.8 0) (size 0.8 0.9) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 1 \"GND\"))) \+ (footprint \"Package_TO_SOT_SMD:SOT-23\" (layer \"F.Cu\") (at 35 20) (property \"Reference\" \"Q1\") (property \"Value\" \"FET\") \+ (pad \"1\" smd rect (at -0.9 0) (size 0.8 0.9) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 3 \"VIN\")) \+ (pad \"2\" smd rect (at 0.9 0) (size 0.8 0.9) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 1 \"GND\"))) \+ (zone (net 1) (net_name \"GND\") (layer \"F.Cu\") (connect_pads yes (clearance 0.2)) \+ (polygon (pts (xy 2 2) (xy 58 2) (xy 58 38) (xy 2 38))) \+ (filled_polygon (layer \"F.Cu\") (pts (xy 2 2) (xy 58 2) (xy 58 38) (xy 2 38)))) \+ (zone (net 3) (net_name \"VIN\") (layer \"F.Cu\") (priority 2) (connect_pads yes (clearance 0.2)) \+ (polygon (pts (xy 30 15) (xy 42 15) (xy 42 25) (xy 30 25))) \+ (filled_polygon (layer \"F.Cu\") (pts (xy 30 15) (xy 42 15) (xy 42 25) (xy 30 25))))",+ three_fids("F.Cu")+ );+ let b = mk_board(60.0, 40.0, &body);+ let spec = json!({+ "solidAt": ["R2.2"],+ "hot": {"Q1": {"watts": 0.5, "tabNet": "GND"}},+ "loads": {"VIN": {"amps": 5.0}}+ });+ let r = audit_board(&b, &spec, &json!({}), None, "");+ assert_eq!(r["solidPads"]["count"], 1, "{r}");+ assert_eq!(r["solidPads"]["items"][0]["pad"], "R1.2");+ assert!(r["solidPads"]["exemptBreakdown"]["solidAt"].as_u64().unwrap() >= 1);+ assert!(r["solidPads"]["exemptBreakdown"]["hotTab"].as_u64().unwrap() >= 1);+ assert_eq!(r["pass"], false);+ assert_eq!(r["blocking"], false);++ // Switching zone to thermal relief clears the finding+ let body_thermal = body.replace("(connect_pads yes", "(connect_pads");+ let b2 = mk_board(60.0, 40.0, &body_thermal);+ let r2 = audit_board(&b2, &spec, &json!({}), None, "");+ assert_eq!(r2["solidPads"]["count"], 0, "{r2}");+ assert_eq!(r2["pass"], true, "{r2}");+ }++ #[test]+ fn tombstone_catches_real_asymmetry_and_avoids_thermal_relief_and_offpad_via_false_positives() {+ let body = format!(+ "{} \+ (footprint \"Resistor_SMD:R_0402_1005Metric\" (layer \"F.Cu\") (at 15 15) (property \"Reference\" \"R_WIDE\") (property \"Value\" \"10k\") \+ (pad \"1\" smd rect (at -0.5 0) (size 0.54 0.64) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 3 \"VIN\")) \+ (pad \"2\" smd rect (at 0.5 0) (size 0.54 0.64) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 2 \"SIG\"))) \+ (segment (start 14.5 15) (end 10.0 15) (width 0.60) (layer \"F.Cu\") (net 3)) \+ (segment (start 15.5 15) (end 19.0 15) (width 0.15) (layer \"F.Cu\") (net 2)) \+ (footprint \"Capacitor_SMD:C_0402_1005Metric\" (layer \"F.Cu\") (at 25 15) (property \"Reference\" \"C_VIP\") (property \"Value\" \"100n\") \+ (pad \"1\" smd rect (at -0.5 0) (size 0.54 0.64) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 2 \"SIG\")) \+ (pad \"2\" smd rect (at 0.5 0) (size 0.54 0.64) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 1 \"GND\"))) \+ (via (at 25.5 15) (size 0.5) (drill 0.25) (layers \"F.Cu\" \"B.Cu\") (net 1)) \+ (segment (start 24.5 15) (end 22.0 15) (width 0.20) (layer \"F.Cu\") (net 2)) \+ (footprint \"Capacitor_SMD:C_0402_1005Metric\" (layer \"F.Cu\") (at 35 15) (property \"Reference\" \"C_OK_THERM\") (property \"Value\" \"100n\") \+ (pad \"1\" smd rect (at -0.5 0) (size 0.54 0.64) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 4 \"V3V3\")) \+ (pad \"2\" smd rect (at 0.5 0) (size 0.54 0.64) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 1 \"GND\"))) \+ (segment (start 34.5 15) (end 32.0 15) (width 0.20) (layer \"F.Cu\") (net 4)) \+ (via (at 35.95 15) (size 0.45) (drill 0.20) (layers \"F.Cu\" \"B.Cu\") (net 1)) \+ (footprint \"Resistor_SMD:R_0402_1005Metric\" (layer \"F.Cu\") (at 45 15) (property \"Reference\" \"R_THIN_OK\") (property \"Value\" \"10k\") \+ (pad \"1\" smd rect (at -0.5 0) (size 0.54 0.64) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 2 \"SIG\")) \+ (pad \"2\" smd rect (at 0.5 0) (size 0.54 0.64) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 4 \"V3V3\"))) \+ (segment (start 44.5 15) (end 42.0 15) (width 0.10) (layer \"F.Cu\") (net 2)) \+ (segment (start 45.5 15) (end 48.0 15) (width 0.20) (layer \"F.Cu\") (net 4)) \+ (zone (net 1) (net_name \"GND\") (layer \"F.Cu\") (connect_pads (clearance 0.2)) (fill yes (thermal_gap 0.3) (thermal_bridge_width 0.35)) \+ (polygon (pts (xy 33 10) (xy 40 10) (xy 40 20) (xy 33 20))) \+ (filled_polygon (layer \"F.Cu\") (pts (xy 33 10) (xy 40 10) (xy 40 20) (xy 33 20))))",+ three_fids("F.Cu")+ );+ let b = mk_board(60.0, 40.0, &body);+ let r = audit_board(&b, &json!({}), &json!({}), None, "");+ assert_eq!(r["tombstone"]["checkedChips"], 4);+ assert_eq!(r["tombstone"]["count"], 2, "{r}");+ let flagged: Vec<&str> = r["tombstone"]["items"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|x| x["ref"].as_str())+ .collect();+ assert!(flagged.contains(&"R_WIDE"), "{flagged:?}");+ assert!(flagged.contains(&"C_VIP"), "{flagged:?}");+ assert!(!flagged.contains(&"C_OK_THERM"), "thermal relief + off-pad via must not false-positive: {flagged:?}");+ assert!(!flagged.contains(&"R_THIN_OK"), "0.20 vs 0.10 mm thin traces must not false-positive: {flagged:?}");+ }++ #[test]+ fn tombstone_perimeter_sampler_ignores_internal_bends_and_catches_wide_passthrough_bus() {+ // R_BEND: 0.18 mm trace with 3 jog segments inside pad 1 vs single 0.18 mm trace on pad 2 -> must NOT flag+ // R_BUS: 0.50 mm power bus passing straight through pad 1 (enters left, exits right = 1.0 mm) vs 0.20 mm trace -> MUST flag+ let body = format!(+ "{} \+ (footprint \"Resistor_SMD:R_0402_1005Metric\" (layer \"F.Cu\") (at 15 15) (property \"Reference\" \"R_BEND\") (property \"Value\" \"10k\") \+ (pad \"1\" smd rect (at -0.5 0) (size 0.54 0.64) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 2 \"SIG\")) \+ (pad \"2\" smd rect (at 0.5 0) (size 0.54 0.64) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 4 \"V3V3\"))) \+ (segment (start 14.5 15.0) (end 14.4 15.1) (width 0.18) (layer \"F.Cu\") (net 2)) \+ (segment (start 14.4 15.1) (end 14.3 14.9) (width 0.18) (layer \"F.Cu\") (net 2)) \+ (segment (start 14.3 14.9) (end 12.0 14.9) (width 0.18) (layer \"F.Cu\") (net 2)) \+ (segment (start 15.5 15.0) (end 18.0 15.0) (width 0.18) (layer \"F.Cu\") (net 4)) \+ (footprint \"Resistor_SMD:R_0402_1005Metric\" (layer \"F.Cu\") (at 30 15) (property \"Reference\" \"R_BUS\") (property \"Value\" \"10k\") \+ (pad \"1\" smd rect (at -0.5 0) (size 0.54 0.64) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 3 \"VIN\")) \+ (pad \"2\" smd rect (at 0.5 0) (size 0.54 0.64) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 2 \"SIG\"))) \+ (segment (start 29.5 10.0) (end 29.5 20.0) (width 0.50) (layer \"F.Cu\") (net 3)) \+ (segment (start 30.5 15.0) (end 34.0 15.0) (width 0.20) (layer \"F.Cu\") (net 2))",+ three_fids("F.Cu")+ );+ let b = mk_board(60.0, 40.0, &body);+ let r = audit_board(&b, &json!({}), &json!({}), None, "");+ let flagged: Vec<&str> = r["tombstone"]["items"]+ .as_array()+ .unwrap()+ .iter()+ .filter_map(|x| x["ref"].as_str())+ .collect();+ assert!(!flagged.contains(&"R_BEND"), "internal pad bends must not inflate exit width: {r}");+ assert!(flagged.contains(&"R_BUS"), "wide pass-through bus vs 0.20 mm trace must flag: {r}");+ }++ #[test]+ fn fiducials_handle_global_local_tiny_boards_molecules_and_panels() {+ // 1. Standard 60x40 board with 0.5 mm 16-pin QFN and 0 fiducials -> flags global + local+ let mut qfn_pads = String::new();+ for i in 0..16 {+ let side = i / 4;+ let k = (i % 4) as f64 - 1.5;+ let (px, py) = match side {+ 0 => (-2.0, k * 0.5),+ 1 => (k * 0.5, 2.0),+ 2 => (2.0, -k * 0.5),+ _ => (-k * 0.5, -2.0),+ };+ qfn_pads.push_str(&format!(+ "(pad \"{}\" smd rect (at {px} {py}) (size 0.3 0.7) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 2 \"SIG\")) ",+ i + 1+ ));+ }+ let qfn = format!(+ "(footprint \"Package_DFN_QFN:QFN-16_4x4mm_P0.5mm\" (layer \"F.Cu\") (at 30 20) (property \"Reference\" \"U1\") (property \"Value\" \"IC\") {qfn_pads})"+ );+ let b_no_fid = mk_board(60.0, 40.0, &qfn);+ let r0 = audit_board(&b_no_fid, &json!({}), &json!({}), None, "");+ assert_eq!(r0["fiducials"]["pass"], false, "{r0}");+ let fs = r0["fiducials"]["findings"].to_string();+ assert!(fs.contains("global fiducials on F.Cu") && fs.contains("local fiducials missing"), "{fs}");++ // Adding 3 asymmetric global + 2 diagonal local fiducials around U1 passes+ let with_all = format!(+ "{} {} {} {qfn}",+ three_fids("F.Cu"),+ fiducial_sexpr("FID4", "F.Cu", 26.5, 16.5),+ fiducial_sexpr("FID5", "F.Cu", 33.5, 23.5),+ );+ let b_ok = mk_board(60.0, 40.0, &with_all);+ let r1 = audit_board(&b_ok, &json!({}), &json!({}), None, "");+ assert_eq!(r1["fiducials"]["pass"], true, "{r1}");++ // 2. Tiny 18x18 mm breakout with only 0805s -> no fiducial warning+ let tiny = mk_board(+ 18.0,+ 18.0,+ "(footprint \"Resistor_SMD:R_0805\" (layer \"F.Cu\") (at 9 9) (property \"Reference\" \"R1\") (property \"Value\" \"1k\") \+ (pad \"1\" smd rect (at -1 0) (size 1.0 1.2) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 2 \"SIG\")) \+ (pad \"2\" smd rect (at 1 0) (size 1.0 1.2) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 1 \"GND\")))",+ );+ let rt = audit_board(&tiny, &json!({}), &json!({}), None, "");+ assert_eq!(rt["fiducials"]["pass"], true, "{rt}");++ // 3. Compact 38x38 molecule with 2 diagonal fiducials at 3.0 mm from edge passes+ let mol_body = format!(+ "(footprint \"Molecule:MachinePinLargeShort\" (layer \"F.Cu\") (at 3 3) (property \"Reference\" \"MP1\") \+ (pad \"1\" thru_hole circle (at 0 0) (size 5.0 5.0) (drill 3.6) (layers \"*.Cu\" \"*.Mask\") (net 1 \"GND\"))) \+ (footprint \"Resistor_SMD:R_0603\" (layer \"F.Cu\") (at 19 19) (property \"Reference\" \"R1\") \+ (pad \"1\" smd rect (at -0.8 0) (size 0.8 0.9) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 2 \"SIG\")) \+ (pad \"2\" smd rect (at 0.8 0) (size 0.8 0.9) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 1 \"GND\"))) \+ {} {}",+ fiducial_sexpr("FID1", "F.Cu", 3.0, 35.0),+ fiducial_sexpr("FID2", "F.Cu", 35.0, 3.0),+ );+ let b_mol = mk_board(38.0, 38.0, &mol_body);+ let rm = audit_board(&b_mol, &json!({"molecule": {"pin": "large"}}), &json!({}), None, "");+ assert_eq!(rm["fiducials"]["pass"], true, "{rm}");+ assert_eq!(rm["context"]["isMolecule"], true);+ }++ #[test]+ fn bottom_reflow_flags_heavy_and_tall_parts_and_respects_single_sided_and_bom_mass() {+ let top_r = "(footprint \"Resistor_SMD:R_0603\" (layer \"F.Cu\") (at 15 15) (property \"Reference\" \"R1\") \+ (pad \"1\" smd rect (at -0.8 0) (size 0.8 0.9) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 2 \"SIG\")) \+ (pad \"2\" smd rect (at 0.8 0) (size 0.8 0.9) (layers \"F.Cu\" \"F.Paste\" \"F.Mask\") (net 1 \"GND\")))";+ let bot_ind = "(footprint \"Inductor_SMD:L_Wuerth_WE-PD_7345_H4.5mm\" (layer \"B.Cu\") (at 30 20) (property \"Reference\" \"L1\") (property \"Value\" \"10uH\") \+ (fp_rect (start -3.6 -3.6) (end 3.6 3.6) (layer \"B.Fab\")) \+ (pad \"1\" smd rect (at -2.5 0) (size 2.0 3.0) (layers \"B.Cu\" \"B.Paste\" \"B.Mask\") (net 3 \"VIN\")) \+ (pad \"2\" smd rect (at 2.5 0) (size 2.0 3.0) (layers \"B.Cu\" \"B.Paste\" \"B.Mask\") (net 2 \"SIG\")))";+ let bot_cap_tall = "(footprint \"Capacitor_SMD:CP_Elec_6.3x7.7\" (layer \"B.Cu\") (at 42 20) (property \"Reference\" \"C1\") (property \"Value\" \"100uF\") \+ (fp_rect (start -3.3 -3.3) (end 3.3 3.3) (layer \"B.Fab\")) \+ (pad \"1\" smd rect (at -2.0 0) (size 2.2 1.6) (layers \"B.Cu\" \"B.Paste\" \"B.Mask\") (net 3 \"VIN\")) \+ (pad \"2\" smd rect (at 2.0 0) (size 2.2 1.6) (layers \"B.Cu\" \"B.Paste\" \"B.Mask\") (net 1 \"GND\")))";++ let b = mk_board(+ 60.0,+ 40.0,+ &format!("{} {} {top_r} {bot_ind} {bot_cap_tall}", three_fids("F.Cu"), three_fids("B.Cu")),+ );+ let r = audit_board(&b, &json!({}), &json!({}), None, "");+ assert_eq!(r["bottomReflow"]["pass"], false, "{r}");+ assert_eq!(r["bottomReflow"]["heavyOrTall"].as_array().unwrap().len(), 2, "{r}");++ // BOM mass check on a generic package: 1.5 g on 12 mm2 (0.12 cm2) = 12.5 g/cm2 > 4.6 g/cm2+ let bom = "ref,value,mass_g\nL1,10uH,1.5\nC1,100uF,0.2\n";+ let r_bom = audit_board(&b, &json!({}), &json!({}), Some(bom), "");+ let l1_row = r_bom["bottomReflow"]["heavyOrTall"]+ .as_array()+ .unwrap()+ .iter()+ .find(|x| x["ref"] == "L1")+ .unwrap();+ assert!(l1_row["reason"].as_str().unwrap().contains("12.5 g/cm2"), "{l1_row}");++ // Single-sided bottom-only board (0 top SMD) is reflowed face-up: no heavy bottom drop risk+ let b_bot_only = mk_board(60.0, 40.0, &format!("{} {bot_ind}", three_fids("B.Cu")));+ let r_bo = audit_board(&b_bot_only, &json!({}), &json!({}), None, "");+ assert_eq!(r_bo["bottomReflow"]["pass"], true, "{r_bo}");+ assert_eq!(r_bo["bottomReflow"]["doubleSided"], false);+ }++ #[test]+ fn blocking_policy_from_spec_profile_and_dru_and_no_assembly_skip() {+ let dir = aiflow_sys::temp_dir().join(format!("aiflow-dfa-policy-{}", aiflow_sys::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let board_p = dir.join("b.kicad_pcb").display().to_string();++ // Warn by default+ let c0 = DfaConfig::from_sources(&json!({}), &json!({}), &board_p);+ assert!(!c0.blocking);++ // Spec opt-in+ let c1 = DfaConfig::from_sources(&json!({"dfa": {"blocking": true}}), &json!({}), &board_p);+ assert!(c1.blocking);++ // Strict profile opt-in+ let c2 = DfaConfig::from_sources(&json!({"assembly": {"profile": "production"}}), &json!({}), &board_p);+ assert!(c2.blocking);++ // .kicad_dru opt-in, overridden by explicit spec false+ std::fs::write(dir.join("b.kicad_dru"), "(version 1)\n# adom-aiflow: dfaBlocking\n").unwrap();+ let c3 = DfaConfig::from_sources(&json!({}), &json!({}), &board_p);+ assert!(c3.blocking);+ let c4 = DfaConfig::from_sources(&json!({"dfa": {"blocking": false}}), &json!({}), &board_p);+ assert!(!c4.blocking);+ let _ = std::fs::remove_dir_all(&dir);++ // Through-hole only board -> not applicable+ let tht = mk_board(+ 40.0,+ 30.0,+ "(footprint \"Connector_PinHeader:PinHeader_1x02\" (layer \"F.Cu\") (at 10 10) (property \"Reference\" \"J1\") \+ (pad \"1\" thru_hole circle (at 0 0) (size 1.7 1.7) (drill 1.0) (layers \"*.Cu\" \"*.Mask\") (net 1 \"GND\")))",+ );+ let r_tht = audit_board(&tht, &json!({}), &json!({}), None, "");+ assert_eq!(r_tht["applicable"], false);+ assert_eq!(r_tht["pass"], true);+ }+}
crates/adom-aiflow/src/gate_eval.rs+3@@ -108,6 +108,9 @@ pub fn evaluate(r: &Run, b: &Board, plan_v: &Value, routed: &Path, base: &Value, let xt = crate::si_checks::crosstalk_3w_audit(&rb, &spec_g); s["siChecks"] = json!({"returnVias": ret, "crosstalk3W": xt}); s["copperBalance"] = aiflow_analyze::copper_balance::audit(&rb, &spec_g, &r.current_board());+ let req_g = crate::requirements_of(r);+ let bom_text = crate::run_bom(r).and_then(|p| std::fs::read_to_string(p).ok());+ s["dfa"] = crate::dfa::audit_board(&rb, &spec_g, &req_g, bom_text.as_deref(), &r.current_board()); } Ok(GateEval { s, pu, pu_issues, sw_issues, dec, mech, stairs, quality }) }
crates/adom-aiflow/src/main.rs+99−3@@ -55,6 +55,7 @@ mod vippo; mod si_checks; mod fields_review; mod usb_power;+mod dfa; /// 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");@@ -170,6 +171,8 @@ enum Cmd { /// `molecule check`: Adom molecule conformance (MP1 to MP4 machine pins, contacts on the grid from MP1, edge margin, fixed references) and the corner-pin class (large pins when the board seats in the base scaffold, weighs over 100 g, carries a motor/actuator/heavy heatsink/cabled connector/hard-pressed button, is over 100 mm long or a pin carries over 3.5 A; issue #87) from spec.molecule; `place check`, `gate` and `finish` run it too when the spec has "molecule". Molecule { #[arg(value_parser = ["check"])] action: String, #[arg(long)] board: Option<String>, #[arg(long)] spec: Option<String>, /// a BOM CSV whose mass_g / weight_g column gives the board's mass for the corner-pin class (default in a run: the BOM sourcing check or parts passed) #[arg(long)] bom: Option<String> },+ /// `dfa check`: Design for Assembly (DFA) solderability, 0402/0201 tombstone symmetry, global/local fiducials, and bottom-side reflow checks. Warns by default; blocking when configured via spec.dfa.blocking, strict assembly profile, or `# adom-aiflow: dfaBlocking` in `<board>.kicad_dru`. Works inside a run or standalone with `--board`.+ Dfa { #[arg(value_parser = ["check"])] action: String, #[arg(long)] board: Option<String>, #[arg(long)] spec: Option<String>, #[arg(long)] bom: Option<String>, #[arg(long)] json: bool }, /// `rules use --profile 3rdPartyFab|<slug>`: the design-rules step. Loads a fab's rule pack from the wiki page adom/pcb-design-rules (3rdPartyFab is the default; `rules list` shows them all): the KiCad .kicad_dru beside the board and in the run, the Fusion DRC rules into the open design, the choice into the spec and the run. `rules install --profile jlcpcb --layers 2`: put the shipped JLCPCB 2-layer .kicad_dru beside the board (the only shipped pack; other layer counts come from `rules use`); `rules check`: does the board's project carry the rules profile spec.fab.rules names, else run.json fabRules ("fab" = the project's own .kicad_dru, "jlcpcb" = the JLCPCB pack for the board's copper layer count, "jlcpcb-6L" = that count exactly). /// `testplan check --tests tests.json`: the test-plan step. Every measurement the AI plans for the probing workcell gets a probe spot: before the board, a test point on its net in the netlist (`--netlist <netlist.json> --add` adds TP<n> for each gap, 0.5 mm round pads from adom/testpoint-pad-0-5mm); with a board, a real 0.5 mm landing (test point or exposed pad) clear of part bodies and other nets, within 50 mm of a ground contact. finish runs the board check again. /// `thermal-vias plan`: the heatsink-via step. For every part in spec.hot ({REF: {watts, tabNet}}) a via target from its dissipation and the rise budget (at least 6), and the spots beside its heat pads, clear of other nets, the edge and every pad; existing vias count. `thermal-vias land` lands the plan one via at a time; `--ack REF --why` (on plan or land; a comma list or repeated, and kept across calls) accepts a part short of its target. finish lists a hot part below target as an open item.@@ -334,7 +337,7 @@ enum Cmd { #[arg(long)] why: Option<String> }, /// Filled copper per layer from the live board Measure,- /// current, thermal or impedance (spec impedanceTargets: each target's impedance from the landed copper, compared with a same-input Fields Signals solve when there is one). `analyze current --ack [email protected]|NET@x,y --why "..."` records a reviewed part-limited peak over the Fields density screen (repeat --ack for more); it covers only that place (the pad or 0.5 mm), keeps the number reported and expires when the copper fingerprint or the spec changes. spec.boardSink declares a board-face heat sink for named parts (thermal).+ /// current, thermal, impedance, si, or dfa (assembly solderability, tombstoning, fiducials, bottom-side reflow). `analyze current --ack [email protected]|NET@x,y --why "..."` records a reviewed part-limited peak over the Fields density screen (repeat --ack for more); it covers only that place (the pad or 0.5 mm), keeps the number reported and expires when the copper fingerprint or the spec changes. spec.boardSink declares a board-face heat sink for named parts (thermal). Analyze { what: String, #[arg(long)] plan: Option<String>, #[arg(long)] fields: Option<PathBuf>, #[arg(long)] ack: Vec<String>, #[arg(long)] why: Option<String> }, /// The finish line, as a report card: what passed, what is still open and what to do next (it never refuses) Finish,@@ -4275,13 +4278,13 @@ fn main() { // All engines share the same default. Server/write children must never open tabs recursively. // `status` reads a run, often another thread's (an audit, a director): it opens no tab, records no // turn and leaves the run's clips alone, so the run's own files are byte for byte what they were.- if !matches!(cli.cmd, Cmd::Timeline { .. } | Cmd::Demo { .. } | Cmd::Status) {+ if !matches!(cli.cmd, Cmd::Timeline { .. } | Cmd::Demo { .. } | Cmd::Status) && !matches!(&cli.cmd, Cmd::Dfa { board: Some(_), .. }) { let ai_thread = cli.ai_thread.clone().or_else(|| Run::open(&dir).and_then(|r|r.data["aiThread"].as_str().map(str::to_owned))).unwrap_or_else(|| "adom-aiflow".into()); let _ = DASHBOARD.set((dir.clone(), ai_thread.clone())); ensure_dashboard(&dir, &ai_thread, matches!(cli.cmd, Cmd::Prompt { .. })); } // every command is a turn in the run's ledger; the gap before it is the AI's thinking time- if !matches!(cli.cmd, Cmd::Start { .. } | Cmd::Intake { .. } | Cmd::Demo { .. } | Cmd::Status) && !matches!(&cli.cmd, Cmd::Timeline { action, .. } if action == "serve" || action == "list" || action == "close") {+ if !matches!(cli.cmd, Cmd::Start { .. } | Cmd::Intake { .. } | Cmd::Demo { .. } | Cmd::Status) && !matches!(&cli.cmd, Cmd::Dfa { board: Some(_), .. }) && !matches!(&cli.cmd, Cmd::Timeline { action, .. } if action == "serve" || action == "list" || action == "close") { if let Some(mut r) = Run::open(&dir) { let idx = r.turn_begin(&command_line()); // the thread that last drove the run: the dashboard header and the tab registry name it@@ -5586,6 +5589,16 @@ fn main() { let spec_i=spec_of(&r); let intent_lines=placement_intent::check(&mut r,&dir,&spec_i,&b,"place verify").unwrap_or_else(|e|{r.save().ok();note(&e,&[placement_intent::HINT.into()]);Vec::new()}); for l in &intent_lines { eprintln!("{l}"); }+ {+ let req_v = requirements_of(&r);+ let bom_txt = run_bom(&r).and_then(|p| std::fs::read_to_string(p).ok());+ let dfa_p = dfa::audit_placement(&b, &spec_i, &req_v, bom_txt.as_deref(), &board_path);+ let (dmsg, dhints) = dfa::format_summary(&dfa_p);+ if dfa_p["pass"] == false {+ eprintln!("Warning (DFA placement): {dmsg}");+ for h in &dhints { eprintln!("Hint (DFA): {h}"); }+ }+ } let rb=r.data["remoteBoard"].as_str().filter(|s|!s.is_empty()).unwrap_or_else(||err("place verify requires the named native board",&[])).to_string(); let br=bridge_of(&r,&cli); let (before,validation,after)=if let Some((plan,rev))=first_read {@@ -5704,6 +5717,16 @@ fn main() { // issue #130: the placement scored in the order of spec.placementPriorities (suggestions) let (rank_v, rank_lines) = priorities::placement_score(&spec_i, &nb); r.outcome("placement-ranking", json!({"board": outp.display().to_string(), "score": rank_v}));+ {+ let req_v = requirements_of(&r);+ let bom_txt = run_bom(&r).and_then(|p| std::fs::read_to_string(p).ok());+ let dfa_p = dfa::audit_placement(&nb, &spec_i, &req_v, bom_txt.as_deref(), &outp.display().to_string());+ if dfa_p["pass"] == false {+ let (dmsg, dhints) = dfa::format_summary(&dfa_p);+ eprintln!("Warning (DFA placement): {dmsg}");+ for h in &dhints { eprintln!("Hint (DFA): {h}"); }+ }+ } let old_board = r.current_board(); if let Some(n) = reviews::void_on_service_change(&mut r, Path::new(&old_board), &outp) { eprintln!("{n}"); } r.add_board(&outp.display().to_string());@@ -6125,6 +6148,17 @@ fn main() { } } }+ {+ let dfa_blocking = dfa::blocking_findings(&s["dfa"]);+ if !dfa_blocking.is_empty() {+ let (_, dhints) = dfa::format_summary(&s["dfa"]);+ findings(&format!("gate failed: DFA assembly check (blocking):\n {}", dfa_blocking.join("\n ")), &dhints);+ } else if s["dfa"]["pass"] == false {+ let (dmsg, dhints) = dfa::format_summary(&s["dfa"]);+ eprintln!("Warning (DFA): {dmsg}");+ for h in &dhints { eprintln!("Hint (DFA): {h}"); }+ }+ } 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 ")); }@@ -6470,6 +6504,25 @@ fn main() { ok(&lines.join("\n"), &hints); return; }+ if what == "dfa" {+ let live = live_board(&r, &cli, &dir);+ let (board_now, board_path) = match &live {+ Some((_, k)) => (Board::load(k).unwrap_or_else(|e| err(&e, &[])), k.clone()),+ None => (board_of(&r), r.current_board()),+ };+ let spec = spec_of(&r);+ let req = requirements_of(&r);+ let bom_txt = run_bom(&r).and_then(|p| std::fs::read_to_string(p).ok());+ let rep = dfa::audit_board(&board_now, &spec, &req, bom_txt.as_deref(), &board_path);+ r.outcome("analyze-dfa", rep.clone());+ r.save().unwrap();+ let (msg, hints) = dfa::format_summary(&rep);+ if !dfa::blocking_findings(&rep).is_empty() {+ err(&msg, &hints);+ }+ ok(&msg, &hints);+ return;+ } if what == "si" { // issues #214, #215: reference-plane copper coverage, return-path stitching vias, // 3W/3H crosstalk, USB VBUS inrush capacitance, rail load budgets, and Fields SI/noise/EMC/ESD/PDN review@@ -7210,6 +7263,20 @@ fn main() { } } r.outcome("copper-balance", cb);++ let bom_txt = run_bom(&r).and_then(|p| std::fs::read_to_string(p).ok());+ let dfa_rep = dfa::audit_board(&b_now, &spec_v, &req_v, bom_txt.as_deref(), &r.current_board());+ let dfa_block = dfa::blocking_findings(&dfa_rep);+ if !dfa_block.is_empty() {+ for f in &dfa_block {+ missing.push(format!("dfa: {f}"));+ }+ } else if dfa_rep["pass"] == false {+ for f in dfa_rep["findings"].as_array().into_iter().flatten().filter_map(Value::as_str) {+ quality_lines.push(format!("dfa (advisory): {f}"));+ }+ }+ r.outcome("dfa", dfa_rep); } // 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();@@ -7820,6 +7887,35 @@ fn main() { hints.push("Keep MP1 to MP4 and the contacts in spec.fixedRefs so placement never moves them; export with step2glb convert --molecule after finish, then adom-aiflow board-glb copper so pads and test points are real copper (skill aiflow-molecule).".into()); ok(&text, &hints); }+ Cmd::Dfa { action: _, board, spec, bom, json: as_json } => {+ let mut run = if board.is_some() { None } else { Run::open(&dir) };+ let board_path = board.clone().or_else(|| run.as_ref().map(|r| r.current_board())).unwrap_or_else(|| err("dfa check needs --board <file.kicad_pcb> outside a run", &[]));+ let spec_v = match spec {+ Some(p) => read_json(p),+ None => run.as_ref().map(spec_soft).unwrap_or_else(|| json!({})),+ };+ let req_v = run.as_ref().map(requirements_of).unwrap_or_else(|| json!({}));+ let bom_path = bom.clone().or_else(|| run.as_ref().and_then(run_bom));+ let bom_txt = bom_path.as_ref().map(|p| std::fs::read_to_string(p).unwrap_or_else(|e| err(&format!("{p}: {e}"), &[])));+ let b = Board::load(&board_path).unwrap_or_else(|e| err(&e, &[]));+ let rep = dfa::audit_board(&b, &spec_v, &req_v, bom_txt.as_deref(), &board_path);+ if let (Some(r), None) = (run.as_mut(), board) {+ r.outcome("analyze-dfa", rep.clone());+ let _ = r.save();+ }+ if *as_json {+ println!("{}", serde_json::to_string_pretty(&rep).unwrap());+ if !dfa::blocking_findings(&rep).is_empty() {+ std::process::exit(2);+ }+ return;+ }+ let (msg, hints) = dfa::format_summary(&rep);+ if !dfa::blocking_findings(&rep).is_empty() {+ err(&msg, &hints);+ }+ ok(&msg, &hints);+ } Cmd::ThermalVias { action, ack, why, pause_ms } => { thread(&cli); let mut r = load_run(&cli);
skills/adom-aiflow/SKILL.md+7@@ -346,6 +346,13 @@ The clock starts at the prompt even when there is no board yet. - Hints name the lighter layer and suggest rebalancing pours, adding a hatched fill, or placing non-functional copper thieving (keeping thieving at least `1.5 mm` from high-speed traces). - Never blocks a finished board by default. Opt in to blocking with `"fab": {"copperBalanceBlocking": true}` in the spec or `# adom-aiflow: copperBalanceBlocking` in the board's `.kicad_dru` rules profile (an explicit `"copperBalanceBlocking": false` in the spec wins over the rules file). Results are recorded in `gate.json`, `run.json` (`pour`, `gate`, `copper-balance`, `summary.copperBalance`) and `export-check.json`. +**Assembly (DFA) solderability, tombstone, fiducial, and bottom-side reflow checks.** `adom-aiflow dfa check [--board B] [--spec S] [--bom M] [--json]` and `adom-aiflow analyze dfa` check four SMT assembly rules and return `OK:`/`ERROR:` with fix `Hint:` lines. `place check` and `place verify` run the placement subset (fiducials and bottom-side reflow), while `gate` and `finish` run the full audit and record it in `gate.json` (`dfa`) and `run.json`.+- **Thermal relief on small SMD pads:** flags 0201/0402/0603 chip pads, fine-pitch IC pins, and small SMD pads (`< 2.0 mm2`) tied solid (`connect_pads yes`, `thru_hole_only`, or pad/footprint `zone_connect 2/3`) to large outer copper pours (`>= 15 mm2`). Intentional solid connections are exempted automatically: `spec.solidAt`, `spec.hot` thermal tabs, high-current `spec.loads` terminals, small local copper patches, mechanical/shield pads, and molecule pins/contacts (`MP*`/`MC*`).+- **0402/0201/01005 tombstone asymmetry:** compares both pads for solid-pour mismatch, exact drill-based one-sided via-in-pad, pad-area mismatch, or large connected copper-width imbalance (default ratio `>= 2.5:1` with wide side `>= 0.35 mm`, crediting thermal-relieved pours and pass-through traces).+- **Global and local fiducials:** checks each assembled face for global fiducials (default 3 asymmetric per board/panel, 2 diagonal on compact `<= 45 mm` molecules, `>= 3.8 mm` from edge or `2.5 mm` on compact molecules, bare copper with no paste) and 2 diagonal local fiducials near `<= 0.50 mm` pitch BGAs/QFNs (skipping mechanically keyed connectors with NPTH alignment pegs, tiny boards without fine-pitch ICs, no-assembly/pattern boards, and hand/`self` assembly profiles).+- **Bottom-side reflow rules:** notes double-sided SMT counts and flags heavy (`> 4.6 g/cm2` from BOM `mass_g` or heavy package class such as power inductors, electrolytic cans, relays, or large connectors) or tall (`> 5.0 mm` from `spec.bodies`, BOM `height_mm`, or footprint name) parts on `B.Cu`. Single-sided bottom-only boards and bare pogo/contact pads are not flagged.+- **Warn by default, opt in to blocking:** findings warn without blocking unless enabled via `"dfa": {"blocking": true}`, `"fab": {"dfaBlocking": true}`, `"strictDfa": true`, a strict assembly profile (`"assembly": {"profile": "production"}`), or `# adom-aiflow: dfaBlocking` in `<board>.kicad_dru` (an explicit `"blocking": false` wins over the rules file). Threshold knobs live under `spec.dfa` (`smallPadMaxAreaMm2`, `minPourAreaMm2`, `tombstoneWidthRatio`, `tombstoneMinWideMm`, `minGlobalFiducials`, `fiducialEdgeClearanceMm`, `localFiducialMaxPitchMm`, `fiducialsOnPanel`, `bottomMaxMassPerAreaGPerCm2`, `bottomMaxHeightMm`, `singleSidedOnly`, `solidExempt`, `bottomExempt`).+ ## A KiCad board from scratch (0.2.0) A KiCad run that starts with no board (`intake` with no `start --board`) follows the `kicad-new` sequence: intake, rules, design, test-plan, sourcing, **parts**, **project-page**, **library**, **schematic**, simulation, then components, models and the board steps as usual. Hydrogen is the stage for the steps without KiCad (the step dashboard comes up at every new phase), KiCad's window for the rest.
skills/aiflow-power-layout/SKILL.md+1−1@@ -55,7 +55,7 @@ Kelvin keepouts follow the tap's own layer (both layers only at its vias) and st ## 4. Pours: small SW, solid heat paths - **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`).+- **Solid, not thermal-relief, at heat paths**: the IC GND pin and the inductor pads (`solidAt`). Keep general outer pours on thermal relief so small SMD pads (0201/0402/0603 and fine-pitch IC pins) do not tombstone or cold-joint; `adom-aiflow dfa check` (`analyze dfa`, `gate`, and `finish`) audits solid-poured small SMD pads, 0402/0201 copper asymmetry, global/local fiducials, and heavy/tall bottom-side reflow parts, exempting `spec.solidAt`, `spec.hot` tabs, high-current terminals, and compact molecule hardware. Warn by default; set `"dfa": {"blocking": true}` or `# adom-aiflow: dfaBlocking` in `.kicad_dru` to make DFA blocking. - **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/dfa-gate-workflow.pyadded+200@@ -0,0 +1,200 @@+"""Design for Assembly (DFA) solderability, tombstone, fiducial, and bottom-side reflow gate end to end:+1. Failing board: solid pour on small SMD pads, asymmetric 0402 (wide trace + one-sided via-in-pad),+ missing global/local fiducials, and heavy/tall bottom-side inductor + electrolytic can.+ - Default (warn): `dfa check` exits 0 with OK + Hint lines; `gate` warns on stderr and records gate.json["dfa"]+ - Blocking (`spec.dfa.blocking: true` or `# adom-aiflow: dfaBlocking` in .kicad_dru): `dfa check` and+ `analyze dfa` exit 2 (ERROR), `gate` flags blocking DFA findings; explicit `blocking: false` overrides DRU+2. Clean board (thermal relief, symmetric 0402s, 3 asymmetric global + 2 local fiducials, no heavy/tall bottom parts)+ passes `dfa check`, `analyze dfa`, and `gate` even in blocking mode+3. False-positive exemptions: `spec.solidAt` / `spec.hot` / high-current `spec.loads`, through-hole/no-assembly+ board, compact molecule with 2 diagonal fiducials, and hand/self assembly profile.+Usage: python3 tests/dfa-gate-workflow.py <adom-aiflow binary>"""+import json, os, pathlib, subprocess, sys, tempfile++binary = str(pathlib.Path(sys.argv[1]).resolve())+++def qfn16(x, y):+ pads = []+ for i in range(16):+ side = i // 4+ k = (i % 4) - 1.5+ if side == 0:+ px, py = -2.0, k * 0.5+ elif side == 1:+ px, py = k * 0.5, 2.0+ elif side == 2:+ px, py = 2.0, -k * 0.5+ else:+ px, py = -k * 0.5, -2.0+ pads.append(+ f'(pad "{i + 1}" smd rect (at {px} {py}) (size 0.3 0.7) '+ f'(layers "F.Cu" "F.Paste" "F.Mask") (net 2 "SIG"))'+ )+ return (+ f'(footprint "Package_DFN_QFN:QFN-16_4x4mm_P0.5mm" (layer "F.Cu") (at {x} {y}) '+ f'(property "Reference" "U1") (property "Value" "IC") '+ f'(fp_rect (start -2.5 -2.5) (end 2.5 2.5) (layer "F.CrtYd") (stroke (width 0.05) (type solid))) '+ f'{" ".join(pads)})'+ )+++def fid(ref, layer, x, y):+ mask = "B.Mask" if layer == "B.Cu" else "F.Mask"+ cy = "B.CrtYd" if layer == "B.Cu" else "F.CrtYd"+ return (+ f'(footprint "Fiducial:Fiducial_1mm_Mask2mm" (layer "{layer}") (at {x} {y}) '+ f'(property "Reference" "{ref}") (property "Value" "Fiducial") '+ f'(fp_circle (center 0 0) (end 1.2 0) (layer "{cy}") (stroke (width 0.05) (type solid))) '+ f'(pad "" smd circle (at 0 0) (size 1.0 1.0) (layers "{layer}" "{mask}") (solder_mask_margin 0.5)))'+ )+++def make_board(path, w, h, body):+ path.write_text(+ '(kicad_pcb (version 20241229) (generator "test") (general (thickness 1.6)) '+ '(layers (0 "F.Cu" signal) (2 "B.Cu" signal) (25 "Edge.Cuts" user)) '+ '(net 0 "") (net 1 "GND") (net 2 "SIG") (net 3 "VIN") '+ f'{body} '+ f'(gr_rect (start 0 0) (end {w} {h}) (layer "Edge.Cuts") (stroke (width 0.1) (type solid))))'+ )+++with tempfile.TemporaryDirectory(prefix="aiflow-dfa-") as td:+ p = pathlib.Path(td)+ env = dict(os.environ, AIFLOW_DASHBOARD="off", XDG_CONFIG_HOME=str(p / "xdg"))++ def call(run, *args):+ cmd = [binary]+ if run is not None:+ cmd.extend(["--run", str(run), "--ai-thread", "dfa-test"])+ cmd.extend(args)+ return subprocess.run(cmd, env=env, capture_output=True, text=True, timeout=120)++ # 1. Failing board with all 4 DFA issues+ bad_body = (+ '(footprint "Resistor_SMD:R_0603_1608Metric" (layer "F.Cu") (at 12 10) (property "Reference" "R1") (property "Value" "10k") '+ '(fp_rect (start -1.4 -0.7) (end 1.4 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" "F.Paste" "F.Mask") (net 2 "SIG")) '+ '(pad "2" smd rect (at 0.8 0) (size 0.8 0.9) (layers "F.Cu" "F.Paste" "F.Mask") (net 1 "GND"))) '+ '(footprint "Resistor_SMD:R_0402_1005Metric" (layer "F.Cu") (at 22 10) (property "Reference" "R2") (property "Value" "10k") '+ '(fp_rect (start -1.0 -0.5) (end 1.0 0.5) (layer "F.CrtYd") (stroke (width 0.05) (type solid))) '+ '(pad "1" smd rect (at -0.5 0) (size 0.54 0.64) (layers "F.Cu" "F.Paste" "F.Mask") (net 3 "VIN")) '+ '(pad "2" smd rect (at 0.5 0) (size 0.54 0.64) (layers "F.Cu" "F.Paste" "F.Mask") (net 2 "SIG"))) '+ '(segment (start 21.5 10) (end 18.0 10) (width 0.60) (layer "F.Cu") (net 3)) '+ '(segment (start 22.5 10) (end 26.0 10) (width 0.15) (layer "F.Cu") (net 2)) '+ + qfn16(38, 20)+ + ' (footprint "Inductor_SMD:L_Wuerth_WE-PD_7345_H6.5mm" (layer "B.Cu") (at 20 26) (property "Reference" "L1") (property "Value" "10uH") '+ '(fp_rect (start -4.0 -4.0) (end 4.0 4.0) (layer "B.CrtYd") (stroke (width 0.05) (type solid))) '+ '(fp_rect (start -3.6 -3.6) (end 3.6 3.6) (layer "B.Fab")) '+ '(pad "1" smd rect (at -2.5 0) (size 2.0 3.0) (layers "B.Cu" "B.Paste" "B.Mask") (net 3 "VIN")) '+ '(pad "2" smd rect (at 2.5 0) (size 2.0 3.0) (layers "B.Cu" "B.Paste" "B.Mask") (net 2 "SIG"))) '+ '(zone (net 1) (net_name "GND") (layer "F.Cu") (connect_pads yes (clearance 0.2)) '+ '(polygon (pts (xy 2 2) (xy 58 2) (xy 58 38) (xy 2 38))) '+ '(filled_polygon (layer "F.Cu") (pts (xy 2 2) (xy 58 2) (xy 58 38) (xy 2 38))))'+ )+ b_bad = p / "bad.kicad_pcb"+ make_board(b_bad, 60, 40, bad_body)+ spec_warn = p / "spec-warn.json"+ spec_warn.write_text(json.dumps({"clearance": 0.15, "minTrackWidth": 0.127, "track": 0.25}))+ spec_block = p / "spec-block.json"+ spec_block.write_text(json.dumps({"clearance": 0.15, "minTrackWidth": 0.127, "track": 0.25, "dfa": {"blocking": True}}))++ # 1a. Default warn mode exits 0 with OK + Hint lines+ rw = call(None, "dfa", "check", "--board", str(b_bad), "--spec", str(spec_warn))+ assert rw.returncode == 0 and rw.stdout.startswith("OK:") and "Hint:" in rw.stdout, rw.stdout + rw.stderr+ rj = call(None, "dfa", "check", "--board", str(b_bad), "--spec", str(spec_warn), "--json")+ assert rj.returncode == 0, rj.stderr+ doc = json.loads(rj.stdout)+ assert doc["pass"] is False and doc["blocking"] is False+ assert doc["solidPads"]["count"] >= 1, doc["solidPads"]+ assert doc["tombstone"]["count"] == 1, doc["tombstone"]+ assert doc["fiducials"]["pass"] is False, doc["fiducials"]+ assert doc["bottomReflow"]["pass"] is False and len(doc["bottomReflow"]["heavyOrTall"]) == 1, doc["bottomReflow"]+ print(" [1/5] warn mode reports all 4 DFA categories with hints and exits 0")++ # 1b. Blocking mode via spec exits 2 (ERROR)+ rb = call(None, "dfa", "check", "--board", str(b_bad), "--spec", str(spec_block))+ assert rb.returncode == 2 and rb.stdout.startswith("ERROR:") and "Hint:" in rb.stdout, rb.stdout + rb.stderr++ # 1c. Blocking mode via .kicad_dru comment marker, overridden by explicit blocking: false+ b_bad.with_suffix(".kicad_dru").write_text('(version 1)\n# adom-aiflow: dfaBlocking\n(rule "c" (constraint clearance (min 0.127mm)))\n')+ rdru = call(None, "dfa", "check", "--board", str(b_bad), "--spec", str(spec_warn))+ assert rdru.returncode == 2 and rdru.stdout.startswith("ERROR:"), rdru.stdout + rdru.stderr+ spec_off = p / "spec-off.json"+ spec_off.write_text(json.dumps({"dfa": {"blocking": False}}))+ roff = call(None, "dfa", "check", "--board", str(b_bad), "--spec", str(spec_off))+ assert roff.returncode == 0 and roff.stdout.startswith("OK:"), roff.stdout + roff.stderr+ b_bad.with_suffix(".kicad_dru").unlink()+ print(" [2/5] blocking opt-in via spec.dfa.blocking and .kicad_dru marker works (and explicit false wins)")++ # 2. Clean board passes analyze dfa and gate even in blocking mode+ clean_body = (+ fid("FID1", "F.Cu", 5, 5) + " " + fid("FID2", "F.Cu", 55, 5) + " " + fid("FID3", "F.Cu", 5, 35) + " "+ + fid("FID4", "F.Cu", 34.5, 16.5) + " " + fid("FID5", "F.Cu", 41.5, 23.5) + " "+ '(footprint "Resistor_SMD:R_0603_1608Metric" (layer "F.Cu") (at 12 10) (property "Reference" "R1") (property "Value" "10k") '+ '(fp_rect (start -1.4 -0.7) (end 1.4 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" "F.Paste" "F.Mask") (net 2 "SIG")) '+ '(pad "2" smd rect (at 0.8 0) (size 0.8 0.9) (layers "F.Cu" "F.Paste" "F.Mask") (net 1 "GND"))) '+ '(footprint "Resistor_SMD:R_0402_1005Metric" (layer "F.Cu") (at 22 10) (property "Reference" "R2") (property "Value" "10k") '+ '(fp_rect (start -1.0 -0.5) (end 1.0 0.5) (layer "F.CrtYd") (stroke (width 0.05) (type solid))) '+ '(pad "1" smd rect (at -0.5 0) (size 0.54 0.64) (layers "F.Cu" "F.Paste" "F.Mask") (net 3 "VIN")) '+ '(pad "2" smd rect (at 0.5 0) (size 0.54 0.64) (layers "F.Cu" "F.Paste" "F.Mask") (net 2 "SIG"))) '+ '(segment (start 21.5 10) (end 18.0 10) (width 0.25) (layer "F.Cu") (net 3)) '+ '(segment (start 22.5 10) (end 26.0 10) (width 0.20) (layer "F.Cu") (net 2)) '+ '(segment (start 11.2 10) (end 22.5 10) (width 0.20) (layer "F.Cu") (net 2)) '+ '(zone (net 1) (net_name "GND") (layer "F.Cu") (connect_pads (clearance 0.2)) (fill yes (thermal_gap 0.3) (thermal_bridge_width 0.35)) '+ '(polygon (pts (xy 2 2) (xy 58 2) (xy 58 38) (xy 2 38))) '+ '(filled_polygon (layer "F.Cu") (pts (xy 2 2) (xy 58 2) (xy 58 38) (xy 2 38))))'+ )+ b_clean = p / "clean.kicad_pcb"+ make_board(b_clean, 60, 40, clean_body)+ run_clean = p / "run-clean"+ assert call(run_clean, "start", "--board", str(b_clean), "--spec", str(spec_block), "--engine", "test", "--prompt-time", "2026-12-02T00:00:00Z").returncode == 0+ ra_clean = call(run_clean, "analyze", "dfa")+ assert ra_clean.returncode == 0 and ra_clean.stdout.startswith("OK: DFA check clean"), ra_clean.stdout + ra_clean.stderr+ out_run = json.loads((run_clean / "run.json").read_text())+ assert out_run["outcomes"]["analyze-dfa"]["pass"] is True+ print(" [3/5] clean board passes analyze dfa in blocking mode and records run outcome")++ # 3. Inside a run with blocking DFA on failing board: analyze dfa fails (exit 2) and gate flags blocking DFA+ run_bad = p / "run-bad"+ assert call(run_bad, "start", "--board", str(b_bad), "--spec", str(spec_block), "--engine", "test", "--prompt-time", "2026-12-02T00:00:00Z").returncode == 0+ ra_bad = call(run_bad, "analyze", "dfa")+ assert ra_bad.returncode == 2 and ra_bad.stdout.startswith("ERROR:"), ra_bad.stdout + ra_bad.stderr+ # Gate with empty plan tests gate_eval + blocking DFA hook+ plan_empty = p / "empty-plan.json"+ plan_empty.write_text(json.dumps({"nets": []}))+ rg_bad = call(run_bad, "gate", "--plan", str(plan_empty))+ gdoc = json.loads((run_bad / "gate.json").read_text())+ assert gdoc["dfa"]["blocking"] is True and gdoc["dfa"]["pass"] is False, gdoc.get("dfa")+ print(" [4/5] analyze dfa and gate enforce blocking DFA inside a run and record gate.json['dfa']")++ # 4. Exemptions: solidAt + hot + compact molecule with 2 diagonal fiducials + hand assembly+ mol_body = (+ '(footprint "Molecule:MachinePinLargeShort" (layer "F.Cu") (at 3 3) (property "Reference" "MP1") '+ '(pad "1" thru_hole circle (at 0 0) (size 5.0 5.0) (drill 3.6) (layers "*.Cu" "*.Mask") (net 1 "GND"))) '+ '(footprint "Resistor_SMD:R_0603" (layer "F.Cu") (at 19 19) (property "Reference" "R1") '+ '(pad "1" smd rect (at -0.8 0) (size 0.8 0.9) (layers "F.Cu" "F.Paste" "F.Mask") (net 2 "SIG")) '+ '(pad "2" smd rect (at 0.8 0) (size 0.8 0.9) (layers "F.Cu" "F.Paste" "F.Mask") (net 1 "GND"))) '+ + fid("FID1", "F.Cu", 3.0, 35.0) + " " + fid("FID2", "F.Cu", 35.0, 3.0) + " "+ '(zone (net 1) (net_name "GND") (layer "F.Cu") (connect_pads yes (clearance 0.2)) '+ '(polygon (pts (xy 1 1) (xy 37 1) (xy 37 37) (xy 1 37))) '+ '(filled_polygon (layer "F.Cu") (pts (xy 1 1) (xy 37 1) (xy 37 37) (xy 1 37))))'+ )+ b_mol = p / "mol.kicad_pcb"+ make_board(b_mol, 38, 38, mol_body)+ spec_mol = p / "spec-mol.json"+ spec_mol.write_text(json.dumps({"molecule": {"pin": "large"}, "solidAt": ["R1.2"], "dfa": {"blocking": True}}))+ rm = call(None, "dfa", "check", "--board", str(b_mol), "--spec", str(spec_mol))+ assert rm.returncode == 0 and rm.stdout.startswith("OK: DFA check clean"), rm.stdout + rm.stderr++ # Hand/self assembly skips fiducials & bottom-side reflow+ spec_hand = p / "spec-hand.json"+ spec_hand.write_text(json.dumps({"sourcing": {"profile": "self"}}))+ rh = call(None, "dfa", "check", "--board", str(b_bad), "--spec", str(spec_hand), "--json")+ hdoc = json.loads(rh.stdout)+ assert hdoc["fiducials"]["checked"] is False and hdoc["bottomReflow"]["checked"] is False, hdoc+ print(" [5/5] molecule, solidAt, and hand-assembly exemptions pass without false positives")++print("PASS: DFA check stage/gate workflow verified (warn default, blocking opt-in, exemptions, clean pass).")